SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler offline
Build go kit Microservices at
Kubernetes with ease
HELLO!
Cage Chung
@CageChung @cage1016
cage.chung@gmail.com
GDG Cloud Taipei co-organizer
Google Developer Expert (GCP)
Agenda
◉ Gokitistiok8s
◉ Go-kit
◉ Service mesh
Gokitistiok8s
go kit microservice demo with istio & jaeger at kubernetes 1
Gokitistiok8s (3 microservice)
Router
◉ HTTP
◉ GRPC
Addsvc
◉ sum
◉ concat
Foosvc
◉ foo
istio (service discovery)
Tracing (trace service)
Prometheus (monitor)
Grafana (monitor)
Fluentd (log)
Elasticsearch (log)
Kibana (log)
Gokitconsulk8s
https://github.com/cage1016/gokitconsulk8s
Gokitistiok8s
https://github.com/cage1016/gokitistiok8s
├── cmd
│ ├── addsvc
│ │ └── main.go
│ ├── foosvc
│ │ └── main.go
│ └── router
│ └── main.go
├── consul-helm
├── deployments
│ ├── docker
│ │ ├── Dockerfile
│ │ ├── Dockerfile.cleanbuild
│ │ └── Dockerfile.debug
│ └── helm
│ ├── templates
│ ├── .helmignore
│ ├── Chart.yaml
│ └── values.yaml
├── pkg
│ ├── addsvc
│ │ ├── endpoints
│ │ ├── service
│ │ └── transports
│ ├── foosvc
│ │ ├── endpoints
│ │ │ ├── endpoints.go
│ │ │ ├── middleware.go
│ │ │ ├── requests.go
│ │ │ └── responses.go
│ │ ├── service
│ │ │ ├── logging.go
│ │ │ └── service.go
│ │ └── transports
│ │ ├── errors.go
│ │ ├── grpc.go
│ │ └── http.go
│ └── router
│ └── transports
├── makefile
└── skaffold.yaml
$ make rest_sum
curl -X "POST" "http://35.187.144.211/api/v1/add/sum" -H 'Content-Type: application/json; charset=utf-8' -d '{ "a": 3, "b": 34}'
{"apiVersion":"","data":{"rs":37}}
$ make rest_concat
curl -X "POST" "http://35.187.144.211/api/v1/add/concat" -H 'Content-Type: application/json; charset=utf-8' -d '{ "a": "3", "b": "34"}'
{"apiVersion":"","data":{"rs":"334"}}
$ make rest_foo
curl -X "POST" "http://35.187.144.211/api/v1/foo/foo" -H 'Content-Type: application/json; charset=utf-8' -d '{"s": "foo"}'
{"apiVersion":"","data":{"res":"foo bar"}}
$ make grpc_sum
grpcurl -plaintext -proto ./pb/addsvc/addsvc.proto -d '{"a": 3, "b":5}' 35.187.144.211:443 pb.Addsvc.Sum
{
"rs": "8"
}
$ make grpc_concat
grpcurl -plaintext -proto ./pb/addsvc/addsvc.proto -d '{"a": "3", "b":"5"}' 35.187.144.211:443 pb.Addsvc.Concat
{
"rs": "35"
}
$ make grpc_foo
grpcurl -plaintext -proto ./pb/foosvc/foosvc.proto -d '{"s": "foo"}' 35.187.144.211:443 pb.Foosvc.Foo
{
"res": "foo bar"
}
Demohttps://github.com/cage1016/gokitistiok8s
Go-kit
Toolkit for microservices 2
“Microservice solve organizational
problems
~
Microservice cause technical
problems
Problem solved
1. Team are blocked on other teams, can’t make progress
2. Product velocity stalled
Problem cause
1. Testing becomes really hard
2. Build pipelines
3. Requires dev/ops culture: devs deploy and operate their
work
4. Monitoring and instrumentation - tailing logs?
5. Distributed tracing
6. Security
Go-kit goals
1. Make Go a first-class citizen for business logic
2. Microservice architecture
3. RPC as the messaging pattern
4. Provide best practices, idioms, examples and patterns
Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://www.youtube.com/watch?v=aL6sd4d4hxk
Go-kit non-goals
1. Be a turnkey solution
2. Require any specific infrastructure
3. Have opinions about orchestration, configuration, etc.
Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://www.youtube.com/watch?v=aL6sd4d4hxk
Go HTTP Servers
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello Devfest Taipei 2019")
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":8888", nil)
}
Add service: service and implement
type Addsvc interface {
sum(a, b int64) (int64, error)
}
type SumRequest struct {
A int64 `json:"a"`
B int64 `json:"b"`
}
func (s *addService) sum(a, b int64) (int64, error) {
return a + b, nil
}
type addService struct{}
Transports: Implement HTTP handler
func (s *addService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var req SumRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if res, err := s.sum(req.A, req.B); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
fmt.Fprint(w, res)
}
}
}
main.go
func main() {
http.ListenAndServe(":8888", &addService{})
}
$ go run main.go
$ curl -X "POST" "http://localhost:8888" -d '{ "a": 3, "b": 34}'
37
Addservice an HTTP handler, we can pass it to ListenAndServe
Logging: try to add logging
func (s *addService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var req SumRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
code := http.StatusBadRequest
http.Error(w, err.Error(), code)
log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, code)
return
}
if res, err := s.sum(req.A, req.B); err != nil {
code := http.StatusInternalServerError
http.Error(w, err.Error(), code)
log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, code)
return
} else {
log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, 200)
fmt.Fprint(w, res)
}
}
Logging
func main() {
log.Printf("listening on :8888")
log.Fatal(http.ListenAndServe(":8888", &addService{}))
}
$ go run main.go
2019/11/29 15:24:29 listening on :8888
2019/11/29 15:24:32 [::1]:52200: POST / 200
$ curl -X "POST" "http://localhost:8888" -d '{ "a": 3, "b": 34}'
37
Endpoint
Endpoint is the fundamental building block of servers and clients.It represents
a single RPC method.
type Endpoint func(request) (response)
type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
Add service endpoint
Create endpoint by add service constructor and keep add service pure
func MakePostSumEndpoint(s addService) endpoint.Endpoint {
return func(_ context.Context, request interface{}) (response interface{}, err error) {
p := request.(SumRequest)
return s.sum(p.A, p.B)
}
}
Endpoint middleware
Middleware is a chainable behavior modifier for endpoints.
type Middleware func(Endpoint) Endpoint
Logging middleware
Create endpoint by add service constructor and keep add service pure
func loggingMiddleware(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
begin := time.Now()
defer func() {
log.Printf("request took %s", time.Since(begin))
}()
return next(ctx, request)
}
}
s := addService{}
var e endpoint.Endpoint
e = MakePostSumEndpoint(s)
e = loggingMiddleware(e)
Http transport
Go kit comes with handy HTTP transport. NewServer constructs a new server,
which implements http.Handler and wraps the provided endpoint.
func NewServer(
e endpoint.Endpoint,
dec DecodeRequestFunc,
enc EncodeResponseFunc,
options ...ServerOption,
) *Server { ... }
postSum := httptransport.NewServer(e, decodeHTTPSumRequest, httptransport.EncodeJSONResponse)
r := mux.NewRouter()
r.Methods(http.MethodPost).Handler(postSum)
log.Printf("listening on :8888")
log.Fatal(http.ListenAndServe(":8888", r))
Design — How is a Go kit microservice modeled?
Transport
Endpoint
Service
https://gokit.io/faq/#design-mdash-how-is-a-go-kit-microservice-modeled
Go + microservices = Go kit - Speaker Deck - https://speakerdeck.com/peterbourgon/go-plus-microservices-equals-go-kit?slide=78
Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://youtu.be/aL6sd4d4hxk?t=1022
● Authentication: Basic, casbin, JWT.
● Circuit Breaker: Hystrix, GoBreaker, and HandyBreaker.
● Logging: Provide an interface for structured logging. Recognizes
that logs are data. They need context and semantics to be useful
for analysis. Supported formats are logfmt and JSON.
● Metrics: Provides uniform interfaces for service instrumentation.
Comes with counters, gauges, and histograms. Has adapters for
CloudWatch, Prometheus, Graphite, DogStatsD, StatsD, expvar,
and more.
● Rate Limit: Uses Go's token bucket implementation.
● Service Discovery: Consul, DNS SRV, etcd, Eureka, ZooKeeper,
and more.
● Tracing: OpenCensus, OpenTracing, and Zipkin.
● Transport: AMQP, AWS Lambda, gRPC, HTTP, NATS, Thrift.
.
├── auth
├── circuitbreaker
├── cmd
├── endpoint
├── examples
├── log
├── metrics
├── ratelimit
├── sd
├── tracing
├── transport
├── util
├── .build.yml
├── .gitignore
├── .travis.yml
DemoGokit generator: squaresvc
Service mesh
3
“Microservice cause technical
problems
~
Service Mesh solve technical
problems
What Is a Service Mesh? By NGINX
1. Container orchestration framework
2. Services and instances (Kubernetes pods).
3. Sidecar proxy
4. Service discovery
5. Load balancing
6. Encryption
7. Authentication and authorization
8. Support for the circuit breaker pattern
What Is a Service Mesh? - NGINX - https://www.nginx.com/blog/what-is-a-service-mesh/
The control plane in a service mesh distributes configuration
across the sidecar proxies in the data plane
What Is a Service Mesh? - NGINX - https://www.nginx.com/blog/what-is-a-service-mesh/
kind: Gateway
metadata:
name: http-gateway
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
kind: VirtualService
metadata:
name: ingress-http
spec:
hosts:
- "*"
gateways:
- http-gateway
http:
- match:
- uri:
prefix: /api/v1/
rewrite:
uri: /
route:
- destination:
host: router
port:
number: 80
- match:
- uri:
prefix: /
route:
- destination:
host: website
port:
number: 80
kind: DestinationRule
metadata:
name: router
spec:
host: router
trafficPolicy:
loadBalancer:
simple: RANDOM
tls:
mode: ISTIO_MUTUAL
kind: VirtualService
metadata:
name: router
spec:
hosts:
- router
http:
- route:
- destination:
host: router
kind: Deployment
metadata:
name: router
spec:
replicas: 1
selector:
matchLabels:
app: router
template:
metadata:
labels:
app: router
spec:
containers:
- env:
- name: QS_ADDSVC_URL
value: addsvc:8000
- name: QS_FOOSVC_URL
value: foosvc:8000
- name: QS_ROUTER_HTTP_PORT
value: "8000"
- name: QS_ROUTER_LOG_LEVEL
value: info
- name: QS_ZIPKIN_V2_URL
value: http://zipki....spans
image: qeekdev/retailbase-router
kind: DestinationRule
metadata:
name: addsvc
spec:
host: addsvc
trafficPolicy:
connectionPool:
http:
http1MaxPendingRequests: 1
maxRequestsPerConnection: 1
tcp:
maxConnections: 1
loadBalancer:
simple: RANDOM
outlierDetection:
baseEjectionTime: 3m
consecutiveErrors: 1
interval: 1s
maxEjectionPercent: 100
tls:
mode: ISTIO_MUTUAL
kind: Service
metadata:
name: addsvc
spec:
ports:
- name: http
port: 80
protocol: TCP
targetPort: 8020
- name:
grpc-web-port
port: 8000
protocol: TCP
targetPort: 8021
selector:
app: addsvc
kind: Deployment
metadata:
name: addsvc
spec:
replicas: 1
selector:
matchLabels:
app: addsvc
template:
metadata:
labels:
app: addsvc
spec:
containers:
- env:
- name: QS_..._GRPC_PORT
value: "8021"
- name: QS_..._HTTP_PORT
value: "8020"
- name: QS_..._LOG_LEVEL
value: info
- name: QS_ZIPKIN_V2_URL
value: http://zipkin….
image:...
Addsvc Tracing
Consul vs. Istio
Consul Service Mesh实战【转】 - 简书 - https://www.jianshu.com/p/ad970554403d
Reference
1. Go + Microservices = Go Kit [I] - Peter Bourgon, Go Kit
2. Go kit
3. https://gokit.io/faq/
4. cage1016/gokitistio8s
5. cage1016/gk
6. What Is a Service Mesh?
Q & A

