Httplib (cpp-httplib) Sample

Introduction https://github.com/yhirose/cpp-httplib{:target="_blank"} A C++11 single-file header-only cross platform HTTP/HTTPS library. This is a multi-threaded ‘blocking’ HTTP library header-only 라이브러리로 Server와 Client Http 지원 SSL을 위한 OpenSSL 필요 cpprestsdk비해 가볍고, 쉽게 사용 가능 Httplib package install (w/ vcpkg) https://github.com/microsoft/vcpkg{:target="_blank"} vcpkg 통해서 패키지 설치 header-only로 바로 사용가능하나 OpenSSL 필요시 패키지 설치가 용이 # --triplet=x64-windows-static $ vcpkg.exe install cpp-httplib openssl --triplet=x64-windows-static ... The package cpp-httplib:x64-windows-static is header only and can be used from CMake via: find_path(CPP_HTTPLIB_INCLUDE_DIRS "httplib.h") target_include_directories(main PRIVATE ${CPP_HTTPLIB_INCLUDE_DIRS}) The package openssl is compatible with built-in CMake targets: find_package(OpenSSL REQUIRED) target_link_libraries(main PRIVATE OpenSSL::SSL OpenSSL::Crypto) Json test https://github.com/nlohmann/json{:target="_blank"} $ vcpkg.exe install nlohmann-json --triplet=x64-windows-static The package nlohmann-json:x64-windows-static provides CMake targets: find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) Sample code HTTPS 호출을 위해 CPPHTTPLIB_OPENSSL_SUPPORT 매크로가 정의 되어 있어야 함 정의하지 않고 HTTPS 호출시 : 'https' scheme is not supported. using namespace std; std namespace 노출시 byte 타입 정의 모호함으로 인한 에러 발생 표준 라이브러리 보다 먼저 선언되던가 using namespace std;를 피해야 함 ‘byte’: 모호한 기호입니다. #define CPPHTTPLIB_OPENSSL_SUPPORT #include <httplib.h> #include <iostream> using namespace std; #include <nlohmann/json.hpp> using json = nlohmann::json; void HttpRequest() { httplib::Client cli("https://httpbin.org"); { auto resp = cli.Get("/get"); cout << "status: " << resp->status << endl; cout << resp->body << endl; } { auto resp = cli.Post("/post"); cout << "status: " << resp->status << endl; cout << resp->body << endl; auto js = json::parse(resp->body); cout << "User-Agent: " << js["headers"]["User-Agent"] << endl; } } int main() { try { HttpRequest(); } catch (exception &e) { cerr << e.what() << endl; } catch (...) { cerr << "catch ..." << endl; } return 0; } CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) set(CMAKE_CXX_STANDARD 17) add_executable(main main.cpp) target_compile_options(main PRIVATE /MT) find_package(OpenSSL REQUIRED) target_link_libraries(main PRIVATE OpenSSL::SSL OpenSSL::Crypto) find_path(CPP_HTTPLIB_INCLUDE_DIRS "httplib.h") target_include_directories(main PRIVATE ${CPP_HTTPLIB_INCLUDE_DIRS}) find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) $ mkdir build && cd build # x64-windows-static $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static Build & Run # build $ echo cmake --build . --config Release > make.bat $ make.bat # run $ Release\main.exe status: 200 { "args": {}, "headers": { "Accept": "*/*", "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpp-httplib/0.9", "X-Amzn-Trace-Id": "Root=1-611dba9f-0bdb46bb04c05b410da75cf4", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "https://httpbin.org/get" } status: 200 { "args": {}, "data": "", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Content-Length": "0", "Host": "httpbin.org", "User-Agent": "cpp-httplib/0.9", "X-Amzn-Trace-Id": "Root=1-611dba9f-091d99a41e5b3c023550162f", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "json": null, "origin": "xx.xx.xx.xx", "url": "https://httpbin.org/post" } User-Agent: "cpp-httplib/0.9"

August 18, 2021 · Byung Kyu KIM

Vcpkg Basic

