해당 글은 12월 중에 작성 완료 예정입니다.

 


from datetime import timedelta

# The DAG object; we'll need this to instantiate a DAG
from airflow import DAG
# Operators; we need this to operate!
from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
# These args will get passed on to each operator
# You can override them on a per-task basis during operator initialization
default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': days_ago(2),
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
    # 'wait_for_downstream': False,
    # 'dag': dag,
    # 'sla': timedelta(hours=2),
    # 'execution_timeout': timedelta(seconds=300),
    # 'on_failure_callback': some_function,
    # 'on_success_callback': some_other_function,
    # 'on_retry_callback': another_function,
    # 'sla_miss_callback': yet_another_function,
    # 'trigger_rule': 'all_success'
}
dag = DAG(
    'tutorial',
    default_args=default_args,
    description='A simple tutorial DAG',
    schedule_interval=timedelta(days=1),
)

# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
    task_id='print_date',
    bash_command='date',
    dag=dag,
)

t2 = BashOperator(
    task_id='sleep',
    depends_on_past=False,
    bash_command='sleep 5',
    retries=3,
    dag=dag,
)
dag.doc_md = __doc__

t1.doc_md = """\
#### Task Documentation
You can document your task using the attributes `doc_md` (markdown),
`doc` (plain text), `doc_rst`, `doc_json`, `doc_yaml` which gets
rendered in the UI's Task Instance Details page.
![img](http://montcs.bloomu.edu/~bobmon/Semesters/2012-01/491/import%20soul.png)
"""
templated_command = """
{% for i in range(5) %}
    echo "{{ ds }}"
    echo "{{ macros.ds_add(ds, 7)}}"
    echo "{{ params.my_param }}"
{% endfor %}
"""

t3 = BashOperator(
    task_id='templated',
    depends_on_past=False,
    bash_command=templated_command,
    params={'my_param': 'Parameter I passed in'},
    dag=dag,
)

t1 >> [t2, t3]

 

 

'OpenSource > Apache Airflow' 카테고리의 다른 글

Apache Airflow 클러스터를 구성해보자  (0) 2020.12.09
Apache Airflow 란?  (0) 2020.12.09
Posted by CJ.Ree
,

해당 글은 12월 중에 작성 완료 예정입니다.

 

Installation Scripts

sudo yum update –y
sudo yum install gcc python3-devel -y
sudo yum install python3 -y
sudo yum install -y mysql-devel

// Airflow with Extra Packages 설치 
sudo pip3 install apache-airflow[mysql,celery,redis,crypto,aws]==1.10.12
sudo pip3 install apache-airflow-backport-providers-amazon
// Celery 설치 (Celery 서버)
sudo pip3 install celery

// AWS boto3 설치
sudo pip3 install boto3
// Web Authenticate 기능을 위한 flask-bcrypt 설치
sudo pip3 install flask-bcrypt
// Git 설치
sudo yum install git -y
// amazon-efs-utils 설치
sudo yum install -y amazon-efs-utils   

 


Airflow Directory Structure

AIRFLOW_HOME
├ airflow.config
├ dags     // dag_bags
├ plugins  // plugins
└ logs     // logs
  • AIRFLOW_HOME은 Airflow 설정파일 / DAG 정의 파일 / Airflow 플러그인을 저장하는 디렉토리이다.
  • Dag Bags : DAG 파일들이 저장되는 디렉토리 경로이다.
  • Plugins : Opertor, Sensor, Hook 등의 클래스들을 패키지를 의미한다.
  • Logs : Shceduler, DAG, Task 들의 실행 기록이 로그로 기록된다. 

 


Airflow 실행

데몬 실행 스크립트

'OpenSource > Apache Airflow' 카테고리의 다른 글

Apache Airflow 에서 DAG 를 실행시켜 보자  (0) 2020.12.09
Apache Airflow 란?  (0) 2020.12.09
Posted by CJ.Ree
,

Apache Airflow 는 Python programming 기반의 Workflow Management Tool 이다.

  • Airflow는 Python 기반으로 만들어졌기 때문에 데이터 분석가도 쉽게 코드를 작성 가능
  • Web UI 가 기본적으로 제공되어 DAG 및 Task 관리에 용이함
  • Workflow 의 각 작업별 시간이 나오기 때문에 bottleneck을 찾을 때에도 유용함

 