Mais conteúdo relacionado

Mais procurados

GroovyServ - Technical Part
GroovyServ - Technical PartGroovyServ - Technical Part
GroovyServ - Technical Part
Yasuharu Nakano
 

Mais procurados (20)

gRPC
gRPCgRPC
gRPC
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
HTTP/3, QUIC and streaming
HTTP/3, QUIC and streamingHTTP/3, QUIC and streaming
HTTP/3, QUIC and streaming
 
Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;
Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;
Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;
 
Laura Garcia - Shodan API and Coding Skills [rooted2019]
Laura Garcia - Shodan API and Coding Skills [rooted2019]Laura Garcia - Shodan API and Coding Skills [rooted2019]
Laura Garcia - Shodan API and Coding Skills [rooted2019]
 
SnorGen User Guide 2.0
SnorGen User Guide 2.0SnorGen User Guide 2.0
SnorGen User Guide 2.0
 
Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...
 
"Enabling Googley microservices with gRPC" Riga DevDays 2018 edition
"Enabling Googley microservices with gRPC" Riga DevDays 2018 edition"Enabling Googley microservices with gRPC" Riga DevDays 2018 edition
"Enabling Googley microservices with gRPC" Riga DevDays 2018 edition
 
"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski"A rootkits writer’s guide to defense" - Michal Purzynski
"A rootkits writer’s guide to defense" - Michal Purzynski
 