https://vcpkg.io/{:target="_blank"} Vcpkg helps you manage C and C++ libraries on Windows, Linux and MacOS. This tool and ecosystem are constantly evolving, and we always appreciate contributions! Introduction https://github.com/microsoft/vcpkg{:target="_blank"} MS에서 만든 C++ Library Package 관리 (Cross Platform) Vcpkg install Git 이 필요하고, bootstrap-vcpkg 실행으로 필요한 툴을 다운로드(빌드)하는 작업을 수행 vcpkg.exe 생성 $ git clone https://github.com/microsoft/vcpkg $ cd vcpkg # windows $ bootstrap-vcpkg.bat # linux $ ./bootstrap-vcpkg.sh Package search & install triplet : Target configuration set 설치시 triplet 을 지정하지 않으면 설치되어 있는 기본 C++ Toolset 으로 지정 Windows의 경우 x86-windows default 주요 Triplet list vcpkg help triplet $ vcpkg help triplet Available architecture triplets VCPKG built-in triplets: ... x64-windows-static x64-windows x86-windows ... VCPKG community triplets: ... x64-windows-static-md x86-windows-static-md x86-windows-static x64-mingw-dynamic x64-mingw-static x86-mingw-dynamic x86-mingw-static x64-linux ... Search vcpkg search # Package search $ vcpkg search fmt fmt 7.1.3#5 Formatting library for C++. ... The search result may be outdated. Run `git pull` to get the latest results. Install vcpkg install vcpkg search 에서 찾은 패키지를 triplet 을 지정하여 설치 설치가 완료되면 프로젝트 CMakeLists.txt 넣을 find_package 문 표시 # Package 별로 triplet 지정 $ vcpkg.exe install fmt:x64-windows-static nlohmann-json:x64-windows-static # triplet 공통 지정 $ vcpkg.exe install fmt nlohmann-json --triplet=x64-windows-static ... The package fmt provides CMake targets: find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt) # Or use the header-only version find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt-header-only) The package nlohmann-json:x64-windows-static provides CMake targets: find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) 설치된 리스트 vcpkg list # Package installed list $ vcpkg list benchmark:x64-mingw-static 1.5.5 A library to support the benchmarking of functio... benchmark:x64-windows-static 1.5.5 A library to support the benchmarking of functio... cpp-httplib:x64-mingw-static 0.9.1 A single file C++11 header-only HTTP/HTTPS serve... cpp-httplib:x64-windows-static 0.9.1 A single file C++11 header-only HTTP/HTTPS serve... fmt:x64-windows 7.1.3#5 Formatting library for C++. It can be used as a ... fmt:x64-windows-static 7.1.3#5 Formatting library for C++. It can be used as a ... nlohmann-json:x64-mingw-static 3.9.1 JSON for Modern C++ nlohmann-json:x64-windows-static 3.9.1 JSON for Modern C++ openssl:x64-mingw-static 1.1.1k#8 OpenSSL is an open source project that provides ... openssl:x64-windows-static 1.1.1k#8 OpenSSL is an open source project that provides ... vcpkg-cmake-config:x64-windows 2021-05-22#1 vcpkg-cmake:x64-windows 2021-07-30 zlib:x64-mingw-static 1.2.11#11 A compression library zlib:x64-windows-static 1.2.11#11 A compression library Integrate install vcpkg integrate install Windows Visual Studio에서 vcpkg 라이브러리를 별도 설정 없이 바로 사용 $ vcpkg integrate install Applied user-wide integration for this vcpkg root. All MSBuild C++ projects can now #include any installed libraries. Linking will be handled automatically. Installing new libraries will make them instantly available. CMake projects should use: "-DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake" vcpkg 명령어 # Vcpkg package management program version 2021-08-12-85ab112d5ee102bc6eac8cdbbfdd173a71374e04 $ vcpkg help Commands: vcpkg search [pat] Search for packages available to be built vcpkg install <pkg>... Install a package vcpkg remove <pkg>... Uninstall a package vcpkg remove --outdated Uninstall all out-of-date packages vcpkg list List installed packages vcpkg update Display list of packages for updating vcpkg upgrade Rebuild all outdated packages vcpkg x-history <pkg> (Experimental) Shows the history of CONTROL versions of a package vcpkg hash <file> [alg] Hash a file by specific algorithm, default SHA512 vcpkg help topics Display the list of help topics vcpkg help <topic> Display help for a specific topic vcpkg integrate install Make installed packages available user-wide. Requires admin privileges on first use vcpkg integrate remove Remove user-wide integration vcpkg integrate project Generate a referencing nuget package for individual VS project use vcpkg integrate powershell Enable PowerShell tab-completion vcpkg export <pkg>... [opt]... Exports a package vcpkg edit <pkg> Open up a port for editing (uses %EDITOR%, default 'code') vcpkg create <pkg> <url> [archivename] Create a new package vcpkg x-init-registry <path> Initializes a registry in the directory <path> vcpkg owns <pat> Search for files in installed packages vcpkg depend-info <pkg>... Display a list of dependencies for packages vcpkg env Creates a clean shell environment for development or compiling vcpkg version Display version information vcpkg contact Display contact information to send feedback ... 1. 내 프로젝트에서 사용 (CMake, find_package) CMakeLists.txt 에 find_package 내용 추가 CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) set(CMAKE_CXX_STANDARD 17) add_executable(main main.cpp) if(MSVC) target_compile_options(main PRIVATE /MT) else() target_compile_options(main PRIVATE -Wall -O2) endif() find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt) find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) CMake 초기화 CMAKE_TOOLCHAIN_FILE 과 VCPKG_TARGET_TRIPLET 을 지정하여 초기화 CMAKE_TOOLCHAIN_FILE : vcpkg/scripts/buildsystems/vcpkg.cmake $ mkdir build && cd build # windows msvc $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static # windows mingw $ cmake -G "MSYS Makefiles" .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-mingw-static # linux : VCPKG_TARGET_TRIPLET 지정안함, defualt 사용 $ cmake cmake .. -DCMAKE_TOOLCHAIN_FILE=~/lib/vcpkg/scripts/buildsystems/vcpkg.cmake Build # windows msvc : Release 모드 빌드 $ cmake --build . --config=Release # run $ Release\main.exe # mingw, linux $ make $ ./main 2. 내 프로젝트에서 사용 (라이브러리 수동으로 설정) CMake 수동 지정 : target_include_directories, target_link_directories, target_link_libraries 별도 지정 Makefile 사용 : -I -l -L 등의 옵션 추가 vcpkg/installed/triplet 디렉토리 참고 수동으로 include, lib 등 지정 사용 triplet/include : header files triplet/lib : static library triplet/bin : shared library $ tree vcpkg/installed -L 3 vcpkg/installed ├── vcpkg ... ├── x64-mingw-static │ ├── debug │ │ └── lib │ ├── include │ │ ├── benchmark │ │ ├── httplib.h │ │ ├── nlohmann │ │ ├── openssl │ │ ├── zconf.h │ │ └── zlib.h │ ├── lib │ │ ├── libbenchmark.a │ │ ├── libbenchmark_main.a │ │ ├── libcrypto.a │ │ ├── libssl.a │ │ ├── libzlib.a │ │ └── pkgconfig │ └── share │ ├── benchmark │ ├── cpp-httplib │ ├── nlohmann-json │ ├── nlohmann_json │ ├── openssl │ └── zlib ├── x64-windows │ ├── bin │ │ ├── fmt.dll │ │ └── fmt.pdb │ ├── debug │ │ ├── bin │ │ └── lib │ ├── include │ │ └── fmt │ ├── lib │ │ ├── fmt.lib │ │ └── pkgconfig │ └── share │ ├── fmt │ ├── vcpkg-cmake │ └── vcpkg-cmake-config └── x64-windows-static ├── debug │ ├── lib │ └── misc ├── include │ ├── benchmark │ ├── fmt │ ├── httplib.h │ ├── nlohmann │ ├── openssl │ ├── zconf.h │ └── zlib.h ├── lib │ ├── benchmark.lib │ ├── benchmark_main.lib │ ├── fmt.lib │ ├── libcrypto.lib │ ├── libssl.lib │ ├── ossl_static.pdb │ ├── pkgconfig │ └── zlib.lib ├── misc │ ├── CA.pl │ └── tsget.pl ├── share │ ├── benchmark │ ├── cpp-httplib │ ├── fmt │ ├── nlohmann-json │ ├── nlohmann_json │ ├── openssl │ └── zlib └── tools └── openssl

