레이블이 cli인 게시물을 표시합니다. 모든 게시물 표시
레이블이 cli인 게시물을 표시합니다. 모든 게시물 표시

argo-workflows usage

# ingress 가 없는 경우 k8s api 와 통신하는 프록시 서버 띄우기
kubectl proxy

# 프로시 서버로 접근
http://localhost:8001/api/v1/namespaces/{네임스페이스}/services/{서비스}/proxy

# argo-workflows 로그인
# 다음 명령으로 토큰값을 파악해서 입력한다.
echo -n "Bearer $(kubectl get secret argo-workflows -n argo-workflows -o=jsonpath='{.data.token}' | base64 --decode)" | pbcopy

#####

# argo cli 사용하기
# 로그인 설정
export ARGO_SERVER='argo-workflow.ysoftman.test:80'
export ARGO_HTTP1=true
export ARGO_SECURE=false
export ARGO_BASE_HREF=""
export ARGO_TOKEN="Bearer $(kubectl get secret argo-workflows -n argo-workflows -o=jsonpath='{.data.token}' | base64 --decode)"
export ARGO_NAMESPACE="argo-workflows"

# argo_workflow_hello_world.yaml 작성
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: hello-world
spec:
  entrypoint: whalesay
  templates:
    - name: whalesay
      container:
        image: docker/whalesay
        command: [cowsay]
        args: ["hello world"]
        resources:
          limits:
            memory: 32Mi
            cpu: 100m

# workflow 작업 수행(argo server 에서도 워크플로우가 생성된것을 확인할 수 있다.)
argo submit ./argo_workflow_hello_world.yaml

# workflow lis 로 workflow 이름 확인
argo list

# workflow log
argo logs hello-worldd9z5q --follow

# delete workflow
argo delete hello-worldd9z5q

mac cpu temperature

# mac cpu/gpu 온도 파악하기
sudo powermetrics | grep -i temperature

runc 사용하기

# runc 는 docker, kubernetes(k8s)등에서 사용하는 OCI(Open Container Initiative) 표준을 준수하는 container 기동(spawning and running) CLI 툴이다.

# golang 설치
wget https://go.dev/dl/go1.17.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local/ -zxf go1.17.5.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
go version

# runc 빌드 및 설치(최신 golang 버전 필요)
cd runc
make && sudo make install

# 일반유저(vagrant)도 docker 명령을 실행할 수 있게 vagrant 계정을 docker 그룹에 추가
# 한번 exit 하고 다시 로그인해야 한다.
sudo usermod -aG docker vagrant

# busybox 이미지의 파일시스템(파일들)을 tar 로 export
docker export $(docker create busybox) -o busybox_exported.tar

# root 계정으로 전환
sudo -Es

# container 에 압축 풀기
# runc 기동시 rootfs 이름의 디렉토리를 찾는다.
cd ~
mkdir -p ./ysoftman_container/rootfs
tar xvf busybox_exported.tar -C ./ysoftman_container/rootfs

# runc 에서 사용할 명세서 생성
# 기본 명세의 config.json 파일이 생성된다.
# spec -> create a new specification file
cd ysoftman_container
tree -L 2
runc spec
ls config.json

# runc 로 ysoftman1 이름의 컨테이너 기동
runc run ysoftman1

# ysoftman1 컨테이너에서 namespace 확인
ls -ahl /proc/$$/ns

# 호스트 터미널 하나더 열고 root 계정으로 전환
sudo -Es

# 호스트에서 runc 같와 runc 가 실행한 sh 프로세스가 확인
ps -ef | grep -E "runc| sh$"

# 호스트에서 
# runc 네임스페이스 확인
lsns -p $(ps -ef | grep -v grep | grep "runc run ysoftman1" | awk '{print $2}')

# ysoftman1컨테이너(runc)가 실행한 sh pid 로 namespace 상태 확인
lsns -p $(ps --ppid=$(ps -ef | grep -v grep | grep "runc run ysoftman1" | awk '{print $2}') -o pid | grep -v PID)

# 호스트에서 runc 로 기동된 컨테이너 리스트 보기
runc list

# 테스트 결과

