在當前提倡高可用性的環境下,說明服務的容錯機制相當重要。在服務長期執行的過程中難保沒有錯誤發生,一個服務的錯誤也可能導致一連串的相關服務跟著發生問題,使得整個服務變得可用性低。因此,在istio中提供融斷機制,在服務達到指定的錯誤或條件時進行融斷,阻止流量繼續向發生問題的服務進行流量的發送,這樣可以避免流量卡在服務的時間,即時導向健康的服務。
情境:當我的向服務發出請求收到5xx status code時,將該服務視為不健康,進行融斷
kubectl apply -f samples/sleep/sleep.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: circuit-breaker-healthy
labels:
app: circuit-breaker
spec:
replicas: 1
selector:
matchLabels:
app: circuit-breaker
status: healthy
template:
metadata:
labels:
app: circuit-breaker
status: healthy
spec:
containers:
- name: circuit-breaker-healthy
image: allenku0/healthy-server:latest
ports:
- containerPort: 5000
apiVersion: apps/v1
kind: Deployment
metadata:
name: circuit-breaker-unhealthy
labels:
app: circuit-breaker
spec:
replicas: 1
selector:
matchLabels:
app: circuit-breaker
status: unhealthy
template:
metadata:
labels:
app: circuit-breaker
status: unhealthy
spec:
containers:
- name: circuit-breaker-unhealthy
image: allenku0/simulate-500:latest
ports:
- containerPort: 5000
apiVersion: v1
kind: Service
metadata:
name: circuit-breaker-service
spec:
type: ClusterIP
selector:
app: circuit-breaker
ports:
- protocol: TCP
name: http
port: 5000
targetPort: 5000
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: example-destination
spec:
host: circuit-breaker-service.default.svc.cluster.local
trafficPolicy:
loadBalancer:
simple: LEAST_REQUEST
outlierDetection:
consecutive5xxErrors: 1 # Eject instance after 5 consecutive 5xx errors
interval: 10s # Time between ejection checks
baseEjectionTime: 15s # How long an ejected host remains out of the pool
maxEjectionPercent: 100 # Maximum percentage of hosts that can be ejected
在istio中會將服務加入pool,istio會將流量從該pool中找到服務的接收流量,其中outlierDetection包含:
kubectl exec -it sleep-7656cf8794-rxvs5 -- sh
i=1
while [ $i -le 10 ]; do
curl -s http://circuit-breaker-service:5000/api/circuit_break >> result.txt
i=$((i + 1))
done
可以去cat 看看 result.txt的內容,大概會如:
{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}<!doctype html>
<html lang=en>
<head>
<title>TypeError: Exception() takes no keyword arguments
// Werkzeug Debugger</title>
<link rel="stylesheet" href="?__debugger__=yes&cmd=resource&f=style.css">
...
-->
{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}{"server name": "HEALTHY SERVER"}
從結果可以看到,當服務在第三次接收到5xx status code 就會將該服務逐出pool,讓之後七次的流量都能導向至健康的服務。
以上就可以做到融斷的效果了,此外,融斷的條件也可以進行其他更多的設定,就根據自己的需求做調整囉。
今天就到這邊,我們明天再見!