August 18, 2021 · Byung Kyu KIM

C++ REST SDK(cpprestsdk) Sample

Introduction https://github.com/Microsoft/cpprestsdk{:target="_blank"} Microsoft에서 만든 클라이언트, 서버용 C++ HTTP 통신 모듈이며, JSON URI, 비동기, 웹소켓, oAuth 등을 지원 C++11의 비동기, 병렬 프로그램 모델 지원 크로스 플랫폼 지원 등.. cpprestsdk package install (w/ vcpkg) https://github.com/microsoft/vcpkg{:target="_blank"} vcpkg 통해서 패키지 설치 # --triplet=x64-windows-static $ vcpkg.exe install cpprestsdk:x64-windows-static ... The package cpprestsdk:x64-windows-static provides CMake targets: find_package(cpprestsdk CONFIG REQUIRED) target_link_libraries(main PRIVATE cpprestsdk::cpprest cpprestsdk::cpprestsdk_zlib_internal cpprestsdk::cpprestsdk_brotli_internal) Sample code U("") 는 _T("") 와 비슷한, UNICODE 및 MBCS 환경의 문자열 타입을 스위칭 해주는 매크로. 허나 U는 _T와는 다르게 _WIN32 환경이면 기본으로 _UTF16_STRINGS으로 정의되어 있어 프로젝트의 문자집합의 세팅과 관계 없이 UNICODE와 같은 환경으로 동작 리눅스 환경에서는 다른 설정을 해주지 않는 이상 char, std::string으로 정의 utility::string_t은 std::string과 std::wstring을 스위칭 해주는 타입 대체적인 패턴은, 동기는 .get(), 비동기는 then().wait() 조합으로 사용 #include <iostream> using namespace std; #include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace utility; using namespace web; using namespace web::http; using namespace web::http::client; using namespace concurrency::streams; void HttpRequest() { http_client client(U("http://httpbin.org/get")); http_request req(methods::GET); // sync request auto resp = client.request(req).get(); wcout << resp.status_code() << " : sync request" << endl; wcout << resp.extract_string(true).get() << endl; // async request client.request(req).then([=](http_response r){ wcout << r.status_code() << " : async request" << endl; wcout << U("content-type : ") << r.headers().content_type() << endl; r.extract_string(true).then([](string_t v) { wcout << v << endl; }).wait(); }).wait(); // async request json client.request(req).then([=](http_response r){ wcout << r.status_code() << " : async request json" << endl; wcout << U("content-type : ") << r.headers().content_type() << endl; r.extract_json(true).then([](json::value v) { wcout << v << endl; }).wait(); }).wait(); } int main() { // wcout.imbue(locale("kor")); // windows only HttpRequest(); return 0; } CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) add_executable(main main.cpp) target_compile_options(main PRIVATE /MT) find_package(cpprestsdk CONFIG REQUIRED) target_link_libraries(main PRIVATE cpprestsdk::cpprest cpprestsdk::cpprestsdk_zlib_internal cpprestsdk::cpprestsdk_brotli_internal) $ mkdir build && cd build # x64-windows-static $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static Build & Run # build $ cmake --build . --config Release # run $ Release\main.exe 200 : sync request { "args": {}, "headers": { "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpprestsdk/2.10.18", "X-Amzn-Trace-Id": "Root=1-611cbc68-27731b2a1cd55cbd682c517e", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "http://httpbin.org/get" } 200 : async request content-type : application/json { "args": {}, "headers": { "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpprestsdk/2.10.18", "X-Amzn-Trace-Id": "Root=1-611cbc68-27731b2a1cd55cbd682c517e", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "http://httpbin.org/get" } 200 : async request json content-type : application/json {"args":{},"headers":{"Cache-Control":"max-stale=0","Host":"httpbin.org","User-Agent":"cpprestsdk/2.10.18","X-Amzn-Trace-Id":"Root=1-611cbc68-27731b2a1cd55cbd682c517e","X-Bluecoat-Via":"ce2cfae06b3f12b4"},"origin":"180.xx.xx.xx","url":"http://httpbin.org/get"}