History

  • Airflow는 2014년 10월 Airbnb의 Maxime Beauchemin에 의해 시작
  • 첫 번째 커밋의 오픈 소스였으며 공식적으로 Airbnb GitHub에 포함되어 2015 년 6 월에 발표함
  • Airflow는 2016년 3월 Apache Software Foundation의 인큐베이터 프로그램에 가입
  • Apache 재단은 2019년 1월에 Apache Airflow를 최상위 프로젝트로 발표함

 


사용목적

  • 데이터 엔지니어링에서는 데이터들을 ETL(Extract, Transform, Load) 과정을 통해 데이터를 가공하며 적재함
    (머신러닝 분야에서도 모델 학습용 데이터 전처리, Train, Prediction시 사용 가능)
  • 위와 같은 경우 앞의 작업의 Output이 다음 작업의 input이 되는 등 순서데로 처리되야할 여러개의 작업이 존재함
  • 관리할 작업이 적다면 Crontab 처리 + 서버에 직접 접속해 디버깅 하는 방식으로 사용할 수 있지만, 관리할 작업들이 많아지면 해당 작업들을 관리할 도구가 필요해짐
  • Workflow Management Tool 은 Airflow 외에도 하둡 에코시스템에 우지(Oozie), Luigi 같은 솔루션이 있음

 


Airflow Architecture (기본 구조)

Airflow 는 기본적으로 Webserver, Scheduler, Worker, MetaDB (Database Backend) 으로 구성되며, DAG 로 Workflow 를 구성하여 실행한다.

Airflow Cluster 구조 (Local Executor)

1. Webserver
  - Web UI 제공
  - Workflow의 전반적인 조작 및 기록 관리

2. Scheduler
  - DAG 가 저장된 디렉토리(DAG Bag)를 주기적으로 스캔하여 DAG를 최신화함
  - 스케쥴에 따라서 DAG 에 정의된 Task 들을 순차적으로 실행 
  - Task 를 실행할 Worker를 지정하여 작업을 명령

3. MetaDB
  - DAG 정보, 스케쥴링 정보, 작업 실행 결과 등이 저장
  - SQLite, PostgreSQL, MySQL 등의 DB 를 지원

4. Worker
  - Airflow의 Task 가 실행되는 환경
  - Executor 설정에 의하여 Local 에서 실행되거나, 별도의 노드 또는 컨테이너에서 실행됨

5. DAGs
  - Task 간의 관계와 순서를 정의, Task 는 Operator 로 구현됨

 


Executor

Airflow는 다양한 Executor 를 지원하며, Executor 는 Task Instance 가 실제로 실행되는 메커니즘이다.
대표적인 Executor 는 아래와 같다.

  • Sequential Executor : Worker 가 한번에 하나의 Task만 수행할수 있어 제약적임
  • Local Executor : Worker 가 Scheduler 와 같은 서버에서 실행됨
  • Celery Executor : Worker 노드를 별도 구성, Message Broker 를 통하여 작업을 실행시킨
  • Kubernetes Executor : 컨테이너 환경에서 Worker 가 실행되도록 구성

 


동작 방식

Airflow 는 Scheduler 의 스케쥴링으로 Worker 에서 작업이 실행되며 동작 방식은 아래와 같다. 

  • Airflow 에서 WorkflowDAG 로 만들어지며 DAG Task 들로 구성된다.
  • TaskOperator 클래스를 인스턴스화하여 만든다.
  • 구성한 Operator 인스턴스는 다음과 같이 Task 가 된다. my_task = MyOperator(...)
  • DAG가 실행되면 Airflow 의 Scheduler 는 데이터베이스에 DAG Run 항목을 만든다.
  • DAG Run 에서 Task 를 실행하면 Task Instance 가 만들어져서 Worker 가 작업을 수행한다.

 

Posted by CJ.Ree
,

AngularJS 를 이용하여 만든 웹 사이트에 일정시간 이후 자동으로 로그아웃 시키는 기능을 오래전부터 생각 해 왔었다.


오늘 Backend (API) 어플리케이션을 부분 리팩토링 한 후 퇴근까지 시간이 남아서 해당 기능에 대해서 조사해본 결과, setTimeout() 라는 자바스크립트에서 제공하는 타이머 함수가 있는 것을 알게되었다.