# runc help
checkpoint  checkpoint a running container
create      create a container
delete      delete any resources held by the container often used with detached container
events      display container events such as OOM notifications, cpu, memory, and IO usage statistics
exec        execute new process inside the container
kill        kill sends the specified signal (default: SIGTERM) to the container's init process
list        lists containers started by runc with the given root
pause       pause suspends all processes inside the container
ps          ps displays the processes running inside a container
restore     restore a container from a previous checkpoint
resume      resumes all processes that have been previously paused
run         create and run a container
spec        create a new specification file
start       executes the user defined process in a created container
state       output the state of a container
update      update container resource constraints
features    show the enabled features

#####

# 위 golang, runc, busybox 준비되어 있는 상태에서
# rootless container 생성해 보기
# root 계정이라면 일반 계정으로 나오기
exit

# ysoftman_rootless_container 에 압축풀기
cd ~
mkdir -p ./ysoftman_rootless_container/rootfs
tar xvf busybox_exported.tar -C ./ysoftman_rootless_container/rootfs

# rootless 옵션으로 runc 에서 사용할 명세서 생성
cd ysoftman_rootless_container
runc spec --rootless

# /tmp/runc 를 루트로 하는 ysoftman_rootless_container 실행
runc --root /tmp/runc run ysoftman_rootless_container

# 컨터이너에서 user id 와 네임스페이스 확인
id
ls -l /proc/$$/ns

# 호스트에서
# 루트 경로 및 state.json 확인해보기
tree /tmp/runc
cat /tmp/runc/ysoftman_rootless_container/state.json | jq . | head -10

# 호스트에서 runc 같와 runc 가 실행한 sh 프로세스가 확인
ps -ef | grep -E "runc| sh$"

# runc 네임스페이스 확인
lsns -p $(ps -ef | grep -v grep | grep "runc run ysoftman_rootless_container" | awk '{print $2}')

# ysoftman1컨테이너(runc)가 실행한 sh pid 로 namespace 상태 확인
lsns -p $(ps --ppid=$(ps -ef | grep -v grep | grep "runc run ysoftman_rootless_container" | awk '{print $2}') -o pid | grep -v PID)

# user 네이스페이스 id 가 ysoftman_rootless_container 가 호스트와 다르다.
# ysoftman_rootless_container 의 root 로 보이지만 호스트의 root는 아니다.

# 테스트 결과

vscode 커맨드라인에서 실행하기

# vscode 를 mac 터미널 커맨드라인에서 실행하기
# vscode 1.0 이전까지는 
# 쉘 리소스에 (.bashrc, .zshrc ...) 에 다음 코드를 추가해야 한다.
code () {
    VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*
}

# vscode 1.0 부터는
# 명령 팔렛트(command + shift + p) -> install -> "쉘 명령: PATH 에 'code' 명령 설치" 를 수행

# 참고로 vscode 1.0 이후 부터는 위 코드를 사용하고 있다면 중복된다고 경고가 나오니 삭제하자.

# wsl 을 사용하는 경우 경로 추가가 필요하다.
# export PATH=$PATH:"mnt/c/Program/Files/Microsoft/VS/Code/bin/"
# 최신 버전은 경로가 다음과 같이 바뀌었다.
username=$(wslvar userprofile | tr '\\' ' ' | awk '{print $NF}')
export PATH=$PATH:"/mnt/c/Users/${username}/AppData/Local/Programs/Microsoft VS Code/bin"

# 이제 쉘에서 다음과 같이 바로 vscode 로 파일을 열어 실행할 수 있다.
code file.txt

MongoDB 구성 및 쿼리

# ysoftman
# C++ 로 개발된 확장가능하고, 고성능의 document-oriented DB
# MongoDB 자체는 오픈소스(GNU AGPL)이며 사업적 지원은 10gen이라는 회사를 통해 받을 수 있음
# MongoDB Driver 는 Apache 2.0
# RDBMS 의 대부분 index 지원
# 새로운 서버를 쉽게 추가하며, 자동 복구 기능
# Hadoop 의 MapReduce 같은 분산 병렬 처리 가능
# Windows, Linux, OS-X, Solaris 지원
# C, C++, Java, C#, Perl, Python, Ruby 지원
# 사용방법 : CLI(Command Line Interface) 쉘을 이용하거나 프로그램에서 API 를 이용하는 방법 제공
# 데이터모델
# 문서(Document) : 문서는 여러개의 필드,필드값 쌍을 가진 단위로 저장,삭제,수정 할 수 있음
# JSON 을 바이너리로 인코딩한 BSON 포맷으로 데이터 크기는 4MiB 로 제한
# 컬렉션(Collection) : RDB 의 테이블과 유사 개념으로, 네임스페이스로만 의미가 있음
# 데이터베이스(Database) : 컬레션을 관리하는 단위