August 17, 2021 · Byung Kyu KIM

Docker 운영 Tip (daemon.json)

Docker default bridge 네트워크 대역 변경 내부 사설 IP와의 출동 등의 이슈 daemon.json /etc/docker/daemon.json { "default-address-pools": [ { "base": "10.1.0.0/16", "size": 24 } ] } Docker restart $ sudo systemctl restart docker 반영 전 $ ip a ... 4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default link/ether 02:42:82:58:25:33 brd ff:ff:ff:ff:ff:ff inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 valid_lft forever preferred_lft forever ... 반영 후 $ ip a ... 1519: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default link/ether 02:42:c0:d9:e2:56 brd ff:ff:ff:ff:ff:ff inet 10.1.0.1/24 brd 10.1.0.255 scope global docker0 valid_lft forever preferred_lft forever ... Data root directory 경로 변경 기본 경로 : /var/lib/docker daemon.json /etc/docker/daemon.json { "data-root": "/docker", "default-address-pools": [ { "base": "10.1.0.0/16", "size": 24 } ] } $ sudo systemctl restart docker $ sudo ls -l /docker 합계 0 drwx--x--x 4 root root 120 8월 18 11:51 buildkit drwx------ 2 root root 6 8월 18 11:51 containers drwx------ 3 root root 22 8월 18 11:51 image drwxr-x--- 3 root root 19 8월 18 11:51 network drwx------ 4 root root 112 8월 18 11:51 overlay2 drwx------ 4 root root 32 8월 18 11:51 plugins drwx------ 2 root root 6 8월 18 11:51 runtimes drwx------ 2 root root 6 8월 18 11:51 swarm drwx------ 2 root root 6 8월 18 11:51 tmp drwx------ 2 root root 6 8월 18 11:51 trust drwx------ 2 root root 50 8월 18 11:51 volumes Docker log 용량 관리 https://docs.docker.com/config/containers/logging/json-file/{:target="_blank"} /containers/ daemon.json /etc/docker/daemon.json { "data-root": "/docker", "log-opts": { "max-size": "100m" }, "default-address-pools": [ { "base": "10.1.0.0/16", "size": 24 } ] }

August 17, 2021 · Byung Kyu KIM

K3S Overview