OSMC 2008 | PostgreSQL Monitoring - Introduction, Internals And Monitoring S...
OSMC 2008 |  PostgreSQL Monitoring - Introduction, Internals And Monitoring S...OSMC 2008 |  PostgreSQL Monitoring - Introduction, Internals And Monitoring S...
OSMC 2008 | PostgreSQL Monitoring - Introduction, Internals And Monitoring S...
 
Modern javascript localization with c-3po and the good old gettext
Modern javascript localization with c-3po and the good old gettextModern javascript localization with c-3po and the good old gettext
Modern javascript localization with c-3po and the good old gettext
 
How to reverse engineer Android applications
How to reverse engineer Android applicationsHow to reverse engineer Android applications
How to reverse engineer Android applications
 
InChI Resolver and its protocol
InChI Resolver and its protocolInChI Resolver and its protocol
InChI Resolver and its protocol
 
Piratte installation
Piratte installationPiratte installation
Piratte installation
 
Ceph Day SF 2015 - Big Data Applications and Tuning in Ceph
Ceph Day SF 2015 - Big Data Applications and Tuning in Ceph Ceph Day SF 2015 - Big Data Applications and Tuning in Ceph
Ceph Day SF 2015 - Big Data Applications and Tuning in Ceph
 
GroovyServ - Technical Part
GroovyServ - Technical PartGroovyServ - Technical Part
GroovyServ - Technical Part
 
