Skip to content

Service Mesh & the Sidecar Pattern ​

"The network should be transparent to applications. When network and application problems do occur it should be easy to determine the source of the problem." — Envoy documentation, What is Envoy

خلاصه (Summary): Sidecar یک فرایند کمکی است که کنار برنامه و در همان pod اجرا می‌شود؛ service mesh کنار هر workload یک proxy sidecar (یا یک proxy برای هر node) می‌گذارد و بالای همه یک control plane قرار می‌دهد تا mutual TLS، retry، timeout، تقسیم ترافیک، policy و golden metrics از پیکربندی بیایند، نه از کد کتابخانه در هر سرویس. تمرکز (Focus): الگوی sidecar و native sidecarهای Kubernetes، data plane (‏Envoy و linkerd2-proxy) و control plane (‏Istiod، Linkerd، Consul)، xDS، injection و گرفتن ترافیک، meshهای ambient و eBPF، اشیای Istio همراه YAML، معادل‌های Linkerd و Gateway API، retry و circuit breaking در proxy، observability و کاری که برنامه هنوز باید بکند، هزینه‌ها و عملیات، دیباگ با istioctl و رابط admin ‏Envoy، و یک sidecar به زبان Go و یک برنامهٔ Laravel آگاه از mesh همراه تست. هدف یادگیری (Learning goal): تصمیم بگیرید mesh، کتابخانه، فقط gateway یا mesh از نوع ambient/eBPF به سیستم شما می‌خورد؛ routing و retry و timeout و mTLS و policy را بی‌آنکه طوفان retry بسازید پیکربندی کنید؛ برنامه را برای کار پشت proxy درست بنویسید (انتشار header، handlerهای idempotent، readiness)؛ و یک 503 را با ابزار خود proxy ردیابی کنید.

این فصل در گروه Observability & Operations است، بعد از Containers & Kubernetes و پیش از Serverless & Event-Driven Compute. سازوکار و عملیات mesh را این فصل دارد. تصمیم معماری (gateway، BFF و mesh به‌عنوان سبک) در API Gateway، BFF و Service Mesh است؛ خود mutual TLS در Mutual TLS؛ نظریهٔ retry و timeout و breaker در Timeouts, Retries & Jitter و Circuit Breaker؛ tracing و metrics در Observability؛ تزریق خطا در Chaos Engineering؛ شبکهٔ pod در Kubernetes Networking؛ و service discovery در Service Discovery.

نقشهٔ صفحه ​

دنبال چه می‌گردیدکجا بروید
کل صفحه در چهار جدولهمه‌چیز در یک دقیقه
چرا کنار هر برنامه یک proxy می‌گذاریمچرا وجود دارد
Envoy، Istio، Linkerd، ambient، native sidecar: ریشه‌هااز کجا آمده
کانتینر کمکی در همان pod و native sidecarالگوی sidecar، Native sidecar
Envoy، linkerd2-proxy، Istiod، xDSData plane، Control plane و xDS
ترافیک چطور وارد proxy می‌شودInjection و گرفتن ترافیک
ztunnel، waypoint، Cilium، eBPFAmbient و eBPF
mTLS، هویت SPIFFE، PeerAuthenticationmTLS و هویت
VirtualService، DestinationRule، canary، تقسیم ترافیکRouting و تقسیم
retry و timeout در proxyRetry و timeout
circuit breaking و outlier detectionCircuit breaking
mirroring و fault injectionMirroring و خطا
golden metrics، tracing، access logObservability
AuthorizationPolicy و rate limitingPolicy
Gateway، egress gateway، ServiceEntry، Sidecar، multi-clusterGatewayها و محدودسازی
Gateway API، HTTPRoute، GAMMAGateway API
Linkerd، ServiceProfile، ConsulLinkerd و Consul
Kafka، پایگاه‌داده و غیر HTTP از میان meshTCP و protocol sniffing
تأخیر، CPU، حافظه، ارتقا، on-callهزینه‌ها
برنامه باید چه کندرفتار برنامه
پورت‌ها، انواع xDS، پرچم خطاسازوکار
کدGo، Laravel
خرابی‌های واقعی و راه‌حلحل مسئله‌های کلاسیک
mesh یا کتابخانه یا gatewayانتخاب
از مونولیت تا چند clusterدر معماری
اجرا کنیدآزمایشگاه

همه‌چیز در یک دقیقه ​

جزءچیستبه زبان ساده
Sidecarکانتینر دوم در همان podکمک‌کاری که شبکه و دیسک برنامه را شریک است
Data planeproxyهایی که درخواست را می‌برند (Envoy، linkerd2-proxy، ztunnel)جاده‌ها و باجه‌های عوارضی
Control planeIstiod، control plane لینکرد، سرورهای Consulدفتر ترافیک که قوانین را به هر باجه می‌گوید
xDSAPIهای discovery در Envoy (‏LDS، RDS، CDS، EDS، SDS)زبانی که دفتر با آن قانون می‌فرستد
Injectionیک webhook کانتینر proxy را به pod تازه اضافه می‌کندproxy برای شما نصب می‌شود
حالت ambientIstio با ztunnel در هر node و waypoint اختیاری، بدون sidecarیک proxy برای هر ساختمان به‌جای هر واحد
قابلیتچه کسی انجام می‌دهدبا چه چیزی پیکربندی می‌شود
mTLS و هویت workloadproxy + CA در control planePeerAuthentication (Istio)، خودکار (Linkerd)
Routing، canary، تقسیمproxyVirtualService + DestinationRule، HTTPRoute
Retry و timeoutproxy سمت clientفیلدهای retries/timeout در VirtualService، annotationهای Linkerd
Circuit breaking و outlier detectionproxy سمت clientconnectionPool و outlierDetection در DestinationRule
Golden metrics و access logهر دو proxyTelemetry API، قالب access log
Authorizationproxy سمت serverAuthorizationPolicy، Server + AuthorizationPolicy در Linkerd
انتشار traceخود برنامهheader را خودتان کپی کنید
هزینهاندازهٔ معمولکجا درد می‌کند
تأخیردو hop اضافه برای هر فراخوانیtail latency (p99)، زنجیرهٔ فراخوانی‌های زیاد
CPU و حافظهحدود ۰٫۲۰ vCPU و ۶۰ MB برای هر sidecar در ۱۰۰۰ درخواست بر ثانیه (Istio 1.24)podهای کوچک و فراوان
عملیاتcontrol plane، CRDها، ارتقا، گواهی‌هاon-call و پنجرهٔ ارتقا
دیباگیک hop بیشتر که می‌تواند 503 بدهد«تقصیر برنامه است یا proxy؟»
انتخابکِیکِی نه
کتابخانه (Resilience4j، go-kit، Laravel HTTP client)یک یا دو زبان، سرویس کمزبان‌های زیاد و policy یکنواخت
فقط API gatewayدغدغه‌های لبه: auth، rate limit، TLSmTLS و policy بین سرویس‌ها لازم است
mesh با sidecarmTLS یکنواخت، کنترل L7، تیم‌های زیادتیم کوچک، سرویس کم
Ambient / eBPFابتدا امنیت L4، هزینهٔ کمتر برای هر podقابلیت L7 پخته‌ای لازم دارید که بی waypoint ندارید

چرا وجود دارد ​

وقتی برنامه به سرویس‌ها شکسته می‌شود، هر فراخوانی همان کار خسته‌کننده را می‌خواهد: پیدا کردن یک نمونه، رمزگذاری، احراز هویت فراخواننده، timeout، retry، ثبت metric و انتقال trace. اگر این را در کتابخانه بگذاریم، برای هر زبان یک پیاده‌سازی داریم و برای هر اصلاح باید همهٔ سرویس‌ها را دوباره deploy کنیم. اگر در proxy کنار workload بگذاریم، از کد بیرون می‌رود و تبدیل به پیکربندی می‌شود که یک تیم مالکش است.

کتابخانه در برنامهProxy کنار برنامه (mesh)
پشتیبانی از زبانبرای هر زبان یک portهر زبان، یک پیاده‌سازی
تغییر timeoutهر سرویس دوباره deployیک شیء پیکربندی
ارتقای منطقبه‌روزرسانی dependency و deploy همه‌جاproxy را roll کنید (در حالت sidecar هنوز restart pod لازم است)
دامنهٔ خرابیداخل فرایند برنامهفرایند دومی که جدا می‌تواند خراب شود
هزینهCPU کتابخانه در فرایندفرایند و hop و control plane اضافه
دیدهرچه هر تیم ابزارگذاری کندmetric یکنواخت برای همهٔ ترافیک

تصویری از زندگی روزمره: شرکت می‌تواند به همهٔ کارمندان یاد بدهد مهمان را راهنمایی کنند و کارت ورود را کنترل کنند (کتابخانه)، یا کنار در هر دفتر یک نگهبان بگذارد که برای همه یک‌جور کار کند (sidecar). نگهبان یکنواخت و جایگزین‌شدنی است، اما برای هر در حقوق می‌دهید و مهمان یک میز بیشتر رد می‌شود. ambient یعنی یک نگهبان برای هر طبقه، و «waypoint» متخصصی است که فقط برای طبقه‌هایی اضافه می‌کنید که بیش از چک کارت لازم دارند.

سه بدفهمی رایج، از همین اول ​

  • «mesh سرویس‌هایم را مقاوم می‌کند.» ابزار می‌دهد (timeout، retry، circuit breaking). تنظیم بد بار را چند برابر می‌کند؛ برنامه هنوز باید idempotent باشد و fallback داشته باشد.
  • «mesh distributed tracing را مفت می‌دهد.» proxyها span می‌فرستند، اما فقط برنامه می‌تواند traceparent و x-request-id را از درخواست ورودی به فراخوانی‌های خروجی کپی کند. بی‌آن spanها به هم وصل نمی‌شوند.
  • «sidecar-less یعنی بدون proxy.» حالت ambient هم proxy دارد (ztunnel در هر node، waypoint در هر namespace)، فقط داخل podهای شما اجرا نمی‌شود.
Control plane configures; data plane carries the trafficControl plane: Istiodservice discovery + config + CAxDS over gRPC (port 15012)Pod: ordersPod: inventoryapp:8080 plain HTTPEnvoy sidecarin 15006, out 15001Envoy sidecarin 15006, out 15001app:8080 plain HTTPiptables (istio-init or CNI) redirectsall pod traffic through the proxyone network namespace per pod:app and proxy share localhostmTLSencrypted, both sidespresent certificatesxDS pushxDS push+ workload certificates

از کجا آمده ​

مستندات Envoy هدف طراحی و ایدهٔ برون‌فرایندی را صریح می‌گویند: Envoy «is a self contained process that is designed to run alongside every application server»، پس «each application sends and receives messages to and from localhost and is unaware of the network topology»، و یک استقرار برای «Java, C++, Go, PHP, Python, etc.» کار می‌کند (Envoy docs، What is Envoy). Istio از Envoy به‌عنوان data plane در حالت sidecar و از Istiod به‌عنوان control plane استفاده می‌کند؛ Linkerd از proxy ریزِ Rust خودش به نام linkerd2-proxy استفاده می‌کند و می‌گوید «designed specifically for the service mesh use case and is not designed as a general-purpose proxy» (مستندات معماری Linkerd). Cilium، mesh خود را روی eBPF در هسته و یک Envoy در هر node برای L7 ساخته است (مستندات service mesh در Cilium).

Kubernetes خود sidecar را شهروند درجه‌یک کرد: «Kubernetes implements sidecar containers as a special case of init containers; sidecar containers remain running after Pod startup»؛ این قابلیت از v1.28 در دسترس بود، از v1.29 پیش‌فرض فعال شد و از v1.33 پایدار است (مستندات Kubernetes، Sidecar Containers). حالت ambient در Istio proxy درون pod را برمی‌دارد: «ambient mode is often informally referred to as “sidecar-less mesh”» (Istio ambient overview). تاریخ نخستین انتشار Envoy یا Linkerd در صفحه‌هایی که برای این فصل خوانده شد نیامده و عمداً ذکر نشده است.

فهرست مفاهیم ​

هر بلوک به همین ترتیب است: به زبان ساده، باور غلط رایج، تعریف، یک جریان، سناریوی واقعی، اینکه محصولات چگونه ارائه‌اش می‌کنند، و پیکربندی یا راه‌حل.

الگوی sidecar حیاتی ​

به زبان ساده: sidecar فرایند دومی است که کنار برنامه و در همان pod قرار می‌گیرد، پس localhost و volumeها را شریک است و هم‌عمر برنامه است.

بدفهمی رایج: «sidecar همان service mesh است.» sidecar الگوی جاگیری است. log shipper، config reloader، secret fetcher یا وب‌سرور محلی هم sidecar هستند؛ mesh سیستمی است که از proxy sidecarها به‌علاوهٔ control plane ساخته می‌شود.

تعریف: در Kubernetes: «Sidecar containers are the secondary containers that run along with the main application container within the same Pod» که برای «enhance or to extend the functionality of the primary app container» بدون دست‌زدن به کد برنامه به کار می‌روند و «share the same network and storage namespaces with the primary container».

text
     Pod (one network namespace, shared volumes)
1    app container          writes /var/log/app.log      GET localhost:15000/...
2    sidecar: log shipper   tails the same file          ships to the log backend
3    sidecar: config sync   pulls config to /etc/app     app reloads on SIGHUP
4    sidecar: proxy         intercepts app's connections adds mTLS, retries, metrics
5    all four share localhost, volumes and the pod's lifetime

سناریوی واقعی: Fluent Bit که log را دنبال می‌کند؛ Vault Agent که secret را روی یک volume حافظه‌ای می‌نویسد؛ config reloader که یک ConfigMap را می‌پاید؛ Envoy یا linkerd2-proxy که ترافیک را مدیریت می‌کند؛ Cloud SQL proxy که یک port محلی برای پایگاه‌داده می‌دهد.

کار sidecarنمونه محصولچه چیزی را با برنامه شریک است
ProxyEnvoy (Istio)، linkerd2-proxy، Envoy در Consulشبکهٔ localhost
Log shipperFluent Bit، Vectorvolume لاگ
Secret fetcherVault Agent، reloaderهای external-secretsvolume حافظه‌ای
Config reloaderناظر ConfigMapvolume پیکربندی
Local serverNGINX جلوی PHP-FPMشبکهٔ pod
مزیتعیب
هر زبان، بی‌تغییر کدیک فرایند دیگر برای اندازه‌گیری، به‌روزرسانی و پایش
چرخهٔ عمر مشترک، استقرار سادهمنابع به‌ازای هر pod پرداخت می‌شود
جداسازی روشن کد کمک‌کارباگ ترتیب شروع و پایان
رفتار یکنواخت در سرویس‌هاsidecar بد می‌تواند کل pod را بیندازد

راه‌حل / نحوهٔ استفاده: وقتی از sidecar استفاده کنید که کمک‌کار باید شبکه یا فایل‌های برنامه را شریک باشد و دقیقاً به‌اندازهٔ آن زنده بماند؛ اگر نه، Deployment جدا یا DaemonSet. برای sidecar درخواست منابع، readiness probe و نسخه‌ای که خودتان کنترل می‌کنید تعریف کنید.

Native sidecarهای Kubernetes حیاتی ​

به زبان ساده: sidecar را به شکل init container با restartPolicy: Always می‌نویسید؛ Kubernetes اول آن را بالا می‌آورد، زنده نگه می‌دارد و آخر از همه خاموش می‌کند.

بدفهمی رایج: «sidecar فقط یک ردیف دیگر در containers است.» کار می‌کند اما ترتیب ندارد: برنامه ممکن است پیش از آماده‌شدن proxy بالا بیاید (ترافیک به port بسته می‌فرستد) و یک Job هرگز تمام نمی‌شود چون sidecar ادامه می‌دهد.

تعریف: init container با restartPolicy: Always یک init container قابل راه‌اندازی مجدد است، یعنی sidecar در Kubernetes. kubelet وقتی کانتینر بعدی را شروع می‌کند که وضعیت started این sidecar درست شده باشد (فرایند در حال اجرا یا موفقیت startupProbe)؛ نتیجهٔ readinessProbe آن در آماده‌بودن Pod اثر دارد؛ هنگام خاتمه «the kubelet postpones terminating sidecar containers until the main application container has fully stopped» و بعد sidecarها به ترتیب معکوس خاموش می‌شوند. در Job، sidecar مانع تمام‌شدن Job نمی‌شود.

text
     kubelet                       pod: orders
1    start init: sidecar           restartPolicy: Always, startupProbe /ready
2    sidecar startupProbe OK       "started" = true
3    start regular init (if any)   runs to completion, in order
4    start container: app          proxy already listening, no lost first requests
5    SIGTERM                       app stops first
6    app exited -> stop sidecar    proxy still served the app's last outbound calls

سناریوی واقعی: برنامه‌ای که هنگام boot از طریق proxy به پایگاه‌داده وصل می‌شود (بی‌proxy خطا می‌خورد)؛ Job شبانه با log shipper که نباید Job را باز نگه دارد؛ rollout که در آن proxy باید بیشتر از graceful shutdown برنامه زنده بماند. Linkerd می‌گوید: «As of Linkerd 2.20, the proxy is deployed by default as a native sidecar container»؛ Istio گزینهٔ holdApplicationUntilProxyStarts را به‌عنوان راه قدیمی‌تر دارد («delay application startup until the pod proxy is ready»).