Lightweight Kubernetes : The certified Kubernetes distribution built for IoT & Edge computing 특징 https://k3s.io/{:target="_blank"} Kubernetes의 경량화 버전으로 아래와 같은 특징 기본 설치만으로 바로 배포 테스트 가능 Overlay Netowrk(Flannel), Load balancer, Ingress(Traefik), CoreDNS 등이 기본 설치 됨 https://rancher.com/docs/k3s/latest/en/networking/{:target="_blank"} etcd 대신 sqlite 운영 High Availability with an External DB High Availability with Embedded DB (Experimental) Master node schedulable uncordon 제외 가능 Worker node 필요 없음 (필요시 추가 가능) 사용 목적 Edge Computing 개발 테스트 및 스테이징 서버 구성 기타 어플리케이션 테스트 용 Master 설치 설치 curl -sfL https://get.k3s.io | sh - 실행으로 끝 systemd 관리 kubectl 설치 및 심볼릭 링크 설정 해줌 이미 kubectl 가 설치 되어 있는 경우는 심볼릭 링크 실패 # alias 필요시 아래 참고 $ alias kubectl='sudo k3s kubectl' # Install $ curl -sfL https://get.k3s.io | sh - # master node $ kubectl get node NAME STATUS ROLES AGE VERSION centos1 Ready control-plane,master 37s v1.21.3+k3s1 $ kubectl get pod -A NAMESPACE NAME READY STATUS RESTARTS AGE kube-system local-path-provisioner-5ff76fc89d-wh9cg 1/1 Running 0 2m35s kube-system coredns-7448499f4d-2d7pb 1/1 Running 0 2m35s kube-system metrics-server-86cbb8457f-x9l6n 1/1 Running 0 2m35s kube-system helm-install-traefik-crd-w27q7 0/1 Completed 0 2m35s kube-system helm-install-traefik-2zllj 0/1 Completed 1 2m35s kube-system svclb-traefik-55qfd 2/2 Running 0 113s kube-system traefik-97b44b794-smzl9 1/1 Running 0 114s K8S 서비스 테스트 서비스 타입 : NodePort https://kubernetes.github.io/ingress-nginx/deploy/baremetal/{:target="_blank"} apiVersion: apps/v1 kind: Deployment metadata: name: mvcapp spec: selector: matchLabels: app: mvcapp replicas: 2 # --replicas=2 옵션과 동일 template: metadata: labels: app: mvcapp spec: containers: - name: mvcapp image: cdecl/mvcapp:0.6 ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: mvcapp spec: type: NodePort selector: app: mvcapp ports: - port: 80 targetPort: 80 $ kubectl apply -f mvcapp-deploy-service.yaml deployment.apps/mvcapp created service/mvcapp created $ kubectl get pod -A NAMESPACE NAME READY STATUS RESTARTS AGE kube-system local-path-provisioner-5ff76fc89d-wh9cg 1/1 Running 0 9m29s kube-system coredns-7448499f4d-2d7pb 1/1 Running 0 9m29s kube-system metrics-server-86cbb8457f-x9l6n 1/1 Running 0 9m29s kube-system helm-install-traefik-crd-w27q7 0/1 Completed 0 9m29s kube-system helm-install-traefik-2zllj 0/1 Completed 1 9m29s kube-system svclb-traefik-55qfd 2/2 Running 0 8m47s kube-system traefik-97b44b794-smzl9 1/1 Running 0 8m48s default mvcapp-79874d888c-6htvq 1/1 Running 0 62s default mvcapp-79874d888c-clslc 1/1 Running 0 62s $ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.43.0.1 <none> 443/TCP 10m mvcapp NodePort 10.43.36.139 <none> 80:32105/TCP 106s # Nodeport IP $ curl 10.43.36.139:80 * Project : Mvcapp * Version : 0.5 / net5.0 * Hostname : mvcapp-79874d888c-6htvq * RemoteAddr : 10.42.0.1 * X-Forwarded-For : * Request Count : 1 * User-Agent : curl/7.29.0 $ curl localhost:32105 * Project : Mvcapp * Version : 0.5 / net5.0 * Hostname : mvcapp-79874d888c-clslc * RemoteAddr : 10.42.0.1 * X-Forwarded-For : * Request Count : 1 * User-Agent : curl/7.29.0 Agent 추가 Master Node만으로도 테스트 가능하나 Scale 테스트시 Agent(Worker Node) 추가 가능 환경변수 세팅 : 필요시 참고 $ sudo cat /var/lib/rancher/k3s/server/node-token > ~/.node-token $ K3S_TOKEN=$(< ~/.node-token) $ HOST_IP=$(ip a | sed -rn 's/.*inet ([0-9\.]+).*eth0/\1/p') Agent 등록 : 원격실행 OR Agent 머신에서 실행 HostIP, Token 정보 필요 (위 환경변수 세팅 참고) # Agent 머신에서 실행 $ curl -sfL https://get.k3s.io | K3S_URL=https://$HOST_IP:6443 K3S_TOKEN=$K3S_TOKEN sh - # Agent 추가 다른방법 $ ansible node01 -m shell -a "curl -sfL https://get.k3s.io | sh -s - agent --server https://$HOST_IP:6443 --token $K3S_TOKEN" -v K3S 삭제 ls /usr/local/bin/k3s-* | xargs -n1 sh -

August 17, 2021 · Byung Kyu KIM

MinIO 101

