Knative로 서버리스 워크로드 구현
김진웅
Google Cloud Next'19 Extended Korea
About Me
김진웅 @ddiiwoong
Cloud Platform, Data Lake Architect @SK C&C
Interested in Kubernetes and Serverless(FaaS), DevOps, SRE, ML/DL
DevOps
Ops(운영자 여정)
Data Center Virtual Machine Container Serverless
Weeks Minutes Seconds Milliseconds
Dev(개발자 여정)
1단계 : Self-manage 2단계 : Managed 3단계 : Fully-Managed
OS설치/운영,
개발플랫폼 패치,
백업 등 직접관리
서버 기반이나
관리형 서비스로 제공
(설정, Scale 관리)
서버관리 없는 서비스
(No-Ops)
서버리스(Serverless)
서버리스 컴퓨팅
● 기본 인프라 관리 없음
● 자동확장
● 사용한 만큼 지불(초, 횟수단위)
Google Cloud 서버리스 제품
● Compute - Cloud Functions, App Engine
● Storage - Cloud Storage
● Database - Cloud Firestore
● BigQuery, Cloud Dataflow, Cloud Pub/Sub, Cloud ML Engine
FaaS
FaaS (Function as a Service)
이벤트(Event)에 응답하여 코드를 실행(Function)하고 백엔드
서비스(Backend Service)를 통한 서버리스 컴퓨팅 구현
Event Function Services
Managed FaaS
● 멀티, 하이브리드 클라우드 사용 어려움
(Private Cloud, Public Cloud, On-Premise)
● 의존성
제한된 개발언어, 프레임워크
Google Cloud Functions AWS Lambda
Kubernetes
● Kubernetes (K8s)
2014년 Google이 시작한 프로젝트로, 애플리케이션 컨테이너의 배포,
스케일, 오퍼레이팅을 자동화 해주는 오픈소스 플랫폼
(Orchestrates Computing, Networking, Storage Infrastructure)
● Custom Resources (CRs), Custom Resources Definitions(CRDs)
Kubernetes가 기본제공하는 리소스 이외에 사용자가 필요한 리소스를
생성하고 사용할수 있는 가장 간단한 방법
객체를 원하는 상태로 나타나게 하는 선언적 API (Kubenetes API 확장)
● Istio
플랫폼이나 소스코드 언어와 상관없이 서로다른 마이크로 서비스를
연결하고 관리할수 있는 Service Mesh 오픈소스 (다수의 CRDs 구성)
Open Source FaaS
https://landscape.cncf.io/category=installable-platform&format=card-mode
설치형 서버리스 플랫폼 (오픈소스 13개, 상용 2개)
General FaaS Architecture
• Cold Start
• Hot Start (Warm State)
FaaS
Pull
New Function Container
(Cold Start)
Active Function Container
(Warm or Hot Start)
Functions
Store
Container
Registry First Run
Build
Create
Subsequent Run
Event
Call
Knative
서버리스 워크로드를 빌드, 배포, 관리하기 위한
Kubernetes 기반 플랫폼
● Source 중심
○ Any Programming language
○ Any Framework
○ Any libraries
● 컨테이너 기반 애플리케이션
● Kubernetes Cluster가 있으면 어디서나 실행
○ v1.11 이상
(MutatingAdmissionWebhook admission controller)
- 참고 : https://ddii.dev/kubernetes/mutating-web-hook/#
Build Serving Eventing
Knative Stack
Kubernetes (On-premises or Public Cloud)
Platform
Primitives
Istio (Service Mesh) or Gloo (API Gateway)
Knative
Google Cloud Function
Pivotal Funtion Service
riff
GKE Serverless Add-on
IBM Cloud Functions
OpenFaaS
Cloud Run (on GKE)
RedHat Cloud Functions
SAP Kyma
Products
Knative Build
Build
● 컨테이너는 전세계 개발자 공용어
● source-to-image
● 여러 Step으로 추가하여 구성 가능
● CI/CD 솔루션이 아닌 기존 사용하는 pipeline에 통합하여 사용가능
https://blog.openshift.com/knative-building-your-serverless-service/
Knative Build
apiVersion: build.knative.dev/v1alpha1
kind: Build
metadata:
name: python-build
spec:
serviceAccountName: knative-build
source:
git:
url: https://github.com/ddiiwoong/hello-python.git
revision: master
steps:
- name: build-and-push
image: gcr.io/kaniko-project/executor:v0.1.0
args:
- --dockerfile=/workspace/Dockerfile
- --destination=gcr.io/cloudrun-237814/hello-python
Build CRDs Sample
Knative Serving
● Serverless Container의 신속한 배치
● Automatic scaling up and down to zero
● Istio를 백엔드로 활용하여 Routing 구현
● 배포 된 코드 및 config의 특정 시점 스냅샷
Serving
Knative Serving CRDs
● Route : 사용자 서비스에 대한 HTTP endpoint
● Revisions : code(function)와 config로 구성된 불변의
스냅샷. Route를 통해 endpoint를 할당받지 못한 Revision은
자동으로 kubernetes resource에서 삭제됨
● Configuration : 요구되는 Revision 최신 상태를 기록하고
생성하고 추적할수 있음. 소스 패키지(git repo나 archive)를
컨테이너로 변환하기 위한 내용이나 메타데이터등을 포함
● Service : Routes와 Configurations 리소스의 추상화된
집합체. 모든 워크로드의 lifecycle을 관리. 트래픽을 항상
최신의 revision으로 route되도록 정의할수 있음
Knative Serving
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
target = os.environ.get('TARGET', 'NOT SPECIFIED')
return 'Hello World: {}!n'.format(target)
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
“Hello World” Python (Flask)
Knative Serving
FROM python:alpine
ENV APP_HOME /app
COPY . $APP_HOME
WORKDIR $APP_HOME
RUN pip install Flask
ENTRYPOINT ["python"]
CMD ["app.py"]
Dockerfile (Flask)
Knative Serving
apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
name: helloworld-python
namespace: default
spec:
runLatest:
configuration:
revisionTemplate:
spec:
container:
image: gcr.io/cloudrun-237814/hello-python
env:
- name: TARGET
value: "Python Sample v1"
Service CRDs YAML
Knative Eventing
● CNCF의 CloudEvent Spec. 기반
● Event를 produce/comsume 하는 방법을 제공
● 다양한 형태의 Source 지원
(Kubernetes Event, Cronjob, GitHub, IoT core, AWS SQS,
WebSocket 등)
● Eventing Channel 지원
(Kafka, GCP PubSub, NATS, In-Memory)
Eventing
Knative Eventing
apiVersion: sources.eventing.knative.dev/v1alpha1
kind: CronJobSource
metadata:
name: test-cronjob-source
spec:
schedule: "*/2 * * * *"
data: '{"message": "Hello world!"}'
sink:
apiVersion: serving.knative.dev/v1alpha1
kind: Service
name: event-display
예시 : Cron job Source
Cloud Run
● HTTP요청을 통해 Stateless containers를 실행할수 있는 Google
Computing Platform Services
● Serverless : 모든 인프라 관리가 추상화(No-Managed) 되므로
비즈니스 로직에 집중할수 있음
Cloud Run
Cloud Run on GKE
Cloud Run on GKE
● Seamless Knative Integration
● 개발자
○ Simple & Serverless
● 운영자
○ More Configurable
○ CPU, Memory, GPU
○ Custom Networking, more
Cloud Run & Cloud Run on GKE
https://twitter.com/ahmetb/status/1116041166359654400
Cloud Run, Cloud Run on GKE, Knative
Cloud Run Cloud Run on GKE Knative
과금 사용량 클러스터
클러스터 또는
On-Prem
커스터마이징 Memory
Memory, CPU, GPU,
Network
All Resources
URLs and SSL HTTPS URL 자동적용 HTTPS URL 수동적용 HTTPS URL 수동적용
인증 및 정책 Public, IAM, CICP Public or internal Custom
공통
커스텀 도메인 가능, 로깅&모니터링 통합(Stackdriver, Prometheus),
표준 컨테이너 이미지 사용
Demo
● Knative Build, Serving
● Cloud Run on GKE Serving
● Cloud Run Serving
Knative Use-Case
• 웹 애플리케이션
• 정적웹사이트, JS기반 웹앱
• 백엔드
• 애플리케이션 및 서비스, 모바일, IoT
• 빅데이터 분석
• MapReduce, Batch, Deep Learning Model
• 미디어/로그처리
• 스트리밍 데이터, 실시간 데이터 처리, 이미지 처리
• 인공지능
• Chatbot, AI Speaker Skills
• 참고
• https://github.com/steren/awesome-cloudrun
정리
No-managed Computing Productivity Continuous Scalability
• 프로비저닝 단계 제거
(No Provisioning)
• 인프라 관리 없음
(No-Managed)
• 고가용성
(Fault Tolerant Stateless)
• 문제/기능 중심의 개발 집중
• 민첩한 혁신
• 시장 접근성 강화
• 자동화 기반 확장
• 용량 증가/감소 자동화
• Hot / Cold Policy Control
• Concurrency
(ex: Cloud Run 80개)
Knative or Cloud Run
• 규모별 비용에 대한 고려
• 기존 비즈니스 로직 과 통합
여부 (Domain Name 등)
• Lock-in에 대한 고민 (이식성)
Focus
• 어디서 부터?
• 비용보다 생산성에 집중
Q&A
김진웅 @ddiiwoong
@ddiiwoong
@ddiiwoong
ddiiwoong@gmail.com
https://ddii.dev