گزینهترتیب شروعJob تمام می‌شودترتیب پایان
کانتینر اضافی سادهتضمینی نیستنه (sidecar ادامه می‌دهد)بی‌ترتیب
holdApplicationUntilProxyStarts (Istio)hook شروع برنامه را عقب می‌اندازدبه کار اضافه نیاز داردتخلیه با terminationDrainDuration
Native sidecar (init + restartPolicy: Always)پیش از برنامهبلهبعد از برنامه

راه‌حل / نحوهٔ استفاده:

yaml
# A Deployment whose sidecar is a Kubernetes native sidecar: an init container
# with restartPolicy: Always. It starts before the app, keeps running, and is
# stopped after the app on Pod termination.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders
  labels:
    app: orders
spec:
  replicas: 3
  selector:
    matchLabels:
      app: orders
  template:
    metadata:
      labels:
        app: orders
        version: v1
    spec:
      initContainers:
        - name: sidecar
          image: registry.example.com/platform/sidecar:1.0.0
          restartPolicy: Always # this line turns an init container into a sidecar
          ports:
            - containerPort: 15006 # inbound
            - containerPort: 15090 # metrics
          startupProbe: # the next container starts only when this succeeds
            httpGet:
              path: /ready
              port: 15090
            periodSeconds: 1
            failureThreshold: 30
          readinessProbe: # its result also decides Pod readiness
            httpGet:
              path: /ready
              port: 15090
          resources:
            requests: { cpu: 100m, memory: 64Mi }
            limits: { memory: 128Mi }
      containers:
        - name: app
          image: registry.example.com/shop/orders:2.4.1
          ports:
            - containerPort: 8080
              name: http-web # name prefix http- is how Istio picks the protocol
          readinessProbe:
            httpGet:
              path: /healthz/ready
              port: 8080
          resources:
            requests: { cpu: 250m, memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: orders
spec:
  selector:
    app: orders
  ports:
    - name: http-web
      port: 80
      targetPort: 8080
      appProtocol: http

Data plane: ‏Envoy و linkerd2-proxy حیاتی ​

به زبان ساده: data plane مجموعهٔ proxyهایی است که واقعاً هر درخواست را می‌برند.

بدفهمی رایج: «control plane در مسیر درخواست است.» نیست: istiod یا control plane لینکرد فقط پیکربندی می‌فرستند؛ درخواست فقط به proxyها می‌خورد. اگر control plane بیفتد، proxyهای موجود با آخرین پیکربندی کار می‌کنند؛ فقط نمی‌توانید چیزی را عوض کنید یا گواهی تازه بگیرید.

تعریف: Envoy «an L7 proxy and communication bus» است با زنجیرهٔ فیلتر L3/L4 و لایهٔ فیلتر HTTP در L7، پشتیبانی درجه‌یک از HTTP/2، service discovery، health check فعال و غیرفعال و رابط admin. linkerd2-proxy یک micro-proxy به زبان Rust است با «transparent, zero-config proxying for HTTP, HTTP/2, and arbitrary TCP protocols»، metric خودکار Prometheus، TLS خودکار و load balancing لایهٔ ۷ آگاه از تأخیر. به گفتهٔ Linkerd، proxy خروجی مسئول «service discovery, load balancing, circuit breakers, retries, and timeouts» است و proxy ورودی policy مجوز را اجرا می‌کند.

text
     app -> outbound proxy -> network -> inbound proxy -> app
1    app opens a connection to orders:80 (plain)
2    outbound proxy picks an endpoint (EDS), applies route, timeout, retries
3    outbound proxy opens mTLS to the endpoint's inbound proxy
4    inbound proxy checks identity + AuthorizationPolicy, records metrics
5    inbound proxy forwards plain HTTP to the app on localhost
Proxyزبانچه کسی استفاده می‌کندمنبع پیکربندیدامنه
EnvoyC++Istio، Consul، Cilium (در L7)، Contour، پیاده‌سازی‌های Gateway APIxDS از یک management serverهمه‌منظوره
linkerd2-proxyRustLinkerdgRPC از سرویس destination در Linkerdفقط mesh
ztunnelRustIstio ambientxDS از Istiodفقط L4: mTLS، authn، L4 authz، telemetry
WaypointEnvoyIstio ambientxDS از IstiodL7 برای یک namespace یا سرویس

راه‌حل / نحوهٔ استفاده: proxy را بخشی از SLO پاد بدانید: requests و limits بگذارید، restartهایش را ببینید و port admin آن را بشناسید (Envoy ‏15000، و Prometheus ‏15090 در Istio).

Control plane و xDS حیاتی ​

به زبان ساده: control plane می‌داند چه podهایی هستند و چه قانونی نوشته‌اید، و به هر proxy دقیقاً پیکربندی لازم را می‌فرستد.

بدفهمی رایج: «تغییر پیکربندی همه‌جا فوری می‌شود.» Istio مستند می‌کند که «a configuration change will take some time to propagate to all the sidecars»، در استقرارهای بزرگ چند ثانیه، و اینکه «up to 100 requests may be required for weighted version distribution to be observed».

تعریف: Envoy «discovers its various dynamic resources via the filesystem or by querying one or more management servers. Collectively, these discovery services and their corresponding APIs are referred to as xDS.» انواع منبع: Listener (‏LDS)، RouteConfiguration (‏RDS)، Cluster (‏CDS)، ClusterLoadAssignment (‏EDS) و Secret برای TLS (‏SDS). چهار نوع انتقال وجود دارد: State of the World، Incremental، Aggregated Discovery Service (‏ADS) و Incremental ADS.

text
     Envoy sidecar                         Istiod
1    connect gRPC stream (15012, mTLS)     authenticates the pod identity
2    subscribe CDS, EDS, LDS, RDS, SDS     builds config from Services + CRDs
3                                          pushes Listeners, Routes, Clusters, Endpoints
4    ACK each version                      istioctl proxy-status shows SYNCED
5    kubectl apply VirtualService          Istiod recomputes, pushes deltas, Envoy ACKs
Control planeAPI به proxyCA / هویتنکته
Istio (Istiod)xDS به Envoy و ztunnelCA داخلی، هویت‌های شبیه SPIFFEیک باینری: Pilot، Citadel، injector
Linkerdسرویس‌های gRPC به نام destination و identityسرویس identity، CSR را امضا می‌کندproxy injector یک admission webhook است
Consul service meshxDS به EnvoyCA خود Consul یا Vaultبیرون از Kubernetes هم کار می‌کند
CiliumxDS به Envoy هر node برای L7احراز متقابل مبتنی بر SPIFFEeBPF کار L3/L4 را می‌کند

CPU در Istiod با «the rate of deployment changes»، «the rate of configuration changes» و «the number of proxies connecting to Istiod» بالا می‌رود و به‌صورت افقی مقیاس‌پذیر است؛ «at large scale, configuration scoping is highly recommended» (صفحهٔ performance در Istio). به محدودسازی Sidecar نگاه کنید.

راه‌حل / نحوهٔ استفاده: تأخیر push و proxy-status را زیر نظر بگیرید، پیکربندی را به‌ازای namespace محدود کنید و چند replica از Istiod اجرا کنید.

Injection و گرفتن ترافیک (Traffic Capture) حیاتی ​

به زبان ساده: یک webhook هنگام ساخت pod، proxy را اضافه می‌کند و قوانین iptables کل ترافیک pod را به آن می‌کشانند.

بدفهمی رایج: «injection مجوز خاصی نمی‌خواهد.» مگر Istio CNI plugin را به کار ببرید، کانتینر istio-init به NET_ADMIN و NET_RAW برای iptables نیاز دارد که سطوح baseline و restricted در Pod Security آن را مسدود می‌کنند؛ UID ‏1337 برای proxy رزرو است.

تعریف: Istio از «a mutating webhook admission controller» استفاده می‌کند: به namespace برچسب istio-injection=enabled (یا به pod برچسب sidecar.istio.io/inject: "true") بدهید تا podهای تازه sidecar بگیرند. proxy injector در Linkerd به annotation ‏linkerd.io/inject: enabled واکنش نشان می‌دهد و proxy-init و linkerd-proxy را اضافه می‌کند. گرفتن ترافیک با iptables است: Envoy در Istio روی ۱۵۰۰۶ برای ورودی و ۱۵۰۰۱ برای خروجی گوش می‌دهد؛ linkerd-init در Linkerd همین کار را می‌کند.

text
     kubectl apply deployment             API server           webhook
1    POST pod spec                        calls mutating webhooks
2                                         istio-injection=enabled? -> add istio-proxy (+ istio-init)
3    pod scheduled                        istio-init sets iptables: inbound -> 15006, outbound -> 15001
4    app calls inventory:80               iptables redirect -> Envoy 15001 -> mTLS -> peer 15006
5    existing pods                        NOT changed: restart them to inject
محصولفعال‌سازیگرفتن ترافیکدورزدن
Istioبرچسب namespace ‏istio-injection=enabled؛ برچسب pod ‏sidecar.istio.io/injectiptables در istio-init یا Istio CNItraffic.sidecar.istio.io/excludeOutboundPorts
Linkerdlinkerd.io/inject: enabledlinkerd-init یا Linkerd CNIskip portها (کلاً از proxy رد می‌شوند)
Consulannotation ‏consul.hashicorp.com/connect-injectinit container / CNIاستثناهای transparent proxy

راه‌حل / نحوهٔ استفاده:

yaml
# Pod-level knobs that matter in practice (Istio sidecar mode).
apiVersion: apps/v1
kind: Deployment
metadata:
  name: batch-worker
spec:
  selector:
    matchLabels:
      app: batch-worker
  template:
    metadata:
      labels:
        app: batch-worker
        sidecar.istio.io/inject: "true" # per-pod switch; namespace label istio-injection=enabled is the usual way
      annotations:
        proxy.istio.io/config: |
          holdApplicationUntilProxyStarts: true
          terminationDrainDuration: 20s
        sidecar.istio.io/proxyCPU: 100m
        sidecar.istio.io/proxyCPULimit: 500m # set the limit explicitly when you set the request
        sidecar.istio.io/proxyMemory: 128Mi
        sidecar.istio.io/proxyMemoryLimit: 256Mi
        traffic.sidecar.istio.io/excludeOutboundPorts: "5432" # database traffic bypasses the proxy
    spec:
      containers:
        - name: app
          image: registry.example.com/shop/worker:1.8.0

Ambient و meshهای eBPF مهم ​

به زبان ساده: proxy را از pod بیرون ببرید: یک proxy کوچک برای هر node برای رمزگذاری و هویت، و یک proxy مشترک برای هر namespace فقط برای سرویس‌هایی که قابلیت L7 می‌خواهند.

بدفهمی رایج: «ambient حالا همه‌جا جای sidecar را می‌گیرد.» هر دو حالت در یک mesh کنار هم می‌مانند («pods and workloads using sidecar mode can co-exist within the same mesh as pods that use ambient mode») و routing در L7 هنوز waypoint می‌خواهد.

تعریف: ambient در Istio «splits Istio’s functionality into two distinct layers»: پوشش امن ztunnel (در هر node، Rust، L3/L4: «mTLS, authentication, L4 authorization and telemetry»، تونل از طریق HBONE که پروتکلی مبتنی بر HTTP CONNECT است) و proxyهای waypoint اختیاری (Envoy، خارج از podهای برنامه، «installed, upgraded, and scale independently from applications») برای L7 authorization، telemetry و routing با VirtualService. Cilium service mesh برای «IP, TCP, and UDP» از eBPF و برای «HTTP, gRPC, and DNS» از proxyای مثل Envoy استفاده می‌کند.

text
     client pod A          node X ztunnel        node Y ztunnel        server pod B
1    plain TCP to B        captures, adds mTLS identity of A
2                          HBONE tunnel (mTLS)   verifies A, L4 authz
3    (L7 needed?)  ----->  via waypoint Envoy: routes, retries, L7 authz
4                                                forwards to B, plain
جنبهSidecarفقط ztunnel در ambientAmbient + waypointCilium
محل proxyدر هر podیکی برای هر nodeبرای هر namespace یا سرویسهسته + Envoy هر node
قابلیت L7بلهنهبلهبله (از طریق Envoy)
restart pod برای پذیرشبلهنهنهنه
هزینهٔ اندازه‌گیری‌شده (Istio 1.24، ۱۰۰۰ rps با ۱ KB)۰٫۲۰ vCPU و ۶۰ MB برای هر sidecar۰٫۰۶ vCPU و ۱۲ MB برای هر ztunnel۰٫۲۵ vCPU و ۶۰ MB برای هر waypointدر صفحه‌های خوانده‌شده اندازه‌گیری نشده

راه‌حل / نحوهٔ استفاده: از ambient در L4 شروع کنید (mTLS و L4 authorization برای یک namespace)، waypoint را فقط جایی اضافه کنید که policy یا routing در L7 دارید، و sidecar را برای workloadهایی نگه دارید که جداسازی در سطح pod می‌خواهند. اعداد از صفحهٔ خود Istio برای نسخهٔ 1.24 روی یک cluster آزمایشگاهی CNCF است؛ اعداد شما فرق می‌کند.

Where the proxy livesSidecar modeone Envoy per pod, L4 + L7Istio, Linkerd, Consulapp AEnvoyapp BEnvoy+ per-pod identity and policy- proxy memory and CPU x pods- restart pod to upgrade proxyIstio ambient modeper-node L4, optional L7no proxy in the podapp Aapp Bztunnel (per node)mTLS, identity, L4 authz, HBONEwaypoint (optional)Envoy for L7 routing and policyCilium service mesheBPF in the kernel for L3/L4Envoy per node for L7app Aapp BeBPF datapathload balancing, policy, no proxy hopper-node EnvoyHTTP, gRPC parsing when needed

mTLS و هویت workload (SPIFFE) حیاتی ​

به زبان ساده: هر workload گواهی کوتاه‌عمری می‌گیرد که می‌گوید کیست، و دو proxy در هر اتصال گواهی یکدیگر را وارسی می‌کنند.

بدفهمی رایج: «mTLS یعنی authorization.» mTLS ثابت می‌کند فراخواننده کیست و آن hop را رمز می‌کند. اینکه آن فراخواننده اجازهٔ صدازدن این مسیر را دارد یا نه، policy جداگانه‌ای است (AuthorizationPolicy).

تعریف: Linkerd «automatically enables mutually-authenticated Transport Layer Security (mTLS) for all TCP traffic between meshed pods»؛ سرویس identity «acts as a TLS Certificate Authority that accepts CSRs from proxies and returns signed certificates». مدل هویت در Istio از هویت درجه‌یک سرویس (به سبک SPIFFE، مثلاً cluster.local/ns/shop/sa/checkout) استفاده می‌کند. در Istio، PeerAuthentication حالت‌های PERMISSIVE (هم mTLS و هم متن ساده؛ پیش‌فرض وقتی تنظیم نشده) و STRICT (فقط mTLS) دارد؛ مستندات توصیه می‌کنند هنگام گذار به strict از permissive به‌عنوان مرحلهٔ میانی استفاده شود. handshake روی سیم، گواهی‌ها و چرخش در Mutual TLS و TLS in Practice است.

text
     orders proxy                    inventory proxy
1    ClientHello + SNI               
2                                    ServerHello + certificate (SPIFFE id of inventory)
3    verify id against "inventory"   request client certificate
4    send certificate (id of orders)
5                                    verify; AuthorizationPolicy: principal orders allowed?
6    encrypted request ------------> plain request to app on localhost
جنبهIstioLinkerdنکته
پیش‌فرضPERMISSIVE مگر policy مقدار STRICT بدهدmTLS برای ترافیک TCP در meshed روشن استهر دو ترافیک غیر mesh را بیرون می‌گذارند
ترافیک بدون mTLSدر permissive متن ساده مجاز استpodهای غیر mesh، skip portها، probeهای kubeletبا ابزار بررسی کنید
تنظیمات عمر گواهیتنظیمات CA در Istiodtrust anchor پیش‌فرض بعد از ۳۶۵ روز منقضی می‌شودپیش از انقضا بچرخانید
خرابی رایجDestinationRule بی‌ISTIO_MUTUAL باعث 503 با UF می‌شودmulti-cluster به trust anchor مشترک نیاز دارد

راه‌حل / نحوهٔ استفاده:

yaml
# Strict mTLS for the namespace, then identity-based authorization.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: default
  namespace: shop
spec:
  mtls:
    mode: STRICT # PERMISSIVE accepts plaintext too: use it only while migrating
---
# A health port that the kubelet calls without a mesh certificate.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: orders-health
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  mtls:
    mode: STRICT
  portLevelMtls:
    9090:
      mode: DISABLE
---
# Only the checkout service account may POST to /orders; everything else is
# implicitly denied because an ALLOW policy exists for this workload.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: orders-allow-checkout
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/shop/sa/checkout"] # SPIFFE-style identity
      to:
        - operation:
            methods: ["POST"]
            paths: ["/orders*"]
---
# DENY is evaluated before ALLOW: block a known-bad path for everyone.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: orders-deny-admin
  namespace: shop
spec:
  selector:
    matchLabels:
      app: orders
  action: DENY
  rules:
    - to:
        - operation:
            paths: ["/admin*"]

Traffic management: ‏routing، تقسیم و canary حیاتی ​

به زبان ساده: برای هر درخواست تصمیم می‌گیرید کدام نسخهٔ سرویس آن را بگیرد، بی‌آنکه کد یا Service در Kubernetes را عوض کنید.

بدفهمی رایج: «تقسیم ۹۰/۱۰ یعنی دقیقاً ۹ از هر ۱۰ درخواست.» روی تعداد زیاد درخواست همگرا می‌شود؛ Istio یادآوری می‌کند ممکن است تا ۱۰۰ درخواست لازم باشد تا وزن‌ها دیده شوند.

تعریف: در Istio، VirtualService تعریف می‌کند درخواست به یک host چطور مسیر می‌گیرد (match، وزن، timeout، retry، fault injection، mirroring) و DestinationRule تعریف می‌کند بعد از مسیریابی چه می‌شود: subsetها بر اساس label، load balancing («by default, Istio uses a least requests load balancing policy»)، حالت TLS، connection pool و outlier detection. subset واحد canary است: podهای برچسب‌خورده v1 و v2 پشت یک Service.

text
     client proxy                          rules                    pods
1    GET reviews/ (end-user: qa)           match header qa     ->   v2
2    GET reviews/ (everyone else)          90 -> v1, 10 -> v2  ->   v1 or v2
3    raise to 25, 50, 100 while error rate and p99 stay inside the SLO
4    error rate climbs on v2               set v2 weight 0 (one object, instant rollback)
تکنیکشیءکاربرد
تطبیق headermatch.headers در VirtualServiceتستر داخلی، dark launch
تقسیم وزنیroute[].weightcanary، A/B
Mirrormirror + mirrorPercentageمقایسه بدون اثر روی کاربر
Subsetsubsets در DestinationRuleانتخاب نسخه با label pod
Gateway APIbackendRefs.weight در HTTPRoutecanary قابل‌حمل

راه‌حل / نحوهٔ استفاده:

yaml
# Canary + retries + timeout + circuit breaking + outlier detection for "reviews".
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
    - reviews
  http:
    - match: # internal testers always get v2
        - headers:
            end-user:
              exact: qa
      route:
        - destination:
            host: reviews
            subset: v2
    - route: # everyone else: 90/10 canary
        - destination:
            host: reviews
            subset: v1
          weight: 90
        - destination:
            host: reviews
            subset: v2
          weight: 10
      timeout: 3s # whole request, all attempts
      retries:
        attempts: 2
        perTryTimeout: 1s
        retryOn: gateway-error,connect-failure,refused-stream
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: reviews
spec:
  host: reviews
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL # match the mesh-wide mTLS or requests fail with 503 UF
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50 # beyond this the proxy answers 503 UO
        maxRequestsPerConnection: 0
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50 # never eject more than half of the pool
  subsets:
    - name: v1
      labels:
        version: v1
    - name: v2
      labels:
        version: v2

Retry و timeout در proxy حیاتی ​

به زبان ساده: proxy سمت client مدت محدودی صبر می‌کند و اگر فراخوانی به شکل قابل‌تکرار شکست خورد، دوباره می‌فرستد.

بدفهمی رایج: «retry مقاومت مفت است.» مستندات خود Linkerd: «automatically retrying a request that changes system state each time it is called can be disastrous» و «retries by definition will increase the load on your system».

تعریف: Istio: «The Envoy timeout for HTTP requests is disabled in Istio by default» و «the default retry behavior for HTTP requests is to retry twice before returning the error» با فاصلهٔ «25ms+» که Istio خودش تعیین می‌کند. retries.attempts، perTryTimeout و retryOn (مثلاً gateway-error,connect-failure,refused-stream) برای هر route تنظیم می‌شوند؛ timeout کل درخواست را با retryها می‌پوشاند. Linkerd با annotationهای retry.linkerd.io/http، retry.linkerd.io/limit، retry.linkerd.io/timeout و timeout.linkerd.io/request روی HTTPRoute یا Service تنظیم می‌کند، «on the outbound (client) side»، و از نسخهٔ 2.16 timeout و retry با هم ترکیب می‌شوند. نظریه (backoff، jitter، budget) در Timeouts, Retries & Jitter است.

text
     client proxy (timeout 3s, attempts 2, perTryTimeout 1s)         server
1    attempt 1 ------------------------------------------------>   503 (overloaded)
2    wait 25 ms+ (jittered)
3    attempt 2 ------------------------------------------------>   200
4    whole call took 40 ms; the app saw one success and never knew
5    if attempt 3 would pass 3 s total, the route timeout returns 504 instead
تنظیمIstioLinkerdEnvoy (زیرین)
timeout کلtimeouttimeout.linkerd.io/requesttimeout در route
هر تلاشperTryTimeoutretry.linkerd.io/timeoutper_try_timeout
حداکثر retryattemptsretry.linkerd.io/limitnum_retries
چه چیزی retry شودretryOnretry.linkerd.io/http: 5xx (یا کلاس‌های gRPC)retry_on
Budgetدر VirtualService نیست؛ از حدود circuit breaker استفاده کنیدretry budget در دورهٔ ServiceProfileretry circuit breaker
پیش‌فرض‌هاtimeout خاموش، ۲ retryبدون retry مگر تنظیم شودبسته به پیکربندی

راه‌حل / نحوهٔ استفاده: فقط در یک لایه retry کنید (به تقویت retry نگاه کنید)، endpointهای retryشونده را idempotent کنید و timeout خود برنامه را زیر timeout route نگه دارید.

Circuit breaking و outlier detection مهم ​

به زبان ساده: محدود کنید چقدر به یک نمونه فشار می‌آورید، و ارسال به نمونه‌هایی که مدام خراب می‌شوند را قطع کنید.

بدفهمی رایج: «circuit breaker در mesh همان Resilience4j است.» در Istio، circuit breaking سقف اتصال و درخواست به ازای هر host است (connectionPool) و outlier detection میزبان‌های بد را از pool خارج می‌کند؛ هیچ‌کدام مثل breaker کتابخانه‌ای حالت closed/open/half-open برای هر وابستگی نگه نمی‌دارند. به Circuit Breaker نگاه کنید.

تعریف: Istio: «in a circuit breaker, you set limits for calls to individual hosts within a service, such as the number of concurrent connections or how many times calls to this host have failed». Envoy: «outlier detection and ejection is the process of dynamically determining whether some number of hosts in an upstream cluster are performing unlike the others and removing them from the healthy load balancing set»، که نوعی health check غیرفعال (passive) است. تنظیمات: consecutive5xxErrors، interval، baseEjectionTime، maxEjectionPercent.

text
     proxy pool for reviews: 4 pods                          failures
1    pod-3 returns 5xx x5 in a row                           consecutive5xxErrors reached
2    pod-3 ejected for baseEjectionTime (30 s, grows each time)
3    traffic spreads over pods 1, 2, 4                       maxEjectionPercent keeps >= half in
4    after 30 s pod-3 returns to the pool; one more failure ejects it for longer
حدفیلدوقتی از آن رد شود
اتصال هم‌زمانconnectionPool.tcp.maxConnectionsاتصال تازه صف می‌شود یا شکست می‌خورد
درخواست در انتظارconnectionPool.http.http1MaxPendingRequestsproxy با 503 و پرچم UO جواب می‌دهد
میزبان بدoutlierDetection.consecutive5xxErrorsمیزبان از pool خارج می‌شود
سقف اخراجmaxEjectionPercentبیش از این سهم اخراج نمی‌شود

راه‌حل / نحوهٔ استفاده: همان YAML بخش routing؛ maxEjectionPercent را بگذارید تا قطعی یک وابستگی مشترک کل pool را اخراج نکند.

Mirroring و fault injection مهم ​

به زبان ساده: mirroring یک نسخه از ترافیک زنده را به نسخهٔ جدید می‌فرستد؛ fault injection باعث می‌شود proxy عمداً درخواست را کند یا خراب کند.

بدفهمی رایج: «ترافیک mirror بی‌خطر است.» پاسخ دور ریخته می‌شود، اما یک POST آینه‌شده روی v2 اجرا می‌شود و در هر چیزی که v2 به آن وصل است می‌نویسد.

تعریف: «Mirroring sends a copy of live traffic to a mirrored service. The mirrored traffic happens out of band of the critical request path» (تسک mirroring در Istio). fault injection در Istio دو نوع دارد: تأخیر («timing failures») و abort («crash failures»، کد خطای HTTP یا شکست TCP) در لایهٔ برنامه؛ مستندات traffic management می‌گویند fault injection «can not be combined with retry or timeout configuration on the same virtual service». رویهٔ game day در Chaos Engineering است.

text
     client -> proxy                      v1 (serves)            v2 (shadow)
1    GET /reviews                         ----------------->     200 to the user
2                                         copy of 20% ------->   200 discarded
3    compare v2's latency and errors in the dashboards; the user never sees v2
4    fault: 0.1% of requests get +5 s -> does the caller's timeout fire?

راه‌حل / نحوهٔ استفاده:

yaml
# Two separate experiments, shown as two VirtualServices for two hosts.
# 1) Fault injection: 0.1% of ratings requests get a 5 s delay, 0.05% get a 503.
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
    - ratings
  http:
    - fault:
        delay:
          percentage:
            value: 0.1
          fixedDelay: 5s
        abort:
          percentage:
            value: 0.05
          httpStatus: 503
      route:
        - destination:
            host: ratings
            subset: v1
---
# 2) Mirroring: v1 serves the user, a copy of 20% of the requests goes to v2.
# The mirrored response is discarded; writes would hit v2's database too.
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: httpbin
spec:
  hosts:
    - httpbin
  http:
    - route:
        - destination:
            host: httpbin
            subset: v1
      mirror:
        host: httpbin
        subset: v2
      mirrorPercentage:
        value: 20.0
آزمایشامن برایناامن برای
Mirrorخواندن، فراخوانی idempotent، v2 بی‌حالتنوشتن در storeهای مشترک، فراخوانی صورتحساب
Delay faultتست timeout و retryهمان VirtualService که retry هم دارد
Abort faultتست fallbackproduction بدون کلید بازگشت

Observability: ‏golden metrics، tracing، access log حیاتی ​

به زبان ساده: چون هر درخواست از proxy رد می‌شود، شمار درخواست، خطا و تأخیر هر سرویس را بی‌ابزارگذاری برنامه‌ها می‌گیرید؛ اما وصل‌کردن یک درخواست در چند سرویس هنوز به کمک برنامه نیاز دارد.

بدفهمی رایج: «mesh خودش trace می‌کند.» Istio: «Applications must propagate this information in HTTP headers, so that when proxies send spans, the backend can join them together into a single trace.»

تعریف: Istio metricهایی بر اساس «the four golden signals of monitoring (latency, traffic, errors, and saturation)»، spanهای trace و access log تولید می‌کند؛ به‌طور پیش‌فرض فقط زیرمجموعهٔ کوچکی از آمار Envoy روشن است تا CPU کم بماند. headerهایی که باید رد شوند: traceparent و tracestate در W3C، برای Zipkin مجموعهٔ B3 (‏x-b3-traceid، x-b3-spanid، x-b3-parentspanid، x-b3-sampled، x-b3-flags) و x-request-id که شناسهٔ همبستگی Envoy است. Linkerd و Istio metric برای Prometheus ارائه می‌کنند (در Istio: Envoy روی ۱۵۰۹۰، ادغام‌شده روی ۱۵۰۲۰). خود پشتهٔ observability در Observability است.

text
     client -> A -> B -> C         trace id 0af7...319c
1    client sends no trace         ingress proxy creates traceparent 00-0af7...-aaaa-01
2    A's proxy: span A             app A reads headers
3    app A calls B WITHOUT copying headers
4    B's proxy sees no trace       starts a NEW trace: spans A and B are in different traces
5    app A copies traceparent      B's span becomes a child: one trace
سیگنالمنبعبه کد برنامه نیاز دارد؟
نرخ درخواست، نرخ خطا، histogram تأخیرهر دو proxyنه
Saturation (in-flight، صف)آمار proxyنه
access log برای هر درخواستproxyنه (فعالش کنید)
Span برای هر hopproxyنه
trace یکپارچهproxy + برنامهبله: header را کپی کنید
metricهای کسب‌وکاربرنامهبله

راه‌حل / نحوهٔ استفاده: کد Go و Laravel زیر header را کپی می‌کند؛ کتابخانه‌ای مثل OpenTelemetry هم وقتی ابزارگذاری شود این کار را خودکار انجام می‌دهد.

What happens on each hoporders apphttp://inventoryclient sidecaroutbound proxyserver sidecarinbound proxyinventory app:8080 plain HTTPcopies traceparent andx-request-id to the call(only the app can)load balancing, timeout,retries, circuit breaking,outlier detection, starts mTLSterminates mTLS, checksAuthorizationPolicy,records golden metricsanswers; must be safeto call twice if themesh retriesCost per requesttwo extra proxy hops (client and server sidecar), each a few ms at p99 in Istio's published teststwo TLS sessions reused across requests, so the handshake is paid once per connectionCPU and memory in every pod, plus control-plane pushes on every config changelocalhostmTLS over the pod networklocalhost

Authorization policy و rate limiting مهم ​

به زبان ساده: تصمیم می‌گیرید چه کسی با هویت تأییدشده‌اش چه چیزی را صدا بزند، و در proxy سمت callee اجرا می‌شود.

بدفهمی رایج: «نبود policy یعنی deny.» در Istio اگر برای یک workload هیچ policy از نوع ALLOW نباشد، درخواست مجاز است؛ به محض اینکه یک ALLOW وجود داشته باشد، هر چه match نشود رد می‌شود.

تعریف: actionهای AuthorizationPolicy در Istio ‏CUSTOM، DENY، ALLOW و AUDIT هستند؛ ترتیب ارزیابی: CUSTOM، بعد DENY، بعد ALLOW («if there are no ALLOW policies for the workload, allow the request»). ruleها روی from.source.principals، to.operation (متد و مسیر) و شرط‌های when match می‌کنند. Linkerd از Server (یک port از workload)، AuthorizationPolicy و MeshTLSAuthentication استفاده می‌کند. rate limiting جزو AuthorizationPolicy نیست: Envoy فیلترهای rate limiting محلی و سراسری دارد و جای معمول آن gateway است (Rate Limiting). نظریهٔ policy: Authorization Models.

text
     request from checkout -> orders POST /orders
1    CUSTOM policies?      none
2    DENY /admin*?         no match
3    ALLOW exists?         yes: principal cluster.local/ns/shop/sa/checkout, POST /orders*  -> match -> allowed
4    request from cart -> orders POST /orders: ALLOW exists, no rule matches -> 403 "RBAC: access denied"
کنترلIstioLinkerd
چه کسیprincipals (به سبک SPIFFE)هویت‌ها در MeshTLSAuthentication
چه چیزیoperation با متد و مسیرport در Server؛ HTTPRoute برای مسیر
پیش‌فرضاگر ALLOW نباشد مجازconfig.linkerd.io/default-inbound-policy (پیش‌فرض all-unauthenticated)
Auditaction ‏AUDITpolicy پیش‌فرض audit

راه‌حل / نحوهٔ استفاده: istio-security.yaml بالا؛ برای rate limiting محدودکننده را در gateway یا برنامه بگذارید و mesh را برای هویت و routing نگه دارید.

Gateway، egress، ServiceEntry، محدودسازی Sidecar، multi-cluster مهم ​

به زبان ساده: gatewayها proxyهای لبهٔ mesh هستند؛ ServiceEntry سرویس‌های بیرونی را به mesh معرفی می‌کند؛ منبع Sidecar به proxyها می‌گوید هرچه لازم ندارند نادیده بگیرند.

بدفهمی رایج: «منبع Sidecar ترافیک را مسدود می‌کند.» Istio: «A common misunderstanding is that restricting the configuration amounts to blocking the traffic» و «the sidecar is not able to enforce an outbound traffic restriction»؛ برای آن از egress gateway استفاده کنید.

تعریف: Gateway ورودی «an entry point into the mesh» است؛ egress gateway «a symmetrical concept; it defines exit points from the mesh» است و برای این به کار می‌رود که ترافیک خروجی از nodeهای مخصوص برای policy و پایش بگذرد. ServiceEntry میزبان‌های بیرونی را ثبت می‌کند (MESH_EXTERNAL، resolution: DNS). منبع Sidecar فهرست hosts در egress را محدود می‌کند («to prune out unneeded configuration, to improve scalability of the mesh»). Multi-cluster: مدل‌های استقرار Istio و multi-cluster در Linkerd به اعتماد مشترک نیاز دارند (در Linkerd: trust anchor مشترک) و به gateway میان‌cluster یا شبکهٔ مسطح.

text
     pod -> external API
1    app calls api.payments.example.com:443 (TLS)
2    no ServiceEntry: proxy uses PassthroughCluster, no metrics or policy
3    ServiceEntry + (optional) egress gateway: metrics, timeouts, audit, firewall allow-list at one IP
شیءدامنههدف
Gatewayworkload لبهlistenerهای ورودی، TLS، hostها
VirtualService متصل به Gatewayhostهامسیر درخواست‌های بیرونی به داخل
ServiceEntrymeshثبت سرویس بیرونی یا VM
Egress gatewayworkload لبهیک خروجی کنترل‌شده
Sidecarnamespace یا workloadمحدودکردن پیکربندی ارسالی به proxyها
Multi-clusterمجموعهٔ clusterهااعتماد مشترک، discovery میان‌cluster

راه‌حل / نحوهٔ استفاده:

yaml
# Edge objects: ingress Gateway, ServiceEntry for an external API, and a
# Sidecar resource that limits what every proxy in "shop" has to know.
apiVersion: networking.istio.io/v1
kind: Gateway
metadata:
  name: shop-gateway
  namespace: shop
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 443
        name: https
        protocol: HTTPS
      tls:
        mode: SIMPLE
        credentialName: shop-example-com-cert # a Kubernetes Secret
      hosts:
        - shop.example.com
---
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: shop
  namespace: shop
spec:
  hosts:
    - shop.example.com
  gateways:
    - shop-gateway
  http:
    - route:
        - destination:
            host: orders
            port:
              number: 80
---
# Register an external HTTPS API so it gets metrics, timeouts and policy.
apiVersion: networking.istio.io/v1
kind: ServiceEntry
metadata:
  name: payments-api
  namespace: shop
spec:
  hosts:
    - api.payments.example.com
  location: MESH_EXTERNAL
  resolution: DNS
  ports:
    - number: 443
      name: tls
      protocol: TLS
---
# Configuration scoping: proxies in "shop" only receive config for their own
# namespace, the control namespace and the one external host. Fewer clusters
# and routes per proxy means less memory and faster xDS pushes.
apiVersion: networking.istio.io/v1
kind: Sidecar
metadata:
  name: default
  namespace: shop
spec:
  egress:
    - hosts:
        - "./*"
        - "istio-system/*"

Gateway API و GAMMA مهم ​

به زبان ساده: اشیای استاندارد Kubernetes برای مسیریابی (Gateway، HTTPRoute) دارند زبان مشترک می‌شوند، پس routeها فقط مخصوص Istio یا Linkerd نیستند.

بدفهمی رایج: «HTTPRoute برای mesh به Gateway وصل می‌شود.» برای mesh از طریق parentRefs به یک Service وصل می‌شود.

تعریف: مستندات Gateway API: پشتیبانی GAMMA از service mesh «has been part of the Standard Channel since v1.1.0 and is considered GA»؛ «individual route resources (such as HTTPRoute) are associated directly with Service resources». routeای که در namespace خودِ Service باشد producer route است؛ routeای در namespace دیگر consumer route است و فقط clientهای همان namespace را متأثر می‌کند. وقتی route به Service وصل شود، درخواست‌هایی که با هیچ‌کدام match نشوند رد می‌شوند. مستندات Istio می‌گویند «supports the Kubernetes Gateway API and intends to make it the default API for traffic management in the future»؛ Linkerd هم از HTTPRoute استفاده می‌کند.

text
1    HTTPRoute reviews-canary  parentRefs: Service reviews
2    rule 1: header end-user=qa -> reviews-v2
3    rule 2: weights 90 / 10    -> reviews-v1 / reviews-v2, timeouts.request 3s
4    request matching no rule   -> rejected (routes attached to a Service)

راه‌حل / نحوهٔ استفاده:

yaml
# Gateway API for a mesh (GAMMA): the route attaches to a Service, not a Gateway.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: reviews-canary
  namespace: shop
spec:
  parentRefs:
    - group: ""
      kind: Service
      name: reviews
      port: 80
  rules:
    - matches:
        - headers:
            - name: end-user
              value: qa
      backendRefs:
        - name: reviews-v2
          port: 80
    - backendRefs:
        - name: reviews-v1
          port: 80
          weight: 90
        - name: reviews-v2
          port: 80
          weight: 10
      timeouts:
        request: 3s

معادل‌های Linkerd و Consul تکمیلی ​

به زبان ساده: ایده‌ها یکی است، اشیا فرق دارند؛ Linkerd کوچک و خودکار می‌ماند و Consul به بیرون از Kubernetes هم می‌رسد.

بدفهمی رایج: «ServiceProfile راه فعلی پیکربندی routeهای Linkerd است.» Linkerd می‌گوید پیش از 2.16 retry و timeout با ServiceProfile تنظیم می‌شد؛ هنوز پشتیبانی می‌شود، اما «if a ServiceProfile is defined for a Service, proxies will use the ServiceProfile retry configuration and ignore any retry annotations»، پس این دو را قاطی نکنید.

تعریف: Linkerd: control plane (‏destination، identity، proxy injector) به‌علاوهٔ linkerd2-proxy در هر pod، از 2.20 به‌صورت پیش‌فرض native sidecar؛ retry و timeout با annotation روی HTTPRoute/GRPCRoute؛ retry «do not work with headless services». Consul service mesh sidecarهای Envoy را اجرا می‌کند که Consul servers آن‌ها را هدایت می‌کنند (intention برای authorization) و روی VM و Kubernetes کار می‌کند (این جمله از دانش عمومی است؛ مستندات Consul برای این فصل ذخیره نشد).

نیازIstioLinkerdConsul service mesh
Route و تقسیمVirtualService + DestinationRuleHTTPRoute (با وزن)service router/splitter یا Gateway API
Retry و timeoutفیلدهای VirtualServiceannotation روی HTTPRoute (قدیمی‌تر: ServiceProfile)service defaults
mTLSPeerAuthenticationخودکارخودکار با CA
AuthorizationAuthorizationPolicyServer + AuthorizationPolicy + MeshTLSAuthenticationIntentions
ProxyEnvoylinkerd2-proxyEnvoy

راه‌حل / نحوهٔ استفاده:

yaml
# Linkerd equivalents. Retries and timeouts are annotations on an HTTPRoute
# (Linkerd 2.16+), authorization is Server + AuthorizationPolicy + MeshTLSAuthentication.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: reviews-route
  namespace: shop
  annotations:
    retry.linkerd.io/http: "5xx"
    retry.linkerd.io/limit: "2"
    retry.linkerd.io/timeout: 1s
    timeout.linkerd.io/request: 3s
spec:
  parentRefs:
    - name: reviews
      kind: Service
      group: core
      port: 80
  rules:
    - backendRefs:
        - name: reviews-v1
          port: 80
          weight: 90
        - name: reviews-v2
          port: 80
          weight: 10
---
apiVersion: policy.linkerd.io/v1beta1
kind: Server
metadata:
  name: orders-http
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: orders
  port: http-web
  proxyProtocol: HTTP/1
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata:
  name: checkout-only
  namespace: shop
spec:
  identities:
    - "checkout.shop.serviceaccount.identity.linkerd.cluster.local"
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata:
  name: orders-allow-checkout
  namespace: shop
spec:
  targetRef:
    group: policy.linkerd.io
    kind: Server
    name: orders-http
  requiredAuthenticationRefs:
    - name: checkout-only
      kind: MeshTLSAuthentication
      group: policy.linkerd.io

TCP passthrough، brokerها، پایگاه‌داده، protocol sniffing مهم ​

به زبان ساده: mesh هر TCP را proxy می‌کند، اما کارهای HTTP (routing، retry، metric برای هر route) را فقط وقتی می‌کند که پروتکل را بداند.

بدفهمی رایج: «Kafka یا MySQL را داخل mesh بگذارید تا همان قابلیت‌های HTTP را بگیرید.» Istio: تشخیص خودکار برای HTTP و HTTP/2 کار می‌کند؛ «if the protocol cannot automatically be determined, traffic will be treated as plain TCP traffic» و «server first protocols, such as MySQL, are incompatible with automatic protocol selection». ترافیک غیر TCP (مثل UDP) «will continue to function as normal, without any interception».

تعریف: protocol sniffing بایت‌های اول اتصال را می‌خواند؛ انتخاب صریح با نام port در Service (‏http-web، tcp-kafka) یا appProtocol است که «takes precedence over the port name». مقادیر پشتیبانی‌شده شامل http، http2، https، tcp، tls، grpc است؛ mongo، mysql، redis آزمایشی‌اند. با TCP ساده هنوز mTLS و metric سطح L4 دارید، نه retry یا routing در L7.

text
     producer -> Kafka broker through the mesh
1    port named tcp-kafka (opaque TCP)         proxy does mTLS + L4 bytes/connections only
2    broker advertised.listeners return pod IPs  clients connect to each broker directly; check that the mesh can reach them
3    long-lived connections                     sidecar drain on rollout must outlast them
4    a retry setting on an HTTP route           does not apply: the proxy does not parse Kafka
ترافیکmesh می‌دهدmesh نمی‌دهدتوصیه
HTTP/1.1، HTTP/2، gRPCهمهٔ L7portها را http- و grpc- نام بگذارید
Kafka، AMQP، Redis (RabbitMQ، Kafka، Redis Streams)mTLS، metric سطح L4، policy روی TCPretry، routing، metric برای هر پیامretry سمت client در broker را نگه دارید؛ messaging
PostgreSQL، MySQLرمزگذاری، policy در L4قابلیت L7؛ sniffing در پروتکل server-first شکست می‌خوردport را tcp- نام بگذارید یا از interception کنار بگذارید
UDPهیچintercept نمی‌شودCNI/network policy

راه‌حل / نحوهٔ استفاده: وقتی proxy تأخیر اضافه می‌کند یا پروتکل سیمی را می‌شکند، port پایگاه‌داده را از capture کنار بگذارید (excludeOutboundPorts) و بپذیرید که mTLS و metric آن را از دست می‌دهید. چرا برنامه نباید کورکورانه retry کند در Service Communication آمده است.

هزینهٔ mesh حیاتی ​

به زبان ساده: هر درخواست از دو فرایند بیشتر رد می‌شود و هر pod یکی حمل می‌کند.

بدفهمی رایج: «سربار ناچیز است.» صفحهٔ خود Istio: «telemetry filters (logging, tracing, and metrics) are known to have a moderate impact» و زمان جمع‌آوری Envoy «affects average and tail latencies» چون worker مشغول است.

تعریف: اعداد منتشرشدهٔ Istio 1.24 (mesh با ۱۰۰۰ سرویس، ۲۰۰۰ pod، ۷۰٬۰۰۰ درخواست بر ثانیه؛ بار ۱۰۰۰ rps با payload یک KB): sidecar با ۲ worker thread حدود ۰٫۲۰ vCPU و ۶۰ MB؛ waypoint حدود ۰٫۲۵ vCPU و ۶۰ MB؛ ztunnel حدود ۰٫۰۶ vCPU و ۱۲ MB. نمودارهای تأخیر، حالت بدون mesh، ambient L4، ambient L4+L7 و sidecar را در p90 و p99 روی یک cluster آزمایشگاهی CNCF مقایسه می‌کنند («different hardware will give different values»). مصرف حافظه به پیکربندی‌ای بستگی دارد که proxy نگه می‌دارد.

هزینهاندازه یا شکلکاهش
تأخیر هر hopدو proxy برای هر فراخوانی در sidecar؛ جفت ztunnel در ambienthop کمتر، keep-alive، خاموش‌کردن telemetry بلااستفاده
CPU / حافظهبه‌ازای هر pod، متناسب با تعداد podمحدودسازی Sidecar، ambient برای L4، concurrency را تنظیم نکنید
Control planeبا تغییرات پیکربندی و تعداد proxy بالا می‌رودمحدودسازی پیکربندی، چند replica
درد ارتقاناهم‌نسخگی proxy، restart همهٔ podها در حالت sidecarارتقای canary بر پایهٔ revision، ambient
دیباگ503 ممکن است از proxy بیاید، نه برنامهistioctl، access log، پرچم‌های پاسخ
پیچیدگیCRD، گواهی، trust anchor، webhookکوچک شروع کنید؛ یک تیم مالک باشد
«mesh فقط برای mesh»بدون نیاز مشخص پذیرفته شدهمسئله را اول بنویسید (به انتخاب نگاه کنید)

محاسبهٔ سرانگشتی (استنباط، نه از منبع): ۴۰۰ pod با ۰٫۲۰ vCPU و ۶۰ MB برای هر sidecar در بار مستندشده حدود ۸۰ vCPU و ۲۴ GB حافظه فقط برای data plane می‌شود؛ ambient در L4 برای همان podها در ۴۰ node حدود ۲٫۴ vCPU و ۰٫۵ GB لازم دارد.

راه‌حل / نحوهٔ استفاده: با ترافیک خودتان اندازه بگیرید؛ پیش از پذیرش، تأخیری را که می‌توانید بپردازید عدد بگذارید (Latency Budgets).

کدِ برنامه باید چه رفتاری داشته باشد حیاتی ​

به زبان ساده: mesh شبکه را مدیریت می‌کند؛ کد شما هنوز باید header را رد کند، تکرار درخواست را تحمل کند و readiness را صادقانه گزارش کند.

بدفهمی رایج: «sidecar باعث شد POST من امن برای retry شود.» اگر retry را روی routeهای غیر idempotent تنظیم کرده باشید برعکس شده: handler شما حالا می‌تواند دو بار اجرا شود.

تعریف: چهار وظیفه. (۱) انتشار header (Header Propagation): x-request-id، traceparent، tracestate، baggage (و B3 اگر استفاده می‌شود) را به هر فراخوانی خروجی‌ای که هنگام پاسخ به آن درخواست انجام می‌شود کپی کنید. (۲) Idempotency: هر routeای که mesh ممکن است retry کند باید تکرار را تحمل کند (API Idempotency). (۳) Readiness: liveness و readiness را جدا ارائه کنید؛ Istio probeهای HTTP و TCP و gRPC را بازنویسی می‌کند چون kubelet گواهی mesh ندارد و iptables همهٔ portهای TCP را باز نشان می‌دهد. (۴) Timeout: timeout فراخوانی برنامه را زیر timeout route نگه دارید و داخل pod با HTTP ساده صحبت کنید.

text
     inbound request                         app                           outbound call
1    x-request-id: r1, traceparent: 00-T-S1-01
2                                            middleware stores r1, T       
3                                            business code calls inventory with the context
4                                                                          x-request-id: r1, traceparent: 00-T-S2-01 (new span id)
5    mesh retries the call (503)             handler is idempotent (key k1): second run is a no-op
وظیفهGoLaravel 13
انتشار headerpropagate.Middleware + propagate.TransportPropagateMeshHeaders + ماکروی Http::mesh()
handler idempotentجدول کلید، ON CONFLICT DO NOTHINGهمان SQL، header ‏Idempotency-Key
Readiness/healthz/ready جداReadinessController
HTTP ساده در podhttp.ListenAndServetrustProxies برای 127.0.0.1

راه‌حل / نحوهٔ استفاده: بخش‌های Go و Laravel و SQL زیر را ببینید.

sql
CREATE TABLE processed_requests (
    idempotency_key text PRIMARY KEY,
    request_id      text NOT NULL,
    response_status int  NOT NULL,
    response_body   jsonb NOT NULL,
    created_at      timestamptz NOT NULL DEFAULT now()
);
-- First run inserts one row and does the work; a mesh retry inserts 0 rows (ON CONFLICT DO NOTHING).
INSERT INTO processed_requests (idempotency_key, request_id, response_status, response_body)
VALUES ('pay-7f3a', 'req-9c1', 201, '{"charge_id":"ch_100"}')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key;
sql
-- The mesh may replay a request (retryOn: connect-failure, 503, reset). The
-- first attempt can have succeeded even though the caller saw an error, so
-- the handler must make the second run a no-op. PostgreSQL syntax.
CREATE TABLE processed_requests (
    idempotency_key  text        PRIMARY KEY,
    request_id       text        NOT NULL,          -- x-request-id of the first attempt, for the trace
    response_status  int         NOT NULL,
    response_body    jsonb       NOT NULL,
    created_at       timestamptz NOT NULL DEFAULT now()
);

-- Run in the SAME transaction as the business write.
BEGIN;
INSERT INTO processed_requests (idempotency_key, request_id, response_status, response_body)
VALUES ('pay-7f3a', 'req-9c1', 201, '{"charge_id": "ch_100"}')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key;
-- 0 rows returned => a replay: skip the business write and return the stored row.
-- 1 row returned  => first run: do the write, then COMMIT.
COMMIT;

-- Replay path: return what the first attempt answered.
SELECT response_status, response_body FROM processed_requests WHERE idempotency_key = 'pay-7f3a';

-- Housekeeping: keys only need to live as long as callers (and mesh retries) can replay.
DELETE FROM processed_requests WHERE created_at < now() - interval '24 hours';

سازوکار ​

پورت‌ها و listenerها در sidecar ‏Istio ​

برنامه‌ها نباید از پورت‌هایی که Envoy به کار می‌برد استفاده کنند. از application requirements در Istio:

Portپروتکلکاربردفقط داخل pod
15000TCPEnvoy admin (دستور و عیب‌یابی)بله
15001TCPگرفتن ترافیک خروجی Envoyنه
15006TCPگرفتن ترافیک ورودی Envoyنه
15008HTTP/2تونل HBONE mTLS (ambient)نه
15020HTTPtelemetry ادغام‌شدهٔ Prometheus (agent، Envoy، برنامه)نه
15021HTTPhealth checkنه
15090HTTPtelemetry ‏Prometheus از Envoyنه
15012 (Istiod)gRPCxDS و CA، با TLS و mTLS (production)نه

هر sidecar یک listener روی 0.0.0.0:15006 دارد (iptables همهٔ ترافیک ورودی pod را به آن می‌فرستد) و یکی روی 0.0.0.0:15001 (همهٔ ترافیک خروجی). listener ‏15001 درخواست را به virtual listenerی می‌دهد که با مقصد اصلی بهتر جور باشد، وگرنه به PassthroughCluster که مستقیم وصل می‌شود (پس مقصدهای ناشناخته هم کار می‌کنند، اما بی‌قابلیت‌های mesh). برنامهٔ pod نباید با UID ‏1337 اجرا شود.

xDS با جزئیات ​

منبعAPIچه چیزی حمل می‌کند
ListenerLDSPortها، زنجیرهٔ فیلتر
RouteConfigurationRDSvirtual host، match، timeout، retry
ClusterCDSگروه‌های upstream، load balancing، breaker، outlier detection
ClusterLoadAssignmentEDSIP نمونه‌های یک cluster
SecretSDSگواهی و کلید

انواع انتقال (از سند پروتکل xDS): State of the World با یک stream برای هر نوع منبع؛ Incremental xDS (دلتا، بارگذاری تنبل)؛ Aggregated Discovery Service (‏SotW روی یک stream، برای ترتیب‌دهی صریح)؛ Incremental ADS. streamهای جدا سازگاری نهایی (eventual) می‌دهند؛ ADS وقتی ترتیب لازم باشد (به‌روزرسانی make-before-break) ترتیب را تضمین می‌کند.

خواندن وضعیت همگام‌سازی ​

ستون‌های istioctl proxy-status ‏CDS، LDS، EDS، RDS، ISTIOD و VERSION هستند. SYNCED: Envoy آخرین پیکربندی ارسالی Istiod را تأیید کرده. NOT SENT: Istiod چیزی نفرستاده، معمولاً چون چیزی برای ارسال نبوده. STALE: Istiod به‌روزرسانی فرستاده و تأییدی نگرفته، «a networking issue between Envoy and Istiod or a bug». proxyای که در فهرست نباشد به Istiod وصل نیست.

قواعد انتخاب پروتکل ​

نام port در Service را <protocol>[-<suffix>] بگذارید (مثلاً http-web، tcp-kafka) یا appProtocol را تنظیم کنید که بر نام برتری دارد. بی‌هیچ‌کدام، Istio برای HTTP و HTTP/2 sniff می‌کند و بقیه را TCP می‌گیرد. gatewayها sniff نمی‌کنند: مگر پروتکل مشخص شود، HTTP را به‌صورت HTTP/1.1 جلو می‌برند.

پاسخ‌های خطا و پرچم‌هایی که خواهید دید ​

چه می‌بینیدمعناکجا نگاه کنید
503 با پرچم NRroute تنظیم نشدهDestinationRule، VirtualService، نام port در Service
503 با پرچم UOupstream overflow، circuit breaker فعال شدconnectionPool در DestinationRule
503 با پرچم UFاتصال به upstream برقرار نشدناسازگاری حالت mTLS (‏tls.mode در DestinationRule)، peer پایین است
503 با پرچم UCقطع اتصال upstreamheadless service از طریق PassthroughCluster، برنامه اتصال را بست
503 با UH و «no healthy upstream»نمونهٔ سالمی در pool نیستاخراج با outlier detection، podی آماده نیست (نام پرچم از فهرست Envoy است، ذخیره نشده)
504 با UT و «upstream request timeout»timeout در route یا برای هر تلاش فعال شدtimeout، perTryTimeout، تأخیر برنامه (نام پرچم از فهرست Envoy است، ذخیره نشده)
403 با «RBAC: access denied»AuthorizationPolicy رد کردترتیب policy، kubectl get authorizationpolicy -A
headerهای l5d-* در Linkerd نادیده می‌شوندpolicy برای هر درخواست غیرفعال استflag نصب --allow-l5d-request-headers؛ هرگز برای clientهای غیرقابل‌اعتماد روشنش نکنید

Istio یادآوری می‌کند پرچم‌های پاسخ در access log پیش‌فرض «after the response code» می‌آیند؛ در قالب سفارشی %RESPONSE_FLAGS% را بگذارید.

دستورهای دیباگ ​

text
$ istioctl proxy-status                              # who is connected, which config is SYNCED
$ istioctl proxy-config listeners orders-7d9 -n shop # 15001 / 15006 and virtual listeners
$ istioctl proxy-config routes    orders-7d9 -n shop # RDS: matches, timeouts, retries
$ istioctl proxy-config clusters  orders-7d9 -n shop # CDS: outbound|80||inventory.shop.svc...
$ istioctl proxy-config endpoints orders-7d9 -n shop # EDS: which IPs, healthy or not
$ kubectl logs orders-7d9 -c istio-proxy -n shop     # access log with response flags
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s localhost:15000/config_dump   # Envoy admin
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s localhost:15000/stats | grep upstream_rq_retry
$ kubectl exec orders-7d9 -c istio-proxy -- curl -s -X POST 'localhost:15000/logging?level=debug'

رابط admin در Envoy «allows destructive operations to be performed» و «potentially exposes private information»، پس آن را روی localhost نگه دارید (Istio پورت 15000 را فقط داخل pod می‌گذارد).

Go ​

ماژول Go با نام academy/service-mesh-sidecar سه بسته و دو فرمان دارد: sidecar (یک proxy کمینه)، propagate (سمت برنامه) و cmd/lab و cmd/sidecar. همه چیز کتابخانهٔ استاندارد است.

Before ​

برنامه‌ای که تنها کار می‌کند اما trace را رها می‌کند، در حلقه‌ای بی‌حد retry می‌کند و یک probe برای همه‌چیز دارد:

go
// Before: an app that works alone but is invisible to the mesh.
// It drops the headers the sidecar needs to join spans into one trace,
// retries on its own with no limit, and has no readiness separate from liveness.
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
		// New outbound request: nothing from the inbound request is copied.
		// The sidecar sees an unrelated trace for every hop.
		var body []byte
		var err error
		for attempt := 0; attempt < 10; attempt++ { // fixed, unbounded-ish retry loop
			resp, e := http.Get("http://inventory:8080/stock")
			if e != nil {
				err = e
				continue
			}
			body, err = io.ReadAll(resp.Body)
			resp.Body.Close()
			break
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadGateway)
			return
		}
		fmt.Fprintf(w, "stock: %s\n", body)
	})

	// One endpoint for everything: the kubelet probe says "ready" even when
	// the database is down, so traffic keeps arriving.
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	log.Fatal(http.ListenAndServe(":8080", mux))
}

