couchdb - introduction - korean

62
Ultra Durability NoSQL, CouchDB

Upload: -jerry-jeong

Post on 25-Jun-2015

1.152 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: CouchDB - Introduction - Korean

Ultra Durability NoSQL, CouchDB

Page 2: CouchDB - Introduction - Korean

발표자 및 소속 회사

2

• 발표자 , 정명훈• 소속 : Cloudant Korea 에서 CouchDB 기반 DBaaS(PaaS) 컨설팅

• 경력 : Java 개발 , 미들웨어 (Application Server), 가상화 , 데이터베이스 및 CDC

• 관심 : 오픈소스와 클라우드

• 소속 회사 , Cloudant

• CouchDB 기반으로 클라우드 서비스로 제공 (Database As A Service)

• 유럽 입자물리 연구소 (CERN) 의 Higgs 입자 연구에 참여했던 MIT 과학자 세 명이 창립 (2008 년 설립 )

• 약 30,000 개 이상의 회사 / 사용자에게 서비스 제공

Page 3: CouchDB - Introduction - Korean

CouchDB 의 역사

3

• 2005 년 Damien Katz(IBM, Lotus 개발자 ) 에 의해 시작Internet 에 적합한 Database 목표 Cluster Of Unreliable Commodity Hardware 의 약자

• 2006 년 Erlang, JSON, JavaScript 기반으로 전환

• 2008 년 Apache Incubator 프로젝트

• 2010 년 첫 stable version 출시

• 2013 년 Cloudant 에 의해 BigCouch(Clustering) 프로젝트와 통합

• BigCouch 통합 버전 출시 예정… CouchDB 2.0

Damien Katz

Page 4: CouchDB - Introduction - Korean

CouchDB 의 특징

4

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control (MVCC)

• Eventual Consistency between Distributed Nodes

• Erlang OTP

Page 5: CouchDB - Introduction - Korean

CAP 이론 – CouchDB, A-P 특성 만족

5

Page 6: CouchDB - Introduction - Korean

CAP 이론 – CouchDB, A-P 특성 만족

6

No Lock “Optimistic Lock”

Multi Version Concurrency Control Append-Only DB

Eventual Consistency

Page 7: CouchDB - Introduction - Korean

CouchDB 기본 상식

7

• B-Tree 에 데이터와 Index 저장

• CouchDB 의 용어• Database RDB 의 Table

• Document RDB Table 의 Record/Row

• CouchDB 는 Stand-alone, BigCouch/Cloudant 는 Clustering

• Lock 이 없고 복수 Client 의 동시 액세스 허용 (Optimistic Lock)

• 하나의 Document 를 복수의 Version 으로 관리

Page 8: CouchDB - Introduction - Korean

CouchDB 의 특징

8

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 9: CouchDB - Introduction - Korean

CouchDB 의 특징

9

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

JSON based Ultra Durable Data Store

Page 10: CouchDB - Introduction - Korean

JSON Document Store

10

• JSON = JavaScript Objection Notation format

• Boolean, Number, String, Array, Dictionary 등 다양한 데이터 타입• 특별한 스키마 제약이 없고 다중 문서 등과 같은 자유로운 형식 (Schemaless)

• 비정형 데이터 : 텍스트 + 바이너리 혼합 데이터 , 프로파일 데이터 등 • ID 는 특별히 지정하지 않으면 자동으로 Unique 하게 생성

저장

문서 별 , 고유 ID 와 Version 번호 자동 생성 됨

날짜 Type

배열

긴 문자열

Page 11: CouchDB - Introduction - Korean

바이너리 데이터 (attachment) 저장

11

• 바이너리 데이터 ( 파일 , 사진 등 ) 를 Attachment 로 저장• BASE64 형식으로 주고 받고 실제로는 바이너리 형식 저장

저장

Page 12: CouchDB - Introduction - Korean

ACID Compliant Data Store

12

• ACID(Atomic Consistent Isolated Durable) 특성 준수

• “Crash-Only” 디자인 : Commit 된 데이터를 절대로 덮어 쓰지 않고 Consistent 한 데이터 보장 특별한 Shutdown 과정 불필요 Ultra Durable

• DB Read 작업에서 전혀 Lock 을 잡지 않고 , 다른 Client 의 Read/Write 작업 ( 동일 문서라도 ) 을 대기할 필요 없음 대규모 서비스에 적합