https://www.w3schools.com/jsref/met_win_settimeout.asp


이 함수를 이용해서 원하는 기능을 설정 해놓고 일정 시간 뒤에 실행할 수 있는걸 확인했다.


Window Object: clearTimeout() Method

Window Object: clearInterval() Method


위 함수들을 이용하면 타이머 취소도 가능하다.


여기서 갑자기 드는생각.


AngularJS 에 제공되는 기능도 있지 않을까?

찾아 보니 역시나! 있다.


https://docs.angularjs.org/api/ng/service/$timeout


사용방법은 JS 의 타이머 함수와 유사했다.


자, 그럼 기능을 구현해 볼까!!


기본적으로 로그아웃기능을 state('access.signout', ...) 으로 만들어져 있다.


요구사항은 이러하다

  • 로그인 이후 페이지에서 타이머가 동작해야 한다.
  • $state 가 변경될 때마다 타이머를 갱신한다. 
  • 특정시간동안 아무런 액션 없을 경우 로그아웃 시킨다.


/*

 * 특정시간이 지나면 자동으로 로그아웃 시켜주는 기능 

 */

$rootScope.initAutoLogout = function() {

// 설정된 타이머가 있을 경우 타이머 취소

if ($rootScope.autoLogoutPromise) {

$timeout.cancel($rootScope.autoLogoutPromise);    

}

// 타이머 설정

$rootScope.autoLogoutPromise = $timeout (function () {

$state.go('access.signout');

return null;

}, (15 * 60 * 1000), true); // 15 min

}

  

/*

 * $state 가 변경될때마다 호출되는 부분

 */  

$rootScope.$on('$stateChangeStart', function(event, current, previous) {

// 로그인이 필요한 페이지의 경우

if (current.requiedLogin) {

// 특정시간이 지나면 자동으로 로그아웃 기능 설정

$rootScope.initAutoLogout();

  }

});



뒷단에서 제공하는 token 의 유효시간을 20분으로 설정해놨기에 Web 에서는 그보다 조금 짧은 15분으로 세팅하고, 테스트 진행해본 결과  잘 동작한다.


위 코드에서 상황에 따라 양념을 더 쳐야 하겠지만 일단 위의 코드로 자동 로그아웃되는 기능이 추가되었다.


# 참고 사이트


1. [JavaScript] 시간 지연 함수, 일정 시간 뒤 실행시키기, setTimeout() {}

- http://webisfree.com/blog/?titlequery=javascript-%EC%8B%9C%EA%B0%84-%EC%A7%80%EC%97%B0-%ED%95%A8%EC%88%98--%EC%9D%BC%EC%A0%95-%EC%8B%9C%EA%B0%84-%EB%92%A4-%EC%8B%A4%ED%96%89%EC%8B%9C%ED%82%A4%EA%B8%B0--settimeout-


2. JS에서의 타이머와 중지 시키는 법

http://thesoul214.blogspot.kr/2013/08/js.html


3. [AngujarJS] 쉽지만 쉽지않은 $timeout 서비스 - http://programmingsummaries.tistory.com/348

Posted by CJ.Ree
,

OAuth 2.0 과련 서비스를 만들어 테스트하는 도중에 ID/PWD 를 이용한 사용자 인증시 비밀번호가 틀렸을 경우 error : invalid_grant 에러가 발생하는데 이때 HTTP Status 가 400 으로 반환된다.


400 !?


내가 알기론 400 Status 는 Bad Request 인데, client 에서 잘못된 요청이 있을 경우 발생하는 경우라 클라이언트의 요청부분을 수정해야 할 경우 발생시키는 에러로 인지하고 있는데, 비밀번호가 틀렸을 경우 400 에러를 발생시키는게 좀 의아했다.


비밀번호가 틀렸으니 401(Unauthorized) 상태를 반환해야하는것이 맞지 않을까?


그래서 문제를 제기했는데, OAuth 2.0 관련 라이브러리에서 자동으로 그렇게 만들어 주는 부분이라한다. 

관련 이슈를 조사해보니 정말 invalid_grant is 400 이었다.


라이브러리 부분을 뜯어 고치기엔 일이 커지는지라 일단 그대로 400 으로 인지 하자곤 했는데...

계속 "왜??" 라는 의문이 계속 남는다.


