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، xDS | Data plane، Control plane و xDS |
| ترافیک چطور وارد proxy میشود | Injection و گرفتن ترافیک |
| ztunnel، waypoint، Cilium، eBPF | Ambient و eBPF |
| mTLS، هویت SPIFFE، PeerAuthentication | mTLS و هویت |
| VirtualService، DestinationRule، canary، تقسیم ترافیک | Routing و تقسیم |
| retry و timeout در proxy | Retry و timeout |
| circuit breaking و outlier detection | Circuit breaking |
| mirroring و fault injection | Mirroring و خطا |
| golden metrics، tracing، access log | Observability |
| AuthorizationPolicy و rate limiting | Policy |
| Gateway، egress gateway، ServiceEntry، Sidecar، multi-cluster | Gatewayها و محدودسازی |
| Gateway API، HTTPRoute، GAMMA | Gateway API |
| Linkerd، ServiceProfile، Consul | Linkerd و Consul |
| Kafka، پایگاهداده و غیر HTTP از میان mesh | TCP و protocol sniffing |
| تأخیر، CPU، حافظه، ارتقا، on-call | هزینهها |
| برنامه باید چه کند | رفتار برنامه |
| پورتها، انواع xDS، پرچم خطا | سازوکار |
| کد | Go، Laravel |
| خرابیهای واقعی و راهحل | حل مسئلههای کلاسیک |
| mesh یا کتابخانه یا gateway | انتخاب |
| از مونولیت تا چند cluster | در معماری |
| اجرا کنید | آزمایشگاه |
همهچیز در یک دقیقه
| جزء | چیست | به زبان ساده |
|---|---|---|
| Sidecar | کانتینر دوم در همان pod | کمککاری که شبکه و دیسک برنامه را شریک است |
| Data plane | proxyهایی که درخواست را میبرند (Envoy، linkerd2-proxy، ztunnel) | جادهها و باجههای عوارضی |
| Control plane | Istiod، control plane لینکرد، سرورهای Consul | دفتر ترافیک که قوانین را به هر باجه میگوید |
| xDS | APIهای discovery در Envoy (LDS، RDS، CDS، EDS، SDS) | زبانی که دفتر با آن قانون میفرستد |
| Injection | یک webhook کانتینر proxy را به pod تازه اضافه میکند | proxy برای شما نصب میشود |
| حالت ambient | Istio با ztunnel در هر node و waypoint اختیاری، بدون sidecar | یک proxy برای هر ساختمان بهجای هر واحد |
| قابلیت | چه کسی انجام میدهد | با چه چیزی پیکربندی میشود |
|---|---|---|
| mTLS و هویت workload | proxy + CA در control plane | PeerAuthentication (Istio)، خودکار (Linkerd) |
| Routing، canary، تقسیم | proxy | VirtualService + DestinationRule، HTTPRoute |
| Retry و timeout | proxy سمت client | فیلدهای retries/timeout در VirtualService، annotationهای Linkerd |
| Circuit breaking و outlier detection | proxy سمت client | connectionPool و outlierDetection در DestinationRule |
| Golden metrics و access log | هر دو proxy | Telemetry API، قالب access log |
| Authorization | proxy سمت server | AuthorizationPolicy، 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، TLS | mTLS و policy بین سرویسها لازم است |
| mesh با sidecar | mTLS یکنواخت، کنترل 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های شما اجرا نمیشود.
از کجا آمده
مستندات 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».
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 | نمونه محصول | چه چیزی را با برنامه شریک است |
|---|---|---|
| Proxy | Envoy (Istio)، linkerd2-proxy، Envoy در Consul | شبکهٔ localhost |
| Log shipper | Fluent Bit، Vector | volume لاگ |
| Secret fetcher | Vault Agent، reloaderهای external-secrets | volume حافظهای |
| Config reloader | ناظر ConfigMap | volume پیکربندی |
| Local server | NGINX جلوی 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 نمیشود.
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) | پیش از برنامه | بله | بعد از برنامه |
راهحل / نحوهٔ استفاده:
# 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: httpData 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 مجوز را اجرا میکند.
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 | زبان | چه کسی استفاده میکند | منبع پیکربندی | دامنه |
|---|---|---|---|---|
| Envoy | C++ | Istio، Consul، Cilium (در L7)، Contour، پیادهسازیهای Gateway API | xDS از یک management server | همهمنظوره |
linkerd2-proxy | Rust | Linkerd | gRPC از سرویس destination در Linkerd | فقط mesh |
| ztunnel | Rust | Istio ambient | xDS از Istiod | فقط L4: mTLS، authn، L4 authz، telemetry |
| Waypoint | Envoy | Istio ambient | xDS از Istiod | L7 برای یک 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.
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 plane | API به proxy | CA / هویت | نکته |
|---|---|---|---|
| Istio (Istiod) | xDS به Envoy و ztunnel | CA داخلی، هویتهای شبیه SPIFFE | یک باینری: Pilot، Citadel، injector |
| Linkerd | سرویسهای gRPC به نام destination و identity | سرویس identity، CSR را امضا میکند | proxy injector یک admission webhook است |
| Consul service mesh | xDS به Envoy | CA خود Consul یا Vault | بیرون از Kubernetes هم کار میکند |
| Cilium | xDS به Envoy هر node برای L7 | احراز متقابل مبتنی بر SPIFFE | eBPF کار 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 همین کار را میکند.
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/inject | iptables در istio-init یا Istio CNI | traffic.sidecar.istio.io/excludeOutboundPorts |
| Linkerd | linkerd.io/inject: enabled | linkerd-init یا Linkerd CNI | skip portها (کلاً از proxy رد میشوند) |
| Consul | annotation consul.hashicorp.com/connect-inject | init container / CNI | استثناهای transparent proxy |
راهحل / نحوهٔ استفاده:
# 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.0Ambient و 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 استفاده میکند.
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 در ambient | Ambient + waypoint | Cilium |
|---|---|---|---|---|
| محل 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 است؛ اعداد شما فرق میکند.
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 است.
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| جنبه | Istio | Linkerd | نکته |
|---|---|---|---|
| پیشفرض | PERMISSIVE مگر policy مقدار STRICT بدهد | mTLS برای ترافیک TCP در meshed روشن است | هر دو ترافیک غیر mesh را بیرون میگذارند |
| ترافیک بدون mTLS | در permissive متن ساده مجاز است | podهای غیر mesh، skip portها، probeهای kubelet | با ابزار بررسی کنید |
| تنظیمات عمر گواهی | تنظیمات CA در Istiod | trust anchor پیشفرض بعد از ۳۶۵ روز منقضی میشود | پیش از انقضا بچرخانید |
| خرابی رایج | DestinationRule بیISTIO_MUTUAL باعث 503 با UF میشود | multi-cluster به trust anchor مشترک نیاز دارد |
راهحل / نحوهٔ استفاده:
# 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.
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)| تکنیک | شیء | کاربرد |
|---|---|---|
| تطبیق header | match.headers در VirtualService | تستر داخلی، dark launch |
| تقسیم وزنی | route[].weight | canary، A/B |
| Mirror | mirror + mirrorPercentage | مقایسه بدون اثر روی کاربر |
| Subset | subsets در DestinationRule | انتخاب نسخه با label pod |
| Gateway API | backendRefs.weight در HTTPRoute | canary قابلحمل |
راهحل / نحوهٔ استفاده:
# 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: v2Retry و 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 است.
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| تنظیم | Istio | Linkerd | Envoy (زیرین) |
|---|---|---|---|
| timeout کل | timeout | timeout.linkerd.io/request | timeout در route |
| هر تلاش | perTryTimeout | retry.linkerd.io/timeout | per_try_timeout |
| حداکثر retry | attempts | retry.linkerd.io/limit | num_retries |
| چه چیزی retry شود | retryOn | retry.linkerd.io/http: 5xx (یا کلاسهای gRPC) | retry_on |
| Budget | در VirtualService نیست؛ از حدود circuit breaker استفاده کنید | retry budget در دورهٔ ServiceProfile | retry 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.
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.http1MaxPendingRequests | proxy با 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 است.
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?راهحل / نحوهٔ استفاده:
# 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 | تست fallback | production بدون کلید بازگشت |
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 است.
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 برای هر hop | proxy | نه |
| trace یکپارچه | proxy + برنامه | بله: header را کپی کنید |
| metricهای کسبوکار | برنامه | بله |
راهحل / نحوهٔ استفاده: کد Go و Laravel زیر header را کپی میکند؛ کتابخانهای مثل OpenTelemetry هم وقتی ابزارگذاری شود این کار را خودکار انجام میدهد.
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.
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"| کنترل | Istio | Linkerd |
|---|---|---|
| چه کسی | principals (به سبک SPIFFE) | هویتها در MeshTLSAuthentication |
| چه چیزی | operation با متد و مسیر | port در Server؛ HTTPRoute برای مسیر |
| پیشفرض | اگر ALLOW نباشد مجاز | config.linkerd.io/default-inbound-policy (پیشفرض all-unauthenticated) |
| Audit | action AUDIT | policy پیشفرض 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 یا شبکهٔ مسطح.
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| شیء | دامنه | هدف |
|---|---|---|
| Gateway | workload لبه | listenerهای ورودی، TLS، hostها |
| VirtualService متصل به Gateway | hostها | مسیر درخواستهای بیرونی به داخل |
| ServiceEntry | mesh | ثبت سرویس بیرونی یا VM |
| Egress gateway | workload لبه | یک خروجی کنترلشده |
| Sidecar | namespace یا workload | محدودکردن پیکربندی ارسالی به proxyها |
| Multi-cluster | مجموعهٔ clusterها | اعتماد مشترک، discovery میانcluster |
راهحل / نحوهٔ استفاده:
# 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 استفاده میکند.
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)راهحل / نحوهٔ استفاده:
# 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 برای این فصل ذخیره نشد).
| نیاز | Istio | Linkerd | Consul service mesh |
|---|---|---|---|
| Route و تقسیم | VirtualService + DestinationRule | HTTPRoute (با وزن) | service router/splitter یا Gateway API |
| Retry و timeout | فیلدهای VirtualService | annotation روی HTTPRoute (قدیمیتر: ServiceProfile) | service defaults |
| mTLS | PeerAuthentication | خودکار | خودکار با CA |
| Authorization | AuthorizationPolicy | Server + AuthorizationPolicy + MeshTLSAuthentication | Intentions |
| Proxy | Envoy | linkerd2-proxy | Envoy |
راهحل / نحوهٔ استفاده:
# 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.ioTCP 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.
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 | همهٔ L7 | portها را http- و grpc- نام بگذارید | |
| Kafka، AMQP، Redis (RabbitMQ، Kafka، Redis Streams) | mTLS، metric سطح L4، policy روی TCP | retry، 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 در ambient | hop کمتر، 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 ساده صحبت کنید.
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| وظیفه | Go | Laravel 13 |
|---|---|---|
| انتشار header | propagate.Middleware + propagate.Transport | PropagateMeshHeaders + ماکروی Http::mesh() |
| handler idempotent | جدول کلید، ON CONFLICT DO NOTHING | همان SQL، header Idempotency-Key |
| Readiness | /healthz/ready جدا | ReadinessController |
| HTTP ساده در pod | http.ListenAndServe | trustProxies برای 127.0.0.1 |
راهحل / نحوهٔ استفاده: بخشهای Go و Laravel و 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;-- 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 |
|---|---|---|---|
| 15000 | TCP | Envoy admin (دستور و عیبیابی) | بله |
| 15001 | TCP | گرفتن ترافیک خروجی Envoy | نه |
| 15006 | TCP | گرفتن ترافیک ورودی Envoy | نه |
| 15008 | HTTP/2 | تونل HBONE mTLS (ambient) | نه |
| 15020 | HTTP | telemetry ادغامشدهٔ Prometheus (agent، Envoy، برنامه) | نه |
| 15021 | HTTP | health check | نه |
| 15090 | HTTP | telemetry Prometheus از Envoy | نه |
| 15012 (Istiod) | gRPC | xDS و 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 | چه چیزی حمل میکند |
|---|---|---|
| Listener | LDS | Portها، زنجیرهٔ فیلتر |
| RouteConfiguration | RDS | virtual host، match، timeout، retry |
| Cluster | CDS | گروههای upstream، load balancing، breaker، outlier detection |
| ClusterLoadAssignment | EDS | IP نمونههای یک cluster |
| Secret | SDS | گواهی و کلید |
انواع انتقال (از سند پروتکل 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 با پرچم NR | route تنظیم نشده | DestinationRule، VirtualService، نام port در Service |
503 با پرچم UO | upstream overflow، circuit breaker فعال شد | connectionPool در DestinationRule |
503 با پرچم UF | اتصال به upstream برقرار نشد | ناسازگاری حالت mTLS (tls.mode در DestinationRule)، peer پایین است |
503 با پرچم UC | قطع اتصال upstream | headless 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% را بگذارید.
دستورهای دیباگ
$ 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 برای همهچیز دارد:
// 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 میکند ساخته شده است.
// 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 }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
}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
}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ها.
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 تازه روی هر درخواست خروجی میگذارد.
// 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)
}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) گوش میدهد.
// 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 برای سلامت دارد:
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
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
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
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
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
// 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
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
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
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
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 قابلاستفادهٔ مجدد ثبت میکند وwithHeadersheaderها را به درخواست ادغام میکند؛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 در یک لایه | حلقهٔ سمت برنامه را بردارید یا attempts: 1 در mesh | بار قابلپیشبینی | به توافق میان تیمها نیاز دارد |
| Retry budget | retry بهاندازهٔ کسری از ترافیک (به Budget در Go نگاه کنید) | قطعی retryها را تخلیه میکند | VirtualService در Istio budget ندارد؛ Linkerd و Envoy حدهای شبیه budget دارند |
retryOn محدود | connect-failure,refused-stream نه 5xx | فقط آنچه هرگز به برنامه نرسیده retry میشود | اضافهبار گزارششده توسط برنامه را از دست میدهد |
| timeout برنامه زیر timeout route | برنامه ۲٫۵ ثانیه، route ۳ ثانیه | برنامه fallback را تعیین میکند | هر دو عدد باید هماهنگ بمانند |
| کلیدهای idempotency | Idempotency-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 (پیشفرض ۵ ثانیه) برای تمامشدن اتصالها.
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 exitsJob و 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
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انتخاب
| وضعیت | توصیه | تکنیک اضافه | دلیل |
|---|---|---|---|
| ۵ سرویس، یک زبان، یک تیم | کتابخانه (Resilience4j در Java، go-kit در Go، Laravel HTTP client) | gateway در لبه | mesh بیش از آنچه صرفه میدهد خرج دارد |
| ۴۰ سرویس، ۴ زبان، نیاز zero-trust | mesh با sidecar (Linkerd برای بار عملیاتی کم، Istio برای گستردهترین قابلیت) | mTLS سختگیر، AuthorizationPolicy | یک پیادهسازی امنیت برای همهجا |
| فقط رمزگذاری و هویت بین podها | Istio ambient (ztunnel) یا Cilium | waypoint فقط جایی که L7 لازم است | کمترین هزینه برای هر pod |
| API عمومی، rate limit، auth در لبه | فقط API gateway (به API Gateway، BFF و Service Mesh نگاه کنید) | WAF، rate limiting | mesh جای دغدغههای لبه را نمیگیرد |
| ترافیک سنگین Kafka یا پایگاهداده | خارج از capture یا بهصورت TCP کدر | retry سمت client در broker | proxy در آنجا ارزش L7 اضافه نمیکند |
| محیط تنظیمشده، ممیزی هر فراخوانی | mesh با access log و AUDIT در AuthorizationPolicy | egress gateway | شواهد یکنواخت |
| زیرساخت VM بهعلاوهٔ Kubernetes | Consul service mesh یا Istio با پشتیبانی VM | mesh gateway | policy یکسان در همهٔ پلتفرمها |
| پرسش | mesh با sidecar | Ambient / 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 | حدود ۱۰۰ تا ۴۰۰ pod | mesh برای mTLS یکنواخت میارزد؛ از روز اول محدودسازی Sidecar؛ ارتقا بر پایهٔ revision |
| 100x | هزاران pod، چند cluster | ambient در L4 برای کاهش هزینهٔ هر pod، waypoint جایی که لازم است، چند replica از Istiod، اعتماد multi-cluster، تیم پلتفرمی که مالک mesh است |
آزمایشگاه: retry و budget و trace در sidecar در یک فرایند
آزمایشگاه Go دو برنامه را که هرکدام پشت sidecar خود هستند در یک فرایند اجرا میکند (اجرا شده؛ خروجی زیر). بخش Istio «خروجی موردانتظار؛ اجرا نشده» است (اینجا cluster نداریم).
$ 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های تأخیر در هر اجرا فرق میکند.
آزمایشهایی برای امتحان:
- در آزمایشگاه
RetryRatio: 0بگذارید و دوباره اجرا کنید: خطاهای گذرای اول بهصورت 503 دیده میشوند. - برنامه را طوری کنید که همیشه شکست بخورد:
sidecar_retries_denied_totalپس از مصرف ۱۰ توکن اولیه بالا میرود؛ فراخوانیها به برنامه نزدیک ۱ + ratio بهازای هر درخواست میماند. propagate.Transportرا از برنامهٔ orders بردارید: برنامهٔ inventory trace id دیگری میبیند (trace میشکند).- مسیر
beforeرا با ۱۰ بار retry درون mesh که خودش هم retry میکند اجرا کنید: شمار فراخوانیهای upstream را بشمارید (تقویت).
آزمایشگاه Istio (خروجی موردانتظار؛ اجرا نشده): istio-routing.yaml را روی clusterای با istio-injection=enabled اعمال کنید، سپس:
$ 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 یعنی بدون proxy | ztunnel در هر 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 plane | Envoy، linkerd2-proxy، ztunnel، waypoint |
| Control plane | Istiod، 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 کنید |
| Capture | iptables به ۱۵۰۰۶ ورودی و ۱۵۰۰۱ خروجی؛ UID 1337 رزرو است |
| mTLS | ابتدا PERMISSIVE بعد STRICT؛ در صورت نیاز ISTIO_MUTUAL در DestinationRule |
| Routing | VirtualService (کجا) + DestinationRule (چگونه، subset) |
| Retry | پیشفرض ۲ تلاش، timeout خاموش؛ فقط یک لایه؛ فقط routeهای idempotent |
| Breaking | حدود connectionPool و اخراج با outlierDetection، نه breaker با حالت |
| Policy | ترتیب CUSTOM، DENY، ALLOW؛ وجود ALLOW یعنی پیشفرض deny |
| Observability | golden 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) |
| Envoy | proxy لایهٔ ۷ به زبان C++ که Istio، Consul و دیگران به کار میبرند |
| linkerd2-proxy | micro-proxy Rust در Linkerd |
| Istiod | باینری یکپارچهٔ control plane در Istio |
| xDS | APIهای discovery در Envoy: LDS، RDS، CDS، EDS، SDS |
| Sidecar injection (تزریق سایدکار) | افزودن کانتینر proxy با mutating webhook |
| Ambient mesh | data plane Istio بدون proxy درون pod |
| ztunnel | proxy L4 در هر node در حالت ambient |
| Waypoint proxy | Envoyای که برای قابلیت L7 در ambient مستقر میشود |
| HBONE | تونل مبتنی بر HTTP CONNECT بین مؤلفههای ambient |
| Cilium | CNI با 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-id | header همبستگی درخواست در Envoy |
| traceparent | header W3C Trace Context |
| Egress gateway | نقطهٔ خروج کنترلشده از mesh |
| Multi-cluster (چند خوشهای) | یک mesh در چند cluster با اعتماد مشترک |
| Gateway API | API استاندارد Kubernetes (Gateway، HTTPRoute) |
| HTTPRoute | شیء route در Gateway API؛ در GAMMA به Service وصل میشود |
| ServiceProfile | CRD قدیمیتر Linkerd برای پیکربندی هر route |
| Linkerd | mesh از CNCF با proxy Rust خودش |
| Consul service mesh | mesh از 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 ترافیک بگیرد یا نه |
منابع
- Envoy: What is Envoy، xDS REST and gRPC protocol، Outlier detection، Administration interface
- Istio: Traffic management، Security، Observability، Ambient overview، Performance and scalability، Debugging Envoy and Istiod، Protocol selection، Application requirements، Sidecar injection، Traffic management problems، Health checking، Distributed tracing overview، Mirroring، Egress gateways، Circuit breaking، MeshConfig reference
- مرجع Istio: VirtualService، DestinationRule، Sidecar، ServiceEntry، Gateway، PeerAuthentication، AuthorizationPolicy
- Linkerd: Architecture، Automatic mTLS، Retries and timeouts، Server policy، Authorization policy reference
- Kubernetes: Sidecar containers، Init containers
- Gateway API: Gateway API for service mesh (GAMMA)
- Cilium: Service Mesh
- W3C: Trace Context
- Go:
net/http/httputil - Laravel 13: HTTP Client، Middleware، Octane، Service Container