Post on 06-Aug-2015
Python 초심자의 Openstack
by Cha Dong-Hwi
개요
a. 스터디 시작 계기 - 더 많은 사람들과 만나 보고 싶어서
b. 상반기 스터디 진행- 제한된 시간, 다양한 주제, black box 방식
c. 차기 스터디- 소스 스터디로 전환 해서 근본적인 이해 확장- 커뮤니티에서 공개적으로 contribution 활동 기대
목차
자료: 스터디 때 분석 한 것 + 하반기 진행 예정
I. Python 기초II. Openstack 소스 구조
I. Openstack 이해를 위한 Python 기초 (compared with java, javascript )
● Python 컴파일
a. Java, .Net과 유사 - Human Code ->Byte Code -> Run by Machine
b. Python Implementations (Bytecode Compilers)
- Cpython, Jython (based on jvm), PyPy (custom JIT), etc
c. Compiled or Interpreted ? - 관점의 차이(ruby, php ..)- Dynamic language- vs LLVM (Infra) or .Net Roslyn (As a service)
>>> def foo(a):... if a !=0:... a = a % 3... else:... a = None... return a... >>> foo(5)2>>> foo("hello %s")'hello 3'
>>> import dis>>> dis.dis(foo) 2 0 LOAD_FAST 0 (a) 3 LOAD_CONST 1 (0) 6 COMPARE_OP 3 (!=) 9 POP_JUMP_IF_FALSE 25
3 12 LOAD_FAST 0 (a) 15 LOAD_CONST 2 (3) 18 BINARY_MODULO 19 STORE_FAST 0 (a) 22 JUMP_FORWARD 6 (to 31)
5 >> 25 LOAD_CONST 0 (None) 28 STORE_FAST 0 (a)
6 >> 31 LOAD_FAST 0 (a) 34 RETURN_VALUE
● Python 메모리 관리
a. 개별 Implementations 별로 모두 다름 - 각각의 virtual machine 타입 별 구현 방식의 차이
b. CPython 원리 및 메모리 관리- bytecode를 이용해서 ceval.c 에서 loop를 돌면서 작동- “Memory management in Python involves a private heap
containing all Python objects and data structures. link”- PyMalloc: 자체 메모리 관리 lib 이용 (heap)- Reference counting을 관리 후 Garbage collection
● 파이선 함수 ( comapred with java, javascript )
a. 접근자 없음 - "__" 를 이용 ( subclass 에서도 접근 불가 )
b. Return type 없음- 여느 dynamic language와 유사
c. Inner Function - 자바스크립트와 유사
d. Multiple return value (java 튜플 개념과 유사)- 함수에서 "여러 value 리턴" 기능을 내장
class SayHi(object): def hello(self): self.__hello() def __hello(self): a = "hello" def world(): b = "world" return a, b c,d = world() print "really", c,d
if __name__ == '__main__': s = SayHi() s.hello() s.__hello()
python test.py>> really hello worldTraceback (most recent call last): File "test.py", line 15, in <module> s.__hello()AttributeError: 'SayHi' object has no attribute '__hello'
● 메소드 Type
a. Static method- 자바의 static 과 유사
b. Class method- static + Instance
c. Instance method- 자바의 member function 과 유사
class What(object): v_static = 1 def __init__(self): print "Instantiation" self.v_inst = 1 @classmethod def add_with_class(cls): print "created inst in Classmethod" cls().add_with_instance() @staticmethod def add_with_static(): What.v_static = What.v_static + 1 print "from staic" , What.v_static def add_with_instance(self): self.v_inst = self.v_inst + 1 print "from inst" , self.v_inst
>> print "called from static way" , What.v_staticcalled from static way 1
>> What.add_with_static()from staic 2
>>What.add_with_class()created Instance in Class methodInstantiation of What Classfrom inst 2
>>What().add_with_instance()Instantiation of What Classfrom inst 2
● 인스턴스 및 상속
a. 상속 방법 (자바와 유사)- 클래스 명 끝에 ()안에 부모 클래스 명기
b. Interface, Abstract class- 없음. 수동으로 구현 또는 라이브러리를 이용
c. 생성자 - __init__
d. __call__ 메소드 - __init__ 이후 생성자 실행 시 호출됨
● Decorator and Closure
a. Java의 Annotation과는 다른 개념- Java Metadata의 개념과는 다르게 Wrapper function - AOP 구현에 사용 할 수 있으나 다른 방식으로 접근 필요
b. Closure- Javascript 와 유사하게 사용 가능- 익명 함수는 없음. 제한적으로 lamda 연산자 활용 가능
class MyDeco(object): def __init__(self, f): print "instantiation start" self.__test=0 self.__f = f print "instantiation ends" def __call__(self): print "inside of __call__" self.__test += 1 print self.__test self.__f()@MyDecodef myfunc(): print "inside of myfunc"
>> myfunc()instantiation startinstantiation endsinside of __call__1inside of myfunc
def bam(func): def wrap(cc):
cc = cc + 11 func(cc) return wrap
def foo(aa): @bam def bar(bb):
print "bb >> ", bb print aa+bb return bar
>> foo(22)(33)bb >> 4466
II. Web Server(of nova)
● Eventleta. Green thread 란?
- VM 기반의 Thread 모사 (java library 이름에서 유래)- kernel thread 와 별개의 software based- 연관 키워드:Coroutine, Async, NIO, Non-Preemptive
b. Eventlet- CPython 기반 green thread library- GIL의 속도 문제에 대한 대안 (CPython의 Threadsafe 문제)
c. Monkey Patch - 라이브러리가 아닌, patch 형태로 작동 방식의 교체
import timeitsetup = '''from random import randomimport threadingdef ox(i): print 'starts >> ', i print max([random() for x in xrange(20000000)])def go(): r1 = threading.Thread(target=ox, args=(1,)) r1.start() r2 = threading.Thread(target=ox, args=(2,)) r2.start() ox(3)'''
print min(timeit.Timer('go()', setup=setup).repeat(1, 1))#print min(timeit.Timer('ox(1);ox(2);ox(3)', setup=setup).repeat(1, 1))
starts >> 1 starts >> 2 starts >> 30.9999999775020.9999999955620.9999999836068.01049184799starts >> 10.999999988552starts >> 20.999999931983starts >> 30.9999999952184.16765999794
Nova 의 eventlet 관련 Code
● WSGI Service with Paste
a. WSGI- python base CGI (PEP 0333)- Dynamic web app
b. Paste - Middleware로 사용 (an intermediary software)- App 기능 보다는 인증 및 필터링 용도로 사용
WSGI with Paste in Nova- Text 기반으로 Class Loading
● Server Controllers with Routes
a. 컨트롤러 구현 - Class Loading 및 runtime Operation 정의
b. Routes- Package Loading 및 URL 및 server Controller - Rails routes system의 python Implementation(출처)- resource : controller class
Routes of Nova
Controllers of Nova
● SQLAlchemy
a. SQLAlchemy- Python의 대표적인 ORM (object-relational mapper)- Data mapper pattern(Mybatis, Hibernate)- Martin Fowler's book 'Patterns of Enterprise
Application Architecture'- Oslo.db 에서 Wrapping 해서 사용
b. Database Connection Pool 관련 - 관련 링크 - 없음(?) (Server side의 Eventlet NIO로 의존 )- 구현 되긴 했으나 삭제됨
DB API : Database Service of Nova
III. Message Queue API(of nova)
● Message Broker
a. AMQP RPC- Decoupling Client and Servant, Async- Random Balancing
b. Pub / Sub & Broker- Broker를 통한 Reliability for Message Delivery 확보- Direct, Fanout, Topic
c. RPC Calls- RPC Cast와는 다르게 worker의 response를 기다림
Message Queue API of Nova
RPC API Module
oslo.messaging.rpc.client
PayloadAPI to Conductor
Conductor to API
Conductor to Compute
● MQ API Manager Class
a. Loading- Process Service Loading 시 같이 시작
b. Periodic_tasks- Message 처리
V. Study @ Openstack Korea
● 스터디 로드맵
a. 현재 2차 스터디 진행 중- 개발자 및 Engineer Team 으로 구성 - 온라인 인프라를 이용한 스터디 - 스터디의 절차와 방법에 대한 고민 - 장현정 회장님 지원- 최영락님, 강성진님 과 같이 진행
b. 다음 스터디- 9월 예정 (예정)
● 컨트리뷰터 모집 소개
a. 컨트리뷰션 팀 구성 목적 - 경험 공유를 위함 - 저변 확대 및 핵심 기술에 대한 인식 전환 - 간접 소통 중심에서 직접 참여로
b. What’s not- Nationalism- Enlightenment
● 컨트리뷰터 채널
a. Slack 도메인 접속 - 웹브라우저로 아래 주소 접속 - https://openstackkr-slackin.herokuapp.
com/- 누구나 등록 없이 참여 가능 - 모바일 앱 가능 (iphone, android)- 크롬 앱 사용 가능(slacky)
Endby Cha Dong-Hwi
dhcha0617@sptek.co.kr(or tzniuta@gmail.com )