Gokit
GokitGokit
Gokit
 
Un-split brain MySQL
Un-split brain MySQLUn-split brain MySQL
Un-split brain MySQL
 
Delex 2020: Deep diving into the dynamic provisioning of GlusterFS volumes in...
Delex 2020: Deep diving into the dynamic provisioning of GlusterFS volumes in...Delex 2020: Deep diving into the dynamic provisioning of GlusterFS volumes in...
Delex 2020: Deep diving into the dynamic provisioning of GlusterFS volumes in...
 

Semelhante a GDG Cloud Taipei meetup #50 - Build go kit microservices at kubernetes with ease

OGCE Overview for SciDAC 2009
OGCE Overview for SciDAC 2009OGCE Overview for SciDAC 2009
OGCE Overview for SciDAC 2009
marpierc
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
Fred Sauer
 

Semelhante a GDG Cloud Taipei meetup #50 - Build go kit microservices at kubernetes with ease (20)

如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰如何透過 Go-kit 快速搭建微服務架構應用程式實戰
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
 
Using Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network SystemsUsing Groovy to empower WebRTC Network Systems
Using Groovy to empower WebRTC Network Systems
 
Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and Practice
 
OGCE Overview for SciDAC 2009
OGCE Overview for SciDAC 2009OGCE Overview for SciDAC 2009
OGCE Overview for SciDAC 2009
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
SaltConf14 - Eric johnson, Google - Orchestrating Google Compute Engine with ...
SaltConf14 - Eric johnson, Google - Orchestrating Google Compute Engine with ...SaltConf14 - Eric johnson, Google - Orchestrating Google Compute Engine with ...
SaltConf14 - Eric johnson, Google - Orchestrating Google Compute Engine with ...
 