MinIO 101 Introduction https://docs.min.io/{:target="_blank"} Open Source, S3 Compatible, Enterprise Hardened and Really, Really Fast S3 Compatible : Client(mc), SDK (Java, Javascript, Python, Golang, .Net ..) high performance, distributed object storage system Private cloud object storage Getting Started MinID 는 Golang으로 제작되어 의존성 없는 단일 파일로 운영 가능 Docker의 경우 Alpine linux 로 배포 Downloads : https://min.io/download{:target="_blank"} Quickstart Server https://docs.min.io/docs/minio-quickstart-guide.html{:target="_blank"} # linux - server run $ wget https://dl.min.io/server/minio/release/linux-amd64/minio $ chmod +x minio $ export MINIO_ROOT_USER=minio $ export MINIO_ROOT_PASSWORD=miniopass # ./minio server --address 0.0.0.0:9000 /data $ ./minio server /data Status: 1 Online, 0 Offline. Endpoint: http://192.168.144.5:9000 http://127.0.0.1:9000 Browser Access: http://192.168.144.5:9000 http://127.0.0.1:9000 Object API (Amazon S3 compatible): Go: https://docs.min.io/docs/golang-client-quickstart-guide Java: https://docs.min.io/docs/java-client-quickstart-guide Python: https://docs.min.io/docs/python-client-quickstart-guide JavaScript: https://docs.min.io/docs/javascript-client-quickstart-guide .NET: https://docs.min.io/docs/dotnet-client-quickstart-guide docker-compose 9000 : 데이터 I/F 포트 9001 : Web Console Port ./data:/data : 데이터 영역 version: '3' services: minio: image: minio/minio command: server /data --console-address ":9001" container_name: minio environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9000:9000" - "9001:9001" volumes: - ./data:/data $ docker-compose up -d Creating network "minio_default" with the default driver Pulling minio (minio/minio:)... latest: Pulling from minio/minio c2c17d84f25a: Pull complete 46cdcde062b2: Pull complete c88923a3df19: Pull complete 1afaaeffed49: Pull complete 6c066ed8931e: Pull complete b889e4f29831: Pull complete 51b722521628: Pull complete Digest: sha256:ff4892c4248ad0ef73981d9f2e7b8a721dae45c55bdd25d7a23e1670540f36e1 Status: Downloaded newer image for minio/minio:latest Creating minio ... done Quickstart Client https://docs.min.io/docs/minio-client-quickstart-guide.html{:target="_blank"} # linux # wget https://dl.min.io/client/mc/release/linux-amd64/mc $ curl -O https://dl.min.io/client/mc/release/linux-amd64/mc $ chmod +x mc $ mv ./mc /usr/bin/ $ mc --help # add server config $ mc alias set local http://localhost:9000 minio miniopass Added `local` successfully. # creates a new bucket $ minio mc mb local/backup Bucket created successfully `local/backup`. # copy $ mc cp docker-compose.yml local/backup docker-compose.yml: 322 B / 322 B ┃▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┃ 30.39 KiB/s 0s # list $ mc ls local/backup [2021-08-18 11:01:50 KST] 322B docker-compose.yml # remove $ mc rm --recursive --force local/backup/ Removing `local/backup/docker-compose.yml`. MinIO Erasure Code https://docs.min.io/docs/minio-erasure-code-quickstart-guide.html{:target="_blank"} Erasure Code 누락되거나 손상된 데이터를 재구성하는 수학적 알고리즘 Erasure code와 Checksums 사용하여 하드웨어 오류 및 자동 데이터 손상으로부터 데이터를 보호 중복 수준이 높으면 전체 드라이브의 최대 절반 (N/2)이 손실 되어도 데이터를 복구 가능 드라이브를 4, 6, 8, 10, 12, 14 또는 16 개의 erasure-coding sets 구성 (최소 4개) Run MinIO Server with Erasure Code 4 drives setup Drives를 물리적인 디스크로 구성하면 별도의 Raid 구성이 필요 없음 $ minio server /data1 /data2 /data3 /data4 docker-compose docker-compose.yml version: '3' services: minio1: image: minio/minio command: server /data1 /data2 /data3 /data4 --console-address ":9001" container_name: minio1 environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9000:9000" - "9001:9001" volumes: - ./data1:/data1 - ./data2:/data2 - ./data3:/data3 - ./data4:/data4 Distributed MinIO https://docs.min.io/docs/distributed-minio-quickstart-guide.html{:target="_blank"} MinIO in distributed mode lets you pool multiple drives (even on different machines) into a single object storage server. 서버를 분리하여 다중 Drives를 지원 Data protection High availability Consistency Guarantees Run distributed MinIO MINIO_ROOT_USER and MINIO_ROOT_PASSWORD 같은 키로 구성 Erasure Code와 동일한 Drivers 정책으로 분산 Distributed MinIO 와 서버별로 Erasure Code 같이 적용 가능 docker-compose : docker로 4대 서버 시뮬레이션 version: '3' services: minio1: image: minio/minio command: server http://minio{1...4}:9000/data --console-address ":9001" container_name: minio1 environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9101:9000" - "9001:9001" volumes: - ./minio1:/data minio2: image: minio/minio command: server http://minio{1...4}:9000/data --console-address ":9001" container_name: minio2 environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9102:9000" volumes: - ./minio2:/data minio3: image: minio/minio command: server http://minio{1...4}:9000/data --console-address ":9001" container_name: minio3 environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9103:9000" volumes: - ./minio3:/data minio4: image: minio/minio command: server http://minio{1...4}:9000/data --console-address ":9001" container_name: minio4 environment: MINIO_ROOT_USER: minio MINIO_ROOT_PASSWORD: miniopass restart: always ports: - "9104:9000" volumes: - ./minio4:/data MinIO Admin Guide mc 명령어를 통해 Admin 기능을 수행 https://docs.min.io/docs/minio-admin-complete-guide.html{:target="_blank"} service restart and stop all MinIO servers update update all MinIO servers info display MinIO server information user manage users group manage groups policy manage policies defined in the MinIO server config manage MinIO server configuration heal heal disks, buckets and objects on MinIO server profile generate profile data for debugging purposes top provide top like statistics for MinIO trace show http trace for MinIO server console show console logs for MinIO server prometheus manages prometheus config kms perform KMS management operations user - Manage users User 생성 및 삭제 ## create User $ mc admin user add myinfo cdecl cdeclpass ## remove User # mc admin user remove myinfo cdecl $ mc admin user info myinfo cdecl AccessKey: cdecl Status: enabled PolicyName: MemberOf: Policy $ mc admin policy set myinfo readonly user=cdecl Policy readonly is set on user `cdecl` $ mc admin policy set myinfo writeonly user=cdecl Policy writeonly is set on user `cdecl` $ mc admin policy set myinfo readwrite user=cdecl Policy readwrite is set on user `cdecl` heal - Heal disks, buckets and objects on MinIO server This command is only applicable for MinIO erasure coded setup (standalone and distributed). Erasure Code 상태에서 특정 디스크의 데이터가 문제가 있을 경우, 균등하게 데이터를 복구 해줌 $ mc admin heal -r myinfo - data1 2/2 objects; 403 MiB in 1s ┌────────┬───┬─────────────────────┐ │ Green │ 5 │ 100.0% ████████████ │ │ Yellow │ 0 │ 0.0% │ │ Red │ 0 │ 0.0% │ │ Grey │ 0 │ 0.0% │ └────────┴───┴─────────────────────┘

August 17, 2021 · Byung Kyu KIM

MySQL 8 Docker Basic, Json Type 지원