After ​

خود sidecar. یک listener محلی که با timeout کل، timeout برای هر تلاش، retry فقط برای درخواست‌های idempotent (یا دارای Idempotency-Key)، budget برای retry، golden metrics و تزریق header به برنامه می‌فرستد. بر پایهٔ httputil.ReverseProxy با Rewrite (جانشین پشتیبانی‌شدهٔ Director) و یک RoundTripper که retry می‌کند ساخته شده است.

go
// Package sidecar is a minimal sidecar-style proxy: a local listener that
// forwards to the application in the same pod, with a total timeout, per-try
// timeouts, budgeted retries, golden-signal metrics and header propagation.
// It shows the mechanics; production meshes use Envoy or linkerd2-proxy.
package sidecar

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"time"
)

// Config describes one sidecar instance.
type Config struct {
	Target        *url.URL      // the application, usually http://127.0.0.1:8080
	Timeout       time.Duration // whole request, all attempts (Envoy route timeout)
	PerTryTimeout time.Duration // one attempt (Envoy per_try_timeout)
	MaxRetries    int
	RetryRatio    float64 // retries allowed per request, e.g. 0.2
	Backoff       func(n int) time.Duration
	Transport     http.RoundTripper // nil: http.DefaultTransport
}

// Proxy is the sidecar: Handler serves traffic, Stats feeds the metrics port.
type Proxy struct {
	Handler http.Handler
	Stats   *Stats
}