Aplicações realtime com gRPC
Aplicações realtime com gRPCAplicações realtime com gRPC
Aplicações realtime com gRPC
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
GWT Extreme!
GWT Extreme!GWT Extreme!
GWT Extreme!
 
FIWARE Wednesday Webinars - Short Term History within Smart Systems
FIWARE Wednesday Webinars - Short Term History within Smart SystemsFIWARE Wednesday Webinars - Short Term History within Smart Systems
FIWARE Wednesday Webinars - Short Term History within Smart Systems
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
 
Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022
 
Developing with the Go client for Apache Kafka
Developing with the Go client for Apache KafkaDeveloping with the Go client for Apache Kafka
Developing with the Go client for Apache Kafka
 
2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf2015-GopherCon-Talk-Uptime.pdf
2015-GopherCon-Talk-Uptime.pdf
 
OGCE Project Overview
OGCE Project OverviewOGCE Project Overview
OGCE Project Overview
 
REST in Peace. Long live gRPC!
REST in Peace. Long live gRPC!REST in Peace. Long live gRPC!
REST in Peace. Long live gRPC!
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
 

Mais de KAI CHU CHUNG

Mais de KAI CHU CHUNG (20)

Devfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfDevfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
 
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdfDevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
DevFest 2022 - Skaffold 2 Deep Dive Taipei.pdf
 
DevFest 2022 - Cloud Workstation Introduction TaiChung
DevFest 2022 - Cloud Workstation Introduction TaiChungDevFest 2022 - Cloud Workstation Introduction TaiChung
DevFest 2022 - Cloud Workstation Introduction TaiChung
 
Devfest 2021' - Artifact Registry Introduction (Taipei)
Devfest 2021' - Artifact Registry Introduction (Taipei)Devfest 2021' - Artifact Registry Introduction (Taipei)
Devfest 2021' - Artifact Registry Introduction (Taipei)
 
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
 
Velero search & practice 20210609
Velero search & practice 20210609Velero search & practice 20210609
Velero search & practice 20210609
 
Gdg cloud taipei ddt meetup #53 buildpack
Gdg cloud taipei ddt meetup #53 buildpackGdg cloud taipei ddt meetup #53 buildpack
Gdg cloud taipei ddt meetup #53 buildpack
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
 