언제 관련 부분 조사를 좀 해봐야할듯해서 기록을 남긴다.


덧. 


# Stackoverflow 에서도 나와 유사한 의문을 가진 사람이 있었군..


http://stackoverflow.com/questions/22586825/oauth-2-0-why-does-the-authorization-server-return-400-instead-of-401-when-the


# 여기 스펙에서는 invalid_grant is 401 이다.


https://www.tutorialspoint.com/oauth2.0/error_response_codes.htm



# OAuth2 flows


http://apiwiki.poken.com/authentication/oauth2


# OAuth2 Response Codes


https://www.docusign.com/p/RESTAPIGuide/Content/OAuth2/OAuth2%20Response%20Codes.htm


OAuth2 Response Codes

The OAuth2 –related endpoints return 200-OK on success. On failure, they typically return 400-Bad Request, or 401-Unauthorized.

In order to be consistent with OAuth2 documentation, the OAuth2-related endpoints support a different error response format than other DocuSign REST API calls. The body of an error response to the “oauth2/token” and “oauth2/revoke” endpoints have the format:

{

"error":"<error code>",

"error_description":"<optional description>"

}

 

Oauth2/token Endpoint error codes:

Error code values are all lower-case to match OAuth2 documentation.

Error CodeError Description
invalid_requestThe request was malformed, or contains unsupported parameters
invalid_clientThe client authentication failed.
invalid_grantThe provided authorization is invalid.
unauthorized_clientThe client application is not allowed to use this grant_type.
unsupported_grant_typeA grant_type other than “password” was used in the request.
invalid_scopeThe scope was not set to “api”.

 

OAuth2/revoke Endpoint error codes

Error code values are all lower-case to match OAuth2 documentation.

Error CodeError Description
unsupported_token_typeThe client tried to revoke an access token on a server not supporting this feature. This error is not supported in DocuSign.
invalid_tokenThe presented token is invalid.

 



Posted by CJ.Ree
,

# Before

SHOW FULL PROCESSLIST;  


# After

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE USER = 'chang-jae.lee';

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST ORDER BY TIME DESC;



참고 : http://stackoverflow.com/questions/929612/how-to-customize-show-processlist-in-mysql

Posted by CJ.Ree
,

SVN 이용하다가 커밋을 잘못하는 경우가 발생할 수 있다.


이전버전의 소스코드를 일일이 비교하여 복구하는 노가다를 하는 방법도 있지만 아래 방법이 더 편하다. 

(수정된 내용이 많을수록 더욱 더!!)


# CLI 이용시


 svn merge -rHEAD:xxxx svn+ssh://svn/myserver/trunk ./

 svn ci -m "Roll back to the revision xxxx" 


- svn merge 를 이용하여 rollback 할 버전으로 merge.

- rollback 한 소스를 commit



# Eclipce 이용시


- 해당프로젝트 우클릭 - Team - Update to Revision .. (rollback 할 버전 설정 후 OK)



- rollback 한 소스를 commit



* 만약 변경 이력을 남기면 안되는 내용(보안상의 문제라던지) 을 커밋했을 경우 SVN Dump 를 이용하여, 해당 svn repository 의 특정 revision 까지 백업 후 repository 를  다시 설정해야 한다.