// New builds a Proxy. It never modifies the application; it only sits in front of it.
func New(cfg Config) *Proxy {
	stats := &Stats{}
	rt := &RetryTransport{
		Base:          cfg.Transport,
		PerTryTimeout: cfg.PerTryTimeout,
		MaxRetries:    cfg.MaxRetries,
		Budget:        NewBudget(cfg.RetryRatio, 10),
		Stats:         stats,
		Backoff:       cfg.Backoff,
	}
	rp := &httputil.ReverseProxy{
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(cfg.Target)
			pr.Out.Host = pr.In.Host // keep the original authority, like a transparent proxy
			pr.SetXForwarded()
			propagate(pr.In, pr.Out)
		},
		Transport: rt,
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			// Same texts Envoy writes, so dashboards and tests look familiar.
			switch {
			case errors.Is(err, context.DeadlineExceeded), isTimeout(err):
				stats.Timeouts.Add(1)
				http.Error(w, "upstream request timeout", http.StatusGatewayTimeout)
			case errors.Is(err, errBodyTooLarge):
				http.Error(w, "request body too large to retry", http.StatusRequestEntityTooLarge)
			default:
				http.Error(w, "upstream connect error or disconnect/reset before headers", http.StatusServiceUnavailable)
			}
		},
	}
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		stats.Requests.Add(1)
		stats.InFlight.Add(1)
		defer func() {
			stats.InFlight.Add(-1)
			stats.Observe(time.Since(start))
		}()
		if cfg.Timeout > 0 {
			ctx, cancel := context.WithTimeout(r.Context(), cfg.Timeout)
			defer cancel()
			r = r.WithContext(ctx)
		}
		sw := &statusWriter{ResponseWriter: w}
		rp.ServeHTTP(sw, r)
		if sw.status >= 500 {
			stats.Responses5xx.Add(1)
		}
	})
	return &Proxy{Handler: h, Stats: stats}
}