• CouchDB 의 Read 작업은 MVCC(Multi-Version Concurrency Control) 모델 기반으로 Consistent 한 데이터 snapshot 사용

Page 13: CouchDB - Introduction - Korean

CouchDB 의 특징

13

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 14: CouchDB - Introduction - Korean

Secondary Index

14

• _id 를 기준으로 한 Primary Unique Index 를 보완

• _id 이외의 다른 필드 또는 필드들의 조합을 대상으로 함• Key 값은 중복 허용

• 예 : author, subject, [author, subject]

• 생성 방법• 일반 Design Document

• Map/Reduce 를 사용 (Map 의 emit 함수 )

데이터Map 함수

인덱스

조회 결과

Page 15: CouchDB - Introduction - Korean

View – Secondary Index 의 결과

15

• Map 의 emit 함수 실행 결과가 실시간 처리 되어 View 형태로 저장( 원본 DB 의 별도 )

• 원본 데이터 변경 시 전체 재 계산이 아닌 변경분만 재 계산 (Incremental Map/Reduce)

• 클러스터 (Cloudant, BigCouch) 에서는 여러 노드에 분산되어 처리 및 저장 됨

• 동일 데이터 (Database) 에 대한 복수 View 생성 가능

• Reduce 를 통해 데이터 통계 (RDB 의 sum & group by 에 해당 ) 생성( 사용 여부는 선택적 )

Page 16: CouchDB - Introduction - Korean

Map/Reduce

16

• 주로 JavaScript 로 작성 되며 , 다른 언어도 지원 가능

• 일반적인 Map/Reduce 와 마찬가지로…• Map 함수에서 key, value 쌍을 생성

• Reduce 함수에서 데이터 (key, value 쌍의 배열 ) 에 대한 계산 , 통계 작업

• 병렬 처리 – 클러스터에서는 여러 노드에서 분산 처리 및 결과 취합

Page 17: CouchDB - Introduction - Korean

Map/Reduce

17

• CouchDB 의 Map/Reduce 는…• Real time: DB 의 데이터에 변경이 생기면 바로 실시간 재 계산 (View)

