1.0.0 • Published 1 year ago

buildblock v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

BuildBlock

Development

Poetry

Installation

osx / linux / bashonwindows install instructions

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

windows powershell install instructions

(Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -

설치는 Poetry's의 bin 디렉터리에 됩니다. Unix같은 경우에는 $HOME/.poetry/bin에 위치하며 Windows는 %USERPROFILE%\.poetry\bin 위치합니다. 이 디렉터리는 자동적으로 환경변수로 등록이 될 것입니다. 만약 직접 환경변수로 등록을 하고싶으시면 --no-modify-path 옵션을 추가해주세요.

설치가 완료되었으면 shell에 poetry --version을 입력하여 확인

Basic Usage

# pyproject.toml file내의 기재되어있는 모든 library를 설치합니다.
$ poetry install
# python 가상 환경을 실행합니다.
$ poetry shell
# 설치/추가 하고싶으신 library를 추가합니다.
$ poetry add [패키지명]
$ poetry add [package_name] --dev  # Dev dependency에서만 사용할 패키지 추가

간단하게 빠른 테스트를 위한 명령어 3개만 공유드리겠습니다.

더 자세하고 다양한 사용법은 https://python-poetry.org/docs/basic-usage/ 참고하시면 될 것 같습니다.

Docker를 이용한 로컬 개발방법

TL;DR

$ docker-compose up     # docker-compose 서비스 시작 (use `--build` flag for local image rebuild)
$ docker-compose down   # docker-compose 서비스 종료

http://localhost:8000

AWS ECR 로그인

  1. AWS cli를 이용해 AWS 접속 credential을 설정 (MFA 및 기타 설정은 해당문서 참조)
  2. 터미널에서 다음을 입력
$ aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 943771268559.dkr.ecr.ap-northeast-2.amazonaws.com
Login Succeeded

로컬 Docker compose 사용

$ docker-compose up     # (만약 작업중인 이미지를 다시 빌드하려면 `--build` 필요)

docker-compose 전체가 아닌 buildblock 컨테이너만 빌드, 혹은 실행할 경우

$ docker build --target develop . -t buildblock-web:latest      # develop 컨테이너
$ docker build --target prod . -t buildblock-web:latest         # prod 컨테이너 (No debug toolings)

빌드한 컨테이너 실행 (자체 DB설정 필요)

$ docker run -v ${PWD}/.env:/app/.env -p 8080:80 -e NGINX_PORT=80 -e DJANGO_SETTINGS_MODULE="config.settings.local" buildblock-web:latest

BASE 이미지 정보

동작중인 Docker Container 에 들어가서 디버그 하는 방법

# 현재 docker-compose 로 동작중인 컨테이너들
$ docker-compose ps
CONTAINER ID   IMAGE                       COMMAND                  CREATED          STATUS          PORTS                                       NAMES
e8e2eaf1663a   stripe/stripe-cli:v1.7.0    "/bin/stripe listen …"   54 minutes ago   Up 54 minutes                                               buildblock_stripe-cli_1
4f94b0ab1591   buildblock_buildblock-web   "/init ./entrypoint-…"   54 minutes ago   Up 54 minutes   0.0.0.0:8080->80/tcp, :::8080->80/tcp       buildblock_buildblock-web_1
08e00a0f5592   postgres:11.12-alpine       "docker-entrypoint.s…"   2 hours ago      Up 54 minutes   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp   buildblock_buildblock-db_1

# web 컨테이너에 접속 (`CONTAINER ID` 혹은 `NAME`으로 접속 가능)
$ docker exec -it 4f94b0ab1591 bash     # `4f94b0ab1591` 외에 `buildblock_buildblock-web_1` 이름으로도 가능
root@4f94b0ab1591:/app#

Test coverage

coverage run -m pytest
coverage html
open htmlcov/index.html

Operational Actions

Access Containers - Run interactive shell

Requirements:

  • AWS CLI v1 은 1.19.99 부터 사용가능, AWS CLI v2 는 2.1.31 부터 사용 가능
  • Session Manager plugin 설치
  1. List ECS task(s)

    1. Command: CLUSTER_NAME의 경우
      1. dev: buildblock-cluster-dev
      2. prod: buildblock-cluster-prod
    aws ecs list-tasks \
      --cluster (CLUSTER_NAME) \
      --region ap-northeast-2
    1. Sample Output: 여기서 TASK_ID 값을 확인한다.
    {
      "taskArns": [
        "arn:aws:ecs:ap-northeast-2:943771268559:task/buildblock-cluster-dev/(TASK_ID)"
     ]
    }
  2. Access container: CLUSTER_NAME과 위에서 확인된 TASK_ID 기입하여 실행

    1. Command:
    aws ecs execute-command  \
      --region ap-northeast-2 \
      --cluster (CLUSTER_NAME) \
      --task (TASK_ID) \
      --command bash \
      --interactive
    1. Sample Output: 제대로 실행되면 아래와 같은 output이 나온다.
    The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.
    
    Starting session with SessionId: ecs-execute-command-0b7a452e26025cf0e
    root@ip-172-31-4-135:/app#

Testing DB migration and background tasks in Pull Request deployments

DB migration과background tasks들은 develop과 main브랜치에서 생성된 배포에서만 실행되도록 설정되어 있습니다. 만약 PR 배포에서 해당 작업을 테스트 하기 위해서는 위의 방법대로 Interactive Shell에 접속한뒤 다음의 커맨드를 입력 해 주면 됩니다.

  1. DB migration
python /app/manage.py lintmigrations --unapplied-migrations
python /app/manage.py migrate --noinput
python /app/manage.py populate_history --auto
  1. Background Task
python /app/manage.py process_tasks
@next/eslint-plugin-nextacornacorn-import-assertionsacorn-jsxajvajv-keywordsansi-regexansi-stylesargparsearray-includesarray-unionarray.prototype.flatmapbalanced-matchbrace-expansionbracesbrowserslistbuffer-fromcall-bindcallsitescaniuse-litechalkchrome-trace-eventclone-deepcolor-convertcolor-namecolorettecommanderconcat-mapcross-spawndebugdeep-isdefine-propertiesdir-globdoctrineelectron-to-chromiumenhanced-resolveenvinfoes-abstractes-module-lexeres-shim-unscopableses-to-primitiveescaladeescape-string-regexpeslinteslint-config-googleeslint-config-nexteslint-plugin-reacteslint-scopeeslint-utilseslint-visitor-keysespreeesqueryesrecurseestraverseesutilseventsexecafast-deep-equalfast-globfast-json-stable-stringifyfast-levenshteinfastest-levenshteinfastqfile-entry-cachefill-rangefind-upflat-cacheflattedfs.realpathfunction-bindfunction.prototype.namefunctional-red-black-treefunctions-have-namesget-intrinsicget-streamget-symbol-descriptionglobglob-parentglob-to-regexpglobalsglobbygraceful-fsgrapheme-splitterhashas-bigintshas-flaghas-property-descriptorshas-symbolshas-tostringtaghuman-signalsignoreimport-freshimport-localimurmurhashinflightinheritsinternal-slotinterpretis-bigintis-boolean-objectis-callableis-core-moduleis-date-objectis-extglobis-globis-negative-zerois-numberis-number-objectis-plain-objectis-regexis-shared-array-bufferis-streamis-stringis-symbolis-weakrefisexeisobjectjest-workerjs-tokensjs-yamljson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjsx-ast-utilskind-oflevnloader-runnerlocate-pathlodash.mergeloose-envifymerge-streammerge2micromatchmime-dbmime-typesmimic-fnminimatchmsnatural-compareneo-asyncnextnode-releasesnpm-run-pathobject-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.hasownobject.valuesonceonetimeoptionatorp-limitp-locatep-tryparent-modulepath-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpkg-dirprelude-lsprop-typespunycodequeue-microtaskrandombytesreact-isrechoirregexp.prototype.flagsregexppresolveresolve-cwdresolve-fromreusifyrimrafrun-parallelsafe-bufferschema-utilssemverserialize-javascriptshallow-cloneshebang-commandshebang-regexside-channelsignal-exitslashsource-mapsource-map-supportstring.prototype.matchallstring.prototype.trimendstring.prototype.trimstartstrip-ansistrip-final-newlinestrip-json-commentssupports-colorsupports-preserve-symlinks-flagtapableterserterser-webpack-plugintext-tabletippy.jsto-regex-rangetype-checktype-festunbox-primitiveupdate-browserslist-dburi-jsv8-compile-cachewatchpackwebpackwebpack-cliwebpack-mergewebpack-sourceswhichwhich-boxed-primitivewildcardword-wrapwrappyyocto-queue
1.0.0

1 year ago