// Admin returns the metrics and readiness handler for the sidecar's own port.
func (p *Proxy) Admin() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("/stats/prometheus", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; version=0.0.4")
		p.Stats.WritePrometheus(w)
	})
	mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
	return mux
}

// propagate makes sure the application sees x-request-id and a traceparent.
// An inbound traceparent gets a new span id (this hop is a span of its own);
// without one the sidecar starts a trace, which is what an ingress proxy does.
func propagate(in, out *http.Request) {
	if in.Header.Get("x-request-id") == "" {
		out.Header.Set("x-request-id", randHex(16))
	}
	if tp := childTraceparent(in.Header.Get("traceparent")); tp != "" {
		out.Header.Set("traceparent", tp)
	} else {
		out.Header.Set("traceparent", "00-"+randHex(16)+"-"+randHex(8)+"-01")
	}
}

func childTraceparent(tp string) string {
	p := strings.Split(tp, "-")
	if len(p) != 4 || p[0] != "00" || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
		return ""
	}
	return strings.Join([]string{"00", p[1], randHex(8), p[3]}, "-")
}

func randHex(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}

func isTimeout(err error) bool {
	var ne net.Error
	return errors.As(err, &ne) && ne.Timeout()
}

type statusWriter struct {
	http.ResponseWriter
	status int
}

func (s *statusWriter) WriteHeader(code int) {
	if s.status == 0 {
		s.status = code
	}
	s.ResponseWriter.WriteHeader(code)
}

func (s *statusWriter) Write(b []byte) (int, error) {
	if s.status == 0 {
		s.status = http.StatusOK
	}
	return s.ResponseWriter.Write(b)
}

// Unwrap lets http.ResponseController reach the real writer (flushing, deadlines).
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
go
package sidecar

import (
	"bytes"
	"context"
	"io"
	"math/rand/v2"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

// maxBuffered is the largest request body the proxy buffers so it can replay it.
// Bigger bodies are sent once and never retried (Envoy has a similar buffer limit).
const maxBuffered = 1 << 20

// RetryTransport is the client half of a sidecar: it sends the request to the
// local application with a per-try timeout and retries only what is safe.
type RetryTransport struct {
	Base          http.RoundTripper
	PerTryTimeout time.Duration
	MaxRetries    int // retries after the first attempt
	Budget        *Budget
	Stats         *Stats
	// Backoff returns the pause before retry number n (1-based). Nil means
	// full jitter over 25ms * 2^(n-1), the same floor Istio documents (25ms+).
	Backoff func(n int) time.Duration
}

// Retriable says whether a result deserves another attempt: a connection
// error, or 502/503/504 (Envoy's gateway-error class).
func Retriable(status int, err error) bool {
	if err != nil {
		return true
	}
	return status == http.StatusBadGateway || status == http.StatusServiceUnavailable || status == http.StatusGatewayTimeout
}

// Idempotent says whether replaying the request cannot do harm: a safe or
// idempotent method (RFC 9110), or a request that carries an Idempotency-Key.
func Idempotent(r *http.Request) bool {
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
		return true
	}
	return r.Header.Get("Idempotency-Key") != ""
}

func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	var body []byte
	canReplay := Idempotent(req)
	if req.Body != nil && req.Body != http.NoBody {
		b, err := io.ReadAll(io.LimitReader(req.Body, maxBuffered+1))
		req.Body.Close()
		if err != nil {
			return nil, err
		}
		if len(b) > maxBuffered {
			return nil, errBodyTooLarge // read bytes are gone, so the request cannot even be sent once
		}
		body = b
	}
	if t.Budget != nil {
		t.Budget.Deposit()
	}
	for attempt := 0; ; attempt++ {
		ctx, cancel := context.WithCancel(req.Context())
		var timer *time.Timer
		var fired atomic.Bool
		if t.PerTryTimeout > 0 {
			timer = time.AfterFunc(t.PerTryTimeout, func() { fired.Store(true); cancel() })
		}
		out := req.Clone(ctx)
		if body != nil {
			out.Body = io.NopCloser(bytes.NewReader(body))
			out.ContentLength = int64(len(body))
		}
		out.Header.Set("x-sidecar-attempt-count", strconv.Itoa(attempt+1))
		resp, err := base.RoundTrip(out)
		if err != nil && fired.Load() {
			err = context.DeadlineExceeded // our own per-try timer, not a client cancel
		}

		status := 0
		if resp != nil {
			status = resp.StatusCode
		}
		last := attempt >= t.MaxRetries || !canReplay || !Retriable(status, err) || req.Context().Err() != nil
		if !last && t.Budget != nil && !t.Budget.Withdraw() {
			if t.Stats != nil {
				t.Stats.RetriesDenied.Add(1)
			}
			last = true
		}
		if last {
			if err != nil {
				cancel()
				if timer != nil {
					timer.Stop()
				}
				return nil, err
			}
			resp.Body = &cancelOnClose{ReadCloser: resp.Body, cancel: cancel, timer: timer}
			return resp, nil
		}
		// Retry: drop this attempt completely before sleeping.
		if resp != nil {
			io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
			resp.Body.Close()
		}
		cancel()
		if timer != nil {
			timer.Stop()
		}
		if t.Stats != nil {
			t.Stats.Retries.Add(1)
		}
		select {
		case <-time.After(t.backoff(attempt + 1)):
		case <-req.Context().Done():
			return nil, req.Context().Err()
		}
	}
}

func (t *RetryTransport) backoff(n int) time.Duration {
	if t.Backoff != nil {
		return t.Backoff(n)
	}
	ceil := 25 * time.Millisecond << (n - 1)
	return time.Duration(rand.Int64N(int64(ceil)) + 1)
}

type cancelOnClose struct {
	io.ReadCloser
	cancel context.CancelFunc
	timer  *time.Timer
}

func (c *cancelOnClose) Close() error {
	err := c.ReadCloser.Close()
	if c.timer != nil {
		c.timer.Stop()
	}
	c.cancel()
	return err
}
go
package sidecar

import "sync"

// Budget limits retries to a fraction of the traffic, like Envoy's retry
// budget or Linkerd's retry budget: every first attempt earns Ratio tokens
// (up to Max) and every retry spends one. During a full outage the budget
// drains and retries stop, so the mesh cannot multiply the load.
type Budget struct {
	mu     sync.Mutex
	tokens float64
	Ratio  float64
	Max    float64
}

// NewBudget returns a budget that allows about ratio retries per request.
func NewBudget(ratio, max float64) *Budget {
	return &Budget{Ratio: ratio, Max: max, tokens: max}
}

// Deposit is called once per first attempt.
func (b *Budget) Deposit() {
	b.mu.Lock()
	b.tokens += b.Ratio
	if b.tokens > b.Max {
		b.tokens = b.Max
	}
	b.mu.Unlock()
}

// Withdraw reports whether a retry may be sent.
func (b *Budget) Withdraw() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens < 1 {
		return false
	}
	b.tokens--
	return true
}
go
package sidecar

import (
	"fmt"
	"io"
	"sync/atomic"
	"time"
)

// Upper bounds of the latency buckets in milliseconds (the last bucket is +Inf).
var bucketsMs = []int64{5, 10, 25, 50, 100, 250, 500, 1000}

// Stats holds the four golden signals a mesh proxy gives for free:
// latency, traffic, errors and saturation (in-flight requests).
type Stats struct {
	Requests      atomic.Int64 // traffic: requests accepted
	Responses5xx  atomic.Int64 // errors: final responses with status >= 500
	Retries       atomic.Int64 // extra attempts sent upstream
	RetriesDenied atomic.Int64 // retries refused by the budget
	Timeouts      atomic.Int64 // requests ended by a timeout
	InFlight      atomic.Int64 // saturation: requests being served now
	latency       [9]atomic.Int64
	latencySumMs  atomic.Int64
}

// Observe records one finished request.
func (s *Stats) Observe(d time.Duration) {
	ms := d.Milliseconds()
	i := 0
	for i < len(bucketsMs) && ms > bucketsMs[i] {
		i++
	}
	s.latency[i].Add(1)
	s.latencySumMs.Add(ms)
}

// WritePrometheus writes the counters in the Prometheus text format, the same
// shape a real sidecar exposes on its metrics port (Envoy: 15090, Istio agent: 15020).
func (s *Stats) WritePrometheus(w io.Writer) {
	fmt.Fprintf(w, "sidecar_requests_total %d\n", s.Requests.Load())
	fmt.Fprintf(w, "sidecar_responses_5xx_total %d\n", s.Responses5xx.Load())
	fmt.Fprintf(w, "sidecar_retries_total %d\n", s.Retries.Load())
	fmt.Fprintf(w, "sidecar_retries_denied_total %d\n", s.RetriesDenied.Load())
	fmt.Fprintf(w, "sidecar_timeouts_total %d\n", s.Timeouts.Load())
	fmt.Fprintf(w, "sidecar_in_flight %d\n", s.InFlight.Load())
	var cum int64
	for i, ub := range bucketsMs {
		cum += s.latency[i].Load()
		fmt.Fprintf(w, "sidecar_request_duration_ms_bucket{le=\"%d\"} %d\n", ub, cum)
	}
	cum += s.latency[len(bucketsMs)].Load()
	fmt.Fprintf(w, "sidecar_request_duration_ms_bucket{le=\"+Inf\"} %d\n", cum)
	fmt.Fprintf(w, "sidecar_request_duration_ms_sum %d\n", s.latencySumMs.Load())
	fmt.Fprintf(w, "sidecar_request_duration_ms_count %d\n", cum)
}