• Incremental: 데이터 변경 시 , 전체를 재 계산 하지 않고 필요한 부분만 재 계산 하는 방법 (http://eagain.net/articles/incremental-mapreduce/)

• Chained Map/Reduce

• 복수의 Map/Reduce 작업을 이어서 하는 것 (Real time, Incremental 특성 유지 )

• Map/Reduce 결과를 2 차 DB 로 동기화하여 거기서 다시 Map/Reduce 를 실행

• Cloudant 에서 제공

• http://examples.cloudant.com/sales/_design/sales/index.html

Page 18: CouchDB - Introduction - Korean

CouchDB 의 특징

18

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 19: CouchDB - Introduction - Korean

Strong Focus on Replication

19

• Couch 계열 DB 의 특징• CouchDB 호환 DB(Cloudant, TouchDB, PouchDB) 간 상호 동기화 지원

• 모든 Document( 레코드 ) 에 Revision ID(MVCC) 가 있어 변경 사항을 쉽게 추출 변경 데이터만 증분 (incremental) 복제 / 동기화 Fault Tolerant ( 서버 /DB Crash 시에도 , 데이터 동기화 보장 )

• 단방향 , 양방향 , N:N Multi-Master, Server/Cloud to Mobile 동기화 가능

• 일회성 복제 및 동기화 , 지속적인 (Continuous), 필터 ( 원하는 패턴 ) 동기화

• Use Cases

• 글로벌 거점 간 데이터 동기화 (Multi-Master 복제 )

• 모바일 , 사물인터넷 (Internet Of Things) 데이터 수집

• 각종 기기 (Device) 또는 단말 (Edge) 에서 수집된 정보를 메인 DB 로 복제

Page 20: CouchDB - Introduction - Korean

Replication 동작 과정

20

REV-10 REV-09 REV-08 REV-07 REV-05 REV-04…REV-11

REV-14

REV-16

• 초기 Replication 설정

• 동작 중인 Replication 모니터링

BARFOO

REV-01

REV-02

REV-03

Pull 방식 Replication 소스 및

타겟 지정

Replication 상태 정보

Push 방식

Pull 방식

• 동기화를 담당할 Job 을 소스 , 타겟 원하는 위치에서 운영 가능 ( 소스 -Push or 타겟 -Pull)

• DB 자체의 고유 기능 (Document 의 Revision ID 관리 ) 을 바탕으로 정확하고 안정적인 동기화 가능

• 별도의 동기화 서버나 프로세스 불필요 (DB 자체의 기본 기능 )

• 상호 양방향 동기화 지원

Page 21: CouchDB - Introduction - Korean

Changes Event 를 통한 메시징

21

• Replication 및 Revision History(MVCC) 에 기반한 변경 이벤트 수신• Changes Event 를 수신하고 있는 각 Client 별로 전달할 메시지 (DB Insert/Update/Delete) 관리

• Client 가 다운되어 있는 경우에도 재 기동 시 , 해당 시간 동안 발생한 메시지 수신 가능 ( 무시도 가능 )

• CouchDB Replication 프로토콜 기반

CouchDB

Client Client

DB Changes History

Changes Event 수신

ClientDown Client

Changes Event 수신

REV-10 REV-09 REV-08 REV-07 REV-05 REV-04… REV-01REV-02REV-03

REV-03REV-02REV-01 REV-04 REV-05 REV-06 REV-05 REV-04 REV-02REV-03 …

REV-01REV-02REV-03

REV-4

REV-6 REV-7

Client 별로 다음에 수신할 Changes 번호 관리

다음 전송할데이터

Page 22: CouchDB - Introduction - Korean

Replication 활용 예제 : Quilter

22

• Replication 과 Changes Feed 를 활용한 로컬 – 원격 클라우드 / 서버 파일 동기화 프로젝트 • 관련 문서 :

http://cloudantkug.wordpress.com/2014/02/19/quilter-cloudant%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%A1%9C%EC%BB%AC%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%ED%8C%8C%EC%9D%BC-%EB%8F%99%EA%B8%B0%ED%99%94/

• 소스 Repository: https://github.com/garbados/quilter

• Node.js 기반

• 서버에 올린 사진 파일을 CouchApp 을 통해 Publishing 가능• https://github.com/garbados/egg_chair

Page 23: CouchDB - Introduction - Korean

CouchDB 의 특징

23

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 24: CouchDB - Introduction - Korean

RESTful API

24

• 예제 :

• 문서• http://docs.couchdb.org/en/latest/intro/api.html

• http://docs.couchdb.org/en/latest/api/index.html

Page 25: CouchDB - Introduction - Korean

Web Friendly

• CouchDB 자체가 HTTP 웹서버

• REST 기반 API 를 통해 웹 상에서 쉽게 액세스 가능

• Java, JavaScript, Ruby, PHP 등에서 쉽게 호출 가능

• 기존 웹 인프라와 쉽게 연동 가능 ( 예 : Cache, Proxy, Firewall)

• 웹과 유사한 Optimistic Locking 모델

Page 26: CouchDB - Introduction - Korean

CouchApp

26

• CouchDB 의 자체 HTTP 웹서버 기능을 활용한 Application Deployment 방법

• Design Document 를 통해 애플리케이션 제어

• 웹 리소스 (HTML, 이미지 , CSS 등 ) 들을 Attachment 형태로 저장

• JavaScript 에서 REST 를 통해 DB 데이터 접근 가능

• Virtual Hosting, URL Redirecting 기능 지원

• Application 과 Data 가 한 번에 관리 , 배포 , 복제 (Replication 통한 App/Data 동시 복제 가능 )

• 예제• DB 에 저장된 주소록과 CouchApp 으로 제작된 주소록 Viewer

Page 27: CouchDB - Introduction - Korean

Futon (GUI Tool)

27

• Futon

• 기본 내장된 DB 관리툴

• CouchApp 으로 만들어짐

• Fauxton

• Cloudant 가 기여한 새로운 Admin Tool

• CouchDB 1.5 부터 포함 ( 사용하려면 별도 작업 필요 )

• Node.js 기반

• Design Document 작성 편리

Futon

Fauxton

Page 28: CouchDB - Introduction - Korean

cURL

28

• Command Line 기반 REST API 테스트 도구

• 쉽고 간단하게 사용할 수 있어 소규모 , 즉석 테스트에 사용

• Unix, Linux, Window 버전

• 예제• Create

• curl -X POST http://localhost:5984/db -H "Content-Type: application/json" -d ‘{"name": "data"}’

• Read

• curl -X GET http://localhost:5984/db/key

• Update

• curl -X PUT http://localhost:5984/db/key -H "Content-Type: application/json" -d ‘{"_rev": "1-XXXX", "name": "data"}’

• Delete

• curl -X DELETE http://localhost:5984/db/key?rev=1-XXXX

Page 29: CouchDB - Introduction - Korean

GUI REST Client

29

• Firefox 나 Chrome 브라우저의 Plugin

• REST Client

• Java 기반의 REST 테스트 전용 도구

• https://github.com/wiztools/rest-client

• SoapUI

• SOAP/XML 성능 테스트 도구

• REST 지원

• http://www.soapui.org/

• JSON 처리 관련 개선 사항http://blog.naver.com/javalove93/130185743179

REST Client

SoapUI

Page 30: CouchDB - Introduction - Korean

Ektorp Java API

30

• 가장 많이 사용되고 기능이 풍부한 API

• Repository: https://github.com/helun/Ektorp

• JPA 와 유사한 기능을 가지면서도 단순 , 유연한 CouchDB API

• Jackson 을 이용한 JSON Document 핸들링

• Spring, Mobile(Android) 지원

• 예제 코드

DB 접속

Secondary Index(MR) 호출

Page 31: CouchDB - Introduction - Korean

CouchDB 의 특징

31

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 32: CouchDB - Introduction - Korean

Mobile Support

32

• HTTP REST & JSON 기반• Mobile 에서 직접 통신 용이

• Cookie 기반 세션 , OAuth 등을 통해 Mobile 애플리케이션 지원

• Replication 을 통한 Disconnected Device 지원• Mobile DB 작업 내용을 서버 DB 와 동기화 가능

• TouchDB, PouchDB(JavaScript), Cloudant Sync for Android/iOS 등 각종 모바일 전용 DB (CouchDB 와 호환 )

Page 33: CouchDB - Introduction - Korean

CouchDB 의 특징

33

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control (MVCC)

• Eventual Consistency

• Erlang OTP

Page 34: CouchDB - Introduction - Korean

Multi Version Concurrency Control(MVCC)

34

• RDBMS 는 lock 을 통해 read/write consistency( 일관성 ) 보장

• CouchDB 는 lock 대신 , 문서의 이력 (Revision History) 을 모두 보관

• 문서 Update 시 Version 이 바뀌었다면( 변경이 있어났음을 의미 ) Conflict 에러 발생 (Optimistic Lock)

• 예 : Ver 2 를 기준으로 Document Update 를 시도했는데 , 현재 최신 버전이 Ver 3 인 경우 UpdateConflict

• MVCC 를 통해 Replication 처리가 매우 용이

• Lock 이 필요하면 애플리케이션 로직으로 처리

Page 35: CouchDB - Introduction - Korean

Append Only DB

35

• Update 도 새로운 Version 추가 (Append) 로 처리

• 오래된 Revision 은 주기적으로 정리 (Compaction)

• 보안 등의 목적으로 Revision 강제 삭제 가능 (Purging)

Page 36: CouchDB - Introduction - Korean

CouchDB 의 특징

36

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency between Distributed Nodes

• Erlang OTP

Page 37: CouchDB - Introduction - Korean

Eventual Consistency

• 단일 노드에서 Consistency 보장은 상대적으로 용이

• 분산된 클러스터 환경에서 훨씬 복잡한 문제 (CAP Theorem)

• Incremental Replication 을 통해 Consistency 해결• Client 는 각자 노드에서 데이터 변경

• 이후 Replication 을 통해 동기화

• 다른 노드의 가용성 고민 불필요

• 전체 시스템 Availability 향상

• Conflict 발생 가능성• 충돌이 발생한 데이터를 모두 보관

• 애플리케이션 로직을 통해 충돌 해결

Page 38: CouchDB - Introduction - Korean

CouchDB 의 특징

38

• JSON Document Storage/Store

• ACID Compliant Data Store “Ultra Durable”

• Map/Reduce View and Secondary Indexes

• Distributed Architecture and Replication

• REST/HTTP API “Web Friendly”

• Strong Mobile Support

• Multi Version Concurrency Control

• Eventual Consistency

• Erlang OTP

Page 39: CouchDB - Introduction - Korean

Erlang OTP(Open Telecom Platform)

39

• Ericsson 에서 만든 Erlang 언어와 해당 언어 기반 Application Server

• CouchDB 는 Erlang 언어 및 Erlang OTP 기반으로 작성됨

• Erlang 인터프리터 , 컴파일러

• 각 노드 간 통신 프로토콜 및 브로커 (Java 의 RMI 와 유사 )

• Tuxedo, CICS 등과 매우 유사

• Actor Model Concurrency

• 멀티코어 , 분산환경에 적합한 모델

• 모든 프로세스나 컴포넌트가 Actor 가되어 서로 Message 를 통해 통신

Erlang OTP 에 등록되어 동작 중인 프로세스 목록

Page 40: CouchDB - Introduction - Korean

다 못한 얘기…

40

• 설치 방법• Cloudant(CouchDB Cloud 서비스 ) 를 통한 테스트

• Security

• HTTP Basic Auth

• Cookie Auth

• OAuth

• Clustering

• BigCouch

Page 41: CouchDB - Introduction - Korean

Cloudant 를 이용한 CouchDB 테스트

41

• Cloudant DB 시작 가이드• 5GB까지 무료 서비스

• http://www.slideshare.net/JerryJeong2/getting-started-with-cloudant-dbaaskorean

• Cloudant 웹 UI 사용 방법• http://cloudantkug.wordpress.com/2014/02/19/cloudant-new-webui/

Page 42: CouchDB - Introduction - Korean

More Deep-Dive Session

42

?

Page 43: CouchDB - Introduction - Korean

CouchDB Clustering

43

• BigCouch + CouchDB CouchDB 2.0

Page 44: CouchDB - Introduction - Korean

44

Page 45: CouchDB - Introduction - Korean

45

Page 46: CouchDB - Introduction - Korean

46

Page 47: CouchDB - Introduction - Korean

47

Page 48: CouchDB - Introduction - Korean

48

Sharding

PUT /db2/docid92

DB Computes:• key = hash(“docid92”)• get_shards(key) ==> shard• get_nodes(shard) ==>

[N1,N3,N4]• Nodes.foreach: store(doc)

Page 49: CouchDB - Introduction - Korean

49

Sharding (“Q”)

• Example with Q = 24

• 6 Nodes

• Each node handles 4 shards

• General Rule:

• Few large DBs use large Q

• Many small DBs use small Q

• Q is degree of parallelism

Page 50: CouchDB - Introduction - Korean

50

Node Computes:• key = hash(doc._id)• get_shards(key) ==> shard• get_nodes(shard) ==> [N1,N3,N4]• Nodes.foreach: store(doc)

Replication (“N”)

• Store N copies of data

• Configurable per DB

Page 51: CouchDB - Introduction - Korean

51

Write Quorum (“W”)

• When does DB say “written”?

• When enough nodes have “written”

• What is “enough”?

• Try to store all replicas (N copies)• When ‘W’ nodes reply

• After fsync’ing to disk

PUT /db2/docid92

Page 52: CouchDB - Introduction - Korean

52

Read Quorum (“R”)

• When does DB say “here it is”?

• When enough nodes say “here it is”

• What is “enough”?• Try to read it from N Nodes

• When “R” nodes reply and agree

GET /db2/docid92

Page 53: CouchDB - Introduction - Korean

53

Page 54: CouchDB - Introduction - Korean

54

Page 55: CouchDB - Introduction - Korean

55

Page 56: CouchDB - Introduction - Korean

56

Page 57: CouchDB - Introduction - Korean

57

Indexing - Views, Search, Geo

• What about indexes?

• Built locally for each shard • Shards runs in parallel - utilize all CPUs• Merge-sort responses at query time

Page 58: CouchDB - Introduction - Korean

58

Page 59: CouchDB - Introduction - Korean

59

Page 60: CouchDB - Introduction - Korean

60

Page 61: CouchDB - Introduction - Korean

61

Page 62: CouchDB - Introduction - Korean

More Deep Dive Contents

62

• 추가 세미나 or 교육…

• CouchDB 관련 웹사이트• http://docs.couchdb.org/en/latest/ (매뉴얼 )

• http://cloudantkug.wordpress.com/ ( 한국 Cloudant 블로그 )