MySQL 8 Docker 실행 및 백업, 복원 MySQL Docker 실행 docker-compose data:/var/lib/mysql : Data 파일 conf.d:/etc/mysql/conf.d : my.cnf 등의 설정파일 root:/root : login-path 사용시 ports : “3380:3306” : mysql port “33800:33060” : mysql-shell port version: '3' services: db: image: mysql:8 container_name: mysql8 command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_ROOT_PASSWORD: passwd TZ: Asia/Seoul ports: - "3380:3306" - "33800:33060" volumes: - data:/var/lib/mysql - conf.d:/etc/mysql/conf.d - root:/root volumes: data: conf.d: root: $ docker-compose up -d Creating network "mysql_default" with the default driver Creating volume "mysql_data" with default driver Creating volume "mysql_conf.d" with default driver Creating volume "mysql_root" with default driver Pulling db (mysql:8)... 8: Pulling from library/mysql e1acddbe380c: Pull complete bed879327370: Pull complete 03285f80bafd: Pull complete ccc17412a00a: Pull complete 1f556ecc09d1: Pull complete adc5528e468d: Pull complete 1afc286d5d53: Pull complete 6c724a59adff: Pull complete 0f2345f8b0a3: Pull complete c8461a25b23b: Pull complete 3adb49279bed: Pull complete 77f22cd6c363: Pull complete Digest: sha256:d45561a65aba6edac77be36e0a53f0c1fba67b951cb728348522b671ad63f926 Status: Downloaded newer image for mysql:8 Creating mysql8 ... done 연결 테스트 docker -t 옵션 제외 : the input device is not a TTY # echo 'select host, user from mysql.user' | docker exec -i mysql8 mysql -uroot -ppasswd $ docker exec -i mysql8 mysql -uroot -ppasswd <<< 'select host, user from mysql.user' mysql: [Warning] Using a password on the command line interface can be insecure. host user % root localhost mysql.infoschema localhost mysql.session localhost mysql.sys localhost root mysql: [Warning] Using a password on the command line interface can be insecure. ...

August 16, 2021 · Byung Kyu KIM

ElasticSearch to MySQL ETL