# MongoDB 구성 하기
# 구성도 http://www.mongodb.org/display/DOCSKR/Introduction
# client(application) 은 router Server 에 접속해서 쿼리를 요청하면 된다.
# client 가 write 요청을 했다면 router 는 master mongodb 로, read 했다면 slave mongodb 로 안내한다.
# mongodb 서버에 1000을 더한 포트로 접속하면 MongoDB 모니터링 웹을 볼 수 있다.(http://127.0.0.1:56555)

# mkdir ysoftman_db_master
# mkdir ysoftman_db_slave
# mkdir ysoftman_db_config

# .lock 파일 삭제
rm -rfv ./ysoftman_db_master/*.lock
rm -rfv ./ysoftman_db_slave/*.lock
rm -rfv ./ysoftman_db_config/*.lock

# master mongoDB Server 시작하기
bin/mongod --master --dbpath ./ysoftman_db_master --port 10010 > /dev/null &

# slave mongoDB Server 시작하기(master 와 다른 장비에서)
#bin/mongod --slave --dbpath ./ysoftman_db_slave --port 10020 --source 10.10.10.100:10010 --autoresync > /dev/null &

# config mongoDB Server 시작하기
bin/mongod --dbpath ./ysoftman_db_config --port 10001 > /dev/null &

# router Server 시작하기
bin/mongos --port 10000 --configdb 10.10.10.100:10001 > /dev/null &

# router Server 접속해서 Sharding 하기
bin/mongo 10.10.10.100:10000

# 참고로 mac 에서 mongo cli 설치 후
brew tap mongodb/brew
brew install mongodb-community-shell

# 원격 접속하기
mongo "mongomongodb://root:ysoftman@10.10.10.10.200:9300/admin?connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-1"

# SQL to mongo mapping chart
# http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

# MySQL term   Mongo term
# database database
# table collection
# index index
# row BSON document
# 하나의 document 최대 크기 16MB

# admin db 를 사용해서 설정해야 한다.
use admin;

# shard 추가하기, router 랑 같은 머신의 shard 를 사용할 수 있도록 옵션 명시
# 실제 사용시에는 router 랑 다른 머신의 shard 를 사용해야 한다.
db.runCommand({addshard:"10.10.10.100:10010", allowLocal:true});

# database 단위에서 sharding enable 하기
db.runCommand({enablesharding:"testdb"});

# col1 collection 의 _id 별로 자동 분산되어 저장하도록 하기
db.runCommand({shardcollection:"testdb.col1", key:{"_id":1}});

# sharding 상태확인
db.printShardingStatus();

# shard 삭제하기
db.runCommand({removeshard:"10.10.10.100:10010"});

# testdb 사용하기(DB 를 미리 생성하지 않는다.)
use testdb

# routerinfo 콜렉션 생성
db.createCollection("routerinfo");

# 예) JSON 형식으로 정보 추가
db.routerinfo.save(
{"id": "1234",
"name": "ysoftman",
"timestamp": 12345,
"userkey": "UserNo",
"metainfo": {"list":[
{"name":"UserNo", "desc":"사용자", "type":"int"},
{"name":"Item", "desc":"아이템", "list":[
{"name":"a", "desc":"아이템1"},
{"name":"b", "desc":"아이템2"}
]
},
{"name":"phone", "desc":"전화번호", "type":"int"},
{"name":"name", "desc":"이름"},
{"name":"trash", "desc":"쓰레기"},
{"name":"Map", "desc":"맵", "pk":"MapID", "array":[
{"name":"MapID", "desc":"맵번호", "type":"int"},
{"name":"MinScore", "desc":"최소점수", "type":"int"},
{"name":"MaxScore", "desc":"최대점수", "type":"int"}
]
}
]
}
}
);


#####


# mongo cli 예시
# 도움말
help()

# Database 목록보기
show dbs

# testdb 사용하기(DB 를 미리 생성하지 않는다.)
use testdb

# 현재 사용중인 DB 확인
db.getName()

# 현재 Databse 컬렉션 보기
show collections

# 크기 제한 설정하여 컬레션 생성 size: 크기, max: 최대 개수
#db.createCollection("col1", {capped:true, size:100000, max: 1000});
db.createCollection("col1");

# 컬렉션 이름이 숫자로 시작하거너 - 이 있으면
db["1234"] 또는 db.getCollection("aaa-bbbb")
# 위 해당 사항이 아니라면 다음과같 간단히도 사용할 수 있다. 
db.col1

# 컬렉션 상태 보기
db.col1.validate()

# col1 켈렉션 자체 삭제하기
db.col1.drop()

# col1 컬렉션 모든 document 삭제
db.col1.remove({})

# col1 컬렉션에스 쿼리에 해당하는 document 만 삭제
db.col1.remove({_id:"123"})

# col1 라는 컬렉션에 Name, URL, LastUpdate 등의 데이터를 저장하기(insert() or save())
db.col1.save({UserNo:0, Map:[{MapID:1, Score:100}, {MapID:2, Score:200}]});

# col1 의 다큐먼트 개수 파악하기
db.col1.count()

# col1 의 모든 다큐먼트 검색하기
db.col1.find()

# col1 의 모든 다큐먼트 검색하기(들여쓰기하여 출력)
db.col1.find().pretty()

# UserNo 가 555 인 다큐먼트 찾기
db.col1.find({UserNo:555})

# UserNo 가 555 인 다큐먼트를 찾아서 Map.MapID 필드만 보여주기
db.col1.find({"UserNo":555}, {"Map.MapID":1});

# UserNo 가 555 인 다큐먼트를 찾아서 _id 는 제외하고 Map.MapID 필드만 보여주기
db.col1.find({"UserNo":555}, {_id:0, "Map.MapID":1});

# col1 의 모든 다큐먼트 검색하기(_id 로 오름차순 정렬로 보여주기 -1이면 내림차순)
db.col1.find().sort({_id:1})

# Map.MapID 의 값이 10 인 다큐먼트 개수
db.col1.find({"Map.MapID":10}).count()

# Map.MapID 의 값이 100 보다 큰거나 같은 다큐먼트 개수
db.col1.find({"Map.MapID":{$gte:100}}).count()

# UserNo 가 555 이고 Map 배열의 첫번째 MapID 값을 1234 로 변경하기(조건에 해당하는 내용이 없으면 다큐먼트 하나가 추가된다)
db.col1.update({"UserNo":555}, {$set:{"Map.0.MapID":1234}}, true);

# UserNo 가 555 이고 Map 배열의 100번째 MapID 값을 삭제하기
db.col1.update({"UserNo":555}, {$unset:{"Map.100.MapID":1}});

# UserNo 가 555 이고 Map 배열중 MapID 가 2인 곳을 찾아내어 123 값으로 설정한다.
db.col1.update({UserNo:555, "Map.MapID":2}, {$set:{"Map.$.MapID":123}})

# UserNo 가 555 이고 Map 배열에 object 추가(array 필드에 대해서만 사용할 수 있다)
db.col1.update({UserNo:555}, {$push:{Map:{"MapID":333, "MinScore":300, "MaxScore":500}}})

# 현재 컬렉션의 데이터 하나 삭제하기(검색 결과 id로 지운다)
db.col1.remove({_id:ObjectId("4d5a1ad2e812000000000515")})

# 현재 컬렉션의 모든 document 삭제
db.col1.remove({})

# 인덱스 생성(1:ascending, -1:descending)
db.col1.ensureIndex({"UserNo":1});

# 현재 인덱스 확인(db.system.indexes.find() 전체 인덱스 확인)
db.col1.getIndexes()

# 인덱스 삭제
db.col1.dropIndexes()

# db 상태 확인(data, index 사이즈 등...)
db.stats();

# 서버 상태 확인
db.serverStatus()
db.serverStatus().mem
db.serverStatus().extra_info

# 클라이언트 종료
exit