Dev fest 2020 taiwan how to debug microservices on kubernetes as a pros (ht...
Dev fest 2020 taiwan   how to debug microservices on kubernetes as a pros (ht...Dev fest 2020 taiwan   how to debug microservices on kubernetes as a pros (ht...
Dev fest 2020 taiwan how to debug microservices on kubernetes as a pros (ht...
 
Google App Engine: Basic
Google App Engine: BasicGoogle App Engine: Basic
Google App Engine: Basic
 
COSCUP 2020 Google 技術 x 公共參與 x 開源 口罩地圖技術開源
COSCUP 2020 Google 技術 x 公共參與 x 開源 口罩地圖技術開源COSCUP 2020 Google 技術 x 公共參與 x 開源 口罩地圖技術開源
COSCUP 2020 Google 技術 x 公共參與 x 開源 口罩地圖技術開源
 
Global GDG Leaders Summit, Google I/O 2018 經驗分享
Global GDG Leaders Summit, Google I/O 2018 經驗分享Global GDG Leaders Summit, Google I/O 2018 經驗分享
Global GDG Leaders Summit, Google I/O 2018 經驗分享
 
Google apps script introduction
Google apps script introductionGoogle apps script introduction
Google apps script introduction
 
Screenshot as a service
Screenshot as a serviceScreenshot as a service
Screenshot as a service
 
Nas 也可以揀土豆
Nas 也可以揀土豆Nas 也可以揀土豆
Nas 也可以揀土豆
 
60分鐘完送百萬edm,背後雲端ci/cd實戰大公開
60分鐘完送百萬edm,背後雲端ci/cd實戰大公開60分鐘完送百萬edm,背後雲端ci/cd實戰大公開
60分鐘完送百萬edm,背後雲端ci/cd實戰大公開
 
Django oscar introduction
Django oscar introductionDjango oscar introduction
Django oscar introduction
 
Continuous Integration & Continuous Delivery with GCP
Continuous Integration & Continuous Delivery with GCPContinuous Integration & Continuous Delivery with GCP
Continuous Integration & Continuous Delivery with GCP
 
Google apps script introduction
Google apps script introductionGoogle apps script introduction
Google apps script introduction
 
Gae managed vm introduction
Gae managed vm introductionGae managed vm introduction
Gae managed vm introduction
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Último (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

GDG Cloud Taipei meetup #50 - Build go kit microservices at kubernetes with ease

  • 1. Build go kit Microservices at Kubernetes with ease
  • 2. HELLO! Cage Chung @CageChung @cage1016 cage.chung@gmail.com GDG Cloud Taipei co-organizer Google Developer Expert (GCP)
  • 4. Gokitistiok8s go kit microservice demo with istio & jaeger at kubernetes 1
  • 5. Gokitistiok8s (3 microservice) Router ◉ HTTP ◉ GRPC Addsvc ◉ sum ◉ concat Foosvc ◉ foo istio (service discovery) Tracing (trace service) Prometheus (monitor) Grafana (monitor) Fluentd (log) Elasticsearch (log) Kibana (log)
  • 8.
  • 9. ├── cmd │ ├── addsvc │ │ └── main.go │ ├── foosvc │ │ └── main.go │ └── router │ └── main.go ├── consul-helm ├── deployments │ ├── docker │ │ ├── Dockerfile │ │ ├── Dockerfile.cleanbuild │ │ └── Dockerfile.debug │ └── helm │ ├── templates │ ├── .helmignore │ ├── Chart.yaml │ └── values.yaml ├── pkg │ ├── addsvc │ │ ├── endpoints │ │ ├── service │ │ └── transports │ ├── foosvc │ │ ├── endpoints │ │ │ ├── endpoints.go │ │ │ ├── middleware.go │ │ │ ├── requests.go │ │ │ └── responses.go │ │ ├── service │ │ │ ├── logging.go │ │ │ └── service.go │ │ └── transports │ │ ├── errors.go │ │ ├── grpc.go │ │ └── http.go │ └── router │ └── transports ├── makefile └── skaffold.yaml
  • 10. $ make rest_sum curl -X "POST" "http://35.187.144.211/api/v1/add/sum" -H 'Content-Type: application/json; charset=utf-8' -d '{ "a": 3, "b": 34}' {"apiVersion":"","data":{"rs":37}} $ make rest_concat curl -X "POST" "http://35.187.144.211/api/v1/add/concat" -H 'Content-Type: application/json; charset=utf-8' -d '{ "a": "3", "b": "34"}' {"apiVersion":"","data":{"rs":"334"}} $ make rest_foo curl -X "POST" "http://35.187.144.211/api/v1/foo/foo" -H 'Content-Type: application/json; charset=utf-8' -d '{"s": "foo"}' {"apiVersion":"","data":{"res":"foo bar"}} $ make grpc_sum grpcurl -plaintext -proto ./pb/addsvc/addsvc.proto -d '{"a": 3, "b":5}' 35.187.144.211:443 pb.Addsvc.Sum { "rs": "8" } $ make grpc_concat grpcurl -plaintext -proto ./pb/addsvc/addsvc.proto -d '{"a": "3", "b":"5"}' 35.187.144.211:443 pb.Addsvc.Concat { "rs": "35" } $ make grpc_foo grpcurl -plaintext -proto ./pb/foosvc/foosvc.proto -d '{"s": "foo"}' 35.187.144.211:443 pb.Foosvc.Foo { "res": "foo bar" }
  • 14. Problem solved 1. Team are blocked on other teams, can’t make progress 2. Product velocity stalled
  • 15. Problem cause 1. Testing becomes really hard 2. Build pipelines 3. Requires dev/ops culture: devs deploy and operate their work 4. Monitoring and instrumentation - tailing logs? 5. Distributed tracing 6. Security
  • 16. Go-kit goals 1. Make Go a first-class citizen for business logic 2. Microservice architecture 3. RPC as the messaging pattern 4. Provide best practices, idioms, examples and patterns Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://www.youtube.com/watch?v=aL6sd4d4hxk
  • 17. Go-kit non-goals 1. Be a turnkey solution 2. Require any specific infrastructure 3. Have opinions about orchestration, configuration, etc. Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://www.youtube.com/watch?v=aL6sd4d4hxk
  • 18. Go HTTP Servers package main import ( "fmt" "net/http" ) func hello(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hello Devfest Taipei 2019") } func main() { http.HandleFunc("/", hello) http.ListenAndServe(":8888", nil) }
  • 19. Add service: service and implement type Addsvc interface { sum(a, b int64) (int64, error) } type SumRequest struct { A int64 `json:"a"` B int64 `json:"b"` } func (s *addService) sum(a, b int64) (int64, error) { return a + b, nil } type addService struct{}
  • 20. Transports: Implement HTTP handler func (s *addService) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: var req SumRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if res, err := s.sum(req.A, req.B); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } else { fmt.Fprint(w, res) } } }
  • 21. main.go func main() { http.ListenAndServe(":8888", &addService{}) } $ go run main.go $ curl -X "POST" "http://localhost:8888" -d '{ "a": 3, "b": 34}' 37 Addservice an HTTP handler, we can pass it to ListenAndServe
  • 22. Logging: try to add logging func (s *addService) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: var req SumRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { code := http.StatusBadRequest http.Error(w, err.Error(), code) log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, code) return } if res, err := s.sum(req.A, req.B); err != nil { code := http.StatusInternalServerError http.Error(w, err.Error(), code) log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, code) return } else { log.Printf("%s: %s %s %d", r.RemoteAddr, r.Method, r.URL, 200) fmt.Fprint(w, res) } }
  • 23. Logging func main() { log.Printf("listening on :8888") log.Fatal(http.ListenAndServe(":8888", &addService{})) } $ go run main.go 2019/11/29 15:24:29 listening on :8888 2019/11/29 15:24:32 [::1]:52200: POST / 200 $ curl -X "POST" "http://localhost:8888" -d '{ "a": 3, "b": 34}' 37
  • 24. Endpoint Endpoint is the fundamental building block of servers and clients.It represents a single RPC method. type Endpoint func(request) (response) type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
  • 25. Add service endpoint Create endpoint by add service constructor and keep add service pure func MakePostSumEndpoint(s addService) endpoint.Endpoint { return func(_ context.Context, request interface{}) (response interface{}, err error) { p := request.(SumRequest) return s.sum(p.A, p.B) } }
  • 26. Endpoint middleware Middleware is a chainable behavior modifier for endpoints. type Middleware func(Endpoint) Endpoint
  • 27. Logging middleware Create endpoint by add service constructor and keep add service pure func loggingMiddleware(next endpoint.Endpoint) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { begin := time.Now() defer func() { log.Printf("request took %s", time.Since(begin)) }() return next(ctx, request) } } s := addService{} var e endpoint.Endpoint e = MakePostSumEndpoint(s) e = loggingMiddleware(e)
  • 28. Http transport Go kit comes with handy HTTP transport. NewServer constructs a new server, which implements http.Handler and wraps the provided endpoint. func NewServer( e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, options ...ServerOption, ) *Server { ... } postSum := httptransport.NewServer(e, decodeHTTPSumRequest, httptransport.EncodeJSONResponse) r := mux.NewRouter() r.Methods(http.MethodPost).Handler(postSum) log.Printf("listening on :8888") log.Fatal(http.ListenAndServe(":8888", r))
  • 29. Design — How is a Go kit microservice modeled? Transport Endpoint Service https://gokit.io/faq/#design-mdash-how-is-a-go-kit-microservice-modeled
  • 30. Go + microservices = Go kit - Speaker Deck - https://speakerdeck.com/peterbourgon/go-plus-microservices-equals-go-kit?slide=78
  • 31. Golang UK Conference 2015 - Peter Bourgon - Go Kit A Toolkit for Microservices - https://youtu.be/aL6sd4d4hxk?t=1022
  • 32. ● Authentication: Basic, casbin, JWT. ● Circuit Breaker: Hystrix, GoBreaker, and HandyBreaker. ● Logging: Provide an interface for structured logging. Recognizes that logs are data. They need context and semantics to be useful for analysis. Supported formats are logfmt and JSON. ● Metrics: Provides uniform interfaces for service instrumentation. Comes with counters, gauges, and histograms. Has adapters for CloudWatch, Prometheus, Graphite, DogStatsD, StatsD, expvar, and more. ● Rate Limit: Uses Go's token bucket implementation. ● Service Discovery: Consul, DNS SRV, etcd, Eureka, ZooKeeper, and more. ● Tracing: OpenCensus, OpenTracing, and Zipkin. ● Transport: AMQP, AWS Lambda, gRPC, HTTP, NATS, Thrift. . ├── auth ├── circuitbreaker ├── cmd ├── endpoint ├── examples ├── log ├── metrics ├── ratelimit ├── sd ├── tracing ├── transport ├── util ├── .build.yml ├── .gitignore ├── .travis.yml
  • 35. “Microservice cause technical problems ~ Service Mesh solve technical problems
  • 36. What Is a Service Mesh? By NGINX 1. Container orchestration framework 2. Services and instances (Kubernetes pods). 3. Sidecar proxy 4. Service discovery 5. Load balancing 6. Encryption 7. Authentication and authorization 8. Support for the circuit breaker pattern What Is a Service Mesh? - NGINX - https://www.nginx.com/blog/what-is-a-service-mesh/
  • 37. The control plane in a service mesh distributes configuration across the sidecar proxies in the data plane What Is a Service Mesh? - NGINX - https://www.nginx.com/blog/what-is-a-service-mesh/
  • 38. kind: Gateway metadata: name: http-gateway spec: selector: istio: ingressgateway servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" kind: VirtualService metadata: name: ingress-http spec: hosts: - "*" gateways: - http-gateway http: - match: - uri: prefix: /api/v1/ rewrite: uri: / route: - destination: host: router port: number: 80 - match: - uri: prefix: / route: - destination: host: website port: number: 80 kind: DestinationRule metadata: name: router spec: host: router trafficPolicy: loadBalancer: simple: RANDOM tls: mode: ISTIO_MUTUAL kind: VirtualService metadata: name: router spec: hosts: - router http: - route: - destination: host: router kind: Deployment metadata: name: router spec: replicas: 1 selector: matchLabels: app: router template: metadata: labels: app: router spec: containers: - env: - name: QS_ADDSVC_URL value: addsvc:8000 - name: QS_FOOSVC_URL value: foosvc:8000 - name: QS_ROUTER_HTTP_PORT value: "8000" - name: QS_ROUTER_LOG_LEVEL value: info - name: QS_ZIPKIN_V2_URL value: http://zipki....spans image: qeekdev/retailbase-router
  • 39. kind: DestinationRule metadata: name: addsvc spec: host: addsvc trafficPolicy: connectionPool: http: http1MaxPendingRequests: 1 maxRequestsPerConnection: 1 tcp: maxConnections: 1 loadBalancer: simple: RANDOM outlierDetection: baseEjectionTime: 3m consecutiveErrors: 1 interval: 1s maxEjectionPercent: 100 tls: mode: ISTIO_MUTUAL kind: Service metadata: name: addsvc spec: ports: - name: http port: 80 protocol: TCP targetPort: 8020 - name: grpc-web-port port: 8000 protocol: TCP targetPort: 8021 selector: app: addsvc kind: Deployment metadata: name: addsvc spec: replicas: 1 selector: matchLabels: app: addsvc template: metadata: labels: app: addsvc spec: containers: - env: - name: QS_..._GRPC_PORT value: "8021" - name: QS_..._HTTP_PORT value: "8020" - name: QS_..._LOG_LEVEL value: info - name: QS_ZIPKIN_V2_URL value: http://zipkin…. image:...
  • 41. Consul vs. Istio Consul Service Mesh实战【转】 - 简书 - https://www.jianshu.com/p/ad970554403d
  • 42. Reference 1. Go + Microservices = Go Kit [I] - Peter Bourgon, Go Kit 2. Go kit 3. https://gokit.io/faq/ 4. cage1016/gokitistio8s 5. cage1016/gk 6. What Is a Service Mesh?
  • 43. Q & A