تست‌های sidecar این‌ها را پوشش می‌دهند: GET تا موفقیت retry می‌شود، POST یک بار فرستاده می‌شود، POST با Idempotency-Key با همان body دوباره ارسال می‌شود، budget تقویت retry را سقف می‌زند، timeout برای هر تلاش، timeout کل که 504 می‌دهد، خطای اتصال که 503 می‌دهد، تزریق header و متن metricها.

go
package sidecar

import (
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

func noBackoff(int) time.Duration { return 0 }

func newProxy(t *testing.T, app http.Handler, mod func(*Config)) (*Proxy, *httptest.Server) {
	t.Helper()
	upstream := httptest.NewServer(app)
	t.Cleanup(upstream.Close)
	u, _ := url.Parse(upstream.URL)
	cfg := Config{Target: u, Timeout: 2 * time.Second, PerTryTimeout: 300 * time.Millisecond,
		MaxRetries: 2, RetryRatio: 1, Backoff: noBackoff}
	if mod != nil {
		mod(&cfg)
	}
	p := New(cfg)
	front := httptest.NewServer(p.Handler)
	t.Cleanup(front.Close)
	return p, front
}

func do(t *testing.T, method, url string, hdr map[string]string) (int, string) {
	t.Helper()
	req, _ := http.NewRequest(method, url, strings.NewReader("payload"))
	for k, v := range hdr {
		req.Header.Set(k, v)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, string(b)
}

// failFirst answers 503 for the first n calls, then 200.
func failFirst(n int32, calls *atomic.Int32) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if calls.Add(1) <= n {
			http.Error(w, "boom", http.StatusServiceUnavailable)
			return
		}
		io.Copy(io.Discard, r.Body)
		w.Write([]byte("ok"))
	})
}

func TestGETIsRetriedUntilSuccess(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(2, &calls), nil)
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != 200 || body != "ok" || calls.Load() != 3 {
		t.Fatalf("code=%d body=%q calls=%d", code, body, calls.Load())
	}
	if p.Stats.Retries.Load() != 2 {
		t.Errorf("retries = %d, want 2", p.Stats.Retries.Load())
	}
}

func TestPOSTWithoutKeyIsNeverRetried(t *testing.T) {
	var calls atomic.Int32
	_, front := newProxy(t, failFirst(5, &calls), nil)
	code, _ := do(t, http.MethodPost, front.URL, nil)
	if code != 503 || calls.Load() != 1 {
		t.Fatalf("POST must be sent once: code=%d calls=%d", code, calls.Load())
	}
}

func TestPOSTWithIdempotencyKeyIsRetriedWithSameBody(t *testing.T) {
	var calls atomic.Int32
	var bodies []string
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, _ := io.ReadAll(r.Body)
		bodies = append(bodies, string(b))
		if calls.Add(1) == 1 {
			http.Error(w, "boom", 503)
			return
		}
		w.Write([]byte("ok"))
	})
	_, front := newProxy(t, app, nil)
	code, _ := do(t, http.MethodPost, front.URL, map[string]string{"Idempotency-Key": "k1"})
	if code != 200 || len(bodies) != 2 || bodies[0] != "payload" || bodies[1] != "payload" {
		t.Fatalf("code=%d bodies=%v", code, bodies)
	}
}

func TestRetryBudgetStopsAmplification(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(1<<20, &calls), func(c *Config) {
		c.RetryRatio = 0.1 // one retry per ten requests once the initial tokens are spent
		c.MaxRetries = 3
	})
	const n = 100
	for i := 0; i < n; i++ {
		do(t, http.MethodGet, front.URL, nil)
	}
	// 100 first attempts + at most 10 initial tokens + 100*0.1 earned = 120 calls.
	if got := calls.Load(); got > 125 {
		t.Fatalf("budget did not cap retries: %d upstream calls for %d requests", got, n)
	}
	if p.Stats.RetriesDenied.Load() == 0 {
		t.Error("expected denied retries to be counted")
	}
}

func TestPerTryTimeoutRetriesASlowAttempt(t *testing.T) {
	var calls atomic.Int32
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if calls.Add(1) == 1 {
			time.Sleep(400 * time.Millisecond) // longer than the 300 ms per-try timeout
		}
		w.Write([]byte("ok"))
	})
	_, front := newProxy(t, app, nil)
	code, _ := do(t, http.MethodGet, front.URL, nil)
	if code != 200 || calls.Load() != 2 {
		t.Fatalf("code=%d calls=%d", code, calls.Load())
	}
}

func TestTotalTimeoutGives504(t *testing.T) {
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(300 * time.Millisecond) })
	p, front := newProxy(t, app, func(c *Config) {
		c.Timeout = 100 * time.Millisecond
		c.PerTryTimeout = 0
	})
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != http.StatusGatewayTimeout || !strings.Contains(body, "upstream request timeout") {
		t.Fatalf("code=%d body=%q", code, body)
	}
	if p.Stats.Timeouts.Load() != 1 || p.Stats.Responses5xx.Load() != 1 {
		t.Errorf("stats: timeouts=%d 5xx=%d", p.Stats.Timeouts.Load(), p.Stats.Responses5xx.Load())
	}
}

func TestConnectErrorGives503(t *testing.T) {
	u, _ := url.Parse("http://127.0.0.1:1") // nothing listens on port 1
	p := New(Config{Target: u, Timeout: time.Second, MaxRetries: 1, RetryRatio: 1, Backoff: noBackoff})
	front := httptest.NewServer(p.Handler)
	defer front.Close()
	code, body := do(t, http.MethodGet, front.URL, nil)
	if code != 503 || !strings.Contains(body, "upstream connect error") {
		t.Fatalf("code=%d body=%q", code, body)
	}
}

func TestHeadersAreInjectedAndForwarded(t *testing.T) {
	var got http.Header
	app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got = r.Header.Clone() })
	_, front := newProxy(t, app, nil)

	do(t, http.MethodGet, front.URL, nil)
	if len(got.Get("x-request-id")) != 32 || !strings.HasPrefix(got.Get("traceparent"), "00-") || got.Get("x-sidecar-attempt-count") != "1" {
		t.Errorf("sidecar must start request id and trace: %v", got)
	}

	do(t, http.MethodGet, front.URL, map[string]string{
		"x-request-id": "abc",
		"traceparent":  "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
	})
	if got.Get("x-request-id") != "abc" ||
		!strings.HasPrefix(got.Get("traceparent"), "00-0af7651916cd43dd8448eb211c80319c-") ||
		strings.Contains(got.Get("traceparent"), "b7ad6b7169203331") {
		t.Errorf("existing ids must be kept, span id renewed: %v", got)
	}
}

func TestMetricsAreExposed(t *testing.T) {
	var calls atomic.Int32
	p, front := newProxy(t, failFirst(1, &calls), nil)
	do(t, http.MethodGet, front.URL, nil)
	rec := httptest.NewRecorder()
	p.Admin().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/stats/prometheus", nil))
	out := rec.Body.String()
	for _, want := range []string{"sidecar_requests_total 1", "sidecar_retries_total 1", "sidecar_in_flight 0",
		`sidecar_request_duration_ms_bucket{le="+Inf"} 1`} {
		if !strings.Contains(out, want) {
			t.Errorf("metrics missing %q in:\n%s", want, out)
		}
	}
}

سمت برنامه. middleware مقدار x-request-id، traceparent، tracestate و baggage را در context درخواست نگه می‌دارد؛ یک RoundTripper آن‌ها را با span id تازه روی هر درخواست خروجی می‌گذارد.

go
// Package propagate is the application side of a service mesh: the proxy can
// emit spans, but only the app can carry trace headers from an inbound request
// to the outbound calls it makes while serving it.
package propagate

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"net/http"
	"strings"
)

// Headers the mesh needs the app to forward. traceparent and tracestate are
// the W3C Trace Context headers; x-request-id is Envoy's request correlation id.
var Forwarded = []string{"x-request-id", "traceparent", "tracestate", "baggage"}

type ctxKey struct{}

// Carrier holds the header values of one inbound request.
type Carrier map[string]string

// FromContext returns the carrier stored by Middleware (nil if absent).
func FromContext(ctx context.Context) Carrier {
	c, _ := ctx.Value(ctxKey{}).(Carrier)
	return c
}

// Middleware copies the forwarded headers into the request context. A missing
// x-request-id is created so that logs of this service can still be joined.
func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c := Carrier{}
		for _, h := range Forwarded {
			if v := r.Header.Get(h); v != "" {
				c[h] = v
			}
		}
		if c["x-request-id"] == "" {
			c["x-request-id"] = randHex(16)
		}
		w.Header().Set("x-request-id", c["x-request-id"])
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, c)))
	})
}

// Transport stamps the carrier of the request's context onto every outbound
// request. traceparent gets a fresh span id (a child span) with the same
// trace id, which is what a tracing backend needs to build the tree.
type Transport struct{ Base http.RoundTripper }

func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) {
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	c := FromContext(r.Context())
	if len(c) == 0 {
		return base.RoundTrip(r)
	}
	r2 := r.Clone(r.Context()) // never mutate the caller's request
	for _, h := range Forwarded {
		if v, ok := c[h]; ok && r2.Header.Get(h) == "" {
			r2.Header.Set(h, v)
		}
	}
	if tp := ChildTraceparent(c["traceparent"]); tp != "" {
		r2.Header.Set("traceparent", tp)
	}
	return base.RoundTrip(r2)
}

// ChildTraceparent keeps the trace id and flags of a valid version-00
// traceparent and replaces the parent id with a new random span id.
// It returns "" for an invalid input.
func ChildTraceparent(tp string) string {
	p := strings.Split(tp, "-")
	if len(p) != 4 || p[0] != "00" || len(p[1]) != 32 || len(p[2]) != 16 || len(p[3]) != 2 {
		return ""
	}
	if p[1] == strings.Repeat("0", 32) {
		return ""
	}
	return strings.Join([]string{"00", p[1], randHex(8), p[3]}, "-")
}

func randHex(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err) // crypto/rand failing means the OS is broken
	}
	return hex.EncodeToString(b)
}
go
package propagate

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestChildTraceparent(t *testing.T) {
	in := "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
	out := ChildTraceparent(in)
	p := strings.Split(out, "-")
	if len(p) != 4 || p[1] != "0af7651916cd43dd8448eb211c80319c" || p[3] != "01" {
		t.Fatalf("trace id or flags changed: %q", out)
	}
	if p[2] == "b7ad6b7169203331" || len(p[2]) != 16 {
		t.Fatalf("span id was not replaced: %q", out)
	}
	for _, bad := range []string{"", "garbage", "01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
		"00-00000000000000000000000000000000-b7ad6b7169203331-01"} {
		if ChildTraceparent(bad) != "" {
			t.Errorf("accepted invalid traceparent %q", bad)
		}
	}
}

func TestMiddlewareAndTransportForwardHeaders(t *testing.T) {
	var got http.Header
	downstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		got = r.Header.Clone()
	}))
	defer downstream.Close()

	client := &http.Client{Transport: Transport{}}
	app := Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, downstream.URL, nil)
		resp, err := client.Do(req)
		if err != nil {
			t.Error(err)
			return
		}
		resp.Body.Close()
	}))

	in := httptest.NewRequest(http.MethodGet, "/", nil)
	in.Header.Set("x-request-id", "req-123")
	in.Header.Set("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")
	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, in)

	if got.Get("x-request-id") != "req-123" {
		t.Errorf("x-request-id not forwarded: %q", got.Get("x-request-id"))
	}
	if !strings.HasPrefix(got.Get("traceparent"), "00-0af7651916cd43dd8448eb211c80319c-") ||
		strings.Contains(got.Get("traceparent"), "b7ad6b7169203331") {
		t.Errorf("traceparent must keep trace id and change span id: %q", got.Get("traceparent"))
	}
	if rec.Header().Get("x-request-id") != "req-123" {
		t.Errorf("response must echo x-request-id")
	}
}

func TestMiddlewareCreatesRequestID(t *testing.T) {
	rec := httptest.NewRecorder()
	Middleware(http.NotFoundHandler()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	if len(rec.Header().Get("x-request-id")) != 32 {
		t.Errorf("expected generated 32-hex id, got %q", rec.Header().Get("x-request-id"))
	}
}

func TestTransportWithoutContextIsPassThrough(t *testing.T) {
	var got http.Header
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got = r.Header.Clone() }))
	defer s.Close()
	resp, err := (&http.Client{Transport: Transport{}}).Get(s.URL)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if got.Get("x-request-id") != "" {
		t.Errorf("must not invent headers outside a request: %q", got.Get("x-request-id"))
	}
}

اجرا به‌عنوان sidecar در pod: cmd/sidecar روی ۱۵۰۰۶ (ورودی) و ۱۵۰۹۰ (metric و /ready) گوش می‌دهد.

go
// Command sidecar runs the minimal proxy next to an application:
// inbound traffic on :15006 is forwarded to the app on 127.0.0.1:8080,
// metrics and readiness are served on :15090 (same ports Istio's Envoy uses).
package main

import (
	"log"
	"net/http"
	"net/url"
	"os"
	"time"

	"academy/service-mesh-sidecar/sidecar"
)

func main() {
	target := os.Getenv("APP_URL")
	if target == "" {
		target = "http://127.0.0.1:8080"
	}
	u, err := url.Parse(target)
	if err != nil {
		log.Fatal(err)
	}
	p := sidecar.New(sidecar.Config{
		Target:        u,
		Timeout:       5 * time.Second,
		PerTryTimeout: 1500 * time.Millisecond,
		MaxRetries:    2,
		RetryRatio:    0.2,
	})
	go func() { log.Fatal(http.ListenAndServe(":15090", p.Admin())) }()
	srv := &http.Server{Addr: ":15006", Handler: p.Handler, ReadHeaderTimeout: 5 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

زاویهٔ Go ​

  • از Rewrite استفاده کنید نه Director: با Rewrite، headerهای hop-by-hop و headerهای forwarding از درخواست خروجی پیش‌تر حذف شده‌اند، پس client نمی‌تواند X-Forwarded-For را جعل کند. ProxyRequest.SetURL و SetXForwarded دقیقاً برای همین هستند.
  • RoundTripper جای درست retry است: هم درخواست و هم پاسخ را می‌بیند و ReverseProxy آن را برای هر درخواست دوباره به کار می‌برد. هرگز درخواست caller را تغییر ندهید؛ clone کنید.
  • فقط آنچه امن است retry کنید: body درخواست برای ارسال مجدد باید بافر شود، پس sidecar سقفی (۱ MiB) دارد و body بزرگ‌تر را که نمی‌تواند دوباره بفرستد نمی‌فرستد.
  • context مهلت را حمل می‌کند: timeout کل یک context است و timeout هر تلاش یک timer که همان یک تلاش را لغو می‌کند؛ timerای که خودمان فعال کردیم به‌صورت timeout گزارش می‌شود نه لغو توسط client.
  • clientهای net/http بی‌Timeout تا ابد منتظر می‌مانند؛ پشت mesh، timeout در route تماس را قطع می‌کند، اما برنامه باید timeout خودش را هم، کوتاه‌تر، بگذارد.

Laravel ​

Before ​

نسخهٔ اول معمول: یک controller با Http::get سرویس را صدا می‌زند، headerهای ورودی را رها می‌کند، timeout پیش‌فرض ۳۰ ثانیه را نگه می‌دارد (بلندتر از هر timeout route در mesh، پس proxy اول تماس را می‌برد و برنامه reset می‌بیند) و فقط /up برای سلامت دارد:

php
Route::get('/orders/{id}', fn (string $id) => Http::get("http://inventory/stock/{$id}")->json());

After ​

انتشار header. MeshContext با scoped() bind شده تا Laravel Octane هر درخواست را تازه شروع کند («instances registered using the scoped method will be flushed whenever the Laravel application starts a new lifecycle, such as when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job»). middleware آن را پر می‌کند؛ یک Http::macro clientای می‌سازد که headerها را حمل می‌کند.

php
<?php

namespace App\Mesh;

/**
 * Header values of the inbound request that must reach every outbound call.
 * Bound with scoped() so Octane starts every request with a fresh instance.
 */
final class MeshContext
{
    /** Headers the sidecar needs the application to forward (case-insensitive). */
    public const FORWARDED = ['x-request-id', 'traceparent', 'tracestate', 'baggage'];

    /** @var array<string,string> */
    private array $headers = [];

    /** @param array<string,string> $headers */
    public function fill(array $headers): void
    {
        $this->headers = $headers;
    }

    /** @return array<string,string> */
    public function headers(): array
    {
        return $this->headers;
    }

    public function requestId(): ?string
    {
        return $this->headers['x-request-id'] ?? null;
    }
}
php
<?php

namespace App\Http\Middleware;

use App\Mesh\MeshContext;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/**
 * Reads the headers the sidecar added to the inbound request and keeps them
 * for the outbound calls of this request (see MeshServiceProvider's Http macro).
 * Without this the sidecar cannot join its spans into one trace.
 */
class PropagateMeshHeaders
{
    public function __construct(private readonly MeshContext $mesh)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $headers = [];
        foreach (MeshContext::FORWARDED as $name) {
            $value = $request->header($name);
            if (is_string($value) && $value !== '') {
                $headers[$name] = $value;
            }
        }
        // Direct calls (local development, health checks from outside the mesh)
        // have no sidecar, so create the id the sidecar would have created.
        $headers['x-request-id'] ??= (string) Str::uuid();

        $this->mesh->fill($headers);
        Log::withContext(['request_id' => $headers['x-request-id']]);

        $response = $next($request);
        $response->headers->set('x-request-id', $headers['x-request-id']);

        return $response;
    }
}
php
<?php

namespace App\Providers;

use App\Mesh\MeshContext;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

class MeshServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // scoped(): flushed for every request or queued job, which is what
        // Laravel Octane needs; singleton() would leak ids between requests.
        $this->app->scoped(MeshContext::class);
    }

    public function boot(): void
    {
        // Http::mesh('orders') -> a client for http://orders (plain HTTP in the pod;
        // the sidecar adds mTLS), carrying the inbound trace headers, with a
        // deadline shorter than the sidecar's route timeout so the app fails first
        // and no retry happens behind its back.
        Http::macro('mesh', function (string $service): PendingRequest {
            /** @var MeshContext $ctx */
            $ctx = app(MeshContext::class);

            return Http::baseUrl("http://{$service}")
                ->withHeaders($ctx->headers())
                ->connectTimeout(1)
                ->timeout((float) config('mesh.call_timeout', 2.5))
                ->acceptJson();
        });
    }
}