Posted by CJ.Ree
,
  • Root cause analysis (http://en.wikipedia.org/wiki/Root_cause_analysis)

Root cause analysis (RCA) is a method of problem solving that tries to identify the root causes of faults or problems.[1] A root cause is a cause that once removed from the problem fault sequence, prevents the final undesirable event from recurring. A causal factor is a factor that affects an event's outcome, but is not a root cause. Though removing a causal factor can benefit an outcome, it does not prevent its recurrence for certain. RCA arose in the 1950s as a formal study following the introduction of Kepner-Tregoe Analysis, which had limitations in the highly complex arena of rocket design development and launch in the United States by the National Aeronautics and Space Administration (NASA). New methods of problem analysis developed by NASA included a high level assessment practice called MORT, and acronym for Management Oversight Risk Tree. MORT differed from RCA by assigning causes to common classes of cause shortcomings, that summarized became a short list. These included work practice, procedures, management, fatigue, time pressure, along with several others. For example, an aircraft accident could occur as a result of weather augmented by pressure to leave on time. Failure to observe weather precautions could indicate a management or training problem, while lack of any weather concern might indict work practices.


  • 근본 원인 분석 기법

차이(Variance), 결함 또는 리스크를 유발하는 근본적인 이유를 판별하는데 사용되는 분석기법.
한가지 근본 원인이 여러곳의 차이(Variance), 결함, 리스크를 초래할 수 있다.



'용어정리' 카테고리의 다른 글

프로토타이핑 (Prototyping)  (0) 2014.07.16
파일럿 (Pilot)  (0) 2014.07.16
개념검증 (PoC, Proof of Concept)  (0) 2014.07.16
Posted by CJ.Ree
,
  • 프로토타입 (http://ko.wikipedia.org/wiki/프로토타이핑)

프로토타입(prototype)은 원래의 형태 또는 전형적인 예, 기초 또는 표준이다. 시제품이 나오기 전의 제품의 원형으로 개발검증과 양산 검증을 거쳐야 시제품이 될 수 있다. 프로토타입(prototype)은 '정보시스템의 미완성 버전 또는 중요한 기능들이 포함되어 있는 시스템의 초기모델'이다. 이 프로토타입은 사용자의 모든 요구사항이 정확하게 반영할 때까지 계속해서 개선/보완 된다. 실제로 많은 애플리케이션들이 지속적인 프로토타입의 확장과 보강을 통해 최종 설계가 승인된다.


  • 추가설명

- 새로운 컴퓨터 시스템이나 소프트웨어 개발 기법의 하나

개발 초기 단계에서 핵심적인 기능을 구현한 시제품을 만들어 사용자에게 제공

사용자의 시험 사용을 통해서 요구 사항을 분석하거나 요구 사항의 정당성을 검증하고 시제품의 성능을 평가하여다음 단계 또는 실용 시스템에 반영

시제품화는 시제품, 시험 사용, 개선 과정을 반복하여 실용판의 사양을 완성해 나가는 기법

전통적인 생명 주기 모델인 폭포수 모델의 단점을 보완하여 점진적으로 시스템을 개발하는 접근 방법

시제품의 시험 사용을 통해 명확하지 않았던 사용자의 요구사항 파악 가능

 

  • 프로토타이핑의 세가지 유형

- 탐험적 프로토타이핑: 요구사항의 명확한 파악을 위함. 내부 구현은 중요하지 않음. 개발 후 폐기

- 실험적 프로토타이핑: 요구된 S/W의 기술적 구현 여부 판단을 위함. 개발 후 폐기

- 진화적 프로토타이핑: 분석도구로 이용 후, 지속적으로 발전 시켜 원하는 소프트웨어로 만들어 나감



'용어정리' 카테고리의 다른 글

근본 원인 분석 (RCA, Root cause analysis)  (0) 2014.07.25
파일럿 (Pilot)  (0) 2014.07.16
개념검증 (PoC, Proof of Concept)  (0) 2014.07.16
Posted by CJ.Ree
,

파일럿 (Pilot)

용어정리 2014. 7. 16. 20:40
  •  IT용어사전

원시 프로그램이나 시험 프로그램 등을 시험하는 일. 즉, 프로그램을 실제로 운용하기 전에 오류 또는 부족한 점을 찾기 위하여, 실제 상황과 유사한 조건에서 시험 가동하는 행위이다.


  • 컴퓨터인터넷IT용어대사전

원시 프로그램이나 테스트 프로그램, 프로젝트 또는 장치 등을 일컫는 것.


  • 위키백과 (http://ko.wikipedia.org/wiki/파일럿_테스트)

파일럿 테스트(영어: Pilot Test, 예비 실험)란 주로 컴퓨터 프로그램 등 최신 기술을 개발하여, 실제 상황에서 실현하기 전에 소규모로 시험 작동 해보는 것을 말한다.

대규모 프로젝트를 실행하거나 플랜트를 본격적으로 가동하기 전에, 발생할 수 있는 여러 가지 변인들을 미리 파악해서 수정 보완하기 위해, 모의로 시행해 보는 것을 말하기도 한다.



'용어정리' 카테고리의 다른 글

근본 원인 분석 (RCA, Root cause analysis)  (0) 2014.07.25
프로토타이핑 (Prototyping)  (0) 2014.07.16
개념검증 (PoC, Proof of Concept)  (0) 2014.07.16
Posted by CJ.Ree
,