Knative로 서버리스 워크로드 구현

  • 1.
    Knative로 서버리스 워크로드구현 김진웅 Google Cloud Next'19 Extended Korea
  • 2.
    About Me 김진웅 @ddiiwoong CloudPlatform, Data Lake Architect @SK C&C Interested in Kubernetes and Serverless(FaaS), DevOps, SRE, ML/DL
  • 3.
    DevOps Ops(운영자 여정) Data CenterVirtual Machine Container Serverless Weeks Minutes Seconds Milliseconds Dev(개발자 여정) 1단계 : Self-manage 2단계 : Managed 3단계 : Fully-Managed OS설치/운영, 개발플랫폼 패치, 백업 등 직접관리 서버 기반이나 관리형 서비스로 제공 (설정, Scale 관리) 서버관리 없는 서비스 (No-Ops)
  • 4.
    서버리스(Serverless) 서버리스 컴퓨팅 ● 기본인프라 관리 없음 ● 자동확장 ● 사용한 만큼 지불(초, 횟수단위) Google Cloud 서버리스 제품 ● Compute - Cloud Functions, App Engine ● Storage - Cloud Storage ● Database - Cloud Firestore ● BigQuery, Cloud Dataflow, Cloud Pub/Sub, Cloud ML Engine
  • 5.
    FaaS FaaS (Function asa Service) 이벤트(Event)에 응답하여 코드를 실행(Function)하고 백엔드 서비스(Backend Service)를 통한 서버리스 컴퓨팅 구현 Event Function Services
  • 6.
    Managed FaaS ● 멀티,하이브리드 클라우드 사용 어려움 (Private Cloud, Public Cloud, On-Premise) ● 의존성 제한된 개발언어, 프레임워크 Google Cloud Functions AWS Lambda
  • 7.
    Kubernetes ● Kubernetes (K8s) 2014년Google이 시작한 프로젝트로, 애플리케이션 컨테이너의 배포, 스케일, 오퍼레이팅을 자동화 해주는 오픈소스 플랫폼 (Orchestrates Computing, Networking, Storage Infrastructure) ● Custom Resources (CRs), Custom Resources Definitions(CRDs) Kubernetes가 기본제공하는 리소스 이외에 사용자가 필요한 리소스를 생성하고 사용할수 있는 가장 간단한 방법 객체를 원하는 상태로 나타나게 하는 선언적 API (Kubenetes API 확장) ● Istio 플랫폼이나 소스코드 언어와 상관없이 서로다른 마이크로 서비스를 연결하고 관리할수 있는 Service Mesh 오픈소스 (다수의 CRDs 구성)
  • 8.
  • 9.
    General FaaS Architecture •Cold Start • Hot Start (Warm State) FaaS Pull New Function Container (Cold Start) Active Function Container (Warm or Hot Start) Functions Store Container Registry First Run Build Create Subsequent Run Event Call
  • 10.
    Knative 서버리스 워크로드를 빌드,배포, 관리하기 위한 Kubernetes 기반 플랫폼 ● Source 중심 ○ Any Programming language ○ Any Framework ○ Any libraries ● 컨테이너 기반 애플리케이션 ● Kubernetes Cluster가 있으면 어디서나 실행 ○ v1.11 이상 (MutatingAdmissionWebhook admission controller) - 참고 : https://ddii.dev/kubernetes/mutating-web-hook/#
  • 11.
    Build Serving Eventing KnativeStack Kubernetes (On-premises or Public Cloud) Platform Primitives Istio (Service Mesh) or Gloo (API Gateway) Knative Google Cloud Function Pivotal Funtion Service riff GKE Serverless Add-on IBM Cloud Functions OpenFaaS Cloud Run (on GKE) RedHat Cloud Functions SAP Kyma Products
  • 12.
    Knative Build Build ● 컨테이너는전세계 개발자 공용어 ● source-to-image ● 여러 Step으로 추가하여 구성 가능 ● CI/CD 솔루션이 아닌 기존 사용하는 pipeline에 통합하여 사용가능 https://blog.openshift.com/knative-building-your-serverless-service/
  • 13.
    Knative Build apiVersion: build.knative.dev/v1alpha1 kind:Build metadata: name: python-build spec: serviceAccountName: knative-build source: git: url: https://github.com/ddiiwoong/hello-python.git revision: master steps: - name: build-and-push image: gcr.io/kaniko-project/executor:v0.1.0 args: - --dockerfile=/workspace/Dockerfile - --destination=gcr.io/cloudrun-237814/hello-python Build CRDs Sample
  • 14.
    Knative Serving ● ServerlessContainer의 신속한 배치 ● Automatic scaling up and down to zero ● Istio를 백엔드로 활용하여 Routing 구현 ● 배포 된 코드 및 config의 특정 시점 스냅샷 Serving Knative Serving CRDs ● Route : 사용자 서비스에 대한 HTTP endpoint ● Revisions : code(function)와 config로 구성된 불변의 스냅샷. Route를 통해 endpoint를 할당받지 못한 Revision은 자동으로 kubernetes resource에서 삭제됨 ● Configuration : 요구되는 Revision 최신 상태를 기록하고 생성하고 추적할수 있음. 소스 패키지(git repo나 archive)를 컨테이너로 변환하기 위한 내용이나 메타데이터등을 포함 ● Service : Routes와 Configurations 리소스의 추상화된 집합체. 모든 워크로드의 lifecycle을 관리. 트래픽을 항상 최신의 revision으로 route되도록 정의할수 있음
  • 15.
    Knative Serving import os fromflask import Flask app = Flask(__name__) @app.route('/') def hello_world(): target = os.environ.get('TARGET', 'NOT SPECIFIED') return 'Hello World: {}!n'.format(target) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080))) “Hello World” Python (Flask)
  • 16.
    Knative Serving FROM python:alpine ENVAPP_HOME /app COPY . $APP_HOME WORKDIR $APP_HOME RUN pip install Flask ENTRYPOINT ["python"] CMD ["app.py"] Dockerfile (Flask)
  • 17.
    Knative Serving apiVersion: serving.knative.dev/v1alpha1 kind:Service metadata: name: helloworld-python namespace: default spec: runLatest: configuration: revisionTemplate: spec: container: image: gcr.io/cloudrun-237814/hello-python env: - name: TARGET value: "Python Sample v1" Service CRDs YAML
  • 18.
    Knative Eventing ● CNCF의CloudEvent Spec. 기반 ● Event를 produce/comsume 하는 방법을 제공 ● 다양한 형태의 Source 지원 (Kubernetes Event, Cronjob, GitHub, IoT core, AWS SQS, WebSocket 등) ● Eventing Channel 지원 (Kafka, GCP PubSub, NATS, In-Memory) Eventing
  • 19.
    Knative Eventing apiVersion: sources.eventing.knative.dev/v1alpha1 kind:CronJobSource metadata: name: test-cronjob-source spec: schedule: "*/2 * * * *" data: '{"message": "Hello world!"}' sink: apiVersion: serving.knative.dev/v1alpha1 kind: Service name: event-display 예시 : Cron job Source
  • 20.
    Cloud Run ● HTTP요청을통해 Stateless containers를 실행할수 있는 Google Computing Platform Services ● Serverless : 모든 인프라 관리가 추상화(No-Managed) 되므로 비즈니스 로직에 집중할수 있음 Cloud Run
  • 21.
    Cloud Run onGKE Cloud Run on GKE ● Seamless Knative Integration ● 개발자 ○ Simple & Serverless ● 운영자 ○ More Configurable ○ CPU, Memory, GPU ○ Custom Networking, more
  • 22.
    Cloud Run &Cloud Run on GKE https://twitter.com/ahmetb/status/1116041166359654400
  • 23.
    Cloud Run, CloudRun on GKE, Knative Cloud Run Cloud Run on GKE Knative 과금 사용량 클러스터 클러스터 또는 On-Prem 커스터마이징 Memory Memory, CPU, GPU, Network All Resources URLs and SSL HTTPS URL 자동적용 HTTPS URL 수동적용 HTTPS URL 수동적용 인증 및 정책 Public, IAM, CICP Public or internal Custom 공통 커스텀 도메인 가능, 로깅&모니터링 통합(Stackdriver, Prometheus), 표준 컨테이너 이미지 사용
  • 24.
    Demo ● Knative Build,Serving ● Cloud Run on GKE Serving ● Cloud Run Serving
  • 25.
    Knative Use-Case • 웹애플리케이션 • 정적웹사이트, JS기반 웹앱 • 백엔드 • 애플리케이션 및 서비스, 모바일, IoT • 빅데이터 분석 • MapReduce, Batch, Deep Learning Model • 미디어/로그처리 • 스트리밍 데이터, 실시간 데이터 처리, 이미지 처리 • 인공지능 • Chatbot, AI Speaker Skills • 참고 • https://github.com/steren/awesome-cloudrun
  • 26.
    정리 No-managed Computing ProductivityContinuous Scalability • 프로비저닝 단계 제거 (No Provisioning) • 인프라 관리 없음 (No-Managed) • 고가용성 (Fault Tolerant Stateless) • 문제/기능 중심의 개발 집중 • 민첩한 혁신 • 시장 접근성 강화 • 자동화 기반 확장 • 용량 증가/감소 자동화 • Hot / Cold Policy Control • Concurrency (ex: Cloud Run 80개) Knative or Cloud Run • 규모별 비용에 대한 고려 • 기존 비즈니스 로직 과 통합 여부 (Domain Name 등) • Lock-in에 대한 고민 (이식성) Focus • 어디서 부터? • 비용보다 생산성에 집중
  • 27.