ثبت، پیکربندی و routeها. sidecar از localhost وصل می‌شود، پس trustProxies(at: ['127.0.0.1'])؛ middleware با prepend اول می‌نشیند تا همهٔ لایه‌های بعدی و هر خط لاگ شناسهٔ درخواست را داشته باشند.

php
<?php

use App\Http\Middleware\PropagateMeshHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // The sidecar connects from 127.0.0.1 inside the pod; trust it so
        // X-Forwarded-Proto/For describe the real client and scheme.
        $middleware->trustProxies(at: ['127.0.0.1']);

        // First in the stack: every later middleware and log line has the request id.
        $middleware->prepend(PropagateMeshHeaders::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })
    ->create();
php
<?php

// config/mesh.php
return [
    // Seconds the app waits for one downstream call. Keep it BELOW the mesh route
    // timeout (e.g. Istio VirtualService timeout: 3s) so the app decides the fallback.
    'call_timeout' => (float) env('MESH_CALL_TIMEOUT', 2.5),

    // Inside the pod the app speaks plain HTTP to its sidecar; the proxy does mTLS.
    // Do not configure client certificates here and do not call https:// services
    // by name, or the sidecar sees opaque TLS and can neither route nor measure it.
    'scheme' => 'http',

    // Sidecar readiness: on shutdown keep serving for this long after SIGTERM so
    // in-flight and late-routed requests drain (match terminationGracePeriodSeconds).
    'shutdown_grace_seconds' => (int) env('MESH_SHUTDOWN_GRACE', 15),
];
php
<?php

use App\Http\Controllers\ReadinessController;
use App\Http\Middleware\MeshPeerIdentity;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;

Route::get('/healthz/live', [ReadinessController::class, 'live']);
Route::get('/healthz/ready', [ReadinessController::class, 'ready']);

// A call that keeps the trace: the macro adds x-request-id and traceparent.
Route::get('/orders/{id}', function (string $id) {
    $stock = Http::mesh('inventory')
        ->get('/stock/'.$id)
        ->throw()
        ->json();

    return ['order' => $id, 'stock' => $stock];
});

// Retries are safe only with an idempotency key: the mesh may replay this POST.
Route::post('/payments', function (\Illuminate\Http\Request $request) {
    abort_unless($request->hasHeader('Idempotency-Key'), 400, 'Idempotency-Key required');

    return Http::mesh('payments')
        ->withHeaders(['Idempotency-Key' => $request->header('Idempotency-Key')])
        ->post('/charges', $request->only('amount', 'currency'))
        ->throw()
        ->json();
})->middleware(MeshPeerIdentity::class.':spiffe://cluster.local/ns/shop/sa/checkout');

Readiness و هویت peer. liveness و readiness جدا؛ authorization اختیاری از روی هویت mTLS که sidecar در X-Forwarded-Client-Cert می‌فرستد.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Two separate answers. Liveness: "the process is not wedged" (no dependencies).
 * Readiness: "send me traffic now" (dependencies this pod cannot work without).
 * With a sidecar both probes are rewritten or forwarded by the mesh, so the
 * app must answer on plain HTTP inside the pod.
 */
class ReadinessController
{
    public function live()
    {
        return response()->json(['status' => 'alive']);
    }