ElasticSearch to MySQL ETL 준비 curl : Http 기반 ElasticSearch Query (SQL) jq : ElasticSearch 결과 JSON 변환 (NDJSON) mysql-shell : MySQL 데이터 Bulk Insert (Json 타입의 Table) ElasticSearch Query curl 쿼리 후, 해당 내용 JSON 저장 $ curl -s -XPOST -H 'content-type: application/json' \ -d '{"query" : "select timestamp, activesession, loadavg, processor from \"mysql-perf-*\" limit 100"}' \ 'http://elasticsearch-server:7200/_sql' > result.json $ cat result.json | jq . { "columns": [ { "name": "timestamp", "type": "datetime" }, { "name": "activesession", "type": "long" }, { "name": "loadavg", "type": "float" }, { "name": "processor", "type": "float" } ], "rows": [ [ "2021-05-02T03:40:47.000Z", 2, 0.019999999552965164, 0 ], [ "2021-06-01T00:04:24.000Z", 4, 2.0399999618530273, 14.579999923706055 ], ... NDJSON 형태로 변환 jq -c : compact instead of pretty-printed output $ cat result.json | \ jq -c ' { "col": [.columns[] | .name], "row" : .rows[] } | [.col, .row] | transpose | map({ (.[0]): .[1] }) | add ' > result_t.json $ cat result_t.json | jq . { "timestamp": "2021-05-02T03:40:47.000Z", "activesession": 2, "loadavg": 0.019999999552965164, "processor": 0 } { "timestamp": "2021-06-22T05:25:24.000Z", "activesession": 3, "loadavg": 1.809999942779541, "processor": 4.599999904632568 } { "timestamp": "2021-07-01T00:04:21.000Z", "activesession": 1, "loadavg": 0.2800000011920929, "processor": 0.41999998688697815 MySQL JSON Import mysql-shell 테이블내 doc json 필드 생성 및 JSON 데이터 Row 단위 적재 # truncate table $ mysqlsh --sql user@mysql-server:3360/dbname -p<PASSWD> \ --execute 'truncate table data_table ;' # import $ mysqlsh --mysqlx user@mysql-server:3360/dbname -p<PASSWD> \ --import result_t.json --collection=data_table ...

August 15, 2021 · Byung Kyu KIM

Makefile Simple Template

Makefile 간단한 범용 버전 Makefile 현재 디렉토리 모든 .cpp 파일 빌드 CC = g++ CC_FLAGS = -std=c++11 -pedantic -Wall -O2 LD_LIBS = EXEC = main SOURCES = $(wildcard *.cpp) OBJECTS = $(SOURCES:.cpp=.o) # Main target $(EXEC): $(OBJECTS) $(CC) $(OBJECTS) -o $(EXEC) $(LD_LIBS) %.o: %.cpp $(CC) -c $(CC_FLAGS) $< -o $@ clean: rm -f $(EXEC) $(OBJECTS)

August 13, 2021 · Byung Kyu KIM

암호화 지식 (개발자를 위한 가이드)

현대 소프트웨어 개발에서 암호화는 필수적인 보안 요소입니다. 이 글에서는 개발자가 알아야 할 핵심 암호화 개념과 실제 구현 시 고려사항을 다룹니다. 암호화 알고리즘 선택 시 고려사항 암호화 구현 시 다음 요소들을 신중히 고려해야 합니다: 대칭형 vs 비대칭형 암호화 알고리즘 종류와 보안 강도 운영 모드의 특성과 용도 패딩 방식 키 관리 전략 성능과 보안의 균형 대칭형 vs 비대칭형 암호화 대칭형 암호화 정의: 동일한 키로 암호화와 복호화를 수행 장점: 빠른 처리 속도 적은 컴퓨팅 리소스 요구 대용량 데이터 처리에 적합 단점: 키 공유의 어려움 많은 통신 상대와의 키 관리 복잡성 비대칭형 암호화 정의: 공개키와 개인키를 사용하는 방식 장점: 안전한 키 교환 디지털 서명 가능 부인 방지 기능 단점: 느린 처리 속도 높은 컴퓨팅 리소스 요구 주요 대칭형 블록 알고리즘 DES (Data Encryption Standard) 블록 크기: 64비트 키 길이: 56비트 특징: 역사적으로 중요한 알고리즘 현재는 보안 강도 부족으로 새로운 시스템에는 권장되지 않음 레거시 시스템 호환성을 위해 알아둘 필요 있음 3-DES (Triple DES) 키 길이: 2-키 3-DES: 112비트 3-키 3-DES: 168비트 특징: DES를 3회 적용하여 보안성 향상 DES 대비 약 3배 느린 처리 속도 여전히 안전하나 점차 AES로 대체 중 AES (Advanced Encryption Standard) 블록 크기: 128비트 키 길이: 128/192/256비트 특징: 현대 암호화의 표준 뛰어난 성능과 보안성 하드웨어 가속 지원으로 고성능 권장 사용 사례: 새로운 시스템 개발 시 기본 선택 클라우드 서비스의 데이터 암호화 금융 거래 보안 SEED 블록 크기: 128비트 키 길이: 128비트 특징: 한국 표준 암호화 알고리즘 국제 표준 인증 국내 공공기관 시스템에서 널리 사용 주요 비대칭형(공개키) 알고리즘 RSA (Rivest-Shamir-Adleman) 키 길이: 2048/3072/4096비트 권장 특징: 가장 널리 사용되는 비대칭 암호화 알고리즘 소인수분해의 어려움을 기반으로 한 보안성 디지털 서명과 암호화 모두 지원 장점: 구현이 상대적으로 단순 높은 보안성 폭넓은 라이브러리 지원 단점: 긴 키 길이 필요 느린 처리 속도 주요 용도: SSL/TLS 인증서 디지털 서명 키 교환 ECC (Elliptic Curve Cryptography) 키 길이: 256/384/521비트 특징: 타원곡선의 이산대수 문제를 기반 RSA 대비 짧은 키 길이로 동등한 보안성 제공 장점: 짧은 키 길이 빠른 처리 속도 낮은 리소스 요구사항 단점: 구현의 복잡성 특허 문제 (일부 알고리즘) 주요 용도: 모바일 기기의 암호화 IoT 디바이스 블록체인/암호화폐 DSA (Digital Signature Algorithm) 키 길이: 2048/3072비트 권장 특징: 디지털 서명 전용 알고리즘 NIST FIPS 186 표준 장점: 서명 생성이 RSA보다 빠름 미국 정부 표준 단점: 서명 검증이 RSA보다 느림 암호화 기능 없음 주요 용도: 전자서명 인증서 서명 ElGamal 특징: 이산대수의 어려움을 기반 DSA의 기반이 되는 알고리즘 장점: 학술적 검증이 잘된 알고리즘 확률적 암호화로 높은 보안성 단점: 암호문 크기가 평문의 2배 처리 속도가 느림 주요 용도: PGP 등의 암호화 시스템 하이브리드 암호 시스템 블록 암호화 운영 모드 ECB (Electronic Codebook) 동작 방식: 각 블록을 독립적으로 암호화 장점: 단순한 구현 병렬 처리 가능 단점: 패턴이 그대로 노출될 수 있음 데이터 무결성 보장 없음 사용 권장 사례: 매우 짧은 데이터 (단일 블록) 암호화 키 자체의 암호화 CBC (Cipher Block Chaining) 동작 방식: 이전 블록의 암호문과 현재 평문을 XOR 특징: IV(Initial Vector) 필요 순차적 처리 필요 장점: 높은 보안성 오류 전파 제한적 사용 권장 사례: 일반적인 데이터 암호화 메시지 인증이 필요한 경우 기타 운영 모드 CFB (Cipher Feedback) 스트림 암호처럼 동작 실시간 암호화에 적합 OFB (Output Feedback) 미리 키스트림 생성 가능 노이즈가 많은 채널에 적합 CTR (Counter) 병렬 처리 가능 랜덤 액세스 가능 패딩 (Padding) 방식 NO_PADDING 패딩 없음 데이터가 블록 크기의 배수일 때만 사용 가능 ZEROS_PADDING 남는 공간을 0으로 채움 구현이 단순하나 특정 상황에서 모호성 발생 가능 PKCS7_PADDING (DEFAULT_PADDING) 가장 널리 사용되는 표준 패딩 방식 패딩 바이트 값이 패딩 길이와 동일 예시: 블록 크기: 8바이트 데이터: "HELLO" 패딩 후: "HELLO\x03\x03\x03" ONE_AND_ZEROS_PADDING 첫 바이트는 0x80, 나머지는 0x00 패딩의 시작과 끝이 명확함 하이브리드 암호 시스템 실제 응용에서는 대칭형과 비대칭형 암호화를 결합하여 사용하는 경우가 많습니다. ...

August 13, 2021 · Byung Kyu KIM