    public function ready()
    {
        $checks = [];

        try {
            DB::select('select 1');
            $checks['database'] = true;
        } catch (\Throwable $e) {
            Log::warning('readiness: database failed', ['error' => $e->getMessage()]);
            $checks['database'] = false;
        }

        try {
            Cache::store()->get('readiness-probe');
            $checks['cache'] = true;
        } catch (\Throwable $e) {
            $checks['cache'] = false;
        }

        // A cache outage degrades the app but must not remove every pod from rotation.
        $ready = $checks['database'];

        return response()->json(['status' => $ready ? 'ready' : 'not-ready', 'checks' => $checks], $ready ? 200 : 503);
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Optional: authorize by the caller's mesh identity. The sidecar terminates mTLS
 * and passes the verified client certificate details in X-Forwarded-Client-Cert
 * (Envoy's XFCC header). Trust it ONLY when the pod accepts traffic exclusively
 * through the sidecar (STRICT mTLS and no hostPort/NodePort bypass); otherwise
 * any client can forge it.
 */
class MeshPeerIdentity
{
    /** @param string ...$allowed e.g. spiffe://cluster.local/ns/shop/sa/checkout */
    public function handle(Request $request, Closure $next, string ...$allowed): Response
    {
        $xfcc = (string) $request->header('x-forwarded-client-cert', '');

        if (! preg_match('/URI=([^;,]+)/', $xfcc, $m) || ! in_array($m[1], $allowed, true)) {
            abort(403, 'peer identity not allowed');
        }

        return $next($request);
    }
}

تست feature (نوشته شده، در این محیط اجرا نشده):

php
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class MeshHeadersTest extends TestCase
{
    public function test_outbound_calls_carry_the_inbound_trace_headers(): void
    {
        Http::fake(['inventory/*' => Http::response(['qty' => 3])]);

        $traceparent = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01';

        $this->withHeaders(['x-request-id' => 'req-1', 'traceparent' => $traceparent])
            ->getJson('/orders/42')
            ->assertOk()
            ->assertHeader('x-request-id', 'req-1');

        Http::assertSent(fn ($request) => $request->hasHeader('x-request-id', 'req-1')
            && $request->hasHeader('traceparent', $traceparent));
    }

    public function test_request_id_is_created_when_no_sidecar_added_one(): void
    {
        Http::fake(['inventory/*' => Http::response(['qty' => 3])]);

        $response = $this->getJson('/orders/42')->assertOk();

        $this->assertNotEmpty($response->headers->get('x-request-id'));
    }

    public function test_readiness_is_503_when_the_database_is_down(): void
    {
        config(['database.default' => 'broken']);
        config(['database.connections.broken' => ['driver' => 'sqlite', 'database' => '/nonexistent/db.sqlite']]);

        $this->getJson('/healthz/ready')->assertStatus(503);
    }
}

زاویهٔ Laravel ​

  • Http::macro یک client قابل‌استفادهٔ مجدد ثبت می‌کند و withHeaders headerها را به درخواست ادغام می‌کند؛ connectTimeout() و timeout() مهلت‌ها را تنظیم می‌کنند؛ Http::retry() وجود دارد، اما وقتی mesh retry می‌کند لایهٔ دومی اضافه نکنید (به تقویت retry نگاه کنید).
  • Octane برنامه را بین درخواست‌ها در حافظه نگه می‌دارد، پس state درخواست هرگز نباید در singleton یا property استاتیک بماند. bindingهای scoped() برای هر درخواست یا job صف پاک می‌شوند؛ مستندات Octane هم هشدار می‌دهد container یا request را به singletonها تزریق نکنید.
  • داخل pod برنامه HTTP ساده صحبت می‌کند: بی‌گواهی client در Guzzle، بی‌https:// به سرویس‌های داخل mesh. mTLS کار sidecar است.
  • Octane در production «behind a traditional web server» (‏Nginx یا Apache جلوی آن) سرو می‌شود؛ با mesh، sidecar نقش جلوی پایان‌دهندهٔ TLS را بازی می‌کند و NGINX می‌تواند sidecar دوم یا کانتینر جلوی همان pod باشد.
  • workerهای صف بدون درخواست ورودی اجرا می‌شوند: چیزی برای انتشار نیست، پس اگر پیوند trace می‌خواهید jobها باید request_id را به‌عنوان فیلد payload حمل کنند.

حل مسئله‌های کلاسیک ​

تقویت retry میان برنامه و mesh ​

Retry amplification: 3 x 3 x 3 = 27 callsApp retry loop3 attempts (library)Sidecar retries3 attempts (retries: attempts: 2)Failing servicereceives 3 x 3 = 9 per user callone user requesteach app attempteach sidecar attemptFix1. Retry at exactly one layer (the mesh is simplest to change, the app knows idempotency)2. Cap retries with a budget (a fraction of traffic) so an outage drains it3. Application timeout shorter than the mesh route timeout, so it never retries behind your back
راه‌حلچگونهمزیتهزینه یا حد
retry در یک لایهحلقهٔ سمت برنامه را بردارید یا attempts: 1 در meshبار قابل‌پیش‌بینیبه توافق میان تیم‌ها نیاز دارد
Retry budgetretry به‌اندازهٔ کسری از ترافیک (به Budget در Go نگاه کنید)قطعی retryها را تخلیه می‌کندVirtualService در Istio budget ندارد؛ Linkerd و Envoy حدهای شبیه budget دارند
retryOn محدودconnect-failure,refused-stream نه 5xxفقط آنچه هرگز به برنامه نرسیده retry می‌شوداضافه‌بار گزارش‌شده توسط برنامه را از دست می‌دهد
timeout برنامه زیر timeout routeبرنامه ۲٫۵ ثانیه، route ‏۳ ثانیهبرنامه fallback را تعیین می‌کندهر دو عدد باید هماهنگ بمانند
کلیدهای idempotencyIdempotency-Key + جدول SQL بالاتکراری‌ها بی‌اثر می‌شوندفضا و TTL

trace که در یک سرویس می‌شکند ​

نشانه: Jaeger به‌جای یک trace دو trace کوتاه نشان می‌دهد. علت: یکی از سرویس‌های زنجیره traceparent را کپی نمی‌کند. راه‌حل: middleware و transport را اضافه کنید؛ با فرستادن درخواستی که traceparent شناخته‌شده دارد و دیدن همان trace id در access logهای پایین‌دست بررسی کنید (آزمایشگاه Go این را چاپ می‌کند).

race هنگام شروع و افت درخواست هنگام خاموشی ​

نشانه: اولین درخواست‌ها بعد از deploy با connection refused شکست می‌خورند یا درخواست‌های در جریان هنگام scale-down از دست می‌روند. علت‌ها: برنامه پیش از گوش‌دادن proxy بالا می‌آید؛ proxy پیش از آخرین فراخوانی‌های برنامه خارج می‌شود. راه‌حل: native sidecarهای Kubernetes (پیش از برنامه شروع، بعد از آن پایان)، یا holdApplicationUntilProxyStarts: true در Istio («delay application startup until the pod proxy is ready»، پیش‌فرض false) و terminationDrainDuration (پیش‌فرض ۵ ثانیه) برای تمام‌شدن اتصال‌ها.

text
     scale-down timeline
1    pod gets SIGTERM; endpoint removal reaches proxies with a delay (eventual consistency)
2    late requests still arrive for a few seconds
3    app keeps serving during the grace period, then exits; native sidecar stops after it
4    proxy drains connections for terminationDrainDuration, then exits

Job و CronJobهایی که هرگز تمام نمی‌شوند ​

proxy داخل containers بعد از خروج کانتینر اصلی Job ادامه می‌دهد، پس Job هرگز کامل نمی‌شود. از native sidecar استفاده کنید: Kubernetes می‌گوید sidecar «does not prevent the Job from completing after the main container has finished».

ورم پیکربندی mesh ​

نشانه: هر proxy صدها MB مصرف می‌کند و pushها طول می‌کشند. علت: به‌طور پیش‌فرض هر proxy برای رسیدن به هر workload برنامه‌ریزی می‌شود. راه‌حل: منبع Sidecar با egress.hosts محدود به namespace و istio-system، به‌علاوهٔ exportTo روی سرویس‌ها؛ صفحهٔ performance در Istio می‌گوید این محدودسازی در مقیاس بزرگ «highly recommended» است.

پروتکل‌های server-first و تأخیر sniffing ​

MySQL اول خودش حرف می‌زند، پس sniffing منتظر بایت‌هایی از client می‌ماند که هرگز نمی‌آید و اتصال‌ها گیر می‌کنند یا شکست می‌خورند. راه‌حل: port را tcp-mysql (یا appProtocol: tcp) نام بگذارید یا از interception کنار بگذارید.

دیباگ یک 503 ​

text
1    curl from the client pod returns 503; response header server: envoy, access log flag NR / UF / UH / UO
2    NR  -> no route: istioctl proxy-config routes; check port name http-*, hosts, namespace
3    UF  -> connect failed: mTLS mismatch? kubectl get peerauthentication,destinationrule -A
4    UH  -> no healthy upstream: istioctl proxy-config endpoints; any ready pods? ejected by outlier detection?
5    UO  -> overflow: DestinationRule connectionPool limits too low for the load
6    none of the above -> the 503 came from the app: compare with the app's own log and x-request-id

انتخاب ​

Few services,one language?Need mTLS oridentity policy?Need L7 per-servicerouting, retries, splits?Sidecar mesh orambient + waypointsLibrary + gatewayno meshGateway + librariesTLS at the edgeL4-only meshambient ztunnel, Ciliumbudget operations time:upgrades, debugging, on-callyesnonoyesnoyes
وضعیتتوصیهتکنیک اضافهدلیل
۵ سرویس، یک زبان، یک تیمکتابخانه (Resilience4j در Java، go-kit در Go، Laravel HTTP client)gateway در لبهmesh بیش از آنچه صرفه می‌دهد خرج دارد
۴۰ سرویس، ۴ زبان، نیاز zero-trustmesh با sidecar (Linkerd برای بار عملیاتی کم، Istio برای گسترده‌ترین قابلیت)mTLS سخت‌گیر، AuthorizationPolicyیک پیاده‌سازی امنیت برای همه‌جا
فقط رمزگذاری و هویت بین podهاIstio ambient (ztunnel) یا Ciliumwaypoint فقط جایی که L7 لازم استکمترین هزینه برای هر pod
API عمومی، rate limit، auth در لبهفقط API gateway (به API Gateway، BFF و Service Mesh نگاه کنید)WAF، rate limitingmesh جای دغدغه‌های لبه را نمی‌گیرد
ترافیک سنگین Kafka یا پایگاه‌دادهخارج از capture یا به‌صورت TCP کدرretry سمت client در brokerproxy در آنجا ارزش L7 اضافه نمی‌کند
محیط تنظیم‌شده، ممیزی هر فراخوانیmesh با access log و AUDIT در AuthorizationPolicyegress gatewayشواهد یکنواخت
زیرساخت VM به‌علاوهٔ KubernetesConsul service mesh یا Istio با پشتیبانی VMmesh gatewaypolicy یکسان در همهٔ پلتفرم‌ها
پرسشmesh با sidecarAmbient / eBPFکتابخانهفقط gateway
mTLS یکنواخت بی‌کدبلهبلهنهفقط لبه
routing در L7 برای هر سرویسبلهبا waypointدر کددر لبه
هزینه برای هر podبالاپایینهیچهیچ
پذیرش بدون restartنهبلهنهبله
بلوغ ابزاربالاجدیدتربالابالا

در معماری: از یک فرایند تا سیستم توزیع‌شده ​

مونولیت: یک فرایند، یک پایگاه‌داده ​

یک فرایند Laravel یا Go ترافیک بین‌سرویسی ندارد، پس mesh کاری ندارد. sidecar هنوز برای کمک‌کارها معنا دارد: log shipper، Vault agent، proxy محلی به پایگاه‌دادهٔ مدیریت‌شده. چیزهایی را که فقط فایل‌های pod یا localhost می‌خواهند در native sidecar بگذارید؛ TLS و rate limiting را در ingress یا load balancer نگه دارید (Load Balancing).

مونولیت ماژولار: مرز بدون شبکه ​

ماژول‌ها درون‌فرایندی یکدیگر را صدا می‌زنند، پس retry و timeout تصمیم سطح تابع است. رابط ماژول‌ها را از حالا با مهلت و idempotency طراحی کنید، چون وقتی ماژولی سرویس شود mesh retry و timeout خودش را به آن فراخوانی‌ها اضافه می‌کند.

میکروسرویس‌ها: هر پیکان یک proxy می‌گیرد ​

Checkout سه سرویس Pricing، Inventory و Payments را صدا می‌زند. در حالت sidecar هر پیکان proxy سمت client بعد proxy سمت server است: mTLS بین آن‌ها، route با timeout ‏۳ ثانیه و دو retry روی connect-failure، اخراج یک pod بد Inventory با outlier detection، و AuthorizationPolicyای که فقط Checkout را اجازهٔ POST به /charges می‌دهد. handler در Payments از جدول idempotency استفاده می‌کند؛ برنامه‌ها headerها را کپی می‌کنند تا یک trace چهار سرویس را بپوشاند. بی‌این وظایف برنامه، mesh هنوز می‌تواند رمز کند و اندازه بگیرد، اما نه trace کند و نه امن retry. برای تصمیم‌های سبک به Service Communication و برای جابه‌جایی تدریجی ترافیک با وزن route به Strangler Fig نگاه کنید.

داده توزیع‌شده: replicaها، cacheها، regionها ​

mesh داده را جابه‌جا نمی‌کند؛ درخواست را جابه‌جا می‌کند. load balancing آگاه از locality و outlier detection می‌توانند فراخوانی را در یک zone نگه دارند و endpoint یک replica عقب‌مانده را اخراج کنند، اما تأخیر replica، read-your-writes و failover دغدغهٔ پایگاه‌داده و برنامه‌اند (Replication Topologies). meshهای چند‌cluster اعتماد مشترک و discovery میان‌cluster می‌خواهند؛ وقتی یک region بیفتد ترافیک با پیکربندی جابه‌جا می‌شود و پایگاه‌داده‌ها باید برای آن آماده باشند. پایگاه‌داده‌ای که از میان mesh می‌رسید TCP کدر است: mTLS و metric سطح L4 می‌گیرید، نه قابلیت‌های سطح query.

مسیر مقیاس: ۱x، ۱۰x، ۱۰۰x ​

مقیاسpodهاچه چیزی عوض می‌شود
1xکمتر از حدود ۲۰ سرویسکتابخانه و gateway؛ sidecar فقط برای کمک‌کارها
10xحدود ۱۰۰ تا ۴۰۰ podmesh برای mTLS یکنواخت می‌ارزد؛ از روز اول محدودسازی Sidecar؛ ارتقا بر پایهٔ revision
100xهزاران pod، چند clusterambient در L4 برای کاهش هزینهٔ هر pod، waypoint جایی که لازم است، چند replica از Istiod، اعتماد multi-cluster، تیم پلتفرمی که مالک mesh است

آزمایشگاه: retry و budget و trace در sidecar در یک فرایند ​

آزمایشگاه Go دو برنامه را که هرکدام پشت sidecar خود هستند در یک فرایند اجرا می‌کند (اجرا شده؛ خروجی زیر). بخش Istio «خروجی موردانتظار؛ اجرا نشده» است (اینجا cluster نداریم).

text
$ cd docs/snippets/system-design/service-mesh-sidecar/go && go run ./cmd/lab
request 1: status=200
  inventory saw x-request-id=req-lab-1
  inventory saw trace id=0af7651916cd43dd8448eb211c80319c (same as client)
12 requests, 12 returned 200; inventory app received 17 calls
--- inventory sidecar metrics ---
sidecar_requests_total 12
sidecar_responses_5xx_total 0
sidecar_retries_total 5
sidecar_retries_denied_total 0
sidecar_timeouts_total 0
sidecar_in_flight 0

خواندن آن: ۱۲ درخواست کاربر، ۵ retry پنهان (۱۷ فراخوانی upstream)، بدون خطای دیده‌شده برای کاربر؛ همان trace id و request id به hop دوم رسید. شمار bucketهای تأخیر در هر اجرا فرق می‌کند.

آزمایش‌هایی برای امتحان:

  1. در آزمایشگاه RetryRatio: 0 بگذارید و دوباره اجرا کنید: خطاهای گذرای اول به‌صورت 503 دیده می‌شوند.
  2. برنامه را طوری کنید که همیشه شکست بخورد: sidecar_retries_denied_total پس از مصرف ۱۰ توکن اولیه بالا می‌رود؛ فراخوانی‌ها به برنامه نزدیک ۱ + ratio به‌ازای هر درخواست می‌ماند.
  3. propagate.Transport را از برنامهٔ orders بردارید: برنامهٔ inventory trace id دیگری می‌بیند (trace می‌شکند).
  4. مسیر before را با ۱۰ بار retry درون mesh که خودش هم retry می‌کند اجرا کنید: شمار فراخوانی‌های upstream را بشمارید (تقویت).

آزمایشگاه Istio (خروجی موردانتظار؛ اجرا نشده): istio-routing.yaml را روی clusterای با istio-injection=enabled اعمال کنید، سپس:

text
$ istioctl proxy-status                     # expected: all pods SYNCED
$ for i in $(seq 100); do curl -s reviews/ ; done | sort | uniq -c    # expected: about 90 v1, 10 v2 (can need ~100 requests to converge)
$ kubectl scale deploy/reviews-v1 --replicas=0                     # expected: requests fail with 503 UH during the gap

بدفهمی‌های رایج ​

باورواقعیت
mesh همان API gateway استgateway ترافیک north-south لبه را اداره می‌کند؛ mesh ترافیک سرویس‌به‌سرویس را (ingress gateway فقط درِ ورودی mesh است)
control plane درخواست‌های من را می‌برددرخواست از proxy به proxy می‌رود؛ control plane فقط آن‌ها را پیکربندی می‌کند
mTLS یعنی authorizationهویت و رمزگذاری می‌دهد؛ AuthorizationPolicy دسترسی را تعیین می‌کند
retry همه‌چیز را مطمئن می‌کندretryهای بی‌budget و چندلایه بار را چند برابر می‌کنند و فراخوانی‌های غیر idempotent را تکرار می‌کنند
mesh خودکار trace می‌کندproxyها span می‌فرستند؛ برنامه‌ها باید traceparent و x-request-id را کپی کنند
ambient یعنی بدون proxyztunnel در هر node و waypointها هنوز هستند
منبع Sidecar ترافیک را مسدود می‌کندپیکربندی را محدود می‌کند؛ مسدودسازی egress gateway و policy می‌خواهد
Istio timeout پیش‌فرض داردtimeout درخواست HTTP به‌طور پیش‌فرض غیرفعال است؛ retry پیش‌فرض ۲ تلاش است
بعد از injection همهٔ namespace محافظت‌شده استpodهای غیر mesh، skip portها و حالت permissive هنوز متن ساده را مجاز می‌کنند
mesh مجانی استحدود ۰٫۲۰ vCPU و ۶۰ MB برای هر sidecar در ۱۰۰۰ rps (Istio 1.24)، به‌علاوهٔ دو hop، ارتقا و on-call

چکیده ​

موضوعچه چیزی را به یاد بسپارید
Sidecarهمان pod، شبکه و volume مشترک؛ native sidecar = init container با restartPolicy: Always
Data planeEnvoy، linkerd2-proxy، ztunnel، waypoint
Control planeIstiod، destination و identity در Linkerd، Consul؛ پیکربندی می‌کند، ترافیک نمی‌برد
xDS‏LDS، RDS، CDS، EDS، SDS روی gRPC؛ SotW، incremental، ADS
Injectionبرچسب namespace ‏istio-injection=enabled؛ annotation ‏linkerd.io/inject: enabled؛ podها را restart کنید
Captureiptables به ۱۵۰۰۶ ورودی و ۱۵۰۰۱ خروجی؛ UID ‏1337 رزرو است
mTLSابتدا PERMISSIVE بعد STRICT؛ در صورت نیاز ISTIO_MUTUAL در DestinationRule
RoutingVirtualService (کجا) + DestinationRule (چگونه، subset)
Retryپیش‌فرض ۲ تلاش، timeout خاموش؛ فقط یک لایه؛ فقط routeهای idempotent
Breakingحدود connectionPool و اخراج با outlierDetection، نه breaker با حالت
Policyترتیب CUSTOM، DENY، ALLOW؛ وجود ALLOW یعنی پیش‌فرض deny
Observabilitygolden metrics رایگان؛ headerهای traceparent و x-request-id با شما
پروتکل‌هاportها را http- و tcp- نام بگذارید؛ پروتکل‌های server-first sniffing را می‌شکنند
دیباگistioctl proxy-status و proxy-config، پرچم‌های access log یعنی NR UO UF UC، رابط admin روی 15000
هزینه۰٫۲۰ vCPU و ۶۰ MB برای هر sidecar (Istio 1.24، ۱۰۰۰ rps)؛ ztunnel ‏۰٫۰۶ vCPU و ۱۲ MB

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چه چیزی یک init container را به sidecar در Kubernetes تبدیل می‌کند و برای شروع، پایان و Job چه چیزی را عوض می‌کند؟ تکمیلی ​

پاسخ

پاسخ: restartPolicy: Always روی یک ردیف در initContainers. پیش از برنامه (بعد از موفقیت startup probe) شروع می‌شود، ادامه می‌دهد، بعد از برنامه خاموش می‌شود و مانع تمام‌شدن Job نمی‌شود.

۲ — آیا control plane در مسیر درخواست است؟ اگر Istiod پایین باشد چه می‌شود؟ حیاتی ​

پاسخ

پاسخ: نه. proxyها با آخرین پیکربندی کار می‌کنند؛ تا بازگشت آن نمی‌توانید پیکربندی عوض کنید یا گواهی تازه بگیرید.

۳ — انواع منبع xDS را بگویید و اینکه هرکدام چه حمل می‌کند. تکمیلی ​

پاسخ

پاسخ: Listener (‏LDS: port و زنجیرهٔ فیلتر)، RouteConfiguration (‏RDS: match، timeout، retry)، Cluster (‏CDS: گروه upstream، breaker)، ClusterLoadAssignment (‏EDS: endpointها)، Secret (‏SDS: گواهی).

۴ — چرا در Istio یک pod در namespaceای با Pod Security سخت‌گیر ممکن است بالا نیاید و راه‌حل چیست؟ مهم ​

پاسخ

پاسخ: istio-init به NET_ADMIN و NET_RAW نیاز دارد که baseline و restricted مسدود می‌کنند. از Istio CNI plugin یا namespace با سطح privileged استفاده کنید.

۵ — در حالت ambient چه کسی mTLS می‌کند و چه کسی routing در L7؟ تکمیلی ​

پاسخ

پاسخ: ztunnel (در هر node، L4، روی HBONE) mTLS، احراز هویت و L4 authorization را انجام می‌دهد؛ waypoint (‏Envoy) routing و authorization در L7 را.

۶ — یک VirtualService با attempts: 3 دارید و برنامه هم سه بار retry می‌کند. یک درخواست کاربر چند فراخوانی می‌سازد و چه چیزی را عوض می‌کنید؟ حیاتی ​

پاسخ

پاسخ: تا ۳ × ۳ = ۹ (با لایه‌های بیشتر بیشتر). در یک لایه retry کنید، budget بگذارید و timeout برنامه را کوتاه‌تر از timeout route کنید.

۷ — DestinationRule اعمال کردید و حالا درخواست‌ها به آن سرویس 503 با پرچم UF می‌دهند. علت محتمل چیست؟ مهم ​

پاسخ

پاسخ: ناسازگاری حالت TLS: DestinationRule مقدار trafficPolicy.tls.mode: ISTIO_MUTUAL ندارد در حالی که server به mTLS نیاز دارد، پس proxy سمت client متن ساده می‌فرستد.

۸ — چرا حتی با mesh، trace بین دو سرویس می‌شکند و چگونه درستش می‌کنید؟ حیاتی ​

پاسخ

پاسخ: برنامه traceparent (و x-request-id) را از درخواست ورودی به خروجی کپی نکرده. middleware انتشار و client ابزارگذاری‌شده اضافه کنید.

۹ — اگر برای یک workload هیچ ALLOW policy نباشد AuthorizationPolicy در Istio چه می‌کند؟ و اگر باشد اما چیزی match نشود؟ مهم ​

پاسخ

پاسخ: بی‌ALLOW: مجاز. ALLOW هست و هیچ‌چیز match نمی‌شود: رد (403 با «RBAC: access denied»). DENY اول ارزیابی می‌شود.

۱۰ — چرا MySQL از میان sidecar در Istio به نام صریح port نیاز دارد؟ تکمیلی ​

پاسخ

پاسخ: MySQL پروتکل server-first است و با انتخاب خودکار پروتکل ناسازگار است؛ port را tcp-mysql نام بگذارید یا از interception کنار بگذارید.

۱۱ — کِی mesh توجیه ندارد؟ حیاتی ​

پاسخ

پاسخ: سرویس کم در یک زبان، تیم کوچک و بی‌نیاز zero-trust؛ کتابخانه به‌علاوهٔ gateway هزینهٔ کمتر و دیباگ ساده‌تری دارد.

۱۲ — وقتی mesh ممکن است درخواست را دوباره بفرستد handler چه باید بکند؟ مهم ​

پاسخ

پاسخ: idempotent باشد: کلید idempotency با قید یکتا (ON CONFLICT DO NOTHING) تا اجرای دوم پاسخ ذخیره‌شده را برگرداند.

واژه‌نامه ​

اصطلاحمعنا
Sidecar (سایدکار)کانتینر کمکی در همان pod برنامه
Sidecar pattern (الگوی سایدکار)هم‌جایی یک فرایند کمکی برای گسترش برنامه بدون تغییر کد
Native sidecar (سایدکار بومی)init container با restartPolicy: Always؛ شروع و پایان مرتب
Init container (کانتینر آغازین)کانتینری که پیش از کانتینرهای برنامه در pod اجرا می‌شود
Service mesh (مش سرویس)proxyهای کنار workload به‌علاوهٔ control plane برای mTLS، routing، policy و telemetry
Data plane (صفحهٔ داده)proxyهایی که ترافیک را می‌برند
Control plane (صفحهٔ کنترل)مؤلفه‌ای که proxyها را پیکربندی می‌کند (Istiod، Linkerd، Consul)
Envoyproxy لایهٔ ۷ به زبان C++ که Istio، Consul و دیگران به کار می‌برند
linkerd2-proxymicro-proxy ‏Rust در Linkerd
Istiodباینری یکپارچهٔ control plane در Istio
xDSAPIهای discovery در Envoy: ‏LDS، RDS، CDS، EDS، SDS
Sidecar injection (تزریق سایدکار)افزودن کانتینر proxy با mutating webhook
Ambient meshdata plane ‏Istio بدون proxy درون pod
ztunnelproxy ‏L4 در هر node در حالت ambient
Waypoint proxy‏Envoyای که برای قابلیت L7 در ambient مستقر می‌شود
HBONEتونل مبتنی بر HTTP CONNECT بین مؤلفه‌های ambient
CiliumCNI با service mesh مبتنی بر eBPF
eBPFبرنامه‌های هسته برای شبکه بدون hop روی proxy
mTLS‏TLS که هر دو طرف گواهی ارائه می‌کنند
SPIFFE identity (هویت SPIFFE)یک URI هویت workload مثل spiffe://cluster.local/ns/shop/sa/checkout
Traffic management (مدیریت ترافیک)routing، تقسیم، retry و timeout در proxy
VirtualServiceشیء Istio که routeهای یک host را تعریف می‌کند
DestinationRuleشیء Istio برای subset، load balancing، TLS، pool و outlier detection
Gatewayپیکربندی listener در proxy لبه
ServiceEntryثبت سرویس بیرونی در mesh
PeerAuthenticationسیاست حالت mTLS در Istio (‏PERMISSIVE، STRICT)
AuthorizationPolicyقاعده‌های allow، deny، audit یا custom
Traffic splitting (تقسیم ترافیک)routing وزنی بین نسخه‌ها
Canaryعرضهٔ تدریجی به سهم کوچکی از ترافیک
Traffic mirroring (آینه‌کردن ترافیک)فرستادن نسخه‌ای از ترافیک به نسخهٔ دیگر
Fault injection (تزریق خطا)تأخیر یا abort عمدی برای آزمون
Retries (تلاش مجدد)ارسال دوبارهٔ درخواست شکست‌خورده
Timeouts (مهلت)سقف مدت انتظار
Circuit breaking (قطع مدار)سقف اتصال و درخواست برای هر host
Outlier detection (تشخیص نمونهٔ پرت)اخراج غیرفعال میزبان‌های بدرفتار
Rate limiting (محدودسازی نرخ)محدود کردن نرخ درخواست برای هر client یا route
Golden metricsتأخیر، ترافیک، خطا، saturation
Distributed tracing (ردیابی توزیع‌شده)دنبال‌کردن یک درخواست در چند سرویس
Header propagation (انتشار header)کپی headerهای trace از درخواست ورودی به خروجی
x-request-idheader همبستگی درخواست در Envoy
traceparentheader ‏W3C Trace Context
Egress gatewayنقطهٔ خروج کنترل‌شده از mesh
Multi-cluster (چند خوشه‌ای)یک mesh در چند cluster با اعتماد مشترک
Gateway APIAPI استاندارد Kubernetes (‏Gateway، HTTPRoute)
HTTPRouteشیء route در Gateway API؛ در GAMMA به Service وصل می‌شود
ServiceProfileCRD قدیمی‌تر Linkerd برای پیکربندی هر route
Linkerdmesh از CNCF با proxy ‏Rust خودش
Consul service meshmesh از HashiCorp با sidecarهای Envoy
Latency overhead (سربار تأخیر)زمانی که hopهای proxy اضافه می‌کنند
Resource overhead (سربار منابع)CPU و حافظهٔ proxyها
Operational complexity (پیچیدگی عملیاتی)هزینهٔ اجرا و ارتقای mesh
istioctlابزار خط فرمان Istio از جمله proxy-status و proxy-config
Envoy adminرابط admin محلی روی port ‏15000
Access log (لاگ دسترسی)لاگ هر درخواست در proxy همراه پرچم‌های پاسخ
Protocol sniffing (تشخیص پروتکل)شناسایی HTTP از بایت‌های اول اتصال
TCP passthrough (عبور TCP)عبور بایت‌ها بی‌پردازش L7
Readiness (آمادگی)probeای که تعیین می‌کند pod ترافیک بگیرد یا نه

منابع ​

ساخته‌شده توسط Morteza Negahi