Deployment Strategy: Rolling، Blue-Green، Canary، Progressive Delivery و Rollback
"We define canarying as a partial and time-limited deployment of a change in a service and its evaluation. This evaluation helps us decide whether or not to proceed with the rollout." — Google، The Site Reliability Workbook، فصل "Canarying Releases"
خلاصه (Summary): استقرار (Deployment) کد تازه را روی ماشینها میگذارد؛ انتشار (Release) آن را در اختیار کاربران قرار میدهد؛ استقرار تدریجی (Rollout) شیوهٔ حرکت میان این دو است. بازسازی (Recreate)، بهروزرسانی تدریجی (Rolling update)، آبی/سبز (Blue-green)، قناری (Canary)، تحویل تدریجی (Progressive delivery) و پرچم قابلیت (Feature flag) به سه سؤال پاسخ میدهند: چند کاربر همزمان نسخهٔ تازه را میبینند، خرابی را چگونه تشخیص میدهیم و با چه سرعتی بازگشت (Rollback) میکنیم؟ پاسخ بیش از انتخاب ابزار به دو اصل وابسته است: نسخهٔ قبلی باید با پایگاه دادهٔ فعلی کار کند و سلامت باید اندازهگیری شود، نه با نگاهکردن به نمودار حدس زده شود. تمرکز (Focus): مرز Deployment، Release و Rollout؛ Recreate و Rolling update با ارجاع به فصل Workload؛ تعویض محیط (Environment switch) در Blue-green از طریق انتخابگر (Selector) یک Service، Ingress یا متوازنکنندهٔ بار (Load balancer)؛ وزن ترافیک (Traffic weight)، مسیریابی بر اساس سرآیند (Header-based routing) و کوکی (Cookie-based routing) در Canary با annotationهای Ingress-NGINX، وزنهای backendRefs در HTTPRoute و تقسیم ترافیک شبکهٔ سرویس (Service mesh) با Istio VirtualService، Linkerd HTTPRoute و SMI TrafficSplit منسوخ؛ کنترلگرهای Progressive delivery یعنی Argo Rollouts با Rollout CRD، گامهای setWeight و pause، تحلیل (Analysis) با AnalysisTemplate و AnalysisRun و تأمینکنندهٔ سنجه (Metrics provider) یعنی Prometheus، ارتقا (Promotion)، توقف انتشار (Abort) و Rollback خودکار، و Flagger با Canary CRD و MetricTemplate؛ تفاوت آزمایش A/B با Canary، ترافیک سایه (Shadow traffic) و انتشار پنهان (Dark launch)؛ OpenFeature، ارزیابی پرچم (Flag evaluation)، قواعد هدفگیری (Targeting rules)، انتشار درصدی (Percentage rollout)، کلید قطع اضطراری (Kill switch) و بدهی پرچم (Flag debt) در LaunchDarkly، Unleash، Flagsmith و Laravel Pennant؛ تثبیت تصویر (Image) با چکیدهٔ محتوا (Digest)، kubectl rollout undo، تاریخچهٔ بازبینی (Revision history)، Helm rollback، برگرداندن تغییر GitOps و پنجرهٔ Rollback در Argo Rollouts؛ سازگاری با نسخهٔ قبلی (N-1 compatibility)، گسترش/انقباض (Expand/Contract)، مهاجرت فقط روبهجلو (Forward-only migrations) و ترتیب مهاجرت پایگاه داده (Migration ordering)؛ سلامت انتشار (Release health)، نرخ خطا، تأخیر صدک نودونهم (p99 latency)، ارتقای مبتنی بر هدف سطح خدمت (SLO-based promotion) و نرخ مصرف بودجهٔ خطا (Error budget burn rate)؛ توقف استقرار (Deployment freeze) و بازهٔ مجاز تغییر (Change window)؛ زیرساخت تغییرناپذیر (Immutable infrastructure)، AMI، نوسازی نمونهها (Instance refresh) در ASG و تعویض پیوند نمادین انتشار (Symlink release switch) در Capistrano و Deployer؛ آمادگی (Readiness)، دروازهٔ آمادگی (Readiness gate)، preStop و تخلیهٔ اتصال (Connection draining) در Go؛ بارگذاری مجدد php-fpm، OPcache و $realpath_root، حالت نگهداری (Maintenance mode) با artisan down --with-secret، Octane reload، config:cache/route:cache و queue:restart در Laravel؛ تأیید پس از استقرار (Post-deploy verification)، پایش مصنوعی (Synthetic monitoring)، دستورکار عملیاتی (Runbook) و سنجههای DORA. هدف یادگیری (Learning goal): برای یک سرویس، راهبردی انتخاب کنید و آن را با گسترهٔ اثر خرابی (Blast radius)، هزینه و زمان Rollback توجیه کنید. Manifestهای تعویض Blue-green، Canary با Ingress یا Gateway API و Rollout تدریجی با Argo Rollouts یا Flagger و دروازههای سنجهای را بنویسید. سرویس Go و برنامهٔ Laravel را طوری آماده کنید که درخواستها در هیچیک قطع نشوند؛ تغییر طرحواره (Schema) را به انتشارهای سازگار با N-1 تقسیم کنید و انتشار خراب را از سریعترین راه امن برگردانید.
این فصل در گروه Delivery & Infrastructure قرار دارد. جایگزینی Podها در Deployment، شامل maxSurge، maxUnavailable، minReadySeconds، کاوشگر سلامت (Probe)، PodDisruptionBudget و ترتیب پایان کار در بارهای کاری Kubernetes آمده است. خط لوله (Pipeline) ساخت، امضا و ارتقای مصنوع (Artifact) میان محیطها در CI/CD و موتور اعمال Git به خوشه (Cluster) در GitOps با Argo CD و Flux است. جزئیات Helm و Kustomize و helm rollback را در بستهبندی Kubernetes، داشبورد و عیبیابی با kubectl را در مشاهدهپذیری Kubernetes و اسکریپت تعویض اتمی Symlink را در اسکریپتنویسی Shell بخوانید. جایگاه Progressive delivery، Feature flag و Kill switch در فرایند امن تحویل متعلق به Secure SDLC و پاسخ به رخداد است. Expand/Contract، قفل (Lock) و تکمیل دادههای قبلی (Backfill) در مهاجرت Schema، الگوریتم Load balancer و Connection draining در توزیع بار، هدف سطح خدمت (SLO) و بودجهٔ خطا در SLA، SLO و SLI، هشدار Burn rate در هشدار مؤثر و رسیدگی به SIGTERM در Go در سیستمعامل، پردازه و سیگنال شرح داده شدهاند.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| مرور کل صفحه در سه جدول | همهچیز در یک دقیقه |
| چرا Deploy نباید همان Release باشد | چرا وجود دارد |
| نوشتههای Fowler، Canary در SRE، DORA، عرضهٔ عمومی Gateway API و بازنشستگی Ingress-NGINX | از کجا آمده |
| تفاوت Deployment، Release و Rollout | سه مفهوم |
| راهبرد Recreate و پیوند Rolling update در فصل Workload | Recreate و Rolling |
| تعویض محیط Blue-green با Service selector، Ingress یا Load balancer | Blue-green |
| انتشار Canary با وزن ترافیک، Header یا Cookie | Canary |
nginx.ingress.kubernetes.io/canary-weight و بقیهٔ annotationهای Canary | Ingress-NGINX |
| HTTPRoute و وزن backendRefs در Gateway API | Gateway API |
| تقسیم ترافیک Mesh با Istio VirtualService و جایگزینی TrafficSplit با HTTPRoute در Linkerd | تقسیم ترافیک Mesh |
| Rollout CRD، گامهای setWeight و pause، AnalysisTemplate و AnalysisRun با Prometheus، Promotion، Abort و Rollback خودکار | Argo Rollouts |
| Flagger و Canary CRD آن | Flagger |
| سلامت Release، تأخیر p99، ارتقای مبتنی بر SLO و Burn rate | سلامت انتشار |
| تفاوت A/B و Canary، Shadow traffic و Dark launch | A/B، سایه و پنهان |
| Feature flag با OpenFeature، ارزیابی، قواعد هدفگیری، انتشار درصدی، Kill switch و بدهی پرچم | Feature flag |
| Rollback با Digest ثابت، kubectl rollout undo، تاریخچهٔ Revision، Helm و GitOps revert | سازوکار Rollback |
| انتشار سازگار با پایگاه داده و N-1، سازگاری عقبرو، Migration روبهجلو، ترتیب اجرا و پیوند Expand/Contract | انتشار سازگار |
| استقرار بدون قطعی با Readiness gate، preStop و Connection draining | جزئیات بدون قطعی |
| Immutable infrastructure، AMI، Instance refresh، تعویض Symlink، Capistrano و Deployer | راهبردهای VM |
| php-fpm reload، Maintenance mode، artisan down --with-secret، Octane reload، config:cache route:cache و queue:restart | Laravel بدون قطعی |
| Freeze و Change window، تست سلامت اولیه (Smoke test)، پایش مصنوعی، تأیید پس از استقرار، Runbook و DORA | تأیید و دستورکار |
| تغییرهای کنترلگر در هر گام، حساب وزنها، بودجهٔ زمان، تنظیمات و پیامها | سازوکار |
| قطعهکدها | Go، Laravel |
| ده مسئلهٔ کلاسیک | حل مسئلهها |
| انتخاب راهبرد، لایهٔ ترافیک، کنترلگر و سامانهٔ Flag | انتخاب |
| رشد از یک VM تا چند Cluster | در معماری |
| فرمان با خروجی واقعی یا مورد انتظار | آزمایشگاه |
| باورهای نادرست، مرور، پرسش و اصطلاح | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه (Everything in one minute)
راهبردها در یک جدول.
| راهبرد | چه کسی نسخهٔ تازه را میبیند | هزینهٔ ظرفیت | Rollback | نیاز | مناسب برای |
|---|---|---|---|---|---|
| بازسازی (Recreate) | همه، پس از وقفه | 1x | استقرار دوبارهٔ قبلی، با وقفهٔ تازه | هیچ | نسخههای ناسازگار برای اجرای همزمان؛ محیط توسعه |
| بهروزرسانی تدریجی (Rolling update) | همه، تدریجی بر اساس تعداد Pod | 1x + maxSurge | kubectl rollout undo؛ یک Rolling update دیگر | Readiness probe و N-1 | پیشفرض سرویسهای بدون وضعیت |
| آبی/سبز (Blue-green) | ابتدا هیچکس، سپس همه | 2x هنگام انتشار | برگرداندن یک Selector یا LB در چند ثانیه | دو محیط، نقطهٔ تعویض، DB سازگار با N-1 | تست کامل محیط تازه در Production پیش از رسیدن کاربر |
| قناری (Canary) وزنی | سهم تصادفی کوچک، سپس بزرگتر | 1x + Podهای Canary | وزن 0 | مسیریاب L7 یعنی Ingress، Gateway یا Mesh، یا نسبت Replica | سرویس پرترافیک با آشکارشدن سریع افت سلامت در سنجهها |
| تحویل تدریجی (Progressive delivery) | گامهای Canary هدایتشده با سنجه | 1x + Canary؛ با Traffic routing، stable پیشفرض 100 % میماند | Abort خودکار پس از Analysis ناموفق | Argo Rollouts یا Flagger و Prometheus | سرویس و استقرار زیاد بدون ناظر انسانی برای هرکدام |
| پرچم قابلیت (Feature flag) | کسانی که قواعد هدفگیری انتخاب کنند | 1x | خاموشکردن Flag، بدون Deploy | OpenFeature و Provider | جداسازی Release از Deploy، هدفگیری کاربر و Kill switch |
| آزمایش A/B | سهم ثابت و ماندگار هر کاربر برای چند روز | 1x + گونهٔ آزمایش | پایان آزمایش | Flag یا Header/Cookie routing و تحلیل محصول | سؤال محصول، نه ایمنی انتشار |
| سایه / انتشار پنهان (Shadow / Dark launch) | هیچکس؛ پاسخ دور ریخته یا پنهان میشود | بار اضافی روی نسخهٔ تازه | توقف Mirroring | Mirroring در Mesh/Gateway یا Flag | بار و صحت Backend تازه پیش از Release |
تصمیم ترافیکی کجا گرفته میشود؟
| لایه (Layer) | شیء و فیلد | تقسیم وزنی | بر اساس Header / Cookie | کپی ترافیک (Mirroring) | وضعیت در 2026 |
|---|---|---|---|---|---|
| Kubernetes Service | spec.selector | فقط نسبت نمونهها (Replica) | خیر | خیر | هستهٔ Kubernetes؛ نقطهٔ تعویض Blue-green |
| Ingress-NGINX | Ingress دوم با nginx.ingress.kubernetes.io/canary-* | canary-weight از canary-weight-total با پیشفرض 100 | canary-by-header، canary-by-cookie | خیر | بازنشسته در مارس 2026؛ Ingress API منجمد |
| Gateway API | HTTPRoute.spec.rules[].backendRefs[].weight | وزن نسبی | matches.headers | فیلتر RequestMirror؛ پشتیبانی Extended | GA از v1.0 در 31 اکتبر 2023؛ v1.7.0 در 29 اکتبر 2026 |
| Istio | VirtualService.spec.http[].route[].weight و زیرمجموعههای DestinationRule | بله | match.headers | mirror و mirrorPercentage | Gateway API را هم پشتیبانی میکند |
| Linkerd | HTTPRoute با policy.linkerd.io/v1beta2 یا Gateway API | وزن backendRefs | matches.headers | خیر | SMI TrafficSplit منسوخ |
| Cloud LB شامل ALB، NLB و Cloud Load Balancing | Target group یا Backend service وزنی | بله | قواعد Listener در ALB | متفاوت | نقطهٔ تعویض Blue-green روی VM نیز هست |
سریعترین راه بازگشت، بهترتیب.
| آنچه دارید | سریعترین Rollback | زمان | چه چیزی برنمیگردد |
|---|---|---|---|
| Feature flag دور تغییر | خاموشکردن Flag | چند ثانیه | Schema و دادهٔ نوشتهشده توسط مسیر تازه |
| Canary در حال اجرا | kubectl argo rollouts abort یا Rollback در Flagger | چند ثانیه | Spec در Git هنوز N+1 است |
| Blue-green با محیط قبلی روشن | Patch معکوس Selector یا تعویض LB | چند ثانیه | همان مورد بالا |
| چیدمان Symlink روی VM | اشارهٔ current به انتشار قبلی و reload کردن php-fpm | چند ثانیه | Migration اجراشده |
| Deployment معمولی | kubectl rollout undo؛ فقط Pod template | یک Rolling update | ConfigMap، Secret، تعداد Replica و اشیای دیگر |
| Helm | helm rollback RELEASE [REVISION] | یک Upgrade | داده، CRD و اثر جانبی Hook |
| GitOps با Argo CD یا Flux | git revert تغییر Image و Sync کنترلگر | یک Sync و Rollout | هر وضعیت Cluster که در Git توصیف نشده |
| Migration مخرب | اصلاح با انتشار تازه (Roll forward) | یک Release | اصل اشتباه همین بوده؛ با Expand/Contract پیشگیری کنید |
چرا وجود دارد (Why it exists)
بیشتر قطعیها از تغییر خودمان شروع میشوند: چیزی منتشر میشود و بخشی میشکند. کتاب کار SRE گوگل قناری (Canary) را پاسخ همین مسئله میداند؛ ابتدا تغییر را به بخش کوچکی از محیط عملیاتی (Production) بفرستید، با بقیه مقایسه کنید و بعد ادامه دهید. بقیهٔ راهبردها هم همین بدهبستان را دارند: ظرفیت، زمان یا مؤلفهای اضافه میدهیم تا انتشار خراب افراد کمتری را درگیر کند، زودتر دیده شود و سریعتر برگردد.
اصل دوم این است که استقرار (Deployment) و انتشار (Release) دو عمل جدا هستند. اگر نمایش قابلیت فقط با Deploy ممکن باشد، هر Deploy یک Release و هر بازگشت (Rollback) یک Deploy است. کد پنهان پشت Flag، نسخهای با ترافیک صفر یا محیط green آماده ولی بدون Route این وابستگی را میشکنند. Deploy عادی و مکرر میشود؛ Release به تغییر پیکربندی (Config) تبدیل میشود که چندثانیهای برمیگردد.
| انتخاب سادهتر | انتخاب کاملتر | دستاورد | هزینه |
|---|---|---|---|
| Recreate | Rolling update | حذف قطعی | دو نسخه همزمان باید DB و API مشترک را تحمل کنند |
| Rolling update | Blue-green | تست کامل محیط پیش از کاربر؛ تعویض فوری به قبلی | ظرفیت دوبرابر و تعویض همه یا هیچ |
| Rolling update | Canary وزنی | نسخهٔ خراب 5 % درخواستها را درگیر میکند، نه 100 % | مسیریاب L7 و سنجهٔ قابل مقایسه برای 5 % در برابر 95 % |
| Canary دستی | کنترلگر Progressive delivery | دروازهٔ سنجهای و Abort خودکار، حتی ساعت 3 صبح | کنترلگر، CRD و پرسوجوی قابل اعتماد Prometheus |
| Deploy = Release | Feature flag | Release و Rollback بدون Deploy و هدفگیری هر کاربر | سرویس Flag در مسیر درخواست و بدهی Flag |
kubectl rollout undo | GitOps revert | توافق Git و Cluster پس از Rollback | یک گام Pipeline میان تصمیم و اثر |
| سرور قابل تغییر | Image تغییرناپذیر با AMI یا Digest کانتینر | مقصد Rollback یک Artifact شناختهشده است | ساخت Image برای هر Release |
تشبیه مشترک فصل: رستورانی که منو را عوض میکند. Recreate رستوران را یک بعدازظهر میبندد و با منوی تازه باز میکند. Rolling update آشپزها را یکییکی عوض میکند؛ مدتی غذاهای قدیم و جدید همزمان سرو میشوند، پس آشپزخانه یعنی DB باید مواد هر دو را داشته باشد. Blue-green آشپزخانهٔ دومی کنار اولی میسازد، یک نوبت کامل آن را آزمایش میکند و بعد تابلو ورودی را میچرخاند؛ خرابی یعنی برگرداندن تابلو. Canary غذای تازه را به یک میز از هر بیست میز میدهد؛ Progressive delivery پیشخدمتی دارد که شکایتها را میشمارد و غذا را خودکار از منو خارج میکند. Feature flag غذا را فقط برای کارکنان نشان میدهد. Dark launch برای هر سفارش غذا را میپزد و دور میریزد تا ظرفیت آشپزخانه سنجیده شود. Expand/Contract هم میگوید تا وقتی آشپزی از مادهای استفاده میکند، آن ماده را حذف نکنید.
سه بدفهمی در آغاز (Three common misunderstandings, up front)
۱. «Rollback همیشه انتخاب امن است.» فقط وقتی نسخهٔ قبلی هنوز اجرا شود. Kubernetes میگوید kubectl rollout undo تنها "only the Deployment's Pod template part" را برمیگرداند؛ DB را تغییر نمیدهد. حذف یا تغییر نام ستون باعث شکست کد قبلی روی Schema تازه میشود و راه درست، اصلاح روبهجلو است. انتشار سازگار را ببینید. ۲. «Canary دهدرصدی یعنی ده درصد کاربران.» canary-weight در Ingress-NGINX برابر "percent of random requests" است؛ درخواست بعدی همان کاربر ممکن است به نسخهٔ دیگر برسد. وزن Gateway API هم به درخواست مربوط است. ماندگاری انتخاب برای هر کاربر (Stickiness) به Cookie، Header یا Flag با کلید کاربر نیاز دارد. Canary. ۳. «Rollback در Argo Rollouts، Git را هم اصلاح میکند.» FAQ میگوید: "Argo Rollouts doesn't read/write anything to Git." پس از Abort، Cluster نسخهٔ قدیمی را اجرا میکند ولی Git هنوز تازه را میخواهد؛ باید Commit برگردد یا اصلاح شود. سازوکار Rollback.
از کجا آمده (Where it comes from)
| زمان | رویداد | منبع |
|---|---|---|
| 2006 | Joshua Kerievsky راهبرد بازآرایی بعداً موسوم به Parallel change را مستند میکند: expand، migrate، contract | Fowler، ParallelChange |
| 1 مارس 2010 | مدخل BlueGreenDeployment در bliki فاولر؛ منشأ نام: "some foggy combination of Daniel Terhorst-North and Jez Humble" | martinfowler.com |
| 29 اکتبر 2010 | مدخل FeatureToggle؛ هر دو واژهٔ flag و toggle رایجاند | martinfowler.com |
| 13 مه 2014 | مدخل ParallelChange | martinfowler.com |
| 25 ژوئن 2014 | CanaryRelease نوشتهٔ Danilo Sato: انتشار "to a small subset of users before rolling it out to the entire infrastructure" | martinfowler.com |
| 2014 | نخستین مطالعهٔ DORA با بسامد استقرار، Lead time تغییر، میانگین بازیابی و نرخ شکست تغییر آغاز میشود | تاریخچهٔ سنجهها در dora.dev |
| Kubernetes v1.14 | Readiness gate با readinessGates پایدار میشود | مستندات چرخهٔ حیات Pod |
| 3 اکتبر 2023 | CNCF پروژهٔ Service Mesh Interface یا SMI را بایگانی میکند؛ TrafficSplit آن در Linkerd و Argo Rollouts پشتیبانی میشد | SMI README |
| 2023 | DORA نام MTTR را به Failed deployment recovery time تغییر میدهد | تاریخچهٔ DORA |
| 31 اکتبر 2023 | Gateway API v1.0 به GA میرسد؛ HTTPRoute وزنی استاندارد است | وبلاگ Kubernetes |
| 2024 | پنجمین سنجهٔ DORA، Deployment rework rate، اضافه میشود | تاریخچهٔ DORA |
| 11 نوامبر 2025 | SIG Network بازنشستگی Ingress NGINX را اعلام میکند؛ نگهداری در حد توان تا مارس 2026 | وبلاگ Kubernetes |
| Kubernetes v1.34 | عمل sleep در چرخهٔ حیات با preStop.sleep.seconds پایدار میشود | Feature gate با نام PodLifecycleSleepAction |
| 2026 | Argo Rollouts v1.10.2 در 4 نوامبر و v1.11.0-rc1 در 5 نوامبر؛ Flagger v1.45.0 در 1 سپتامبر؛ Gateway API v1.7.0 در 29 اکتبر | انتشارهای GitHub |
دو جریان اینجا به هم میرسند. تحویل پیوسته (Continuous delivery)، از کتاب Humble و Farley تا bliki فاولر و سخنرانیهای دوران Flickr دربارهٔ چند Deploy روزانه، استقرار را عملی عادی، خودکار و برگشتپذیر میبیند. واژگان Blue-green، Canary، Feature toggle، Dark launch و Parallel change از همین نگاه آمدهاند. جریان مهندسی قابلیت اطمینان سایت (SRE) با فصلهای Release engineering و Canarying گوگل، اندازهگیری را اضافه میکند: ارزش Canary به مقایسه با گروه کنترل (Control) و بررسی مطلق SLO وابسته است. Kubernetes بستر مشترک داد؛ Deployment، Rolling update را پیشفرض کرد؛ Ingress و سپس Gateway API و Mesh وزن ترافیک را به فیلد YAML تبدیل کردند؛ Argo Rollouts و Flagger «Deploy کن، داشبورد ببین، تصمیم بگیر» را به حلقهٔ کنترل بدل کردند. پژوهش DORA نتیجه را با چهار و اکنون پنج سنجهٔ تحویل قابل اندازهگیری کرد.
فهرست مفاهیم (The concept catalogue)
هر بخش ترتیب یکسانی دارد: ابتدا مفهوم را به زبان ساده میگوییم، سپس بدفهمی رایج و تعریف دقیق را میآوریم. توالی اجرا، سناریوهای واقعی، رفتار هر محصول و راهحل عملی پس از آن میآیند.
استقرار، انتشار و حرکت میان آنها (Deployment, release and rollout) حیاتی
به زبان ساده: استقرار (Deployment) یعنی نسخهٔ تازه جایی نصب شود که بتواند اجرا شود. انتشار (Release) یعنی کاربر به آن برسد. استقرار تدریجی (Rollout) راه میان این دو است: چند کاربر، به چه ترتیب و با چه بررسیهایی.
بدفهمی رایج: «فرق Deploy و Release فقط واژه است.» این انتخاب معماری است. فاولر Dark launch را فراخوانی کد Backend تازه "from existing users without the users being able to tell it's being called" توصیف میکند؛ مستقر شده ولی منتشر نشده. محیط green که Smoke test را گذرانده ولی ترافیک ندارد همین وضعیت را دارد. Feature flag صفر درصد هم این جداسازی را داخل یک Binary ایجاد میکند.
تعریف: Deployment در این فصل یعنی اجرای Artifact، مانند Image digest، AMI یا پوشهٔ Release، در زیرساخت Production. Release رسیدن ترافیک یا کاربران واقعی به رفتار تازه است. Rollout پیشروی کنترلشدهٔ Release است؛ یکباره، با تعداد Pod، وزن ترافیک یا گروه کاربران (Cohort). پایان آن ارتقا (Promotion)، یعنی تبدیل نسخهٔ تازه به stable، یا بازگشت (Rollback)، یعنی سرویسدهی دوبارهٔ قبلی است. Kubernetes واژهٔ rollout را برای تعویض Podهای Deployment در kubectl rollout status|undo|history به کار میبرد؛ CRD در Argo Rollouts هم از همین نام گرفته شده است.
Release 1.5.0 of orders-api, decoupled
1 CI builds and signs ghcr.io/acme/orders-api@sha256:d1... (artefact)
2 GitOps commit sets the digest; Argo CD syncs the Rollout (deployment starts)
3 Canary Pods run 1.5.0; HTTPRoute weight 0 -> 5 % (deployment done, release begins)
4 new-checkout flag still 0 %: the new checkout code is deployed and dark
5 analysis passes at 5, 20, 50 %; weight 100 % (promotion: 1.5.0 is stable)
6 product turns new-checkout on for staff, then 5 %, then 100 % (release of the feature)
7 next release removes the flag and the old code path (flag debt paid)سناریوهای واقعی:
- رونمایی بازاریابی سهشنبه ساعت ده: کد هفتهٔ قبل پشت Flag مستقر شده؛ رونمایی فقط تغییر Flag است و به توقف Deploy نیازی ندارد.
- یکپارچهسازی ارائهدهندهٔ پرداخت روی همهٔ Podهاست ولی فقط برای یک پذیرنده فعال میشود تا گزارش تطبیق حساب درست باشد.
- Rollback انتشار یعنی تغییر Flag؛ Rollback استقرار یعنی تغییر Artifact در حال اجرا. اینها دو عملیات جدا هستند.
- Backend موبایل باید APIهای قدیمی را نگه دارد؛ انتشار در فروشگاه برنامه چند هفته از استقرار عقب میماند و زمانبندی این دو ذاتاً جداست.
| ابزار | معنای Deploy / Release در آن |
|---|---|
| Kubernetes Deployment | rollout یعنی تغییر Pod template؛ مفهوم انتشار ترافیک ندارد |
| Argo Rollouts / Flagger | گام Rollout یا Analysis در Canary یعنی Release بر اساس سهم ترافیک |
| Helm | release یعنی نمونهٔ نصبشده (Instance) از Chart با Revisionها؛ در واژگان این فصل Deployment است |
| LaunchDarkly / Unleash / Flagsmith / OpenFeature | Release با هدفگیری و درصد، بدون Deploy |
| GitHub Actions / GitLab environments | Job استقرار در Environment با قواعد حفاظت |
| DORA | Deployment frequency تعداد استقرارهای Production را میشمارد |
راهحل / روش استفاده: «مستقر ولی منتشرنشده» را حالت عادی کنید. هر تغییر را پنهان، با Flag خاموش، وزن صفر یا محیط بیترافیک بفرستید؛ در Production تأیید کنید و مرحلهای منتشر کنید. در Runbook عبارت دقیق بنویسید: «Flag را برگردان» و «Image را برگردان» روش و گسترهٔ اثر متفاوت دارند.
بازسازی و بهروزرسانی تدریجی (Recreate strategy and the rolling update) حیاتی
به زبان ساده: بازسازی (Recreate) همهچیز را متوقف میکند و بعد نسخهٔ تازه را بالا میآورد. بهروزرسانی تدریجی (Rolling update) چند Pod را هر بار عوض میکند؛ مدتی هر دو نسخه پاسخ میدهند.
بدفهمی رایج: «Recreate برای تازهکارهاست.» وقتی دو نسخه نباید همزمان اجرا شوند، این انتخاب صادقانه است: Singleton دارای Lock انحصاری، تغییر Schema ناسازگار با N-1 یا محیط توسعه با یک نمونه (Replica). Kubernetes دقیقاً مشخص میکند چه تضمینی دارد.
تعریف: مقدار .spec.strategy.type طبق مستندات "can be "Recreate" or "RollingUpdate". "RollingUpdate" is the default value." در Recreate، "All existing Pods are killed before new ones are created"؛ اما تضمین فقط مربوط به Upgrade است: "If you manually delete a Pod, the lifecycle is controlled by the ReplicaSet and the replacement will be created immediately". جزئیات Rolling update با maxSurge، maxUnavailable، minReadySeconds، progressDeadlineSeconds و Readiness probe در بارهای کاری Kubernetes، بخش Deployment است. جدول مقایسهٔ Kubernetes، قطعی Rolling update را "None" و ریسک آن را "Low — gradual rollout" مینامد؛ Recreate قطعی دارد و برای "Incompatible versions" است؛ ریسک Canary برابر "Lowest — small traffic percentage" توصیف میشود.
Recreate, 4 replicas, 1.4.2 -> 1.5.0
T0 4 x 1.4.2 Ready
T1 scale old ReplicaSet to 0; Pods Terminating (preStop, SIGTERM, drain)
T2 all old Pods gone <- no Pod serves: downtime starts
T3 new ReplicaSet 4 x 1.5.0 created, pulling, starting
T4 readiness passes <- downtime ends
Rolling (maxSurge 25 %, maxUnavailable 0): T0..Tn always >= 4 Ready, mixed versionsسناریوهای واقعی:
- مصرفکنندهٔ صفی که تنها پردازشکنندهٔ یک Partition باید باشد: Recreate با پذیرش مکث کوتاه مصرف.
- Deployment زمانبند Laravel با یک Replica: Recreate از همپوشانی دو زمانبند هنگام Update جلوگیری میکند.
- سرویس وب: Rolling با Readiness gate تا Image خراب ترافیک نگیرد و Rollout روی نخستین Pod تازه متوقف بماند.
- API با تغییر ناسازگار قالب پاسخ: هیچیک کافی نیست؛ ابتدا هر دو قالب را پشتیبانی کنید و بعد Rollout انجام دهید.
| سکوی اجرا (Platform) | معادل Recreate | معادل Rolling |
|---|---|---|
| Kubernetes Deployment | strategy.type: Recreate | RollingUpdate پیشفرض |
| Kubernetes StatefulSet | راهبرد Update با Recreate: "deletes all of the StatefulSet's Pods before creating new Pods"؛ alpha با StatefulSetRecreateStrategy. گزینهٔ OnDelete متفاوت است: کنترلگر "will not automatically update the Pods" تا خودتان حذف کنید | RollingUpdate با partition |
| Argo Rollouts | از Deployment استفاده کنید | canary بدون گام مانند Rolling update عمل میکند |
| AWS ASG | جایگزینی همهٔ Instanceها | Instance refresh با راهبرد Rolling |
| Docker Compose / تک VM | docker compose up -d؛ توقف، شروع | چند میزبان پشت LB، یکییکی |
راهحل: پیشفرض را Rolling با Readiness probe و maxUnavailable: 0 بگذارید. Recreate را آگاهانه انتخاب و دلیلش را ثبت کنید. اگر دلیل ناسازگاری نسخههاست، ابتدا بررسی کنید آیا یک گام Expand آنها را سازگار میکند.
تعویض محیط آبی/سبز در Service، Ingress یا Load balancer (Blue-green deployment) حیاتی
به زبان ساده: در آبی/سبز (Blue-green) دو کپی کامل از Production دارید. blue به کاربر پاسخ میدهد؛ green را Deploy و تست میکنید و سپس نقطهٔ هدایت کاربر را عوض میکنید. blue را روشن نگه دارید تا راه برگشت آماده باشد.
بدفهمی رایج: «محیط جداست، پس مشکل DB نداریم.» فاولر برعکس میگوید: "Databases can often be a challenge with this technique". معمولاً هر دو رنگ یک DB دارند و Schema باید هر دو نسخه را پشتیبانی کند: "first apply a database refactoring to change the schema to support both the new and old version of the application, deploy that, check everything is working fine so you have a rollback point, then deploy the new version of the application."
تعریف: فاولر: "you have two production environments, as identical as possible. At any time one of them, let's say blue for the example, is live." پس از تست green: "you switch the router so that all incoming requests go to the green environment"؛ برای بازگشت: "if anything goes wrong you switch the router back to your blue environment." تعویض محیط (Environment switch) سه جای ممکن دارد: تعویض Service selector با تغییر spec.selector از slot: blue به slot: green، تغییر Ingress یا Gateway route به Service دیگر، و تعویض Load balancer با Listener یا Target group وزنی و گاهی DNS. Argo Rollouts روش Selector را خودکار میکند: "a unique hash of the ReplicaSet" را در Selector سرویس active و preview میگذارد و هنگام Promotion، active را عوض میکند.
Blue-green with scripts/blue-green-switch.sh
1 green Deployment rolled out with 1.5.0 (all replicas Ready); live Service selects slot=blue
2 patch orders-api-preview -> slot=green; smoke test PREVIEW_URL/version == 1.5.0
3 patch orders-api selector -> slot=green (one API call); EndpointSlices update
4 kube-proxy / Gateway converge: a few seconds where old and new both answer
5 verify LIVE_URL: 20 requests must report 1.5.0 (5 grace requests); else patch back to blue, exit 5
6 blue stays up (scaleDownDelaySeconds in Argo Rollouts, default 30 s) as the instant rollback targetسناریوهای واقعی:
- فروشگاه Laravel با شرط سخت «عدم اختلاط نسخهها» بهدلیل تغییر قالب Session: Blue-green رفتوبرگشت درخواست میان نسخهها را حذف میکند، ولی Session کاربرِ وسط خرید هنگام تعویض همچنان باید سازگار باشد.
- API نیازمند Cache گرم: green پیش از تعویض با Shadow traffic گرم میشود.
- AWS ALB همراه Blue-green در Argo Rollouts: مستندات هشدار میدهند "ALB Ingress with Rollouts blue-green strategy is not supported without a chance of downtime"؛ ممکن است Target group لحظهای خالی بماند. Readiness gate و راهنمای AWS Load Balancer Controller را به کار بگیرید.
- مجموعهٔ VMها: دو Auto Scaling group با وزنهای Target group در ALB از صفر/صد به صد/صفر جابهجا میشوند.
| محصول | نقطهٔ تعویض | نکته |
|---|---|---|
| Kubernetes معمولی | Patch روی Service spec.selector | ساده؛ انتشار تغییر چند ثانیه طول میکشد؛ همراه بررسی اسکریپت شود |
Argo Rollouts blueGreen | Selector در activeService / previewService | autoPromotionEnabled پیشفرض true، prePromotionAnalysis، postPromotionAnalysis، previewReplicaCount، scaleDownDelaySeconds پیشفرض 30 |
| Flagger Blue/Green | Serviceهای تولیدشده؛ "no service mesh or ingress controller is required" | Analysis با تکرار، بهجای وزن |
| Gateway API | HTTPRoute backendRefs از 100/0 به 0/100 | همان شیء Canary؛ اتمی در سطح Route |
| AWS ALB / NLB | قاعدهٔ Listener یا Target group وزنی | Deregistration delay کار Target قدیمی را تخلیه میکند |
| DNS | تعویض رکورد | TTL و Cache Resolver تعویض را کند و ناهمگون میکنند؛ آخرین انتخاب |
راهحل: اسکریپت باید ابتدا Rollout کامل مقصد و Smoke test روی preview را بررسی کند، تعویض را با یک فراخوانی API انجام دهد و از مسیر عمومی واقعی نتیجه را تأیید کند. رنگ قبلی را تا اطمینان از جاافتادن Release روشن نگه دارید. ظرفیت دوبرابر را بودجهبندی کنید یا با previewReplicaCount محیط green را تا Promotion کوچک نگه دارید.
قناری با وزن، Header و Cookie (Canary release) حیاتی
به زبان ساده: در قناری (Canary) سهم کمی از ترافیک واقعی را به نسخهٔ تازه میدهید، با قبلی مقایسه میکنید و تا وقتی سالم است سهم را گامبهگام بالا میبرید.
بدفهمی رایج: «دو Deployment پشت یک Service همان Canary است.» شکل کمدقت آن است. Kubernetes این الگو را مستند میکند: "By adjusting the replica counts, you control the traffic ratio between stable and canary Pods". دقت به تعداد نمونهها (Replica) محدود است؛ یک Pod از ده Pod یعنی ده درصد، نه یک درصد. همچنین kube-proxy اتصالها (Connection) را تقسیم میکند، نه درخواستها را. وزن دقیق و مسیریابی Header یا Cookie به مسیریاب لایهٔ هفت (L7) نیاز دارند.
تعریف: Danilo Sato در CanaryRelease انتشار را "to a small subset of users before rolling it out to the entire infrastructure" توصیف میکند. کتاب کار SRE اندازهگیری را اضافه میکند: بخش تغییریافته "the canary," و بقیهٔ سرویس "the control" است؛ علاوه بر مقایسه باید "use absolute measures, such as defined SLOs". وزن ترافیک (Traffic weight) سهم تصادفی درخواست است. مسیریابی بر اساس سرآیند (Header-based routing)، درخواست X-Canary: always را برای تستکننده یا بررسی مصنوعی به Canary میبرد. مسیریابی بر اساس کوکی (Cookie-based routing) مرورگر کارکنان یا کاربران بتا را روی یک طرف نگه میدارد. Argo Rollouts هم "Raw percentages"، "Header-based routing" و "Mirrored traffic" را نام میبرد.
Canary by weight through an HTTPRoute, 10 000 requests/min
1 weights 100/0: stable only
2 weights 95/5: about 500 req/min hit 1.5.0; error rate compared with stable over 5 min
3 testers send X-Canary: always and always reach 1.5.0 (header rule wins over weights)
4 weights 80/20, 50/50: comparison continues; p99 latency of canary checked against 300 ms
5 weights 0/100: canary is the new stable; old Pods scale down
abort at any step: weights 100/0, canary Pods kept for debugging or scaled downسناریوهای واقعی:
- سرویس Go با دو هزار درخواست در ثانیه: پنج درصد برابر صد درخواست در ثانیه است؛ برای مقایسهٔ نرخ موفقیت طی چند دقیقه کافی است.
- API مدیریتی با دو درخواست در دقیقه: Canary وزنی اطلاعات کافی نمیدهد؛ Header routing با بررسی مصنوعی یا Blue-green با مجموعهٔ Smoke test مناسب است.
- برنامهٔ مرورگر که جابهجایی نسخه بهدلیل Hash فایلهای Asset رابط را میشکند: Cookie routing یا Session affinity لازم است، نه وزن هر درخواست.
- Canary ظاهراً سالم که فقط Cache hit گرفته: نرخ خطا را به تفکیک Endpoint مقایسه کنید، نه فقط کل سرویس.
| مسیریاب | وزن | Header | Cookie |
|---|---|---|---|
| Kubernetes Service با نسبت Replica | کمدقت | خیر | خیر |
| Ingress-NGINX | canary-weight | canary-by-header همراه -value و -pattern | canary-by-cookie |
| Gateway API HTTPRoute | backendRefs[].weight | matches[].headers | تطبیق Header روی Cookie؛ وابسته به پیادهسازی |
| Istio VirtualService | route[].weight | match[].headers | تطبیق Header روی cookie با Regex |
| Linkerd HTTPRoute | backendRefs[].weight | matches[].headers | تطبیق Header |
| Argo Rollouts / Flagger | ابزارهای بالا را هدایت میکنند | setHeaderRoute در Istio و افزونهها / match در A/B فلگر | A/B فلگر با تطبیق Cookie |
راهحل: کلید مسیریابی را بر اساس چیزی انتخاب کنید که باید ثابت بماند: درخواست با وزن، تستکننده با Header، کاربر با Cookie یا Flag. تعداد درخواست Canary در دقیقه باید برای مقایسه کافی باشد. هر پاسخ نیز نسخهٔ پاسخدهنده را مشخص کند؛ سرویس Go این کار را با X-App-Version انجام میدهد.
Annotationهای قناری در Ingress-NGINX (Ingress-NGINX canary annotations) مهم
به زبان ساده: Ingress-NGINX اجازه میدهد Ingress دوم با همان Host و Path، قناری (Canary) اولی باشد. Annotationهای دومی تعیین میکنند کدام درخواست به آن برسد.
بدفهمی رایج: «میتوان چند Canary روی هم گذاشت.» محدودیت مستند این است: "Currently a maximum of one canary ingress can be applied per Ingress rule." همچنین Ingress دوم تقریباً همهچیز را به ارث میبرد: "when you mark an ingress as canary, then all the other non-canary annotations will be ignored (inherited from the corresponding main ingress)"؛ استثناها annotationهای load-balance، upstream-hash-by و session-affinity هستند.
تعریف: پس از nginx.ingress.kubernetes.io/canary: "true"، گزینهٔ canary-by-header مقدار always را به Canary و never را به stable میفرستد؛ مقدار دیگر به قاعدهٔ بعد میرسد. canary-by-header-value و canary-by-header-pattern مقدار سفارشی و تطبیق PCRE را میدهند. canary-by-cookie همین معنای always/never را برای Cookie دارد. nginx.ingress.kubernetes.io/canary-weight برابر "percent of random requests that should be routed to the service specified in the canary Ingress" است؛ برای canary-weight-total: "If unspecified, it defaults to 100". ترتیب دقیق: "Canary rules are evaluated in order of precedence. Precedence is as follows: canary-by-header -> canary-by-cookie -> canary-weight". با Session affinity، مقدار پیشفرض affinity-canary-behavior: sticky کاربر Canary را همانجا نگه میدارد.
وضعیت، بررسیشده در ۲۰۲۶-۱۱-۲۹: وبلاگ Kubernetes در یازدهم نوامبر ۲۰۲۵ اعلام کرد: "Best-effort maintenance will continue until March 2026. Afterward, there will be no further releases, no bugfixes, and no updates to resolve any security vulnerabilities". README پروژه اکنون میگوید ingress-nginx "was an Ingress controller". خود Ingress API باقی میماند: "The Kubernetes project has no plans to remove Ingress from Kubernetes"؛ اما منجمد است و Kubernetes "recommends using Gateway instead of Ingress". Clusterهای موجود هنوز این annotationها را اجرا میکنند؛ طراحی تازه باید Gateway API را به کار ببرد. راهنمای "Migrating from Ingress-NGINX" نیز در مستندات Gateway API موجود است.
# Ingress-NGINX canary: a second Ingress for the same host and path, marked
# canary, sends a share of requests to the canary Service. Precedence is
# canary-by-header -> canary-by-cookie -> canary-weight.
# NOTE: the Ingress-NGINX project was retired in March 2026 (no further
# releases or security fixes); new setups should use the Gateway API file.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop-web
namespace: shop
spec:
ingressClassName: nginx
rules:
- host: shop.example
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: shop-web-stable
port:
number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop-web-canary
namespace: shop
annotations:
nginx.ingress.kubernetes.io/canary: "true"
# Testers send `X-Canary: always` (or `never`) to force a side.
nginx.ingress.kubernetes.io/canary-by-header: "X-Canary"
# A cookie named `canary` with value `always` pins a browser to the canary.
nginx.ingress.kubernetes.io/canary-by-cookie: "canary"
# Everyone else: 10 % of requests, chosen at random per request.
nginx.ingress.kubernetes.io/canary-weight: "10"
spec:
ingressClassName: nginx
rules:
- host: shop.example
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: shop-web-canary
port:
number: 80Request routing with the two Ingresses above
1 GET / with header X-Canary: always -> canary (header rule, highest precedence)
2 GET / with header X-Canary: never -> stable, even if the cookie says always
3 GET / with cookie canary=always -> canary
4 GET / with neither -> canary with probability 10/100, else stable
5 change canary-weight to "0" -> only header/cookie traffic reaches the canary
6 delete the canary Ingress -> everything to stable (the rollback)سناریوهای واقعی:
- QA با افزونهٔ مرورگر که
X-Canary: alwaysمیگذارد، Canary را از اینترنت عمومی تست میکند. - کارکنان از صفحهٔ داخلی Cookie با
canary=alwaysمیگیرند و یک روز پیش از وزندادن آن را استفاده میکنند. - Argo Rollouts با
trafficRouting.nginxخودش Ingress قناری را میسازد و ویرایش میکند؛stableIngressنام Ingress اصلی است. - Cluster باقیمانده روی Ingress-NGINX پس از مارس ۲۰۲۶: الگوی Canary را حفظ کنید ولی برای مهاجرت برنامه داشته باشید؛ اصلاح امنیتی تازه نمیرسد.
| Annotation | مقدار | اثر |
|---|---|---|
canary | "true" | این Ingress را Canary اصلی معرفی میکند |
canary-by-header | نام Header | always به Canary، never به stable |
canary-by-header-value | رشته | مقدار سفارشی بهجای always |
canary-by-header-pattern | PCRE | تطبیق Regex؛ با تنظیم -value نادیده گرفته میشود |
canary-by-cookie | نام Cookie | always / never |
canary-weight | عدد صحیح در قالب رشته | سهم درخواستهای تصادفی |
canary-weight-total | عدد صحیح در قالب رشته | مخرج؛ پیشفرض 100 |
affinity-canary-behavior | sticky / legacy | کاربران Session affinity در همان طرف میمانند |
راهحل: Header و Cookie برای تستکننده و وزن برای بقیه باشد. Ingress قناری را کنترلگر مدیریت کند؛ Argo Rollouts یا Flagger با provider: nginx. برای طراحی تازه از HTTPRoute بخش بعد استفاده کنید.
وزن backendRefs و تطبیق Header در HTTPRoute (Gateway API HTTPRoute) حیاتی
به زبان ساده: یک قاعدهٔ HTTPRoute در Gateway API چند Backend با وزن دارد. تغییر عدد، سهم را عوض میکند. قاعدهٔ تطبیق Header هم تستکنندهها را مستقیم به نسخهٔ تازه میبرد.
بدفهمی رایج: «وزن همان درصد است.» راهنما میگوید: "weight indicates a proportional split of traffic (rather than percentage) and so the sum of all the weights within a single route rule is the denominator for all of the backends." وزن پیشفرض یک است. راهنما برای تک Backend عبارت "implicitly receives 100% of the traffic" را دارد، ولی CRD دقیقتر میگوید: "If only one backend is specified and it has a weight greater than 0, 100% of the traffic is forwarded to that backend. If weight is set to 0, no traffic should be forwarded for this entry." پس Backend تنها با وزن صفر، Route صددرصدی نیست.
تعریف: فیلد HTTPRoute.spec.rules[].backendRefs[] طبق مستندات "accepts a list of backends that a route rule will send traffic to. The relative weights of these backends define the split of traffic between them." تطبیق خاصتر اولویت دارد؛ بنابراین قاعدهٔ Header با X-Canary: always کنار قاعدهٔ عمومی وزنی، تستکننده را همیشه و بقیه را مثلاً ده درصد به نسخهٔ تازه میفرستد. همین شیء Blue-green را با جابهجایی صد/صفر و صفر/صد انجام میدهد؛ فیلتر RequestMirror با پشتیبانی Extended نیز Mirroring میدهد. افزونهٔ Gateway API در Argo Rollouts با نام argoproj-labs/gatewayAPI و Provider مربوط به Gateway API در Flagger وزنها را خودکار مینویسند.
# Gateway API canary by hand (no controller): header rule for testers first,
# then a 90/10 weighted split for everyone else. Weights are proportional:
# 90 and 10 out of a total of 100. Promote by editing the weights in Git
# (90/10 -> 50/50 -> 0/100); roll back by setting them to 100/0.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: orders-api
namespace: shop
spec:
parentRefs:
- name: public
namespace: gateway
hostnames:
- api.shop.example
rules:
- matches:
- headers:
- name: X-Canary
value: always
backendRefs:
- name: orders-api-v2
port: 80
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: orders-api-v1
port: 80
weight: 90
- name: orders-api-v2
port: 80
weight: 10Hand-driven Gateway API canary in a GitOps repo
1 PR: add orders-api-v2 Deployment + Service; HTTPRoute header rule only (dark, testers only)
2 PR: weights 90/10 (canary)
3 PR: weights 50/50, then 0/100 (promotion)
4 PR: remove v1 backendRef and Deployment (cleanup)
rollback at 2 or 3: revert the PR -> Argo CD syncs -> weights 100/0 within one syncسناریوهای واقعی:
- در مهاجرت از Ingress-NGINX،
canary-weightبه وزنbackendRefsوcanary-by-headerبه Header match تبدیل میشود. - Gateway مشترک متعلق به تیم Platform است و تیم برنامه فقط HTTPRoute خود را مدیریت میکند؛ API بر اساس نقش طراحی شده است.
- Argo CD و Argo Rollouts بر سر وزن رقابت میکنند: مستندات افزونه میگویند "Configure Argo CD to ignore the weights that the plugin writes"؛ از
ignoreDifferencesاستفاده کنید. - قاعدهای با همهٔ وزنهای صفر مقصد قابل ارسال ندارد؛ CRD میگوید "If weight is set to 0, no traffic should be forwarded for this entry". اعتبارسنج این فصل آن را رد میکند.
| پیادهسازی | backendRefs وزنی | Header match | Mirror |
|---|---|---|---|
| Envoy Gateway، Istio، Cilium، NGINX Gateway Fabric، Kong، Traefik، GKE Gateway | Core | Core | Extended با RequestMirror |
| Linkerd برای Mesh و ترافیک داخلی | بله؛ HTTPRoute در policy.linkerd.io یا gateway.networking.k8s.io | بله | خیر |
| افزونهٔ Argo Rollouts | نوشتن وزن در گامها | setHeaderRoute؛ پشتیبانی Header routing اعلامشده توسط پروژهٔ Argo | مستندات افزونه را ببینید |
Flagger با provider: gatewayapi | HTTPRoute تولید میکند | match در A/B | Blue/Green mirroring |
راهحل: وزن صحیح با جمع صد انتخاب کنید تا خواننده آن را درصد بخواند؛ قواعد Header تستکننده را ابتدا بگذارید. هنگام Rollout نوشتن وزن به کنترلگر واگذار شود و ابزار GitOps این فیلد را نادیده بگیرد.
تقسیم ترافیک Mesh با Istio و Linkerd (Service mesh traffic split) مهم
به زبان ساده: در شبکهٔ سرویس (Service mesh)، کانتینر همراه (Sidecar) یا Ambient proxy جلوی هر فراخوانی است. در نتیجه ترافیک شرقبهغرب، یعنی سرویس به سرویس، را مانند تقسیم ترافیک شمالبهجنوب در Ingress تقسیم میکند.
بدفهمی رایج: «SMI TrafficSplit راه قابل حمل است.» پروژهٔ SMI بایگانی شده: "This project is ARCHIVED". Linkerd هشدار میدهد: "TrafficSplit functionality and the linkerd-smi extension are deprecated and will be removed in a future release" و Dynamic request routing با HTTPRoute را پیشنهاد میکند. API قابل حمل فعلی، HTTPRoute در Gateway API است که Istio و Linkerd هر دو پیادهسازی میکنند.
تعریف: در Istio، DestinationRule با Labelهای Pod زیرمجموعه میسازد و VirtualService با weight ترافیک را میان آنها توزیع میکند، Header را تطبیق میدهد و با mirror و mirrorPercentage کپی میفرستد. درخواست کپیشده "fire and forget" است؛ پاسخ دور ریخته میشود و به Host پسوند -shadow اضافه میشود. در Linkerd، HTTPRoute از policy.linkerd.io/v1beta2 یا گروه Gateway API، با parentRefs به Service اشاره میکند و در backendRefs وزن دارد؛ Header match برای تستکننده است. مهاجرت Linkerd TrafficSplit به HTTPRoute یعنی هر SMI TrafficSplit را با HTTPRoute دارای همان Backend و وزن جایگزین کنید.
# Istio: subsets by pod label in a DestinationRule, weights and a mirror in a
# VirtualService. Mirrored requests are "fire and forget": responses from v2
# are discarded, and their Host header gets a -shadow suffix.
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: orders-api
namespace: shop
spec:
host: orders-api.shop.svc.cluster.local
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
---
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
name: orders-api
namespace: shop
spec:
hosts:
- orders-api.shop.svc.cluster.local
http:
- name: testers
match:
- headers:
x-canary:
exact: always
route:
- destination:
host: orders-api.shop.svc.cluster.local
subset: v2
- name: split
route:
- destination:
host: orders-api.shop.svc.cluster.local
subset: v1
weight: 95
- destination:
host: orders-api.shop.svc.cluster.local
subset: v2
weight: 5
# Shadow 20 % of v1-bound traffic to v2 as well (dark traffic).
mirror:
host: orders-api.shop.svc.cluster.local
subset: v2
mirrorPercentage:
value: 20.0East-west canary of orders-api called by checkout-service (Istio)
1 checkout-service -> orders-api.shop.svc: sidecar applies the VirtualService
2 x-canary: always set by the caller's test harness -> subset v2
3 otherwise 95 % v1, 5 % v2 by weight
4 20 % of requests also mirrored to v2; v2's responses discarded
5 Argo Rollouts trafficRouting.istio rewrites the weights; Flagger does the same with provider: istioسناریوهای واقعی:
- سرویس Go با gRPC که فقط سرویسهای دیگر آن را صدا میزنند: Ingress در کار نیست و Mesh محل تقسیم است.
- تیم Linkerd با اشیای TrafficSplit قدیمی: پیش از حذف افزونهٔ SMI به HTTPRoute مهاجرت کند.
- بازنویسی سرویس قیمتگذاری: یک هفته فراخوانی Production را کپی و Logها را آفلاین مقایسه کنید.
- راهنمای Traffic shifting خود Istio اکنون هر دو شکل VirtualService و HTTPRoute را برای تقسیم پنجاه/پنجاه نشان میدهد.
| Mesh | شیء | فیلد وزن | وضعیت |
|---|---|---|---|
| Istio | VirtualService و DestinationRule در networking.istio.io/v1 | http[].route[].weight | پشتیبانیشده؛ Gateway API هم پشتیبانی میشود |
| Istio | HTTPRoute در Gateway API | backendRefs[].weight | پشتیبانیشده |
| Linkerd | HTTPRoute | backendRefs[].weight | توصیهشده |
| Linkerd | SMI TrafficSplit | backends[].weight | منسوخ؛ SMI بایگانی شده |
راهحل: Canary داخلی و Mirroring را با Mesh انجام دهید؛ هرجا Mesh پشتیبانی میکند HTTPRoute را ترجیح دهید و مالکیت وزن را به کنترلگر Progressive delivery بدهید.
تحویل تدریجی با Argo Rollouts: CRD، گام، تحلیل و توقف (Progressive delivery with Argo Rollouts) حیاتی
به زبان ساده: Argo Rollouts کنترلگری با منبعی شبیه Deployment به نام Rollout است. راهبرد Update فهرست گامهاست: پنج درصد بفرست، صبر کن، سنجه را بررسی کن، بیست درصد بفرست. اگر بررسی شکست بخورد، خودش همه را به نسخهٔ قدیمی برمیگرداند.
بدفهمی رایج: «وزن Canary یعنی تعداد Podهای Canary.» بدون مسیریابی ترافیک (Traffic routing)، تعداد Pod آن را تقریب میزند: "if a Rollout has 10 Replicas and 10% for the first setWeight step, the controller will scale the new desired ReplicaSet to 1 replicas and the old stable ReplicaSet to 9"؛ چهلویک درصد از ده، چهار Pod میشود. با Traffic routing وزن دقیق را Router اجرا میکند و "the Stable ReplicaSet owned by the Rollout remains fully scaled up as the Rollout progresses through the Canary steps"، مگر dynamicStableScale: true باشد.
تعریف: "Argo Rollouts is a Kubernetes controller and set of CRDs which provide advanced deployment capabilities such as blue-green, canary, canary analysis, experimentation, and progressive delivery features to Kubernetes." منبع Rollout CRD به تعبیر مستندات "acts as a drop-in replacement for a Deployment resource". گامها شامل setWeight با معنای "the percentage of traffic that should be sent to the canary"، pause با duration یا {} برای انتظار تا kubectl argo rollouts promote، analysis درونگامی و مسدودکننده، setCanaryScale، setHeaderRoute، setMirrorRoute و experiment هستند. AnalysisTemplate "defines how to perform a canary analysis, such as the metrics which it should perform, its frequency, and the values which are considered successful or failed"؛ AnalysisRun "is an instantiation of an AnalysisTemplate". پایان اجراها "Successful, Failed, or Inconclusive, and the result of the run affect if the Rollout's update will continue, abort, or pause, respectively" است. با Prometheus بهعنوان Metrics provider، هر اندازهگیری یک PromQL اجرا و successCondition و در صورت وجود failureCondition را ارزیابی میکند. failureLimit پیشفرض صفر است: "no failures are tolerated". ارتقا (Promotion) با پایان گامها یا promote و promote --full رخ میدهد. توقف انتشار (Abort) "stops progressing the current rollout and reverts all steps. The previous ReplicaSet will be active." تحلیل (Analysis) ناموفق همین Abort را خودکار انجام میدهد؛ بازگشت خودکار (Automatic rollback) یعنی "setting the canary weight back to zero, and the Rollout would be considered in a Degraded".
Rollout سرویس Go با افزونهٔ Gateway API، Analysis پسزمینه از گام دوم و یک Analysis درونگامی، همراه Templateها در Go آمده است. بخش اصلی:
strategy:
canary:
canaryService: orders-api-canary
stableService: orders-api-stable
trafficRouting:
plugins:
argoproj-labs/gatewayAPI:
httpRoute: orders-api
analysis: # background, from step index 2; templates have no count,
# so they measure until the rollout ends
startingStep: 2
templates: [{templateName: http-success-rate}, {templateName: http-latency-p99}]
steps:
- setWeight: 5
- pause: {duration: 2m}
- setWeight: 20
- pause: {duration: 5m}
- analysis: {templates: [{templateName: http-success-rate-gate}]} # finite: count 5
- setWeight: 50
- pause: {duration: 10m}
- setWeight: 100kubectl argo rollouts get rollout orders-api --watch (expected, not run: state transitions)
1 image bumped in Git, Argo CD syncs the Rollout: new ReplicaSet created, canary Pods Ready
2 step 0 setWeight 5: plugin sets HTTPRoute weights 95/5
3 step 1 pause 2m; step 2 setWeight 20 -> background AnalysisRun starts (success rate + p99, every 1m)
4 step 4 inline analysis (http-success-rate-gate): 5 measurements, 1 per minute; blocks; the background run continues
5 measurement 3 fails (success 0.991 < 0.995), 4 fails, 5 fails -> failureLimit 2 exceeded -> AnalysisRun Failed
6 Rollout aborts: weights 100/0, status Degraded; abortScaleDownDelaySeconds 30 then canary scaled down
7 Git still says 1.5.0: revert the commit (or push a fix); the next sync starts a new rolloutسناریوهای واقعی:
- پنجاه سرویس هرکدام روزی ده بار Deploy میشوند؛ کسی تکتک داشبوردها را نمیبیند و Analysis دروازهٔ همه است.
- Rollout در پنجاه درصد با
{}آخر هفته متوقف میماند؛ دوشنبه مالک پس از بررسی سنجهٔ کسبوکار Promotion میکند. - اصلاح اضطراری با
kubectl argo rollouts promote orders-api --full، "analysis, pauses, and steps" را رد میکند. - بازگشت به نسخهای داخل
rollbackWindow.revisionsگامها را رد میکند و Canary سیدقیقهای دوباره اجرا نمیشود.
| قابلیت | فیلد / فرمان | پیشفرض / نکته |
|---|---|---|
| Provider ترافیک | trafficRouting: nginx، istio، alb، smi، traefik، apisix، ambassador، appMesh، plugins | Gateway API از افزونهٔ argoproj-labs/gatewayAPI |
| Analysis پسزمینه | strategy.canary.analysis و startingStep | تا پایان Rollout ادامه دارد |
| Analysis درونگامی | steps[].analysis | گام را مسدود میکند |
| Blue-green | strategy.blueGreen.activeService/previewService | autoPromotionEnabled برابر true، scaleDownDelaySeconds برابر 30 |
| Abort / Retry | kubectl argo rollouts abort / retry rollout | Abort، spec.template را روی نسخهٔ تازه نگه میدارد |
| Promotion | kubectl argo rollouts promote [--full] | --full همهٔ بررسیها را رد میکند |
| Undo | kubectl argo rollouts undo | معادل kubectl rollout undo برای Rollout |
| پنجرهٔ Rollback | spec.rollbackWindow.revisions | از v1.4؛ رد گام برای Revisionهای اخیر |
| Git | هیچ | "Argo Rollouts doesn't read/write anything to Git" |
راهحل: با دو سنجهٔ قابل اعتماد، نرخ موفقیت و p99 فقط Canary، شروع کنید. گام کوتاه و failureLimit کوچک باشد. نبود داده باید شکست باشد؛ len(result) > 0 && ... مانع قبولی Canary بیترافیک میشود. برای فیلدهای نوشتهشده توسط کنترلگر در Argo CD، ignoreDifferences اضافه کنید و «پس از Abort، Git را برگردان» را داخل Runbook بنویسید.
Flagger، Canary CRD، MetricTemplate و Webhook مهم
به زبان ساده: Flagger، Deployment معمولی را حفظ میکند و ابزار Canary را دور آن میسازد: یک کپی primary، Serviceها، Routeها و حلقهٔ Analysis که ترافیک را مرحلهای جابهجا میکند.
بدفهمی رایج: «Flagger مثل Argo Rollouts جای Deployment را میگیرد.» چنین نیست: "The primary deployment is considered the stable release of your app, by default all traffic is routed to this version and the target deployment is scaled to zero." شما Deployment اصلی را تغییر میدهید؛ Flagger تغییر را، "including secrets and configmaps"، تشخیص میدهد و پیش از کپی به <name>-primary تحلیل میکند.
تعریف: "Flagger is a progressive delivery tool that automates the release process for applications running on Kubernetes." منبع Canary CRD در flagger.app/v1beta1 دارای targetRef برای Deployment یا DaemonSet، autoscalerRef اختیاری و بلوک service است؛ Flagger سرویسهای ClusterIP با نام <name>، <name>-primary و <name>-canary میسازد. provider میتواند Istio، Linkerd، NGINX، Contour، Gloo، Skipper، Traefik، Kuma، Gateway API، APISIX، Knative یا App Mesh باشد. بلوک analysis شامل interval، threshold با معنای "max number of failed metric checks before rollback"، maxWeight، stepWeight، metrics درونی request-success-rate و request-duration یا ارجاع MetricTemplate با thresholdRange است. webhooks شامل confirm-rollout، pre-rollout، rollout، confirm-traffic-increase، confirm-promotion، post-rollout، rollback و event است؛ تست بار در Webhook با rollout اجرا میشود. حداقل زمان Promotion برابر interval * (maxWeight / stepWeight) و زمان Rollback برابر interval * threshold است. راهبردها: Canary، آزمایش A/B با "HTTP headers and cookies traffic routing"، Blue/green با "no service mesh or ingress controller is required" و Blue/green mirroring.
Flagger canary for shop-web (interval 1m, stepWeight 10, maxWeight 50, threshold 5)
1 edit Deployment shop-web image -> Flagger: "New revision detected"
2 pre-rollout webhook: curl /up on shop-web-canary must pass, else no traffic at all
3 weight 10 % -> check error-rate < 1 %, request-duration p99 < 500 ms -> pass
4 weight 20, 30, 40, 50 % (one minute each, load-test webhook generating traffic)
5 promotion: copy target spec to shop-web-primary, route 100 % to primary, scale target to 0
failure path: 5 failed checks -> weight 0, canary scaled to 0, Canary status Failed (5 min worst case)سناریوهای واقعی:
- Platform مبتنی بر Flux: Flagger عضو خانوادهٔ Flux است و به Deployment اعمالشده توسط آن واکنش نشان میدهد.
- Canary برنامهٔ Laravel با
shop-web، شامل Nginx و php-fpm در یک Pod، از Gateway API و سنجههای درخواست Nginx استفاده میکند. - در اضطرار،
skipAnalysis: true: "Flagger checks if the canary deployment is healthy and promotes it without analysing it". - تغییر صرفاً ConfigMap هم Canary آغاز میکند؛ برای فایل Feature flag مفید است ولی اگر انتظارش را نداشته باشید غافلگیر میشوید.
| محور | Argo Rollouts | Flagger |
|---|---|---|
| شیء Workload | جایگزینی Deployment با Rollout یا workloadRef | حفظ Deployment و تولید -primary |
| گامها | فهرست صریح setWeight، pause، analysis و غیره | stepWeight/maxWeight یا فهرست stepWeights؛ iterations برای A/B |
| سنجهها | Providerهای AnalysisTemplate: Prometheus، Datadog، New Relic، Wavefront، CloudWatch، Graphite، InfluxDB، SkyWalking، Kayenta، web، job، plugin | درونی و MetricTemplate: Prometheus، Datadog، CloudWatch، New Relic، Graphite، Dynatrace، InfluxDB، Stackdriver، Splunk، Azure Monitor، Keptn و External metrics |
| دروازهٔ دستی | pause: {} و promote | Webhookهای confirm-rollout / confirm-promotion |
| رابط کاربری | داشبورد Argo Rollouts و افزونهٔ Argo CD | داشبورد Grafana و هشدار |
| اکوسیستم | Argo CD | Flux |
راهحل: اکوسیستم و امکان تغییر Kindِ Workload معیار انتخاب باشند. در Flagger، Deployment هدف به صفر میرسد؛ پس HPA و داشبورد باید -primary را ببینند.
سلامت انتشار: خطا، p99، SLO و بودجهٔ خطا (Release health) حیاتی
به زبان ساده: «نسخهٔ تازه سالم است؟» باید پرسوجو باشد، نه احساس. نرخ خطا و تأخیر انتهایی Canary را اندازه بگیرید، با آستانه و نسخهٔ stable مقایسه کنید و هر دو را به SLO سرویس پیوند دهید.
بدفهمی رایج: «میانگین تأخیر برای دروازه کافی است.» میانگین دنبالهٔ کندی را که کاربر حس میکند پنهان میکند؛ p99 یا p95 مربوط به Canary را بسنجید. مقایسهٔ Canary و stable هم بهتنهایی کافی نیست. کتاب کار SRE هشدار میدهد: "Canarying is an A/B comparison, and it's possible that both A and B can change in tandem"؛ آستانهٔ مطلق SLO هم لازم است.
تعریف: سلامت انتشار (Release health) مجموعهٔ شاخصهای سطح خدمت (SLI) هنگام و پس از Rollout است: نرخ موفقیت یعنی سهم غیر 5xx، p99، اشباع (Saturation) مانند CPU throttling و عمق صف، و نشانهٔ کسبوکار مانند سفارش در دقیقه. ارتقای مبتنی بر SLO (SLO-based promotion) فقط وقتی مجاز است که SLIهای Canary در حدود SLO بمانند و مصرف بودجهٔ خطا بیش از حد مجاز نباشد. نرخ مصرف بودجهٔ خطا (Error budget burn rate) یعنی "how fast, relative to the SLO, the service consumes the error budget". با SLO برابر ۹۹٫۹ درصد، Burn rate یک یعنی ۰٫۱ درصد خطا و دوام بودجه برای سی روز؛ ده یعنی یک درصد خطا و سه روز. نقطههای شروع هشدار فوری در کتاب "2% budget consumption in one hour and 5% budget consumption in six hours" است. Canary که با کل ترافیک هشدار فوری میدهد نباید Promotion شود؛ نظریه در SLA و SLO و هشدار مؤثر است.
Turning an SLO into AnalysisTemplate thresholds (orders-api, SLO 99.9 % success, p99 < 300 ms)
1 budget = 0.1 % errors over 30 days
2 canary gets 5 % of traffic for 5 minutes; a 10x burn rate (1 % errors) must fail the step
3 successCondition: result[0] >= 0.995 (0.5 % errors = burn rate 5: fail before it pages)
4 p99 latency gate: result[0] <= 0.300 seconds
5 no data at all (canary unrouted, metric renamed): len(result) > 0 required -> Failed
6 promotion after 50 % for 10 min only if the stable service is not already burning budgetسناریوهای واقعی:
- تغییر JSON پرمصرف CPU باعث Abort میشود: نرخ موفقیت خوب است ولی p99 از ۱۸۰ به ۴۵۰ میلیثانیه میرسد.
- Abort کاذب: قطعی سرویس پاییندست هر دو نسخه را زده؛ مقایسه خوب ولی حد مطلق ناموفق است. مکث با Inconclusive از Promotion هنگام رخداد بهتر است.
- نام سنجه از
http_requests_totalبهhttp_server_requests_totalعوض شده؛ Canary ظاهراً «خطا ندارد» چون هیچ سری ندارد. وجود داده الزامی باشد. - سرویس کمترافیک: تحلیل وزن را با Webhook بار مصنوعی، Load tester فلگر یا سنجهٔ
jobدر Argo Rollouts تکمیل یا جایگزین کنید.
| سیگنال | شکل Query در Prometheus | دروازهٔ معمول |
|---|---|---|
| نرخ موفقیت | sum(rate(..{code!~"5.."}[2m])) / sum(rate(..[2m])) | >= 0.99 تا 0.999 بر اساس SLO |
| تأخیر p99 | histogram_quantile(0.99, sum by (le) (rate(.._bucket[2m]))) | <= آستانهٔ تأخیر SLO |
| Burn rate | خطا / (1 - SLO) در یک بازه | < 10؛ چیزی که هشدار میدهد ارتقا ندهید |
| اشباع | CPU throttling، حافظه، عقبماندگی صف | در محدودهٔ Baseline بهعلاوهٔ X % |
| کسبوکار | سفارش در دقیقه، موفقیت پرداخت | در محدودهٔ Baseline |
| سلامت Pod | Restart و نوسان Readiness | صفر Restart |
راهحل: آستانه را از SLO استخراج کنید، سری مختص Canary با ترافیک کافی را بسنجید، داده را الزامی کنید و یک سنجهٔ کسبوکار اضافه کنید. همین Queryها روی داشبورد زمان رخداد هم استفاده شوند.
آزمایش A/B، ترافیک سایه و انتشار پنهان (A/B testing, shadow traffic and dark launch) مهم
به زبان ساده: Canary میپرسد «نسخهٔ تازه خراب است؟»؛ آزمایش A/B میپرسد «کاربر B را بیشتر میپسندد؟». ترافیک سایه (Shadow traffic) درخواست واقعی را کپی و پاسخ را دور میریزد. انتشار پنهان (Dark launch) کد تازه را برای کاربر واقعی اجرا میکند ولی نتیجه را نشان نمیدهد.
بدفهمی رایج: «Canary همان A/B با B کوچک است.» Canary کوتاه، معمولاً بهازای درخواست و مبتنی بر سنجهٔ عملیاتی است. A/B طولانی، برای هر کاربر ثابت و دارای حجم متناسب با توان آماری است و با سنجهٔ محصول تصمیم میگیرد. مخلوطکردن این دو به هر دو سؤال جواب بد میدهد.
تعریف: A/B testing کاربران را با Flag یا Cookie و شناسهٔ کاربر، میان گونهها ثابت تقسیم میکند و تبدیل یا تعامل را میسنجد؛ Flagger از "HTTP headers and cookies" استفاده میکند. Shadow traffic یا Mirroring کپی درخواست را به نسخهٔ تازه میفرستد و مشتری فقط پاسخ primary را میبیند. در Istio درخواست "fire and forget" است؛ Gateway API فیلتر RequestMirror دارد؛ Argo Rollouts میگوید "Mirrored traffic where all the traffic is copied and sent to the new version in parallel (but the response is ignored)". Dark launch در بیان فاولر "taking a new or changed back-end behavior and calling it from existing users without the users being able to tell it's being called" است تا "assess the additional load and performance impacts upon the system before making a public announcement".
Shadowing a rewritten recommendations backend
1 VirtualService: 100 % to v1, mirror 20 % to v2 (mirrorPercentage 20)
2 v2 receives requests with Host "recommendations-shadow"; its responses are discarded
3 compare v2 logs/metrics offline: latency, error rate, result diff against v1
4 side effects: v2 must NOT write orders, send e-mails or charge cards (use a read-only mode)
5 when diff and load look right: canary v2 for real, with v1 as controlسناریوهای واقعی:
- رنگ دکمهٔ خرید: دو هفته A/B با گونههای Feature flag، نه Canary.
- موتور جستوجوی تازه: یک هفته ده درصد Queryها را کپی کنید و همپوشانی ده نتیجهٔ اول را بسنجید.
- پیشنهادهای محصول بهشکل Dark launch: Checkout موتور تازه را صدا میزند و نتیجه را نادیده میگیرد؛ همان مثال توستر و چاقوی استیک فاولر.
- POST کپیشده کارت را دوبار شارژ میکند؛ مقصد Shadow باید اثر جانبی جداشده داشته باشد.
| روش | کاربران متأثر | معیار تصمیم | ابزار |
|---|---|---|---|
| Canary | سهم کوچک بهازای درخواست | نرخ خطا و تأخیر | Argo Rollouts، Flagger، وزن HTTPRoute |
| A/B | سهم ثابت و ماندگار هر کاربر | سنجهٔ محصول و معناداری آماری | آزمایش LaunchDarkly، گونههای Unleash، چندمتغیرهٔ Flagsmith، A/B فلگر |
| Shadow traffic | هیچ؛ پاسخ دور ریخته میشود | بار و اختلاف خروجی | Istio mirror، Gateway RequestMirror، Argo Rollouts setMirrorRoute |
| Dark launch | اثر قابل مشاهده ندارد | بار و تأخیر فراخوانی تازه | Feature flag دور فراخوانی |
راهحل: اول سؤال را تعیین کنید؛ Canary برای ایمنی، A/B برای محصول، Shadow و Dark launch برای بار و صحت. Backend کپیگیرنده باید حالت بدون اثر جانبی داشته باشد.
پرچم قابلیت: OpenFeature، ارزیابی، هدفگیری، درصد، قطع اضطراری و بدهی (Feature flags) حیاتی
به زبان ساده: پرچم قابلیت (Feature flag) یک if است که شرطش بیرون کد زندگی میکند. هر دو مسیر مستقرند؛ سرویس Flag برای درخواست یا کاربر تصمیم میگیرد کدام اجرا شود و تصمیم بدون Deploy تغییر میکند.
بدفهمی رایج: «Flag جای راهبرد استقرار را میگیرد.» مکمل آن است؛ فقط کدی را محافظت میکند که دورش قرار گرفته. Upgrade خراب وابستگی، نشت حافظه، Migration خراب یا Crash شروع برنامه با Canary، Blue-green یا Rolling update همراه Readiness پیدا میشوند. هر Flag هزینه دارد؛ فاولر: "Savvy teams view their Feature Toggles as inventory which comes with a carrying cost, and work to keep that inventory as low as possible."
تعریف: OpenFeature یک پروژهٔ Incubating در CNCF است: "is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool". برنامه Client را صدا میزند؛ ارائهدهنده (Provider) مانند flagd، LaunchDarkly، Unleash، Flagsmith، API سازگار با Unleash در GitLab یا Provider حافظهای تست، ارزیابی پرچم (Flag evaluation) را روی زمینهٔ ارزیابی (Evaluation context) انجام میدهد. کلید هدفگیری (Targeting key) هویت کاربر را مشخص میکند. قرارداد شکست: "Flag evaluation calls must always return the default value in the event of abnormal execution"؛ ساخت Client نیز "MUST NOT throw". قواعد هدفگیری (Targeting rules) صفتهایی مانند Plan، کشور و دامنهٔ ایمیل را تطبیق میدهند. انتشار درصدی (Percentage rollout) کلید را Hash و در Bucket قرار میدهد تا پاسخ برای کاربر ثابت بماند. LaunchDarkly، Context key، Kind، Flag key و Salt را به "100,000 buckets" میبرد. Unleash "uses a normalized MurmurHash of a user's unique ID" و نام Flag، groupId پیشفرض است: "so the same user can fall inside the rollout for one flag and outside it for another". کلید قطع اضطراری (Kill switch) یک Flag عملیاتی دائمی است؛ LaunchDarkly آن را "permanent boolean flags with two variations" برای "to quickly turn off functionality when needed" مینامد. دستههای فاولر Release، Experiment، Ops و Permissioning هستند. بدهی پرچم (Flag debt) هزینهٔ ماندن Flag قدیمی است؛ Unleash پس از عمر مورد انتظار آن را "potentially stale automatically once they pass their expected lifetime" علامت میزند.
Flag evaluation in the Go service (flags.Service.NewCheckout), one request
1 handler builds EvaluationContext{targetingKey: "u-7", plan: "pro", country: "NL"}
2 client.Boolean(ctx, "new-checkout", false, evalCtx) default false = old path
3 provider: deny rule country=DE? no. allow rule plan=internal? no.
4 percentage: Bucket("new-checkout", "u-7") = fnv32a(...) % 100000 = 61234 >= 5 % of 100000 -> off
5 result false, reason SPLIT, variant off; logged as flag=new-checkout value=false reason=SPLIT variant=off
6 provider unreachable instead: OpenFeature returns the default false with reason ERROR (never panics)کد Go و هفت تست آن در Go است: Flag گمشده، Flag غیرفعال، ترتیب Rule، Stickiness و رشد یکنواخت از ده به پنجاه درصد، Targeting key گمشده، تغییر Kill switch در زمان اجرا و Bucket مستقل هر Flag. در Laravel، Release flag با Pennant و Kill switch با Cache پیاده شده است.
سناریوهای واقعی:
- Checkout تازه پشت
new-checkout: اول کارکنان، سپس یک، پنج، بیستوپنج و صد درصد طی یک هفته؛ بعد Flag و کد قدیمی حذف میشوند. - سرویس پیشنهاد هنگام فروش ویژه از پا میافتد؛ مسئول کشیک
recommendationsرا خاموش میکند و خرید بدون Widget ادامه مییابد. - قطعی سرویس Flag: همهٔ ارزیابیها مقدار پیشفرض کد را میدهند؛ Release flag به مسیر قدیمی و Kill switch به روشن برمیگردد. این پیشفرض برای هر Flag یک تصمیم طراحی است.
- سه سال بعد، چهارصد Flag مانده و کسی حذف امن را نمیداند؛ تاریخ انقضا، مالک و گزارش Flag قدیمی از آن جلوگیری میکند.
| محصول | مدل | انتشار درصدی | نکته |
|---|---|---|---|
| OpenFeature | API مستقل از فروشنده و Provider | وابسته به Provider؛ ارزیابی fractional در flagd | Go SDK با github.com/open-feature/go-sdk نسخهٔ v1.17.1؛ PHP SDK هم دارد |
| LaunchDarkly | SaaS؛ SDK با Stream محلی ارزیابی میکند | 100000 Bucket از Hash کلید Context و Flag | قالب Kill switch و Experiment |
| Unleash | متنباز / میزبانیشده؛ راهبرد فعالسازی | Gradual rollout با Stickiness مبتنی بر MurmurHash | کشف Flag قدیمی؛ Flagهای GitLab "based on Unleash" هستند |
| Flagsmith | متنباز / میزبانیشده؛ Identity، Trait، Segment | Segment با تقسیم درصدی | در Remote evaluation، Segment روی سرور ارزیابی میشود |
| Laravel Pennant | داخل برنامه؛ Driver پایگاه داده یا array | Lottery::odds(...)؛ نتیجه برای هر حوزه (Scope) ذخیره میشود | Hash نیست؛ افزایش احتمال فقط روی کاربران ارزیابینشده اثر دارد |
| GitLab feature flags | API سازگار با Unleash | راهبرد درصدی | درون پروژهٔ GitLab |
راهحل: کلیدها، دسترسی Typed و پیشفرض هر Flag را در Wrapper کوچکی جمع کنید. دلیل ارزیابی را Log کنید، برای Release flag مالک و انقضا بگذارید و در Release پس از صد درصد، Flag و شاخهٔ مرده را حذف کنید.
بازگشت با Digest، تاریخچه، Helm و GitOps (Rollback mechanics) حیاتی
به زبان ساده: بازگشت (Rollback) یعنی دقیقاً همان بایتهای قبلی اجرا شوند. باید آن بایتها را با چکیدهٔ محتوا (Digest)، نه برچسب (Tag)، ثبت کرده باشید؛ ابزار اعمال تغییر هم باید با تصمیم بازگشت موافق باشد.
بدفهمی رایج: «kubectl rollout undo همهچیز را برمیگرداند.» Kubernetes میگوید: "the new revision is created if and only if the Deployment's Pod template (.spec.template) is changed"؛ و "when you roll back to an earlier revision, only the Deployment's Pod template part is rolled back." ConfigMap، Secret، Service و تعداد Replica تغییر نمیکنند. زیر GitOps نیز Undo موقت است؛ کنترلگر وضعیت Git را دوباره اعمال میکند.
تعریف: تثبیت Image با Digest (Image digest pinning) یعنی استقرار name@sha256:... تا containerd و هر Runtime سازگار با OCI همان Manifest را بگیرند و مقصد Rollback جابهجا نشود؛ Tag برای انسان است. تاریخچهٔ بازبینی (Revision history) در Deployment، ReplicaSetهای قدیمی را نگه میدارد: "By default, 10 old ReplicaSets will be kept" با revisionHistoryLimit؛ "once an old ReplicaSet is deleted, you lose the ability to rollback to that revision". فرمان kubectl rollout history، Revision و CHANGE-CAUSE از annotation با kubernetes.io/change-cause را نشان میدهد؛ بازگشت با kubectl rollout undo deployment/x [--to-revision=N] است. Helm rollback با helm rollback <RELEASE> [REVISION] انجام میشود: "If this argument is omitted or set to 0, it will roll back to the previous release"؛ حد تاریخچه --history-max و پیشفرض ده است. GitOps revert یعنی برگرداندن Commit افزایش Digest تا Argo CD یا Flux وضعیت قبلی را Sync کند. فرمان argocd app rollback طبق مستندات "cannot be performed against an application with automated sync enabled". در Argo Rollouts، Abort، spec.template را تازه نگه میدارد: "If the Rollout leaves the aborted state, it will try to go to the new version"؛ rollbackWindow.revisions اجازه میدهد Spec قدیمیِ دوبارهاعمالشده گامها را رد کند.
GitOps rollback of orders-api 1.5.0 -> 1.4.2 (Argo CD auto-sync + Argo Rollouts)
1 analysis fails at 20 %: Rollout aborts, cluster serves 1.4.2, app Degraded, Git still says 1.5.0
2 on-call: git revert <bump commit> in the env repo -> digest back to sha256:11... (1.4.2)
3 Argo CD syncs: Rollout spec.template now equals the stable ReplicaSet
4 controller: moving back to the stable ReplicaSet -> no new canary needed; status Healthy
5 without step 2: Argo CD syncs do nothing (Git and the live Rollout both say 1.5.0), the app stays Degraded on 1.4.2,
and `kubectl argo rollouts retry rollout orders-api` (or any new revision) would start the bad 1.5.0 canary againسناریوهای واقعی:
- Pipeline اصلاح فوری دوباره
image: orders-api:1.4را Push کرده؛ Rollback به 1.4 این بار کد دیگری میآورد. Digest مانع آن است. - Helm upgrade هم Secret و هم Image را عوض کرده؛
helm rollbackهر دو را از Release رندرشده برمیگرداند،kubectl rollout undoفقط Image را. revisionHistoryLimit: 0برای صرفهجویی etcd، امکان Rollback را کاملاً حذف میکند.- مسئول کشیک روی برنامهٔ تحت Argo CD با Self-heal،
kubectl rollout undoمیزند؛ Argo CD در یک Sync آن Undo را برمیگرداند.
| ابزار | فرمان Rollback | آنچه بازمیگرداند | آنچه باقی میماند |
|---|---|---|---|
| Deployment | kubectl rollout undo [--to-revision=N] | Pod template | همهٔ موارد دیگر |
| Argo Rollouts | kubectl argo rollouts abort / undo | ترافیک به stable / Template قبلی | Git دستنخورده |
| Helm | helm rollback RELEASE [REV] | همهٔ Manifestهای رندرشدهٔ آن Revision | داده، تغییر CRD، اثر جانبی Hook |
| Argo CD | git revert یا argocd app rollback بدون Auto-sync | وضعیت توصیفشده در Git | اشیای خارج Git |
| Flux | git revert؛ Rollback فلگر برای Canary | وضعیت توصیفشده در Git | |
| AWS ASG | Instance refresh rollback دستی یا auto_rollback روی Alarm | Launch template قبلی | دادهٔ Instanceها |
| Capistrano / Deployer | deploy:rollback / dep rollback؛ Symlink به Release قبلی | کد | Migration |
راهحل: Digest را Deploy و در Git ثبت کنید؛ چند Release تاریخچه با revisionHistoryLimit و --history-max نگه دارید. در GitOps، Rollback عملیاتی در Git است، حتی اگر کنترلگر ترافیک را برگردانده باشد. آن را در Staging تمرین کنید؛ توصیهٔ Capistrano: "test your rollback procedure before trying it for the first time in a time of crisis".
انتشار سازگار با پایگاه داده و ترتیب Migration (Database-compatible releases) حیاتی
به زبان ساده: هنگام Rollout، کد قدیم و جدید روی یک DB اجرا میشوند. پس از Rollback هم کد قدیمی با Schema باقیمانده از Release جدید کار میکند. بنابراین Schema هر Release باید نسخهٔ قبلی را پشتیبانی کند.
بدفهمی رایج: «همراه بازگشت کد، migrate:rollback اجرا کن.» Down migration بهندرت تست میشود، اغلب داده را نابود میکند و با کد تازهٔ هنوز در حال اجرا رقابت دارد. محتوای ستون حذفشده برنمیگردد. روش امن، Migration فقط روبهجلو است که Release قبلی را نشکند.
تعریف: سازگاری N-1 یعنی کد N با Schemaهای N و N-1 و Schema N با کدهای N و N-1 کار کند. انتشار سازگار با گذشته (Backward-compatible release) نتیجهٔ همین قاعده است: افزودن ابتدا، حذف بعداً. گسترش/انقباض (Expand/Contract)، همان Parallel change با "expand, migrate, and contract"، ابتدا ستون، جدول یا فیلد Nullable اضافه میکند؛ کد در هر دو مینویسد و قدیمی را میخواند؛ Backfill انجام میشود؛ خواندن عوض میشود؛ نوشتن قدیمی متوقف و فقط در Release بعدی حذف میشود. جزئیات Lock، Backfill و Online DDL در مهاجرت Schema است. مهاجرت فقط روبهجلو (Forward-only migrations) یعنی در Production، Down migration نداریم و خطا را با Migration تازه اصلاح میکنیم. ترتیب مهاجرت (Migration ordering): Expand پیش از ورود ترافیک به کد تازه، چون قبلی ستون جدید را نادیده میگیرد؛ Contract یک Release پس از توقف استفاده از ساختار قدیمی. این سازگاری Rolling، Canary و Blue-green را امن میکند؛ بدون آن فقط Recreate با قطعی، انتخاب صادقانه است.
Rename orders.addr -> shipping_address, four releases, each one rollback-safe
R1 migrate (before switch): ADD COLUMN shipping_address NULL code: reads/writes addr
R2 code: writes addr AND shipping_address; backfill job in batches
R3 code: reads shipping_address (behind a flag), still writes both
R4 code: stops writing addr; R5 migration: DROP COLUMN addr (R3 can no longer come back)
roll back R3 -> R2: fine (both columns written). "rename in place" in one release: R(N-1) crashesسناریوهای واقعی:
- ستون NOT NULL بدون Default اضافه میشود؛ Insert مربوط به Podهای قدیمی در Rolling update شکست میخورد.
- مقدار Enum در R2 اضافه و فوراً استفاده میشود؛ Podهای R1 مقدار ناشناخته را میخوانند و Crash میکنند. ابتدا Reader را منتشر کنید.
- Blue-green روی DB مشترک: تعویض فوری است ولی Schema باید هر دو رنگ را پاسخ دهد. فاولر: "separate the deployment of schema changes from application upgrades".
- Migration در
deploy.shلاراول پس از تعویض Symlink اجرا میشود؛ چند ثانیه کد تازه ستون ناموجود را Query میکند. اسکریپت این فصل Migration را پیش از تعویض اجرا میکند.
| تغییر | گام Expand در N | گام Contract در N+1 یا بعدتر |
|---|---|---|
| افزودن ستون | Nullable یا دارای Default | NOT NULL پس از Backfill |
| تغییر نام ستون | افزودن جدید، Dual-write، Backfill | حذف قدیمی |
| حذف ستون | توقف خواندن و نوشتن آن | حذف آن |
| تغییر نوع | ستون تازه و Dual-write | حذف قدیمی |
| افزودن مقدار Enum / Status | ابتدا Reader مقدار را تحمل کند | Writer شروع به استفاده کند |
| شکستن جدول | جدول تازه و Dual-write | حذف ستونهای قدیمی |
| افزودن index | ساخت بدون مسدودکردن؛ مهاجرت Schema | ندارد |
راهحل: هر Migration را با سؤال «N-1 هنوز کار میکند؟» بازبینی کنید. Expand پیش از تعویض با deploy.sh، Job در PreSync hookِ Argo CD یا pre-upgrade hookِ Helm اجرا شود. Down migration در Production نداشته باشید و Contract را تا پایان پنجرهٔ Rollback عقب بیندازید.
آمادگی، preStop و تخلیهٔ اتصال برای حذف قطعی (Zero-downtime details) حیاتی
به زبان ساده: Pod در حال توقف باید ابتدا از فهرست Load balancer خارج شود، سپس کار جاری را تمام کند و بعد خارج شود. Pod تازه هم تا آمادهٔ پاسخ نیست نباید ترافیک بگیرد. همهٔ راهبردها به هر دو شرط وابستهاند.
بدفهمی رایج: «SIGTERM یعنی همین حالا درخواست نپذیر.» هنگام Terminating شدن Pod، حذف Endpoint و SIGTERM تقریباً همزماناند؛ kube-proxy، کنترلگر Ingress و Load balancer ابری کمی دیرتر حذف را میفهمند. بستن فوری Listener، درخواستهای هدایتشده در این فاصله را قطع میکند.
تعریف: کاوشگر آمادگی (Readiness probe) بررسی kubelet برای ورود Pod به Endpointهای Service است. دروازهٔ آمادگی (Readiness gate) شرط اضافه در spec.readinessGates است؛ آمادگی فقط وقتی برقرار است که "All containers in the Pod are ready" و "All conditions specified in readinessGates are True"؛ از Kubernetes v1.14 پایدار است. AWS Load Balancer Controller با همین روش مانع توقف Podهای قدیمی میشود "until the newly created pods are »Healthy« in the ALB/NLB target group". preStop یک Hook است که "must complete before the TERM signal to stop the container can be sent". مهلت پایان کار "applies to the total time it takes for both the PreStop hook to execute and for the Container to stop normally"؛ عمل sleep از v1.34 پایدار است و در Image به Shell نیاز ندارد. تخلیهٔ اتصال (Connection draining) یعنی پاسخدادن به درخواست جاری و دیرهدایتشده و سپس بستن. در Go، http.Server.Shutdown طبق مستندات "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle". Load balancer همین مفهوم را با Deregistration delay دارد. توالی کامل در بارهای کاری Kubernetes است.
Pod of orders-api terminating (preStop sleep 5, DrainDelay 5 s, ShutdownTimeout 15 s, grace 30 s)
T+0 Pod marked Terminating; endpoint removal starts; preStop sleep 5 s begins (grace clock starts)
T+5 SIGTERM -> signal.NotifyContext cancels -> /readyz returns 503
T+5..10 DrainDelay: still serving requests that were already routed here
T+10 srv.Shutdown: listener closed, idle conns closed, wait for in-flight (<= 15 s)
T+25 worst case Shutdown returns context.DeadlineExceeded; process exits; SIGKILL would come at T+30سناریوهای واقعی:
- خطای 502 در هر Deploy پشت ALB: Readiness gate نداریم و Target قدیمی پیش از Healthy شدن تازه تخلیه شده است.
- خطای 502 برای یک ثانیه در هر کاهش مقیاس: preStop delay نیست و برنامه پیش از بازخوانی Upstreamهای Ingress خارج شده است.
- تست Go این فصل پنج ثانیه در
Shutdownمنتظر ماند؛ Transport از پیش یک اتصال (Connection) اضافه باز کرده بود که درخواست نفرستاده بود.net/httpچنین اتصالStateNewرا فقط پس از پنج ثانیه Idle میداند؛ "Issue 22682". در Production،ShutdownTimeoutرا بیش از پنج ثانیه بگذارید. - توقف php-fpm با SIGTERM: در
fpm_events.c، SIGTERM برابر "Terminating ..." و SIGQUIT برابر "Finishing ..." یعنی پایان آرام است؛ به همین دلیل Image ازSTOPSIGNAL SIGQUITاستفاده میکند.
| سازوکار | محل | هدف |
|---|---|---|
readinessProbe | Container | ترافیک فقط به Pod آماده |
readinessGates | Pod spec | شرط بیرونی مانند Healthy بودن Target در LB |
minReadySeconds | Deployment | Pod باید N ثانیه آماده بماند تا شمرده شود |
lifecycle.preStop.sleep | Container | انتظار حذف Endpoint پیش از SIGTERM |
terminationGracePeriodSeconds | Pod؛ پیشفرض 30 | بودجهٔ preStop و Shutdown |
تخلیهٔ برنامه با Shutdown، FPM SIGQUIT، Octane graceful | پردازه (Process) | پایان کار جاری |
| Deregistration delay | Target group در Cloud LB | تخلیه در سمت LB |
راهحل: Readiness با SIGTERM ناموفق شود؛ preStop چند ثانیه صبر کند؛ برنامه با Timeout تخلیه شود؛ Grace period از جمع همه بزرگتر باشد. روی AWS، Readiness gate کنترلگر Load balancer را هم اضافه کنید.
زیرساخت تغییرناپذیر، AMI، نوسازی و تعویض Symlink (VM strategies) مهم
به زبان ساده: بدون Kubernetes هم همین راهبردها وجود دارند: یا برای هر Release تصویر ماشین تازه میسازید و ماشینها را جایگزین میکنید، یا ماشین میماند و Symlink با نام current میان پوشههای Release عوض میشود؛ حالت دوم تغییرپذیر ولی تعویضش اتمی است.
بدفهمی رایج: «Symlink بهتنهایی Deploy بدون قطعی است.» تعویض اتمی است، پردازهها نیستند. Workerهای php-fpm و OPcache تا Reload مسیر قدیمی را دارند، Worker صف تا Restart کد قدیمی را در حافظه نگه میدارد و Migration پس از تعویض فاصلهٔ خرابی ایجاد میکند. Laravel بدون قطعی را ببینید.
تعریف: زیرساخت تغییرناپذیر (Immutable infrastructure) یعنی سرور پس از ایجاد تغییر نکند؛ هر Release یک تصویر ماشین آمازون (AMI) تازه، مثلاً ساختهشده با Packer، و جایگزینی Instanceهاست؛ همان ImmutableServer فاولر. نوسازی نمونهها (Instance refresh) در EC2 Auto Scaling: "Terminates instances and launches new ones in batches". حداقل درصد Healthy برابر صد یعنی "Launch the new instances first before terminating the old ones". Checkpointها "Pause the instance refresh after a certain percentage of replacements" و Rollback خودکار "reverses what was deployed if the instance refresh fails for some reason or if any CloudWatch alarms you specify go into the ALARM state". Terraform با بلوک instance_refresh آن را هدایت میکند. تعویض پیوند نمادین انتشار (Symlink release switch) همان چیدمان Capistrano است: "current is a symlink pointing to the latest release. This symlink is updated at the end of a successful deployment. If the deployment fails in any step the current symlink still points to the old release." در Deployer، deploy:symlink در صورت دسترسبودن از mv -T استفاده میکند: "Use mv -T if available"؛ یعنی rename(2) اتمی پیوند تازه روی قدیمی. پیادهسازی Shell در اسکریپتنویسی Shell، deploy.sh است.
# Immutable VM releases: Packer bakes an AMI per version, Terraform points the
# launch template at it, and the Auto Scaling group replaces instances with an
# instance refresh (rolling, checkpoints, automatic rollback on alarm).
# Argument names from the AWS provider's aws_autoscaling_group docs; not applied here.
variable "release_ami_id" {
description = "AMI built by Packer for this release (one AMI per version, never patched in place)"
type = string
}
resource "aws_launch_template" "orders_api" {
name_prefix = "orders-api-"
image_id = var.release_ami_id
instance_type = "t4g.small"
}
resource "aws_autoscaling_group" "orders_api" {
name = "orders-api"
min_size = 4
max_size = 8
desired_capacity = 4
vpc_zone_identifier = var.private_subnet_ids
target_group_arns = [var.target_group_arn]
health_check_type = "ELB"
launch_template {
id = aws_launch_template.orders_api.id
# "$Latest" would not start a refresh; latest_version does.
version = aws_launch_template.orders_api.latest_version
}
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 100 # launch new instances before terminating old ones
max_healthy_percentage = 150
instance_warmup = 120
checkpoint_percentages = [25, 100] # pause after the first quarter: a VM canary
checkpoint_delay = 600
skip_matching = true
auto_rollback = true
alarm_specification {
alarms = [aws_cloudwatch_metric_alarm.orders_5xx.alarm_name]
}
}
}
}
variable "private_subnet_ids" { type = list(string) }
variable "target_group_arn" { type = string }
resource "aws_cloudwatch_metric_alarm" "orders_5xx" {
alarm_name = "orders-api-target-5xx"
namespace = "AWS/ApplicationELB"
metric_name = "HTTPCode_Target_5XX_Count"
statistic = "Sum"
period = 60
evaluation_periods = 3
threshold = 20
comparison_operator = "GreaterThanThreshold"
}Immutable VM release with instance refresh (checkpoint 25 %, min healthy 100 %)
1 Packer bakes ami-orders-1.5.0; Terraform sets launch template image_id -> new latest_version
2 instance refresh starts: launch 1 new instance before terminating 1 old (4 desired)
3 new instance passes ELB health check, warms up 120 s
4 checkpoint at 25 %: wait 600 s, 1 of 4 instances on 1.5.0 = a VM canary
5 alarm orders-api-target-5xx fires -> auto rollback: replace refreshed instances with the old template
6 no alarm -> continue to 100 %سناریوهای واقعی:
- Binary برنامهٔ Go روی چهار EC2: هر Release یک AMI و Instance refresh با Checkpoint بیستوپنج درصد.
- برنامهٔ Laravel روی دو VM مانند Forge: Deployer یا
deploy.shاین فصل، تعویض Symlink و Reload کردن php-fpm. - Blue-green روی VM: دو Auto Scaling group پشت Target groupهای وزنی ALB.
version = "$Latest"در Launch templateِ Terraform: مستندات Provider هشدار میدهند "A refresh will not start"؛ ازlatest_versionاستفاده کنید.
| روش | Rollback | سرعت | مناسب برای |
|---|---|---|---|
| AMI و Instance refresh | Refresh به Template قبلی؛ خودکار با Alarm | چند دقیقه، زمان Boot | Binaryهای Go و مجموعهٔ ماشین بدون وضعیت |
| دو ASG و وزن LB | برگرداندن وزن | چند ثانیه | Blue-green روی VM |
Releaseهای Symlink با Capistrano، Deployer یا deploy.sh | پیوند به قبلی و Reload | چند ثانیه | PHP و Ruby روی VM ماندگار |
| Upgrade بسته درجا | نصب دوبارهٔ بستهٔ قدیمی | چند دقیقه، پرریسک | پرهیز کنید |
راهحل: هرجا بازسازی ارزان است Image تغییرناپذیر را ترجیح دهید. برای PHP روی VM، پوشههای Release با تعویض اتمی و Reloadهای بخش بعد مناسباند. دستکم Release قبلی روی دیسک بماند.
Reload، حالت نگهداری، Cache و صف در Laravel (Laravel zero-downtime) مهم
به زبان ساده: Deploy در Laravel یک تعویض فایل است همراه چهار وضعیت ماندگار که باید آن را بفهمند: Workerهای php-fpm با OPcache، Config و Route کششده، Workerهای Octane با برنامه در حافظه و Workerهای صف.
بدفهمی رایج: «php artisan down روش استقرار امن Laravel است.» حالت نگهداری (Maintenance mode) برای همه 503 میدهد؛ مستندات میگویند "requires your application to have several seconds of downtime" و جایگزین بدون قطعی معرفی میکنند. فقط برای Release نادری که سازگار با N-1 نمیشود از آن استفاده کنید.
تعریف: در php-fpm reload، Master سیگنال SIGUSR2 را با "Reloading in progress ..." رسیدگی میکند؛ Worker تازه با Config جدید و OPcache تازه، بهشکل آرام جایگزین میشود. systemctl reload از طریق واحد (Unit) آن را میفرستد. بدون Reload، با opcache.validate_timestamps=0 بایتکد قبلی تا "restarting the Web server" سرو میشود. متغیر $realpath_root در Nginx، "with all symbolic links resolved to real paths"، در SCRIPT_FILENAME باعث میشود درخواست پوشهٔ واقعی Release را نام ببرد. Maintenance mode با php artisan down پاسخ 503 میدهد؛ گزینهها --refresh، --retry، --secret و artisan down --with-secret هستند: "If you would like Laravel to generate the secret token for you". گزینهٔ --render="errors::503" صفحه را "before any of your application's dependencies have loaded" آماده میکند؛ Driver حافظهٔ نهان (Cache) برای چند سرور با APP_MAINTENANCE_DRIVER=cache است. "While your application is in maintenance mode, no queued jobs will be handled." در Octane reload: "You may gracefully restart the Octane server's application workers using the octane:reload command"، معمولاً "after deployment so that your newly deployed code is loaded into memory". Cacheها شامل config:cache route:cache، View و Event هستند؛ همه با php artisan optimize. پس از Cache شدن Config، "the env function will only return external, system level environment variables". Workerهای صف، "long-lived processes and store the booted application state in memory" هستند؛ php artisan queue:restart باعث میشود "gracefully exit after they finish processing their current job" و Supervisor یا systemd دوباره آنها را بالا میآورد. Laravel 13 با php artisan reload، Worker صف، Reverb و Octane را یکجا پایان میدهد.
deploy.sh 1.1.0 (traced by tests/laravel-deploy-test.sh with stub binaries, real ln/mv)
1 composer install into releases/1.1.0 current=1.0.0
2 php releases/1.1.0/artisan migrate --force current=1.0.0 (expand only)
3 php releases/1.1.0/artisan optimize current=1.0.0 (caches in the new dir)
4 ln -sfn releases/1.1.0 current.new; mv -T current.new current (atomic)
5 systemctl reload php8.4-fpm current=1.1.0
6 php current/artisan queue:restart current=1.1.0
7 curl /up and /version == 1.1.0; on failure: switch back, reload, exit 5 (no migrate:rollback)
(with --maintenance: no switch back; back into maintenance, exit 6 for a human)سناریوهای واقعی:
- یک دقیقه خطای 500 پس از Deploy:
config:cacheپیش از آمادهشدن کد تازه در پوشهٔ زنده اجرا شده است. - Job صف بعد از Deploy با "class not found" میشکند؛ Worker هنوز Release قدیمی را دارد و
queue:restartجا افتاده است. - Octane هنوز Route قدیمی میدهد؛
octane:reloadاجرا نشده است. - Migration مخرب تقسیمناپذیر:
--maintenanceآن را میانdown --render=... --retry=60 --with-secretوupمیگذارد و قطعی را صریح میپذیرد. در این حالت اسکریپت بعد از شکست، کد را برنمیگرداند؛ نسخهٔ قبلی با Schema تازه کار نمیکند. Smoke test ناموفق برنامه را دوباره به نگهداری میبرد و کد خروج شش میدهد. هر شکست میانdownوupبرنامه را پایین نگه میدارد و با پیام روشن، کد خروج هفت و تلهٔEXITاعلام میشود. سپس انسان اصلاح روبهجلو میکند یا پیش از بازگشت کد، DB را بازیابی میکند.
| وضعیت | از تعویض Symlink جان سالم میبرد؟ | تازهسازی |
|---|---|---|
| Workerهای php-fpm و OPcache | بله؛ مسیر و بایتکد قدیمی | systemctl reload php-fpm با SIGUSR2؛ $realpath_root در Nginx |
| Cache پیکربندی / Route / View / Event | در پوشهٔ هر Release با bootstrap/cache | php artisan optimize در Release تازه پیش از تعویض |
| Workerهای Octane | بله؛ برنامه در حافظه | php artisan octane:reload |
| Workerهای صف | بله؛ برنامهٔ Bootشده در حافظه | php artisan queue:restart و Supervisor |
Scheduler با cron و schedule:run | هر دقیقه تازه شروع میشود | هیچ |
| Session، Cache و فایل | مشترک در shared/ یا Redis | باید میان نسخهها سازگار بمانند |
راهحل: تا قدیمی پاسخ میدهد در پوشهٔ تازه Build، Migration افزایشی و Cache را انجام دهید. اتمی تعویض کنید، php-fpm یا Octane را Reload و Worker صف را Restart کنید؛ Smoke test بگیرید و در شکست، بدون دستزدن به DB کد را برگردانید.
توقف استقرار، بازهٔ تغییر، تأیید، Runbook و DORA (Deployment freeze, change windows, post-deploy verification, runbooks and DORA metrics) تکمیلی
به زبان ساده: این بخش دربارهٔ زمان مجاز Deploy، بررسی بلافاصله پس از آن، دستورکار نوشتهشدهٔ خرابی و چهار یا پنج عددی است که نشان میدهند کل فرایند بهتر میشود یا نه.
بدفهمی رایج: «Freeze محیط عملیاتی را امنتر میکند.» Freeze جلوی Deploy را میگیرد، نه ریسک را؛ تغییرها جمع میشوند و اولین Deploy بعدش پرریسکترین میشود. تغییر پرخطر Schema و زیرساخت را محدود کنید، Deploy کوچک پشت Flag را ممکن نگه دارید و راه اضطراری داشته باشید.
تعریف: توقف استقرار (Deployment freeze) و بازهٔ مجاز تغییر (Change window) زمانهای ممنوع یا مجاز Deploy هستند؛ Sync window در Argo CD، "where syncs will either be blocked or allowed"؛ در GitLab هنگام Deploy freeze، "GitLab blocks all deployments"؛ در GitHub Actions حفاظت Environment با بازبین لازم و زمان انتظار. تأیید پس از استقرار (Post-deploy verification) شامل تست سلامت اولیه (Smoke test)، یعنی چند درخواست حیاتی پیش و بلافاصله پس از ترافیک، با پکیج smoke در Go، Webhookهای pre-rollout فلگر یا prePromotionAnalysis در Argo Rollouts است. پایش مصنوعی (Synthetic monitoring) همین سفرهای کاربر را پیوسته از بیرون اجرا میکند تا افت سلامت حتی بدون ترافیک کاربر دیده شود. دستورکار عملیاتی (Runbook) مشخص میکند چه کسی تصمیم میگیرد، کدام فرمان و داشبورد استفاده میشود و Rollback چگونه است. سنجههای DORA: بسامد استقرار (Deployment frequency)، زمان عبور تغییر (Change lead time) با تعریف "from committed to version control to deployed in production"، نرخ شکست تغییر (Change failure rate؛ عبارت فعلی DORA، Change fail rate) برای "deployments that require immediate intervention"، زمان بازیابی استقرار ناموفق (Failed deployment recovery time) که در ۲۰۲۳ جای MTTR را گرفت، و از ۲۰۲۴ نرخ دوبارهکاری استقرار (Deployment rework rate).
Runbook: orders-api release (excerpt)
1 pre: freeze calendar clear? schema change reviewed for N-1? flag default chosen?
2 merge -> CI builds digest -> env repo PR -> Argo CD sync -> Rollout steps start
3 watch: Rollout status, canary success rate, p99, checkout synthetic check
4 abort criteria: analysis Failed, synthetic check red twice, on-call judgement
5 rollback: flag off | kubectl argo rollouts abort | git revert of the bump commit
6 post: smoke suite green on stable; annotate the deploy on dashboards; close the changeسناریوهای واقعی:
- Black Friday: پنجرهٔ منع در Argo CD برای برنامههای زیرساختی، ولی Flagهای برنامه قابل تغییر میمانند.
- Checkout مصنوعی هر دقیقه، Redirect خراب پرداخت را ساعت سه صبح بدون ترافیک واقعی پیدا میکند.
- تیم نرخ شکست را به تفکیک راهبرد میسنجد؛ Rolling بدون Analysis بیشتر از Progressive شکست میخورد و داده هزینهٔ کنترلگر را توجیه میکند.
- Runbook فقط میگوید «برگردان»، بدون روش GitOps؛ مسئول کشیک
kubectl rollout undoمیزند و Argo CD آن را خنثی میکند.
| سنجهٔ DORA | چه چیزی را میسنجد | عامل بهبود |
|---|---|---|
| Deployment frequency | توان تحویل | دستهٔ کوچک، خودکارسازی، Flag |
| Change lead time | توان تحویل | CI سریع و دروازهٔ دستی کمتر |
| Change fail rate | ناپایداری | Analysis در Canary، انضباط N-1، تست |
| Failed deployment recovery time، قبلاً MTTR | توان تحویل / بازیابی | راه بازگشت سریع، Flag، Runbook |
| Deployment rework rate | ناپایداری | Deploy اصلاح فوری کمتر |
راهحل: Freeze را در Config ابزار، Sync window، Deploy freeze یا قواعد Environment ثبت کنید و راه اضطراری مستند داشته باشید. Smoke test جزو هر راهبرد، Runbook متعلق به هر سرویس و سنجش DORA پیش و پس از تغییر راهبرد باشد.
سازوکار (Mechanics)
تغییرهای کنترلگر، گامبهگام (What each controller changes, step by step)
| لحظه | Canary در Argo Rollouts با افزونهٔ Gateway API | Canary در Flagger با Gateway API | اسکریپت سادهٔ Blue-green |
|---|---|---|---|
| کشف تغییر Spec | ReplicaSet تازه برای Canary؛ stable دستنخورده | Deployment هدف از 0 بزرگ میشود | خودتان green را Rollout میکنید |
| پیش از ترافیک | Pod آماده؛ Selector در canaryService Hash تازهٔ Pod template را میگیرد | Webhookهای pre-rollout | rollout status و Smoke test روی preview |
| هر گام | بازنویسی وزن backendRefs در HTTPRoute؛ ایجاد یا ادامهٔ AnalysisRun | افزایش وزن با stepWeight؛ بررسی سنجه و Webhook در هر interval | ندارد؛ یک تعویض |
| موفقیت | Stable RS همان Canary RS میشود؛ وزن 0/100، سپس Label stable جابهجا و RS قدیمی کوچک میشود | Spec به -primary کپی و هدف صفر میشود | Selector سرویس زنده Patch؛ تأیید N درخواست |
| شکست | Abort با وزن 100/0 و Degraded؛ کاهش Canary پس از abortScaleDownDelaySeconds | وزن 0، Canary صفر، Failed | Patch معکوس Selector؛ خروج 5 |
| Git | دستنخورده | دستنخورده | دستنخورده؛ اسکریپت |
حساب وزنها (Weight arithmetic)
- Argo Rollouts بدون Traffic routing: Replicaها وزن را تقریب میزنند: "finding the whole number with the smallest delta, rounding up the calculation if the deltas are equals". ده Replica و
setWeight: 41یعنی چهار Pod قناری و شش stable. - Argo Rollouts با Traffic routing: Router وزن دقیق را میگیرد؛ تعداد Pod در Canary RS بهطور پیشفرض
ceil(weight x replicas)است: "The new ReplicaSet's replica count is equal to the latest SetWeight step percentage multiplied by the total replica count". Stable RS صد درصد میماند مگرdynamicStableScale. مراقب مقدار صریحsetCanaryScaleباشید؛ مثال مستندات "90% of traffic to only be served by 10% of pods" است. - Ingress-NGINX: سهم برابر
canary-weight / canary-weight-totalو مخرج پیشفرض صد است. - Gateway API: سهم Backend با شاخص i برابر
weight_i / sum(weights)است. وزن تعییننشده یک است؛ تک Backend فقط با وزن مثبت صد درصد میگیرد؛ وزن صفر طبق CRD هیچ ترافیکی نمیفرستد. - Flagger: گامها
stepWeight, 2 x stepWeight, ... maxWeightهستند؛ حداقل زمان Promotion ازinterval x (maxWeight / stepWeight)میآید؛ اینجا یک دقیقه ضرب در پنج یعنی پنج دقیقه. زمان Rollback برابرinterval x threshold، یعنی یک دقیقه ضرب در پنج است. - Flag درصدی: Bucket از
= hash(flag, user) mod 100000و روشنبودن ازbucket < percent x 1000میآید. افزایش درصد فقط کاربر اضافه میکند؛ تست Go بررسی میکند همهٔ کاربران ده درصد در گروه پنجاه درصد بمانند.
بودجهٔ زمان (Time budgets)
| بودجه | فرمول | مقادیر فصل |
|---|---|---|
| خاموشی Pod | preStop + Drain delay + Shutdown timeout < terminationGracePeriodSeconds | 5 + 5 + 15 = 25 < 30 |
کف Go Shutdown | بیش از 5 ثانیه با اتصال ازپیشبازشده؛ قاعدهٔ StateNew | 15 s |
| مدت Canary در Argo | جمع Pauseها و زمان Analysis | 2 + 5 + 5 + 10 = 22 min |
| تأخیر Abort در Argo | interval x (failureLimit + 1) | 1 m x 3 = 3 min |
| پنجرهٔ بازگشت Blue-green | scaleDownDelaySeconds یا نگهداشتن Slot قبلی | 60 s در Argo؛ نامحدود در اسکریپت |
| Canary ماشین ASG | Warmup و Checkpoint delay | 120 s + 600 s |
تنظیمات (Knobs)
| تنظیم | محل | پیشفرض | نکته |
|---|---|---|---|
strategy.type | Deployment | RollingUpdate | Recreate ابتدا همهٔ Podها را پایان میدهد |
revisionHistoryLimit | Deployment / Rollout | 10 | 0 بازگشت را غیرفعال میکند |
scaleDownDelaySeconds | Rollout blueGreen | 30 | نگهداشتن RS قدیمی پس از تعویض |
autoPromotionEnabled | Rollout blueGreen | true | false یعنی انتظار برای promote |
abortScaleDownDelaySeconds | Rollout canary | پیشفرض کنترلگر | Canary پس از Abort برای عیبیابی روشن میماند |
failureLimit / consecutiveSuccessLimit | سنجهٔ AnalysisTemplate | 0 / 0، غیرفعال | -1، failureLimit را غیرفعال میکند |
count / interval | سنجهٔ AnalysisTemplate | بدون interval یک اندازهگیری؛ interval بدون count تا توقف Run ادامه میدهد | Template پسزمینه بدون count برای حفاظت همهٔ مراحل؛ Template درونگامی و پس از Promotion با count محدود تا پایانپذیر باشد |
progressDeadlineSeconds | Flagger Canary | 600 | نبود پیشرفت باعث Rollback میشود |
analysis.interval | Flagger | ندارد؛ CRD آن را همراه threshold و stepWeight، stepWeights یا iterations الزامی میکند | یک بررسی در هر بازه؛ این فصل 1m |
canary-weight-total | Ingress-NGINX | 100 | با 1000 وزن ریزتر |
backendRefs[].weight | HTTPRoute | 1 | نسبی |
mirrorPercentage | Istio | در نبود فیلد 100 % | سهم ترافیک کپیشده |
--history-max | Helm | 10 | Revisionهای نگهداشتهشدهٔ هر Release |
min_healthy_percentage / checkpoint_delay | ASG instance refresh | پیشفرض AWS / 3600 | 100 یعنی ایجاد پیش از پایاندادن |
opcache.validate_timestamps | php.ini | 1 | با 0 در Production، FPM هنگام Deploy Reload شود |
process_control_timeout | php-fpm | 0 | زمان واکنش فرزندها به سیگنال Master |
وضعیتها و پیامهای واقعی (Statuses and messages you will actually see)
| محل | پیام / وضعیت | معنا | اقدام |
|---|---|---|---|
| Argo Rollouts | Rollout Degraded پس از Abort | Analysis ناموفق یا Abort دستی | اصلاح یا Revert در Git |
| Argo Rollouts | Paused با CanaryPauseStep | رسیدن به pause: {} | kubectl argo rollouts promote |
| Argo Rollouts | AnalysisRun Inconclusive | هیچیک از شرط موفقیت یا شکست برقرار نیست | انسان Promotion یا Abort را انتخاب کند |
| Argo CD | Application OutOfSync روی وزن HTTPRoute | کنترلگر وزنی نوشته که در Git نیست | ignoreDifferences |
| Argo CD | "Rollback cannot be performed against an application with automated sync enabled." | argocd app rollback همراه Auto-sync | Revert در Git |
| Flagger | Canary با Failed پس از حد بررسی ناموفق | عبور از threshold؛ "halt advancement if any metric is under the specified threshold" و سپس Rollback | بررسی سنجه، اصلاح، Deploy دوباره |
| Kubernetes | Progressing=False، ProgressDeadlineExceeded | Rolling update گیر کرده | kubectl rollout undo یا اصلاح |
| php-fpm | Reloading in progress ... با NOTICE | دریافت SIGUSR2 | هنگام Deploy مورد انتظار است |
| Laravel | HTTP 503 از همهٔ Routeها | Maintenance mode روشن مانده | php artisan up |
| Go | context deadline exceeded از Shutdown | درخواست جاری بیش از Timeout طول کشیده | افزایش Timeout یا اصلاح Handler کند |
Go
سرویس Go همان API سفارش فصلهای قبل است که به نیازهای راهبرد استقرار محدود شده: Flag از OpenFeature با پیشفرض امن، Endpoint آمادگی که پیش از Shutdown غیرفعال میشود، تخلیهٔ زماندار و نشان نسخه در هر پاسخ.
پیش از اصلاح (Before)
Flag از متغیر محیطی خوانده میشود؛ تغییر آن به Deploy دوباره نیاز دارد و هر Pod فقط هنگام شروع آن را میخواند. خاموشی هم درخواست جاری را قطع میکند:
// Before: release = deploy, and every deploy drops requests.
func main() {
newCheckout := os.Getenv("NEW_CHECKOUT") == "true" // flip = new rollout of every Pod
http.HandleFunc("/checkout", func(w http.ResponseWriter, r *http.Request) {
if newCheckout {
checkoutV2(w, r)
return
}
checkoutV1(w, r)
})
http.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
// No readiness, no signal handling: SIGTERM kills the process mid-request,
// and Pods keep receiving traffic until the endpoint update arrives.
log.Fatal(http.ListenAndServe(":8080", nil))
}پس از اصلاح (After)
Flagها: Client مستقل OpenFeature برای هر دامنه (Domain)، Release flag با پیشفرض false و Kill switch با پیشفرض true. ارزیاب حافظهای هدفگیری با Rule منع، Rule اجازه و درصد ثابت برای تست و اجرای محلی استفاده میشود:
// Package flags evaluates the orders service's feature flags through the
// OpenFeature API, so the code never imports a vendor SDK directly: the
// provider (flagd, LaunchDarkly, Unleash, Flagsmith, or the in-memory one in
// tests) is chosen once at start-up.
//
// Two kinds of flag are used, and they need opposite defaults:
//
// - a release flag ("new-checkout") hides unfinished code; when the flag
// system is unreachable the safe answer is the OLD path, so the default is false;
// - a kill switch ("recommendations") keeps a working but expensive feature
// on; when the flag system is unreachable the feature should keep working,
// so the default is true, and operators flip it to false in an incident.
package flags
import (
"context"
"hash/fnv"
"strconv"
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/memprovider"
)
// Flag keys used by the service. Keep them in one place so flag debt is greppable.
const (
NewCheckout = "new-checkout" // release flag, remove after 100 % + one release
Recommendations = "recommendations" // kill switch, permanent
)
// Buckets is the size of the hash space used for percentage rollouts.
// 100,000 buckets give 0.001 % resolution (LaunchDarkly documents the same count).
const Buckets = 100_000
// Bucket maps (flag key, targeting key) to a stable number in [0, Buckets).
// Hashing the flag key together with the user means a user who is in the first
// 10 % of one flag is not automatically in the first 10 % of every other flag
// (Unleash does the same with its groupId, which defaults to the flag name).
func Bucket(flagKey, targetingKey string) int {
h := fnv.New32a()
_, _ = h.Write([]byte(flagKey))
_, _ = h.Write([]byte{0}) // separator: "ab"+"c" must differ from "a"+"bc"
_, _ = h.Write([]byte(targetingKey))
return int(h.Sum32() % Buckets)
}
// Rollout describes a release flag's targeting: rules first, then a percentage.
type Rollout struct {
// Percent of targeting keys (0-100) that get the "on" variant.
Percent float64
// AllowPlans always get "on" (a targeting rule on the "plan" attribute).
AllowPlans []string
// DenyCountries never get "on" (for example, legal review still pending).
DenyCountries []string
}
// Evaluator returns an in-memory ContextEvaluator implementing r. Real providers
// evaluate equivalent rules on their side; this one exists so that tests and
// local runs exercise the same targeting semantics without a network.
func (r Rollout) Evaluator(flagKey string) memprovider.ContextEvaluator {
fn := func(_ memprovider.InMemoryFlag, fc openfeature.FlattenedContext) (any, openfeature.ProviderResolutionDetail) {
country, _ := fc["country"].(string)
for _, c := range r.DenyCountries {
if c == country {
return false, openfeature.ProviderResolutionDetail{Reason: openfeature.TargetingMatchReason, Variant: "off"}
}
}
plan, _ := fc["plan"].(string)
for _, p := range r.AllowPlans {
if p == plan {
return true, openfeature.ProviderResolutionDetail{Reason: openfeature.TargetingMatchReason, Variant: "on"}
}
}
key, _ := fc[openfeature.TargetingKey].(string)
if key == "" {
// No stable identity: a percentage rollout would flip per request.
return false, openfeature.ProviderResolutionDetail{
Reason: openfeature.ErrorReason,
ResolutionError: openfeature.NewTargetingKeyMissingResolutionError("percentage rollout needs a targeting key"),
}
}
on := float64(Bucket(flagKey, key)) < r.Percent/100*Buckets
v := "off"
if on {
v = "on"
}
return on, openfeature.ProviderResolutionDetail{Reason: openfeature.SplitReason, Variant: v}
}
return &fn
}
// User is what the HTTP layer knows about the caller.
type User struct {
ID string
Plan string
Country string
}
// Service wraps one OpenFeature client. It is safe for concurrent use.
type Service struct {
client *openfeature.Client
}
// New returns a Service bound to the provider registered for domain
// (openfeature.SetNamedProviderAndWait). Creating a client never fails: per the
// specification, client creation "MUST NOT throw".
func New(domain string) *Service {
return &Service{client: openfeature.NewClient(domain)}
}
func evalContext(u User) openfeature.EvaluationContext {
return openfeature.NewEvaluationContext(u.ID, map[string]any{
"plan": u.Plan,
"country": u.Country,
})
}
// NewCheckout reports whether u gets the new checkout. On any provider error
// (not ready, flag missing, timeout) OpenFeature returns the default, false.
func (s *Service) NewCheckout(ctx context.Context, u User) bool {
return s.client.Boolean(ctx, NewCheckout, false, evalContext(u))
}
// NewCheckoutDetails is the same evaluation with the reason and error code,
// for logs and the /debug/flags endpoint.
func (s *Service) NewCheckoutDetails(ctx context.Context, u User) openfeature.BooleanEvaluationDetails {
d, _ := s.client.BooleanValueDetails(ctx, NewCheckout, false, evalContext(u))
return d
}
// RecommendationsOn is the kill switch. Default true: if the flag system is down,
// keep the feature; operators turn it off by setting the flag to false.
func (s *Service) RecommendationsOn(ctx context.Context) bool {
return s.client.Boolean(ctx, Recommendations, true, openfeature.NewTargetlessEvaluationContext(nil))
}
// Describe renders an evaluation for a log line: flag=new-checkout value=true reason=SPLIT variant=on.
func Describe(flag string, d openfeature.BooleanEvaluationDetails) string {
s := "flag=" + flag + " value=" + strconv.FormatBool(d.Value) + " reason=" + string(d.Reason)
if d.Variant != "" {
s += " variant=" + d.Variant
}
if d.ErrorCode != "" {
s += " error=" + string(d.ErrorCode)
}
return s
}package flags
import (
"context"
"fmt"
"strings"
"testing"
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/memprovider"
)
// register installs an in-memory provider under a test-specific domain, so
// tests do not share the global default provider.
func register(t *testing.T, flags map[string]memprovider.InMemoryFlag) *Service {
t.Helper()
domain := t.Name()
if err := openfeature.SetNamedProviderAndWait(domain, memprovider.NewInMemoryProvider(flags)); err != nil {
t.Fatalf("set provider: %v", err)
}
return New(domain)
}
func boolFlag(key string, on bool) memprovider.InMemoryFlag {
v := "off"
if on {
v = "on"
}
return memprovider.InMemoryFlag{
Key: key, State: memprovider.Enabled, DefaultVariant: v,
Variants: map[string]any{"on": true, "off": false},
}
}
func rolloutFlag(key string, r Rollout) memprovider.InMemoryFlag {
f := boolFlag(key, false)
f.ContextEvaluator = r.Evaluator(key)
return f
}
func TestMissingFlagFallsBackToDefaults(t *testing.T) {
s := register(t, map[string]memprovider.InMemoryFlag{})
ctx := context.Background()
u := User{ID: "u-1"}
if s.NewCheckout(ctx, u) {
t.Fatal("release flag must default to false (old path) when the flag is missing")
}
if !s.RecommendationsOn(ctx) {
t.Fatal("kill switch must default to true (feature stays on) when the flag is missing")
}
d := s.NewCheckoutDetails(ctx, u)
if d.Reason != openfeature.ErrorReason || d.ErrorCode != openfeature.FlagNotFoundCode {
t.Fatalf("details = %+v, want ERROR / FLAG_NOT_FOUND", d.ResolutionDetail)
}
if got := Describe(NewCheckout, d); !strings.Contains(got, "error=FLAG_NOT_FOUND") {
t.Fatalf("Describe = %q", got)
}
}
func TestDisabledFlagReturnsDefault(t *testing.T) {
f := boolFlag(NewCheckout, true)
f.State = memprovider.Disabled
s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: f})
if s.NewCheckout(context.Background(), User{ID: "u-1"}) {
t.Fatal("a disabled flag must evaluate to the caller's default")
}
}
func TestTargetingRulesBeforePercentage(t *testing.T) {
r := Rollout{Percent: 0, AllowPlans: []string{"internal"}, DenyCountries: []string{"DE"}}
s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, r)})
ctx := context.Background()
cases := []struct {
u User
want bool
}{
{User{ID: "staff-1", Plan: "internal", Country: "NL"}, true}, // allow rule
{User{ID: "staff-2", Plan: "internal", Country: "DE"}, false}, // deny rule wins
{User{ID: "cust-1", Plan: "pro", Country: "NL"}, false}, // 0 % rollout
}
for _, c := range cases {
if got := s.NewCheckout(ctx, c.u); got != c.want {
t.Errorf("%+v: got %v, want %v", c.u, got, c.want)
}
}
if d := s.NewCheckoutDetails(ctx, cases[0].u); d.Reason != openfeature.TargetingMatchReason {
t.Errorf("reason = %s, want TARGETING_MATCH", d.Reason)
}
}
func TestPercentageRolloutIsStickyAndMonotonic(t *testing.T) {
ctx := context.Background()
const users = 20_000
on := func(percent float64) map[string]bool {
s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, Rollout{Percent: percent})})
m := make(map[string]bool, users)
for i := range users {
id := fmt.Sprintf("user-%d", i)
if s.NewCheckout(ctx, User{ID: id}) {
m[id] = true
}
}
return m
}
ten := on(10)
if n := len(ten); n < users*9/100 || n > users*11/100 {
t.Fatalf("10%% rollout enabled %d of %d users", n, users)
}
again := on(10)
for id := range ten {
if !again[id] {
t.Fatalf("%s flipped between two evaluations at the same percentage", id)
}
}
fifty := on(50)
for id := range ten {
if !fifty[id] {
t.Fatalf("%s was in the 10%% cohort but not in the 50%% one: raising a rollout must only add users", id)
}
}
t.Logf("10%%: %d users, 50%%: %d users of %d", len(ten), len(fifty), users)
}
func TestPercentageRolloutNeedsTargetingKey(t *testing.T) {
s := register(t, map[string]memprovider.InMemoryFlag{NewCheckout: rolloutFlag(NewCheckout, Rollout{Percent: 100})})
d := s.NewCheckoutDetails(context.Background(), User{})
if d.Value || d.ErrorCode != openfeature.TargetingKeyMissingCode {
t.Fatalf("got value=%v code=%s, want false / TARGETING_KEY_MISSING", d.Value, d.ErrorCode)
}
}
func TestKillSwitchFlipsWithoutRestart(t *testing.T) {
s := register(t, map[string]memprovider.InMemoryFlag{Recommendations: boolFlag(Recommendations, true)})
ctx := context.Background()
if !s.RecommendationsOn(ctx) {
t.Fatal("kill switch should start on")
}
// Incident: an operator flips the flag. The same Service (same client) sees it.
if err := openfeature.SetNamedProviderAndWait(t.Name(), memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{
Recommendations: boolFlag(Recommendations, false),
})); err != nil {
t.Fatal(err)
}
if s.RecommendationsOn(ctx) {
t.Fatal("kill switch did not take effect for the running client")
}
}
func TestBucketSpreadsAcrossFlags(t *testing.T) {
same := 0
for i := range 1000 {
id := fmt.Sprintf("user-%d", i)
if (Bucket("flag-a", id) < Buckets/10) == (Bucket("flag-b", id) < Buckets/10) {
same++
}
}
// Independent 10 % cohorts agree for about 82 % of users (0.9*0.9 + 0.1*0.1);
// identical cohorts would agree for 100 %.
if same > 900 {
t.Fatalf("cohorts of two flags agree for %d/1000 users: buckets are not independent", same)
}
}سرور: /healthz، /readyz با پاسخ 503 هنگام تخلیه، /version و X-App-Version در همهٔ پاسخها؛ Serve ترتیب غیرفعالکردن Readiness، تأخیر تخلیه و Shutdown زماندار را اجرا میکند:
// Package server is the orders API's HTTP side as far as deployments care:
// readiness that turns off before shutdown, a drain delay so load balancers and
// kube-proxy stop sending new connections, a bounded graceful Shutdown, and a
// /version endpoint that post-deploy smoke tests and blue-green scripts read.
package server
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"sync/atomic"
"time"
"academy/deployment-strategies/flags"
)
// Config holds the timings that must agree with the Pod spec:
// DrainDelay + ShutdownTimeout < terminationGracePeriodSeconds.
type Config struct {
Version string
DrainDelay time.Duration // keep serving after readiness fails (endpoint propagation)
ShutdownTimeout time.Duration // bound on in-flight requests after the drain delay
}
// API is the application handler set.
type API struct {
cfg Config
flags *flags.Service
ready atomic.Bool
log *slog.Logger
}
// New returns an API that is not ready until Serve has its listener running.
func New(cfg Config, f *flags.Service, log *slog.Logger) *API {
return &API{cfg: cfg, flags: f, log: log}
}
// Ready reports the readiness the /readyz probe returns.
func (a *API) Ready() bool { return a.ready.Load() }
// Handler wires the routes (Go 1.22+ method patterns).
func (a *API) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) // liveness: the process works; never tied to dependencies
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
if !a.ready.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, map[string]string{"version": a.cfg.Version})
})
mux.HandleFunc("POST /checkout", a.checkout)
return a.withVersion(mux)
}
// withVersion stamps every response, so a canary analysis or a curl loop can
// count which version answered.
func (a *API) withVersion(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-App-Version", a.cfg.Version)
next.ServeHTTP(w, r)
})
}
func (a *API) checkout(w http.ResponseWriter, r *http.Request) {
u := flags.User{ID: r.Header.Get("X-User-ID"), Plan: r.Header.Get("X-Plan"), Country: r.Header.Get("X-Country")}
flow := "v1"
if a.flags.NewCheckout(r.Context(), u) {
flow = "v2" // new code path, shipped dark until the flag turns on
}
resp := map[string]any{"flow": flow}
if a.flags.RecommendationsOn(r.Context()) {
resp["recommendations"] = []string{"sku-42"} // the expensive call the kill switch can stop
}
writeJSON(w, resp)
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
// Serve runs h on ln until ctx is cancelled (SIGTERM in main), then:
// 1. readiness -> 503, so the endpoint is removed from Services and LB target groups;
// 2. keep serving for DrainDelay (requests already routed here still succeed);
// 3. srv.Shutdown: close listeners, wait for in-flight requests up to ShutdownTimeout.
//
// With a preStop sleep in the Pod spec, step 2 can be 0: Kubernetes waits before SIGTERM.
func Serve(ctx context.Context, ln net.Listener, a *API, h http.Handler) error {
srv := &http.Server{Handler: h, ReadHeaderTimeout: 5 * time.Second}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
a.ready.Store(true)
a.log.Info("serving", "addr", ln.Addr().String(), "version", a.cfg.Version)
select {
case err := <-errc:
return err
case <-ctx.Done():
}
a.ready.Store(false)
a.log.Info("draining", "delay", a.cfg.DrainDelay)
time.Sleep(a.cfg.DrainDelay)
sctx, cancel := context.WithTimeout(context.Background(), a.cfg.ShutdownTimeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return err // context.DeadlineExceeded: requests were still running
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
a.log.Info("stopped")
return nil
}package server
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net"
"net/http"
"strings"
"testing"
"time"
"academy/deployment-strategies/flags"
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/memprovider"
)
func newAPI(t *testing.T, cfg Config, fl map[string]memprovider.InMemoryFlag) *API {
t.Helper()
if err := openfeature.SetNamedProviderAndWait(t.Name(), memprovider.NewInMemoryProvider(fl)); err != nil {
t.Fatal(err)
}
return New(cfg, flags.New(t.Name()), slog.New(slog.NewTextHandler(io.Discard, nil)))
}
func listen(t *testing.T) net.Listener {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return ln
}
// probe uses one connection per request. With keep-alive, Go's Transport may
// dial a spare connection that never carries a request; Server.Shutdown waits
// for such StateNew connections until they are 5 s old (net/http, issue 22682),
// which would make a short ShutdownTimeout expire in this test.
var probe = &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}
func status(t *testing.T, url string) int {
t.Helper()
resp, err := probe.Get(url)
if err != nil {
t.Fatalf("GET %s: %v", url, err)
}
_ = resp.Body.Close()
return resp.StatusCode
}
func waitReady(t *testing.T, base string) {
t.Helper()
for range 100 {
if resp, err := probe.Get(base + "/readyz"); err == nil {
_ = resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("server never became ready")
}
func TestCheckoutFollowsFlagsAndStampsVersion(t *testing.T) {
on := memprovider.InMemoryFlag{Key: flags.NewCheckout, State: memprovider.Enabled, DefaultVariant: "on",
Variants: map[string]any{"on": true, "off": false}}
killed := memprovider.InMemoryFlag{Key: flags.Recommendations, State: memprovider.Enabled, DefaultVariant: "off",
Variants: map[string]any{"on": true, "off": false}}
a := newAPI(t, Config{Version: "1.5.0"}, map[string]memprovider.InMemoryFlag{flags.NewCheckout: on, flags.Recommendations: killed})
ln := listen(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- Serve(ctx, ln, a, a.Handler()) }()
base := "http://" + ln.Addr().String()
waitReady(t, base)
req, _ := http.NewRequest(http.MethodPost, base+"/checkout", strings.NewReader("{}"))
req.Header.Set("X-User-ID", "u-7")
resp, err := probe.Do(req)
if err != nil {
t.Fatal(err)
}
var body map[string]any
_ = json.NewDecoder(resp.Body).Decode(&body)
_ = resp.Body.Close()
if body["flow"] != "v2" {
t.Errorf("flow = %v, want v2 (release flag on)", body["flow"])
}
if _, ok := body["recommendations"]; ok {
t.Error("recommendations present although the kill switch is off")
}
if v := resp.Header.Get("X-App-Version"); v != "1.5.0" {
t.Errorf("X-App-Version = %q", v)
}
cancel()
if err := <-done; err != nil {
t.Fatalf("Serve: %v", err)
}
}
// The drain sequence a rolling update, a blue-green switch or a canary abort relies on.
func TestDrainFailsReadinessThenFinishesInFlight(t *testing.T) {
a := newAPI(t, Config{Version: "1.4.2", DrainDelay: 300 * time.Millisecond, ShutdownTimeout: 2 * time.Second}, nil)
slowStarted := make(chan struct{})
mux := http.NewServeMux()
mux.Handle("/", a.Handler())
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, _ *http.Request) {
close(slowStarted)
time.Sleep(500 * time.Millisecond) // longer than DrainDelay: finishes during Shutdown
w.WriteHeader(http.StatusOK)
})
ln := listen(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- Serve(ctx, ln, a, mux) }()
base := "http://" + ln.Addr().String()
waitReady(t, base)
slow := make(chan int, 1)
go func() {
resp, err := probe.Get(base + "/slow")
if err != nil {
slow <- -1
return
}
_ = resp.Body.Close()
slow <- resp.StatusCode
}()
<-slowStarted
cancel() // SIGTERM
time.Sleep(50 * time.Millisecond)
if a.Ready() {
t.Fatal("still ready after SIGTERM")
}
// During the drain delay the server still answers: readiness 503, work 200.
if got := status(t, base+"/readyz"); got != http.StatusServiceUnavailable {
t.Fatalf("/readyz during drain = %d, want 503", got)
}
if got := status(t, base+"/version"); got != http.StatusOK {
t.Fatalf("/version during drain = %d, want 200 (late-routed requests must still succeed)", got)
}
if got := <-slow; got != http.StatusOK {
t.Fatalf("in-flight request got %d, want 200", got)
}
if err := <-done; err != nil {
t.Fatalf("Serve returned %v", err)
}
if _, err := probe.Get(base + "/healthz"); err == nil {
t.Fatal("listener still open after Shutdown")
}
}
func TestShutdownTimeoutReportsStuckRequests(t *testing.T) {
a := newAPI(t, Config{Version: "1.4.2", DrainDelay: 0, ShutdownTimeout: 100 * time.Millisecond}, nil)
started := make(chan struct{})
release := make(chan struct{})
mux := http.NewServeMux()
mux.HandleFunc("GET /stuck", func(w http.ResponseWriter, _ *http.Request) {
close(started)
<-release
})
ln := listen(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- Serve(ctx, ln, a, mux) }()
go func() {
if resp, err := probe.Get("http://" + ln.Addr().String() + "/stuck"); err == nil {
_ = resp.Body.Close()
}
}()
<-started
cancel()
err := <-done
close(release)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Serve = %v, want context.DeadlineExceeded", err)
}
}تأیید پس از استقرار (Post-deploy verification) برای Pipeline و اسکریپت Blue-green: Check یک Release و VersionMix اثر وزن را تأیید میکند:
// Package smoke is the post-deploy verification the pipeline runs against a
// new release before (blue-green preview) and after (canary, rolling) it takes
// traffic: is it ready, is it the version we meant to ship, and which versions
// are answering behind the shared hostname.
package smoke
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
// Check fails unless base answers /readyz with 200 and /version with want.
func Check(ctx context.Context, c *http.Client, base, want string) error {
var errs []error
if code, err := get(ctx, c, base+"/readyz", nil); err != nil {
errs = append(errs, err)
} else if code != http.StatusOK {
errs = append(errs, fmt.Errorf("readyz: status %d", code))
}
var v struct {
Version string `json:"version"`
}
if code, err := get(ctx, c, base+"/version", &v); err != nil {
errs = append(errs, err)
} else if code != http.StatusOK || v.Version != want {
errs = append(errs, fmt.Errorf("version: status %d, got %q, want %q", code, v.Version, want))
}
return errors.Join(errs...)
}
// VersionMix sends n requests and counts the X-App-Version header, which shows
// whether a weight change (canary 10 %, blue-green 0/100) really took effect.
func VersionMix(ctx context.Context, c *http.Client, url string, n int) (map[string]int, error) {
mix := map[string]int{}
for range n {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return mix, err
}
_ = resp.Body.Close()
mix[resp.Header.Get("X-App-Version")]++
}
return mix, nil
}
func get(ctx context.Context, c *http.Client, url string, into any) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := c.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if into != nil && resp.StatusCode == http.StatusOK {
if err := json.NewDecoder(resp.Body).Decode(into); err != nil {
return resp.StatusCode, fmt.Errorf("%s: %w", url, err)
}
}
return resp.StatusCode, nil
}package smoke
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
func fake(version string, ready bool) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-App-Version", version)
switch r.URL.Path {
case "/readyz":
if !ready {
w.WriteHeader(http.StatusServiceUnavailable)
}
case "/version":
_, _ = w.Write([]byte(`{"version":"` + version + `"}`))
}
}))
}
func TestCheck(t *testing.T) {
ctx := context.Background()
good := fake("1.5.0", true)
defer good.Close()
if err := Check(ctx, good.Client(), good.URL, "1.5.0"); err != nil {
t.Fatalf("healthy release failed: %v", err)
}
if err := Check(ctx, good.Client(), good.URL, "1.6.0"); err == nil || !strings.Contains(err.Error(), `want "1.6.0"`) {
t.Fatalf("wrong version not reported: %v", err)
}
notReady := fake("1.5.0", false)
defer notReady.Close()
if err := Check(ctx, notReady.Client(), notReady.URL, "1.5.0"); err == nil || !strings.Contains(err.Error(), "readyz: status 503") {
t.Fatalf("unready release not reported: %v", err)
}
}
func TestVersionMix(t *testing.T) {
// A stand-in for a weighted route: every 10th request goes to the canary.
var n atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
v := "1.4.2"
if n.Add(1)%10 == 0 {
v = "1.5.0"
}
w.Header().Set("X-App-Version", v)
}))
defer srv.Close()
mix, err := VersionMix(context.Background(), srv.Client(), srv.URL, 200)
if err != nil {
t.Fatal(err)
}
if mix["1.5.0"] != 20 || mix["1.4.2"] != 180 {
t.Fatalf("mix = %v, want 180/20", mix)
}
}// Command orders-api wires flags, server and signals. Version is stamped at
// build time: go build -ldflags "-X main.version=1.5.0".
package main
import (
"context"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"time"
"academy/deployment-strategies/flags"
"academy/deployment-strategies/server"
"github.com/open-feature/go-sdk/openfeature"
"github.com/open-feature/go-sdk/openfeature/memprovider"
)
var version = "dev"
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Production registers a networked provider (flagd, LaunchDarkly, Unleash,
// Flagsmith) here. The in-memory provider keeps this example self-contained:
// new-checkout off, recommendations on.
if err := openfeature.SetNamedProviderAndWait("orders", memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{
flags.NewCheckout: {Key: flags.NewCheckout, State: memprovider.Enabled, DefaultVariant: "off",
Variants: map[string]any{"on": true, "off": false},
ContextEvaluator: flags.Rollout{Percent: 5, AllowPlans: []string{"internal"}}.Evaluator(flags.NewCheckout)},
flags.Recommendations: {Key: flags.Recommendations, State: memprovider.Enabled, DefaultVariant: "on",
Variants: map[string]any{"on": true, "off": false}},
})); err != nil {
log.Error("flag provider", "err", err)
os.Exit(1)
}
defer openfeature.Shutdown()
addr := ":" + envOr("PORT", "8080")
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Error("listen", "err", err)
os.Exit(1)
}
// Pod spec: preStop sleep 5s, terminationGracePeriodSeconds 30.
// Budget: 5 (preStop) + 5 (DrainDelay) + 15 (ShutdownTimeout) = 25 < 30.
api := server.New(server.Config{Version: version, DrainDelay: 5 * time.Second, ShutdownTimeout: 15 * time.Second},
flags.New("orders"), log)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
if err := server.Serve(ctx, ln, api, api.Handler()); err != nil {
log.Error("serve", "err", err)
os.Exit(1)
}
}
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}module academy/deployment-strategies
go 1.24.0
require github.com/open-feature/go-sdk v1.17.1
require (
github.com/go-logr/logr v1.4.3 // indirect
go.uber.org/mock v0.6.0 // indirect
)Rollout و Serviceها و HTTPRoute آن با افزونهٔ Gateway API، Analysis پسزمینه و درونگامی، Image دارای Digest ثابت، Readiness و preStop sleep:
# Argo Rollouts canary for the Go orders API, traffic split by the Gateway API
# plugin (argoproj-labs/gatewayAPI) on an HTTPRoute. The controller rewrites
# the backendRefs weights below; Git keeps 100/0 so Argo CD must ignore them
# (spec.ignoreDifferences on the HTTPRoute, see the chapter).
# Validated offline against the Rollout CRD schema (check-manifests.rb); not applied.
apiVersion: v1
kind: Service
metadata:
name: orders-api-stable
namespace: shop
spec:
selector:
app: orders-api # the controller adds rollouts-pod-template-hash
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: v1
kind: Service
metadata:
name: orders-api-canary
namespace: shop
spec:
selector:
app: orders-api
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: orders-api
namespace: shop
spec:
parentRefs:
- name: public
namespace: gateway
hostnames:
- api.shop.example
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: orders-api-stable
port: 80
weight: 100
- name: orders-api-canary
port: 80
weight: 0
---
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: orders-api
namespace: shop
spec:
replicas: 10
revisionHistoryLimit: 5 # old ReplicaSets kept for `kubectl argo rollouts undo`
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
spec:
terminationGracePeriodSeconds: 30
containers:
- name: orders-api
# Deploy by digest; CI writes it into Git. The tag is for humans only.
image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
ports:
- name: http
containerPort: 8080
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 2
failureThreshold: 1
livenessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 10
lifecycle:
preStop:
sleep:
seconds: 5 # endpoint removal propagates before SIGTERM (Kubernetes 1.34+ GA)
resources:
requests:
cpu: 100m
memory: 64Mi
strategy:
canary:
canaryService: orders-api-canary
stableService: orders-api-stable
maxSurge: "25%"
maxUnavailable: 0
abortScaleDownDelaySeconds: 30
trafficRouting:
plugins:
argoproj-labs/gatewayAPI:
httpRoute: orders-api
namespace: shop
# Background analysis: runs from step 2 until the rollout ends (its
# templates have no count); exceeding failureLimit on either metric
# abort the rollout and send all traffic to stable.
analysis:
startingStep: 2
templates:
- templateName: http-success-rate
- templateName: http-latency-p99
args:
- name: service
value: orders-api-canary
steps:
- setWeight: 5
- pause: {duration: 2m}
- setWeight: 20
- pause: {duration: 5m}
# Inline analysis: blocks here until the five-measurement gate completes.
# The background analysis above keeps running through the 50 % stage.
- analysis:
templates:
- templateName: http-success-rate-gate
args:
- name: service
value: orders-api-canary
- setWeight: 50
- pause: {duration: 10m}
- setWeight: 100AnalysisTemplateها: نرخ موفقیت و p99 نامحدود برای پسزمینه، بدون count تا مرحلهٔ پنجاه درصد هم حفاظت شود؛ دروازهٔ نرخ موفقیت با پنج اندازهگیری محدود برای گام درونی و پس از Promotion؛ و سنجهٔ job برای Smoke test:
# Prometheus-backed AnalysisTemplates used by both Rollouts in this chapter.
# Metric names assume the Go service exports http_requests_total{service,code}
# and http_request_duration_seconds_bucket{service} (OpenTelemetry or
# promhttp naming); adjust the label names to your instrumentation.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: http-success-rate
namespace: shop
spec:
args:
- name: service
metrics:
- name: success-rate
interval: 1m # no count: measures every minute until the rollout ends
successCondition: len(result) > 0 && result[0] >= 0.995 # no data = failed
failureLimit: 2 # third failed measurement -> AnalysisRun Failed -> abort
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
sum(rate(http_requests_total{service="{{args.service}}",code!~"5.."}[2m]))
/
sum(rate(http_requests_total{service="{{args.service}}"}[2m]))
---
# Finite gate for inline steps and post-promotion checks: five measurements,
# one per minute, then the run completes (Successful or Failed). A background
# analysis must NOT use a finite count, or the later stages run unguarded.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: http-success-rate-gate
namespace: shop
spec:
args:
- name: service
metrics:
- name: success-rate
interval: 1m
count: 5
successCondition: len(result) > 0 && result[0] >= 0.995
failureLimit: 2
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
sum(rate(http_requests_total{service="{{args.service}}",code!~"5.."}[2m]))
/
sum(rate(http_requests_total{service="{{args.service}}"}[2m]))
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: http-latency-p99
namespace: shop
spec:
args:
- name: service
metrics:
- name: latency-p99
interval: 1m
successCondition: len(result) > 0 && result[0] <= 0.300 # seconds; no data = failed
failureLimit: 3
provider:
prometheus:
address: http://prometheus.monitoring.svc:9090
query: |
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket{service="{{args.service}}"}[2m])))
---
# Smoke test as a metric: a Kubernetes Job that runs the Go smoke checker
# against the preview Service. Exit 0 = Successful, non-zero = Failed.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: smoke-test
namespace: shop
spec:
args:
- name: base-url
- name: version
metrics:
- name: smoke
provider:
job:
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: smoke
image: ghcr.io/acme/orders-smoke:1.0.0
args: ["--base", "{{args.base-url}}", "--version", "{{args.version}}"]همان سرویس با Blue-green در Argo Rollouts: Service پیشنمایش، Smoke test پیش از Promotion، ارتقای دستی و Analysis پس از آن:
# Argo Rollouts blue-green for the same service: the controller switches the
# active Service's selector (rollouts-pod-template-hash) after the smoke test
# on the preview Service passes and a human promotes.
apiVersion: v1
kind: Service
metadata:
name: orders-api-active
namespace: shop
spec:
selector:
app: orders-api-bg
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: v1
kind: Service
metadata:
name: orders-api-preview
namespace: shop
spec:
selector:
app: orders-api-bg
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: orders-api-bg
namespace: shop
spec:
replicas: 6
revisionHistoryLimit: 3
selector:
matchLabels:
app: orders-api-bg
template:
metadata:
labels:
app: orders-api-bg
spec:
containers:
- name: orders-api
image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
ports:
- name: http
containerPort: 8080
readinessProbe:
httpGet:
path: /readyz
port: http
strategy:
blueGreen:
activeService: orders-api-active
previewService: orders-api-preview
previewReplicaCount: 2 # small green stack while it is tested
autoPromotionEnabled: false # a human (or the pipeline) runs `promote`
scaleDownDelaySeconds: 60 # keep blue for iptables propagation and fast rollback
prePromotionAnalysis:
templates:
- templateName: smoke-test
args:
- name: base-url
value: http://orders-api-preview.shop.svc
- name: version
value: "1.5.0"
postPromotionAnalysis:
templates:
- templateName: http-success-rate-gate # finite: must complete to finish the update
args:
- name: service
value: orders-api-activeBlue-green با Kubernetes معمولی، بدون کنترلگر اضافه، و اسکریپت تعویض همراه بررسی و Rollback:
# Plain-Kubernetes blue-green: two complete Deployments, one Service whose
# selector names the live slot, one preview Service for the idle slot.
# The switch is a single selector patch (scripts/blue-green-switch.sh);
# rollback is the same patch with the old slot.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api-blue
namespace: shop
labels:
app: orders-api
slot: blue
spec:
replicas: 4
selector:
matchLabels:
app: orders-api
slot: blue
template:
metadata:
labels:
app: orders-api
slot: blue
spec:
terminationGracePeriodSeconds: 30
containers:
- name: orders-api
image: ghcr.io/acme/orders-api:1.4.2@sha256:1111111111111111111111111111111111111111111111111111111111111111
ports:
- name: http
containerPort: 8080
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 2
lifecycle:
preStop:
sleep:
seconds: 5
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api-green
namespace: shop
labels:
app: orders-api
slot: green
spec:
replicas: 4
selector:
matchLabels:
app: orders-api
slot: green
template:
metadata:
labels:
app: orders-api
slot: green
spec:
terminationGracePeriodSeconds: 30
containers:
- name: orders-api
image: ghcr.io/acme/orders-api:1.5.0@sha256:0000000000000000000000000000000000000000000000000000000000000000
ports:
- name: http
containerPort: 8080
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 2
lifecycle:
preStop:
sleep:
seconds: 5
---
# Live traffic: whatever slot this selector names.
apiVersion: v1
kind: Service
metadata:
name: orders-api
namespace: shop
annotations:
deploy.acme.io/previous-slot: green
spec:
selector:
app: orders-api
slot: blue
ports:
- name: http
port: 80
targetPort: http
---
# Smoke tests and internal testers reach the idle slot here.
apiVersion: v1
kind: Service
metadata:
name: orders-api-preview
namespace: shop
spec:
selector:
app: orders-api
slot: green
ports:
- name: http
port: 80
targetPort: http#!/usr/bin/env bash
# blue-green-switch.sh: move live traffic of a Kubernetes Service from one slot
# (Deployment <app>-blue / <app>-green) to the other by patching the Service
# selector, with checks before and a verified rollback after.
#
# blue-green-switch.sh [--dry-run] [-n NAMESPACE] APP TARGET_SLOT EXPECTED_VERSION
#
# Environment:
# PREVIEW_URL base URL that reaches <APP>-preview (in-cluster DNS or a port-forward)
# LIVE_URL base URL that reaches <APP> through the real path (Gateway, LB)
# VERIFY_N requests sent after the switch to confirm the new version (default 20)
# VERIFY_GRACE leading requests allowed to see the old slot while routing converges (default 5)
# Exit codes: 0 switched or already live, 2 usage, 3 target not ready,
# 4 smoke test failed (nothing switched), 5 verification failed (rolled back).
set -euo pipefail
NS=default
DRY_RUN=0
VERIFY_N=${VERIFY_N:-20}
usage() { echo "usage: ${0##*/} [--dry-run] [-n NAMESPACE] APP TARGET_SLOT EXPECTED_VERSION" >&2; exit 2; }
log() { printf '%s switch: %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
run() { if [ "$DRY_RUN" = 1 ]; then { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2; else "$@"; fi; }
while [ "$#" -gt 0 ]; do
case $1 in
--dry-run) DRY_RUN=1; shift ;;
-n) NS=${2:?}; shift 2 ;;
-h|--help) usage ;;
-*) echo "unknown option: $1" >&2; usage ;;
*) break ;;
esac
done
[ "$#" -eq 3 ] || usage
APP=$1 TARGET=$2 VERSION=$3
case $TARGET in blue|green) ;; *) echo "slot must be blue or green" >&2; exit 2 ;; esac
: "${PREVIEW_URL:?set PREVIEW_URL}" "${LIVE_URL:?set LIVE_URL}"
k() { kubectl -n "$NS" "$@"; }
version_at() { curl --fail --silent --show-error --max-time 3 "$1/version" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'; }
selector_patch() { printf '{"metadata":{"annotations":{"deploy.acme.io/previous-slot":"%s"}},"spec":{"selector":{"app":"%s","slot":"%s"}}}' "$2" "$APP" "$1"; }
# 1. Where is live traffic now? Idempotent: nothing to do if TARGET is already live.
CURRENT=$(k get service "$APP" -o jsonpath='{.spec.selector.slot}')
if [ "$CURRENT" = "$TARGET" ]; then
log "$APP already serves slot $TARGET; nothing to do"
exit 0
fi
log "live slot: $CURRENT, target: $TARGET, expected version: $VERSION"
# 2. The target Deployment must be fully rolled out (all replicas Ready).
if ! k rollout status "deployment/$APP-$TARGET" --timeout=180s >&2; then
log "deployment $APP-$TARGET is not ready; aborting before any switch"; exit 3
fi
# 3. Point the preview Service at the target slot and smoke-test it.
run kubectl -n "$NS" patch service "$APP-preview" --type=merge -p "$(printf '{"spec":{"selector":{"app":"%s","slot":"%s"}}}' "$APP" "$TARGET")" >&2
if [ "$DRY_RUN" = 0 ]; then
got=""
for _ in 1 2 3 4 5; do got=$(version_at "$PREVIEW_URL" || true); [ "$got" = "$VERSION" ] && break; sleep 1; done
if [ "$got" != "$VERSION" ]; then log "smoke test: preview answers '${got:-nothing}', want $VERSION; not switching"; exit 4; fi
log "smoke test passed on preview ($got)"
fi
# 4. The switch: one PATCH of the live Service's selector. Endpoints follow within seconds.
run kubectl -n "$NS" patch service "$APP" --type=merge -p "$(selector_patch "$TARGET" "$CURRENT")" >&2
[ "$DRY_RUN" = 1 ] && { log "DRY-RUN: would verify $VERIFY_N requests on $LIVE_URL"; exit 0; }
# 5. Verify through the real path; roll back to the previous slot on failure.
# The first GRACE requests may still see the old slot while kube-proxy and the LB
# converge; after that any mismatch rolls back. Whatever VERIFY_N is, the LAST
# answer must be the new version, so a short or fully failing check cannot pass.
GRACE=${VERIFY_GRACE:-5}
rollback() {
log "$1; rolling back to $CURRENT"
k patch service "$APP" --type=merge -p "$(selector_patch "$CURRENT" "$TARGET")" >&2
exit 5
}
ok=0 got=""
for i in $(seq 1 "$VERIFY_N"); do
got=$(version_at "$LIVE_URL" || true)
if [ "$got" = "$VERSION" ]; then ok=$((ok + 1))
elif [ "$i" -gt "$GRACE" ]; then rollback "request $i answered '${got:-error}'"
fi
sleep "${VERIFY_SLEEP:-0.5}"
done
if [ "$ok" -eq 0 ] || [ "$got" != "$VERSION" ]; then
rollback "verification ended with '${got:-error}' ($ok/$VERIFY_N requests on $VERSION)"
fi
log "switched $APP to $TARGET ($ok/$VERIFY_N requests on $VERSION); $APP-$CURRENT kept for rollback"#!/usr/bin/env bash
# Runs scripts/blue-green-switch.sh against stub `kubectl` and `curl` programs
# on PATH (no cluster): the stubs keep Service selectors in files and answer
# /version according to which slot a Service points at.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
SCRIPT="$HERE/../scripts/blue-green-switch.sh"
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
mkdir -p "$T/bin" "$T/state"
export STATE="$T/state" PATH="$T/bin:$PATH" PREVIEW_URL=http://preview LIVE_URL=http://live VERIFY_SLEEP=0 VERIFY_N=10
cat > "$T/bin/kubectl" <<'EOF'
#!/usr/bin/env bash
# stub: kubectl -n NS <verb> ...
shift 2
echo "kubectl $*" >> "$STATE/calls"
case $1 in
get) cat "$STATE/svc-$3" ;;
rollout) d=${3#deployment/}; [ "$(cat "$STATE/ready-$d" 2>/dev/null)" = yes ] && echo "deployment \"$d\" successfully rolled out" ;;
patch) slot=$(printf '%s' "$6" | sed -n 's/.*"slot":"\([a-z]*\)".*/\1/p'); printf '%s' "$slot" > "$STATE/svc-$3"; echo "service/$3 patched" ;;
esac
EOF
cat > "$T/bin/curl" <<'EOF'
#!/usr/bin/env bash
# stub: last argument is the URL; preview -> orders-api-preview, live -> orders-api
url=${!#}
case $url in http://preview/*) svc=orders-api-preview ;; http://live/*) svc=orders-api ;; esac
slot=$(cat "$STATE/svc-$svc")
if [ "$svc" = orders-api ] && [ -f "$STATE/live-broken-$slot" ]; then echo "curl: (22) 502" >&2; exit 22; fi
printf '{"version":"%s"}\n' "$(cat "$STATE/version-$slot")"
EOF
chmod +x "$T/bin/kubectl" "$T/bin/curl"
reset() {
rm -f "$STATE"/*
printf blue > "$STATE/svc-orders-api"; printf blue > "$STATE/svc-orders-api-preview"
printf 1.4.2 > "$STATE/version-blue"; printf 1.5.0 > "$STATE/version-green"
echo yes > "$STATE/ready-orders-api-blue"; echo yes > "$STATE/ready-orders-api-green"
}
pass=0; fail=0
check() { if eval "$2"; then echo "ok - $1"; pass=$((pass+1)); else echo "FAIL - $1"; fail=$((fail+1)); fi; }
reset
out=$("$SCRIPT" --dry-run -n shop orders-api green 1.5.0 2>&1); rc=$?
check "dry run exits 0 and prints the selector patch" '[ $rc = 0 ] && grep -q "DRY-RUN: kubectl -n shop patch service orders-api" <<<"$out"'
check "dry run leaves live traffic on blue" '[ "$(cat $STATE/svc-orders-api)" = blue ]'
reset
"$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?
check "switch to green exits 0" '[ $rc = 0 ]'
check "live Service now selects green" '[ "$(cat $STATE/svc-orders-api)" = green ]'
check "preview was patched before live" '[ "$(grep -n "patch service orders-api-preview" $STATE/calls | cut -d: -f1)" -lt "$(grep -n "patch service orders-api " $STATE/calls | cut -d: -f1)" ]'
sed 's/^[0-9:]* / log: /' "$T/log"
out=$("$SCRIPT" -n shop orders-api green 1.5.0 2>&1); rc=$?
check "second run is a no-op (idempotent)" '[ $rc = 0 ] && grep -q "already serves slot green" <<<"$out"'
reset; echo no > "$STATE/ready-orders-api-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>/dev/null; rc=$?; set -e
check "unready green aborts with 3 and switches nothing" '[ $rc = 3 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
reset; printf 1.4.9 > "$STATE/version-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>/dev/null; rc=$?; set -e
check "wrong version on preview aborts with 4 before the switch" '[ $rc = 4 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
reset; touch "$STATE/live-broken-green"
set +e; "$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?; set -e
check "failing live path after the switch rolls back with 5" '[ $rc = 5 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
grep -E "rolling back" "$T/log" | sed 's/^[0-9:]* / log: /'
reset; touch "$STATE/live-broken-green"
set +e; VERIFY_N=3 "$SCRIPT" -n shop orders-api green 1.5.0 2>"$T/log"; rc=$?; set -e
check "VERIFY_N=3 with a failing live path still rolls back with 5" '[ $rc = 5 ] && [ "$(cat $STATE/svc-orders-api)" = blue ]'
grep -E "rolling back" "$T/log" | sed 's/^[0-9:]* / log: /'
echo "$pass passed, $fail failed"
[ "$fail" = 0 ]همهٔ Manifestهای صفحه آفلاین با سندهای OpenAPI v3 در Kubernetes و CRDهای خود پروژهها، شامل Rollout، AnalysisTemplate، Canary، MetricTemplate، HTTPRoute، VirtualService و DestinationRule، اعتبارسنجی میشوند. قواعد میان اشیا نیز وجود Service، Template و Route ارجاعشده را بررسی میکنند:
#!/usr/bin/env ruby
# Offline schema check for the chapter's manifests (no cluster, no kubectl apply):
# 1. every file parses as YAML (multi-document);
# 2. every object is validated against the schema the API server would use:
# - core kinds (Deployment, Service, Ingress) against Kubernetes' published
# OpenAPI v3 documents (api/openapi-spec/v3 in kubernetes/kubernetes);
# - CRDs (Rollout, AnalysisTemplate, Canary, MetricTemplate, HTTPRoute,
# VirtualService, DestinationRule) against the openAPIV3Schema in the
# projects' own CRD manifests;
# checking unknown fields, required fields, basic types and enums;
# 3. a few cross-object rules the schemas cannot express.
# Usage: ruby check-manifests.rb <saved-sources-dir> <manifest files...>
require 'yaml'
require 'json'
src, *files = ARGV
$errors = []
def err(m); $errors << m; end
# ---- schema registry -------------------------------------------------------
SCHEMAS = {} # "group/version Kind" => [schema, resolver]
OPENAPI = {} # component name => schema (core)
%w[k8s-openapi-apps-v1 k8s-openapi-core-v1 k8s-openapi-networking-v1].each do |n|
doc = JSON.parse(File.read(File.join(src, "#{n}.txt")))
doc['components']['schemas'].each do |name, s|
OPENAPI[name] = s
(s['x-kubernetes-group-version-kind'] || []).each do |gvk|
gv = gvk['group'].to_s.empty? ? gvk['version'] : "#{gvk['group']}/#{gvk['version']}"
SCHEMAS["#{gv} #{gvk['kind']}"] = s
end
end
end
%w[argo-rollouts-crd argo-rollouts-analysis-crd flagger-crd gwapi-httproute-crd istio-crds].each do |n|
YAML.load_stream(File.read(File.join(src, "#{n}.txt"))).compact.each do |crd|
next unless crd['kind'] == 'CustomResourceDefinition'
g = crd['spec']['group']; k = crd['spec']['names']['kind']
crd['spec']['versions'].each do |v|
s = v.dig('schema', 'openAPIV3Schema') || crd.dig('spec', 'validation', 'openAPIV3Schema')
SCHEMAS["#{g}/#{v['name']} #{k}"] = s if s
end
end
end
def resolve(s)
loop do
if s['$ref']
s = OPENAPI.fetch(s['$ref'].sub('#/components/schemas/', ''))
elsif s['allOf'] && s['allOf'].size == 1 && s.keys.all? { |k| %w[allOf default description].include?(k) }
s = s['allOf'][0]
else
return s
end
end
end
def type_ok?(v, s)
return true if s['x-kubernetes-int-or-string'] && (v.is_a?(Integer) || v.is_a?(String))
case s['type']
when 'string' then v.is_a?(String)
when 'integer' then v.is_a?(Integer)
when 'number' then v.is_a?(Numeric)
when 'boolean' then v == true || v == false
when 'array' then v.is_a?(Array)
when 'object' then v.is_a?(Hash)
else true
end
end
def validate(v, s, path, file, root = false)
s = resolve(s)
return if s['x-kubernetes-preserve-unknown-fields'] && !s['properties']
unless type_ok?(v, s)
return err("#{file}: #{path}: expected #{s['type'] || 'int-or-string'}, got #{v.class}")
end
err("#{file}: #{path}: #{v.inspect} not in #{s['enum']}") if s['enum'] && !s['enum'].include?(v)
if v.is_a?(Hash)
props = s['properties'] || {}
(s['required'] || []).each { |r| err("#{file}: #{path}: missing required '#{r}'") unless v.key?(r) }
v.each do |k, val|
next if root && %w[apiVersion kind metadata].include?(k) && !props[k] # Istio CRDs list only spec/status
if props[k] then validate(val, props[k], "#{path}.#{k}", file)
elsif s['additionalProperties'].is_a?(Hash) then validate(val, s['additionalProperties'], "#{path}.#{k}", file)
elsif s['additionalProperties'] == true || s['x-kubernetes-preserve-unknown-fields'] then next
elsif !props.empty? then err("#{file}: #{path}: unknown field '#{k}'")
end
end
elsif v.is_a?(Array) && s['items']
v.each_with_index { |x, i| validate(x, s['items'], "#{path}[#{i}]", file) }
end
end
# ---- validate ----------------------------------------------------------------
objects = []
files.each do |f|
begin
docs = YAML.load_stream(File.read(f)).compact
rescue Psych::SyntaxError => e
err("#{f}: YAML: #{e.message}"); next
end
docs.each do |d|
key = "#{d['apiVersion']} #{d['kind']}"
s = SCHEMAS[key]
if s.nil? then err("#{f}: no schema for #{key}") else validate(d, s, d['kind'], f, true) end
objects << [f, d]
end
end
# ---- cross-object rules --------------------------------------------------------
by = ->(kind, name) { objects.map(&:last).find { |o| o['kind'] == kind && o.dig('metadata', 'name') == name } }
objects.each do |f, d|
case d['kind']
when 'Rollout'
sel = d.dig('spec', 'selector', 'matchLabels') || {}
lab = d.dig('spec', 'template', 'metadata', 'labels') || {}
err("#{f}: Rollout selector not a subset of template labels") unless sel.all? { |k, v| lab[k] == v }
c = d.dig('spec', 'strategy', 'canary') || {}
%w[canaryService stableService].each { |k| err("#{f}: #{k} #{c[k]} not defined") if c[k] && !by.('Service', c[k]) }
b = d.dig('spec', 'strategy', 'blueGreen') || {}
%w[activeService previewService].each { |k| err("#{f}: #{k} #{b[k]} not defined") if b[k] && !by.('Service', b[k]) }
refs = (c.dig('analysis', 'templates') || []) + (c['steps'] || []).flat_map { |st| st.dig('analysis', 'templates') || [] } +
(b.dig('prePromotionAnalysis', 'templates') || []) + (b.dig('postPromotionAnalysis', 'templates') || [])
refs.each { |t| err("#{f}: AnalysisTemplate #{t['templateName']} not defined") unless by.('AnalysisTemplate', t['templateName']) }
route = c.dig('trafficRouting', 'plugins', 'argoproj-labs/gatewayAPI', 'httpRoute')
err("#{f}: HTTPRoute #{route} not defined") if route && !by.('HTTPRoute', route)
ps = d.dig('spec', 'template', 'spec') || {}
grace = ps['terminationGracePeriodSeconds'] || 30
(ps['containers'] || []).each do |ct|
sl = ct.dig('lifecycle', 'preStop', 'sleep', 'seconds')
err("#{f}: preStop sleep #{sl}s >= grace #{grace}s") if sl && sl >= grace
end
when 'Deployment'
sel = d.dig('spec', 'selector', 'matchLabels') || {}
lab = d.dig('spec', 'template', 'metadata', 'labels') || {}
err("#{f}: Deployment selector not a subset of template labels") unless sel.all? { |k, v| lab[k] == v }
when 'HTTPRoute'
(d.dig('spec', 'rules') || []).each do |r|
w = (r['backendRefs'] || []).map { |b| b['weight'] || 1 }.grep(Integer)
err("#{f}: HTTPRoute rule with all weights 0 sends 500s") if !w.empty? && w.sum.zero?
end
when 'Ingress'
an = d.dig('metadata', 'annotations') || {}
if an['nginx.ingress.kubernetes.io/canary'] == 'true'
w = an['nginx.ingress.kubernetes.io/canary-weight']
err("#{f}: canary-weight must be a quoted integer string") if w && w !~ /\A\d+\z/
host = d.dig('spec', 'rules', 0, 'host')
main = objects.map(&:last).find { |o| o['kind'] == 'Ingress' && o != d && o.dig('spec', 'rules', 0, 'host') == host }
err("#{f}: canary Ingress has no main Ingress for host #{host}") unless main
end
when 'Canary'
(d.dig('spec', 'analysis', 'metrics') || []).each do |m|
ref = m.dig('templateRef', 'name')
err("#{f}: MetricTemplate #{ref} not defined") if ref && !by.('MetricTemplate', ref)
end
end
end
puts "#{files.size} files, #{objects.size} objects, #{SCHEMAS.size} schemas loaded"
if $errors.empty? then puts 'manifests ok' else puts $errors; exit 1 endنگاه Go (The Go angle)
- یک Wrapper و پیشفرض Typed: فقط
flags.Serviceکلید و پیشفرض را میشناسد؛ Handler،NewCheckout(ctx, user)را میخواند. بدهی Flag باgrep flags.NewCheckoutاینجا دیده میشود و پیشفرض همینجا تعیین میشود: Release flag در خطا مسیر قدیمی را انتخاب میکند؛ Kill switch قابلیت را روشن نگه میدارد. - OpenFeature در Go:
openfeature.SetNamedProviderAndWait(domain, provider)، Provider را ثبت وopenfeature.NewClient(domain)، Client را میسازد.client.Boolean(ctx, key, default, evalCtx)به فراخوان خطا برنمیگرداند؛ برای دلیل، Variant و Error code ازBooleanValueDetailsاستفاده کنید. Domain نامدار تست را از Provider سراسری مستقل میکند. go-sdk v1.17.1 این فصلgo 1.24.0دارد؛ فایلهای.modدر proxy.golang.org برای v1.17.2 و v1.18.0 مقدارgo 1.25.0و برای v1.19.0 و v1.20.0 مقدارgo 1.26.0دارند. - درصد ثابت: FNV-1a روی
flagKey + 0x00 + targetingKeyبا پیمانهٔ صد هزار، قطعی، ارزان و مستقل برای هر Flag است. بدون Targeting key ارزیابTARGETING_KEY_MISSINGو پیشفرض را میدهد؛ نتیجه برای هر درخواست تصادفی عوض نمیشود. - ترتیب تخلیه: اول Readiness برابر 503، سپس سرویسدهی برای
DrainDelay؛ اگر preStop انتشار حذف Endpoint را پوشش میدهد، این تأخیر صفر باشد. بعدsrv.Shutdownبا Timeout.signal.NotifyContext، SIGTERM را به لغو Context تبدیل میکند؛ سیستمعامل، پردازه و سیگنال. - قاعدهٔ پنجثانیهای StateNew:
Server.Shutdownاتصال Idle را میبندد ولی برای اتصالStateNewتا پنج ثانیه عمر صبر میکند؛net/http، مسئلهٔ ۲۲۶۸۲. تست تخلیه با Keep-alive به آن برخورد و اکنونDisableKeepAlivesدارد؛ در Production،ShutdownTimeoutبا فاصلهٔ کافی بیشتر از پنج ثانیه باشد. - نسخه در همهٔ پاسخها:
X-App-Versionشمارش Canary از بیرون باsmoke.VersionMixو تفکیک Log و Trace بر اساس نسخه را ممکن میکند؛ Query تحلیل به همین نیاز دارد. - Smoke check بهشکل کد: پکیج
smokeدر سنجهٔjob، Webhook فلگر یا گام Pipeline اجرا میشود: Readiness برابر 200 و/versionبرابر Release در حال Promotion.
Laravel
پیش از اصلاح (Before)
Deploy آغازین بسیاری از پروژههای Laravel: git pull در پوشهٔ زنده و فرمانهایی با ترتیبی که خطا را حتمی میکند:
# Before: in-place deploy on the live directory
cd /var/www/shop
php artisan down # everyone gets 503 for the whole deploy
git pull origin main # live code changes file by file while requests run
composer install --no-dev # vendor/ half-updated for tens of seconds
php artisan migrate --force # new schema, new code, no way back
php artisan config:cache # cached while files are still changing
php artisan up
# forgotten: php-fpm reload (OPcache keeps old bytecode), queue:restart (workers run old code)پس از اصلاح (After)
اسکریپت بدون قطعی: پوشهٔ جدا برای Release، Migration فقط افزایشی پیش از تعویض، Cache داخل Release تازه، تعویض اتمی، Reload کردن php-fpm یا Octane، queue:restart، Smoke test و Rollback فقط کد:
#!/usr/bin/env bash
# deploy.sh: zero-downtime Laravel release on a VM (Nginx + php-fpm, or Octane),
# Capistrano/Deployer layout:
# $ROOT/releases/<version>/ one directory per release, never modified after the switch
# $ROOT/shared/.env, storage/ shared between releases
# $ROOT/current -> releases/<version> the only thing that changes at cut-over
#
# deploy.sh [--dry-run] [--maintenance] VERSION ARTIFACT_DIR
#
# Order matters and is the point of the script:
# build the release -> migrate (expand-only, old code still live) -> cache config/routes
# -> atomic symlink switch -> reload php-fpm (or Octane) -> restart queue workers
# -> smoke test -> on failure switch back (code only; migrations are forward-only).
# --maintenance is for the rare release that cannot be N-1 compatible: it wraps the
# migration in `artisan down` and accepts a few seconds of 503s instead. Because the
# previous release cannot run on the new schema, a failure in this mode NEVER switches
# the code back: the app stays (or goes back) in maintenance and a human decides
# (fix forward, or restore the database and then the code). Exit codes: 6 smoke test
# failed in maintenance mode, 7 a step failed between `down` and `up`.
set -euo pipefail
ROOT=${DEPLOY_ROOT:-/srv/shop}
APP_URL=${APP_URL:-http://127.0.0.1}
PHP_FPM_SERVICE=${PHP_FPM_SERVICE:-php8.4-fpm}
OCTANE=${OCTANE:-0}
KEEP=${KEEP:-5}
DRY_RUN=0
MAINTENANCE=0
usage() { echo "usage: ${0##*/} [--dry-run] [--maintenance] VERSION ARTIFACT_DIR" >&2; exit 2; }
log() { printf '%s deploy: %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
run() { if [ "$DRY_RUN" = 1 ]; then { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2; else "$@"; fi; }
while [ "$#" -gt 0 ]; do
case $1 in
--dry-run) DRY_RUN=1; shift ;;
--maintenance) MAINTENANCE=1; shift ;;
-h|--help) usage ;;
-*) echo "unknown option: $1" >&2; usage ;;
*) break ;;
esac
done
[ "$#" -eq 2 ] || usage
VERSION=$1 ARTIFACT=$2
case $VERSION in *[!A-Za-z0-9._-]*|'') echo "bad version: $VERSION" >&2; exit 2 ;; esac
[ -f "$ARTIFACT/artisan" ] || { echo "not a Laravel build: $ARTIFACT" >&2; exit 4; }
REL="$ROOT/releases/$VERSION"
# GNU mv -T / BSD mv -h: rename(2) the new link over the old one, so `current`
# always points at a complete release (no moment where it is missing).
swap_link() { case $(uname -s) in Darwin|*BSD) mv -fh "$1" "$2" ;; *) mv -T "$1" "$2" ;; esac; }
point_current_at() { run ln -sfn "$1" "$ROOT/current.new"; if [ "$DRY_RUN" = 0 ]; then swap_link "$ROOT/current.new" "$ROOT/current"; fi; }
reload_php() {
if [ "$OCTANE" = 1 ]; then
run php "$ROOT/current/artisan" octane:reload # graceful worker restart, new code in memory
else
run systemctl reload "$PHP_FPM_SERVICE" # php-fpm master gets SIGUSR2: graceful reload,
fi # fresh workers and a fresh OPcache
run php "$ROOT/current/artisan" queue:restart # workers exit after their current job
}
smoke() {
curl --fail --silent --show-error --max-time 5 --retry 3 --retry-delay 1 --retry-connrefused "$APP_URL/up" >/dev/null &&
[ "$(curl --fail --silent --max-time 5 "$APP_URL/version")" = "$VERSION" ]
}
# 1. Idempotency.
if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$REL" ]; then
log "$VERSION is already current; nothing to do"; exit 0
fi
PREV=""
if [ -L "$ROOT/current" ]; then PREV=$(readlink "$ROOT/current"); fi
# 2. Build the release next to the live one. Nothing here touches traffic.
run mkdir -p "$REL" "$ROOT/shared/storage"
run cp -R "$ARTIFACT/." "$REL/"
run rm -rf "$REL/storage"
run ln -sfn "$ROOT/shared/storage" "$REL/storage"
run ln -sfn "$ROOT/shared/.env" "$REL/.env"
run composer install --working-dir="$REL" --no-dev --prefer-dist --optimize-autoloader --no-interaction
# 3. Database first, while the OLD code still serves: migrations must be additive
# (expand). The old release keeps working against the new schema (N-1 compatibility).
IN_MAINTENANCE=0
# Anything that fails between `down` and `up` (migrate, optimize, switch, reload) lands
# here: leave maintenance ON (the schema may be half-migrated), say so loudly, exit 7.
on_exit() {
rc=$?
if [ "$IN_MAINTENANCE" = 1 ] && [ "$rc" != 0 ]; then
log "FAILED while in maintenance mode (exit $rc): the app stays DOWN; current -> $(readlink "$ROOT/current" 2>/dev/null || echo none)"
log "the migration may be partly applied; decide by hand: fix forward, or restore the database first. Do not just run 'artisan up'."
exit 7
fi
}
trap on_exit EXIT
if [ "$MAINTENANCE" = 1 ]; then
run php "${PREV:-$REL}/artisan" down --render="errors::503" --retry=60 --with-secret
IN_MAINTENANCE=1
fi
run php "$REL/artisan" migrate --force --no-interaction
# 4. Caches are written inside the new release (bootstrap/cache), so the live one is untouched.
run php "$REL/artisan" optimize # config:cache route:cache view:cache event:cache
# 5. Cut-over.
point_current_at "$REL"
reload_php
if [ "$MAINTENANCE" = 1 ]; then run php "$ROOT/current/artisan" up; IN_MAINTENANCE=0; fi
# 6. Post-deploy verification; roll the CODE back on failure. Never `migrate:rollback`
# here: the previous release was built to run on the expanded schema.
if [ "$DRY_RUN" = 0 ] && ! smoke; then
if [ "$MAINTENANCE" = 1 ]; then
# The old code cannot run on this schema: switching back would trade a broken
# release for a crashing one. Go back into maintenance and stop for a human.
php "$ROOT/current/artisan" down --render="errors::503" --retry=60 || true
log "smoke test failed after a maintenance-mode (incompatible) release; NOT switching code back."
log "app is in maintenance on $VERSION; fix forward, or restore the database before any code rollback."
exit 6
fi
if [ -n "$PREV" ]; then
log "smoke test failed; switching back to $PREV"
point_current_at "$PREV"; reload_php
else
log "smoke test failed on first deploy; removing current"; rm -f "$ROOT/current"
fi
exit 5
fi
# 7. Keep the newest $KEEP releases (the previous one is the instant rollback target).
if [ "$DRY_RUN" = 0 ]; then
# shellcheck disable=SC2012 # release names are validated: no spaces or newlines
ls -1t "$ROOT/releases" | tail -n +"$((KEEP + 1))" | while read -r old; do
[ "$ROOT/releases/$old" = "$REL" ] || [ "$ROOT/releases/$old" = "$PREV" ] || rm -rf "${ROOT:?}/releases/$old"
done
fi
log "deployed $VERSION (previous: ${PREV:-none})"تست اسکریپت با Stub برای php، composer، systemctl و curl، ترتیب هر گام و Release زنده در زمان اجرای آن را اطمینانسنجی میکند:
#!/usr/bin/env bash
# Runs laravel/deploy/deploy.sh in a temp directory with stub `php`, `composer`,
# `systemctl` and `curl` on PATH. The stubs log every call, so the test can
# assert the ORDER of migrate, optimize, switch, reload and queue:restart.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
SCRIPT="$HERE/../laravel/deploy/deploy.sh"
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
mkdir -p "$T/bin" "$T/root/shared" "$T/art"
touch "$T/art/artisan" "$T/root/shared/.env"; mkdir -p "$T/art/storage"
export CALLS="$T/calls" DEPLOY_ROOT="$T/root" PATH="$T/bin:$PATH" APP_URL=http://app
# Each stub logs its arguments and which release `current` points at when it runs
# (`ln` and `mv` are the real ones, so the switch itself is real).
for p in php composer systemctl; do
cat > "$T/bin/$p" <<STUB
#!/usr/bin/env bash
c=\$(basename "\$(readlink "\$DEPLOY_ROOT/current" 2>/dev/null)")
echo "$p \$* (current=\${c:-none})" | sed "s|$T/root/||g" >> "\$CALLS"
case "\$*" in *"artisan migrate "*) [ -n "\${FAIL_MIGRATE:-}" ] && exit 1 ;; esac
exit 0
STUB
done
cat > "$T/bin/curl" <<'EOF'
#!/usr/bin/env bash
url=${!#}; v=$(basename "$(readlink "$DEPLOY_ROOT/current")")
echo "curl $url (current=$v)" >> "$CALLS"
[ -f "$DEPLOY_ROOT/broken-$v" ] && { echo "curl: (22) 500" >&2; exit 22; }
case $url in */version) printf '%s' "$v" ;; esac
EOF
chmod +x "$T/bin/"*
pass=0; fail=0
check() { if eval "$2"; then echo "ok - $1"; pass=$((pass+1)); else echo "FAIL - $1"; fail=$((fail+1)); fi; }
line() { grep -n -- "$1" "$CALLS" | head -1 | cut -d: -f1; }
cur() { basename "$(readlink "$DEPLOY_ROOT/current")"; }
"$SCRIPT" 1.0.0 "$T/art" 2>/dev/null
check "first deploy points current at 1.0.0" '[ "$(cur)" = 1.0.0 ]'
: > "$CALLS"
"$SCRIPT" 1.1.0 "$T/art" 2>/dev/null
echo " calls for 1.1.0:"; sed 's/^/ /' "$CALLS"
check "migrate runs before optimize" '[ "$(line "migrate --force")" -lt "$(line "artisan optimize")" ]'
check "migrate and optimize run while 1.0.0 is still live" 'grep -q "1.1.0/artisan migrate --force --no-interaction (current=1.0.0)" "$CALLS" && grep -q "1.1.0/artisan optimize (current=1.0.0)" "$CALLS"'
check "php-fpm reload runs after the switch" 'grep -q "systemctl reload php8.4-fpm (current=1.1.0)" "$CALLS"'
check "queue:restart comes after the php-fpm reload" '[ "$(line "systemctl reload php8.4-fpm")" -lt "$(line "queue:restart")" ]'
check "smoke test hit the new release" 'grep -q "curl http://app/version (current=1.1.0)" "$CALLS"'
check "no artisan down without --maintenance" '! grep -q "artisan down" "$CALLS"'
out=$("$SCRIPT" 1.1.0 "$T/art" 2>&1)
check "same version again is a no-op" 'grep -q "already current" <<<"$out"'
: > "$CALLS"; touch "$DEPLOY_ROOT/broken-1.2.0"
set +e; "$SCRIPT" 1.2.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "failed smoke test exits 5" '[ $rc = 5 ]'
check "current is back on 1.1.0" '[ "$(cur)" = 1.1.0 ]'
check "rollback reloaded php-fpm twice (switch + switch back)" '[ "$(grep -c "systemctl reload" "$CALLS")" = 2 ]'
check "rollback did not run migrate:rollback (forward-only)" '! grep -q "migrate:rollback" "$CALLS"'
sed "s/^[0-9:]* / log: /; s|$T/||" "$T/log"
: > "$CALLS"
"$SCRIPT" --maintenance 1.3.0 "$T/art" 2>/dev/null
check "--maintenance: down before migrate, up after the switch" '[ "$(line "artisan down")" -lt "$(line "migrate --force")" ] && [ "$(line "systemctl reload")" -lt "$(line "artisan up")" ]'
check "--maintenance uses --with-secret and a pre-rendered 503" 'grep -q -- "down --render=errors::503 --retry=60 --with-secret" "$CALLS"'
: > "$CALLS"
OCTANE=1 "$SCRIPT" 1.4.0 "$T/art" 2>/dev/null
check "OCTANE=1 reloads Octane workers instead of php-fpm" 'grep -q "current/artisan octane:reload" "$CALLS" && ! grep -q systemctl "$CALLS"'
: > "$CALLS"; touch "$DEPLOY_ROOT/broken-1.5.0"
set +e; "$SCRIPT" --maintenance 1.5.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "--maintenance + failed smoke test exits 6 and does NOT switch code back" '[ $rc = 6 ] && [ "$(cur)" = 1.5.0 ]'
check "--maintenance + failed smoke test puts the app back into maintenance" '[ "$(grep -c "artisan down" "$CALLS")" = 2 ] && [ "$(grep -c "systemctl reload" "$CALLS")" = 1 ]'
sed "s/^[0-9:]* / log: /; s|$T/||" "$T/log"
: > "$CALLS"
set +e; FAIL_MIGRATE=1 "$SCRIPT" --maintenance 1.6.0 "$T/art" 2>"$T/log"; rc=$?; set -e
check "--maintenance + failing migrate exits 7, stays down, no switch, no up" '[ $rc = 7 ] && [ "$(cur)" = 1.5.0 ] && grep -q "artisan down" "$CALLS" && ! grep -q "artisan up" "$CALLS" && ! grep -q "systemctl reload" "$CALLS"'
grep "FAILED while in maintenance" "$T/log" | sed "s/^[0-9:]* / log: /; s|$T/||"
: > "$CALLS"
set +e; FAIL_MIGRATE=1 "$SCRIPT" 1.7.0 "$T/art" 2>/dev/null; rc=$?; set -e
check "failing migrate without --maintenance stops before the switch (old release stays live)" '[ $rc != 0 ] && [ "$(cur)" = 1.5.0 ] && ! grep -q "systemctl reload" "$CALLS"'
before=$(cur)
out=$("$SCRIPT" --dry-run 9.9.9 "$T/art" 2>&1)
check "dry run changes nothing" '[ "$(cur)" = "$before" ] && [ ! -d "$DEPLOY_ROOT/releases/9.9.9" ] && grep -q "DRY-RUN: php .*9.9.9/artisan migrate" <<<"$out"'
echo "$pass passed, $fail failed"
[ "$fail" = 0 ]Nginx جلوی php-fpm با $realpath_root تا یک درخواست فایلهای دو Release را مخلوط نکند:
# Nginx in front of php-fpm for the symlinked layout. The root goes through
# the `current` symlink; SCRIPT_FILENAME and DOCUMENT_ROOT use $realpath_root
# (the root "with all symbolic links resolved to real paths"), so each request
# names the real release directory and php-fpm/OPcache never mix files from
# two releases across a switch.
server {
listen 80;
server_name shop.example;
root /srv/shop/current/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/run/php/php8.4-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
internal;
}
location ~ \.php$ {
return 404;
}
}Release flag بهشکل کلاس Pennant: ابتدا قواعد هدفگیری، سپس Lottery پنجدرصدی ذخیرهشده. Kill switch مبتنی بر Cache هنگام خطا قابلیت را روشن نگه میدارد؛ Controller از هر دو استفاده میکند:
<?php
namespace App\Features;
use App\Models\User;
use Illuminate\Support\Lottery;
/**
* Release flag for the new checkout (Laravel Pennant, class-based feature).
*
* Pennant resolves the value once per scope and STORES it (database driver),
* so a user who won the 5 % lottery keeps the new checkout on every request
* and every server. Raising the odds later only affects users who have not
* been resolved yet; `php artisan pennant:purge App\\Features\\NewCheckout`
* re-rolls everyone. Remove this class (and the purge) when the rollout ends.
*/
class NewCheckout
{
public function resolve(?User $user): mixed
{
return match (true) {
$user === null => false, // queued jobs, console, guests
$user->is_staff => true, // targeting rule: dogfood first
in_array($user->country, ['DE'], true) => false, // legal review pending
default => Lottery::odds(5, 100), // percentage rollout: 5 %
};
}
}<?php
namespace App\Support;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* Operational kill switch: a permanent flag that is ON by default and is
* turned OFF in an incident, on every server at once, without a deploy.
*
* It lives in the shared cache store (Redis) rather than in Pennant because it
* is global (no per-user scope) and must be cheap to read on every request.
* If the cache is unreachable the switch fails OPEN (feature keeps running),
* which is the right default for a feature that works but is expensive.
*
* php artisan tinker --execute="App\Support\KillSwitch::off('recommendations')"
*/
final class KillSwitch
{
public static function on(string $name): bool
{
try {
return Cache::get("killswitch:{$name}", true) !== false;
} catch (Throwable) {
return true;
}
}
public static function off(string $name): void
{
Cache::forever("killswitch:{$name}", false);
}
public static function restore(string $name): void
{
Cache::forget("killswitch:{$name}");
}
}<?php
namespace App\Http\Controllers;
use App\Features\NewCheckout;
use App\Services\Recommendations;
use App\Support\KillSwitch;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Pennant\Feature;
class CheckoutController extends Controller
{
public function __construct(private Recommendations $recommendations) {}
public function show(Request $request): JsonResponse
{
// Both code paths ship in every release; the flag decides per user.
$flow = Feature::for($request->user())->active(NewCheckout::class) ? 'v2' : 'v1';
$payload = ['flow' => $flow, 'version' => config('app.version')];
// The expensive call the kill switch can stop during an incident.
if (KillSwitch::on('recommendations')) {
$payload['recommendations'] = $this->recommendations->for($request->user());
}
return response()->json($payload)->header('X-App-Version', (string) config('app.version'));
}
}<?php
// routes/web.php (excerpt): the endpoints deploy.sh and the smoke test call.
// /up is Laravel's built-in health route (bootstrap/app.php: health: '/up').
use App\Http\Controllers\CheckoutController;
use Illuminate\Support\Facades\Route;
Route::get('/version', fn () => response((string) config('app.version'))->header('Content-Type', 'text/plain'));
Route::get('/checkout', [CheckoutController::class, 'show'])->middleware('auth');در Kubernetes، وب Deployment لاراول با نام shop-web شامل Nginx و php-fpm در یک Pod است. Flagger از Gateway API برای Canary استفاده میکند؛ MetricTemplate نرخ خطا روی سنجههای Nginx، بررسی درونی مدت p99، Smoke webhook روی /up و Webhook تست بار دارد:
# Flagger canary for the Laravel web Deployment `shop-web` (Nginx + php-fpm
# pod), traffic shifted through a Gateway API HTTPRoute that Flagger generates.
# Flagger creates shop-web-primary (stable) and scales shop-web (the target)
# to zero between releases; a change to the target's pod template, or to a
# ConfigMap/Secret it uses, starts an analysis.
apiVersion: flagger.app/v1beta1
kind: MetricTemplate
metadata:
name: error-rate
namespace: shop
spec:
provider:
type: prometheus
address: http://prometheus.monitoring.svc:9090
# Flagger fills namespace, target and interval. Result: percentage of 5xx.
query: |
100 * sum(rate(nginx_http_requests_total{namespace="{{ namespace }}",service="{{ target }}-canary",status=~"5.."}[{{ interval }}]))
/
sum(rate(nginx_http_requests_total{namespace="{{ namespace }}",service="{{ target }}-canary"}[{{ interval }}]))
---
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
name: shop-web
namespace: shop
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: shop-web
autoscalerRef:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
name: shop-web
progressDeadlineSeconds: 600
service:
port: 80
targetPort: http
hosts:
- shop.example
gatewayRefs:
- name: public
namespace: gateway
analysis:
interval: 1m # one check per minute
threshold: 5 # 5 failed checks -> rollback (5 minutes at worst)
maxWeight: 50
stepWeight: 10 # 10, 20, 30, 40, 50 -> promote: >= 5 minutes when healthy
metrics:
- name: error-rate
templateRef:
name: error-rate
namespace: shop
thresholdRange:
max: 1 # percent
interval: 1m
- name: request-duration # Flagger builtin: P99 in milliseconds
thresholdRange:
max: 500
interval: 1m
webhooks:
- name: smoke
type: pre-rollout
url: http://flagger-loadtester.test/
timeout: 30s
metadata:
type: bash
cmd: "curl -fsS http://shop-web-canary.shop/up"
- name: load
url: http://flagger-loadtester.test/
timeout: 5s
metadata:
cmd: "hey -z 1m -q 5 -c 2 http://shop-web-canary.shop/"نگاه Laravel (The Laravel angle)
- Migration پیش از تعویض و همیشه افزایشی:
php artisan migrate --forceاز Release تازه اجرا میشود و قدیمی هنوز سرویس میدهد؛ کد قدیمی باید ستون تازه را نادیده بگیرد. حذف، Rename و NOT NULL بدون Default تا Release بعدی صبر میکنند. در Kubernetes همان گام Job در PreSync hookِ Argo CD یا pre-upgrade hookِ Helm است؛ Job در بارهای کاری Kubernetes آمده است. - Cache برای هر Release:
php artisan optimizeفایلهایbootstrap/cache/*.phpرا در پوشهٔ تازه مینویسد و Release زنده تا تعویض Cache خودش را دارد. پس ازconfig:cache،env()بیرون Config فقط متغیر محیطی واقعی را برمیگرداند. - php-fpm و OPcache: با
opcache.validate_timestamps=0در Production، فایل تغییرکرده تا Restart شدن Workerهای FPM دیده نمیشود. Deploy پس از تعویض با SIGUSR2، FPM را Reload میکند؛$realpath_rootهر درخواست را روی یک Release نگه میدارد. در Container چیزی برای Reload نیست؛ Image تازه یعنی Pod تازه. - Octane: برنامه در حافظهٔ Worker است؛ پس از تعویض
octane:reloadلازم است یا Kubernetes با Rollout، Pod را عوض میکند. - صف:
queue:restartسیگنال Restart را در Cache میگذارد؛ Worker بعد از Job جاری خارج و Supervisor آن را با کد تازه شروع میکند. Job سریالشدهٔ قدیمی باید برای جدید خواندنی باشد؛ Payload هم N-1 میخواهد. در Kubernetes، Rolling updateِ Worker Deployment همین کار را میکند؛ Grace period از طولانیترین Job بیشتر باشد. - معنای Pennant: نتیجهٔ Lottery در اولین بررسی برای هر حوزه (Scope) ذخیره میشود؛ ثابت است ولی درصدش برای کاربران قبلی تنظیمپذیر نیست. افزایش احتمال فقط روی ارزیابینشدهها اثر دارد و
pennant:purgeبرای همه دوباره قرعه میاندازد. درصد Hash-based و قابل تغییر، Provider بیرونی مانند Unleash، Flagsmith، LaunchDarkly یا flagd از PHP SDK در OpenFeature میخواهد. - Kill switch بیرون Pennant: کلید عملیاتی سراسری یک Cache key است که هر درخواست میخواند؛ با خرابی Cache، مانند
KillSwitch::on، قابلیت روشن بماند. - Maintenance mode ابزار است، نه پیشفرض:
--render="errors::503"هنگام 503 از Boot چارچوب جلوگیری میکند؛--with-secretتیم را راه میدهد و Cache driver،downرا همزمان به همهٔ سرورها اعمال میکند. Release نگهداری در این الگو با N-1 ناسازگار است؛ مسیر شکست «پایین بمان و انسان را خبر کن» است، نه Rollback خودکار کد. تلهٔEXITمانع ابهام تیم پس از شکستmigrateمیشود.
حل مسئلههای کلاسیک (Solving the classic problems)
| مسئله | راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| هر Deploy یک Release است | Feature flag و Deploy پنهان | Wrapper در OpenFeature و پیشفرض هر Flag | Release و Rollback بدون Deploy | بدهی Flag و سرویس Flag |
| نسخهٔ خراب به 100 % میرسد | Canary با Analysis | Argo Rollouts / Flagger و دروازهٔ Prometheus | گسترهٔ اثر چنددرصدی و Abort خودکار | کنترلگر و سنجهٔ قابل اعتماد |
| خطای 502 هنگام Deploy | Readiness، preStop، تخلیه | Probe با SIGTERM ناموفق، preStop sleep، Shutdown | درخواست قطع نمیشود | گردش Pod کندتر |
| Rollback روی Schema میشکند | Expand/Contract و Forward-only | Migration افزایشی پیش از تعویض | هر گام برگشتپذیر | Release بیشتر برای تغییر Schema |
| Rollback کد دیگری میآورد | Digest ثابت | image@sha256:... در Git | مقصد دقیق Rollback | ابزار نوشتن Digest |
| GitOps بازگشت را خنثی میکند | Rollback در Git | git revert تغییر | توافق Git و Cluster | تأخیر یک Sync |
| ترافیک کم و Canary بیمعنا | Header routing و بار مصنوعی | X-Canary: always و Webhook بار | سیگنال بدون کاربر | ترافیک مصنوعی واقعی نیست |
| Laravel پس از Deploy کد قدیمی میدهد | Reload پردازهٔ ماندگار | FPM reload، octane:reload، queue:restart | کد تازه همهجا | جابهجایی کوتاه Workerها |
| هزینهٔ دوبرابر Blue-green | preview کوچک و Scale-down سریع | previewReplicaCount و scaleDownDelaySeconds کوتاه | ارزانتر | پنجرهٔ کوتاهتر بازگشت فوری |
| بازنشستگی Ingress-NGINX | انتقال Canary به Gateway API | نگاشت Annotation به وزن و Match در HTTPRoute | API استاندارد و نگهداریشده | پروژهٔ مهاجرت |
انتشار خراب به Production رسیده است (A bad release reached production)
از درخت Rollback پیروی کنید: تغییر پشت Flag را خاموش کنید؛ Canary در حال اجرا را Abort کنید؛ اگر Slot یا Release قبلی آماده است تعویض معکوس انجام دهید؛ وگرنه Digest قبلی را از Git دوباره مستقر کنید. سپس Git را با Cluster هماهنگ کنید، این سرویس را تا کشف علت Freeze کنید و سیگنال ازدسترفته را به Analysis اضافه کنید.
تغییر Schema همراه Rolling update (Deploying a schema change with a rolling update)
طبق انتشار سازگار تغییر را چند Release کنید. Expand با Job پیش از Sync در Kubernetes یا پیش از تعویض Symlink در VM اجرا شود. کد هر دو Schema را تحمل کند و Contract پس از پنجرهٔ Rollback در Release بعدی باشد.
سنجهٔ گمراهکنندهٔ Canary (Canary metrics that lie)
فقط سری Canary را با Label سرویس یا Hashِ Pod template بپرسید. با len(result) > 0 وجود داده را الزامی کنید؛ علاوه بر stable با SLO مطلق مقایسه کنید و زمان کافی برای تعداد درخواست کافی بدهید. یک سنجهٔ کسبوکار برای جریان خراب بدون 5xx اضافه کنید؛ سبد خالی هم پاسخ 200 میدهد.
اختلاط نسخه مرورگر را میشکند (Mixed versions break the browser)
وزن بهازای درخواست ممکن است HTML کاربر را به یک نسخه و JS bundle را به دیگری بفرستد. Cookie routing یا Session affinity با affinity-canary-behavior: sticky در Ingress-NGINX استفاده کنید؛ Asset قدیمی را با URL تغییرناپذیر روی CDN نگه دارید یا تغییر UI را با Flag مبتنی بر کلید کاربر منتشر کنید.
کار طولانی هنگام تعویض (Long-running work during a switch)
Worker صف و درخواست طولانی باید تمام شوند یا امن قطع شوند. Grace period در Worker Deployment از طولانیترین Job بیشتر باشد؛ روی VM از queue:restart استفاده کنید؛ Job بیاثر در تکرار (Idempotent) باشد تا Retry پس از SIGKILL آسیبی نزند؛ Payload برای نسخهٔ قبلی هم خواندنی بماند.
انتخاب (Choosing)
کدام راهبرد؟ (Which strategy)
| وضعیت | راهبرد | دلیل |
|---|---|---|
| سرویس بدون وضعیت، Probe خوب، تغییر کمخطر | Rolling update | درونی و بدون ابزار اضافه |
| نسخهها نمیتوانند همزمان باشند؛ Singleton یا پروتکل ناسازگار | Recreate با بازهٔ نگهداری | پذیرش صریح قطعی |
| Release پرخطر، تأیید کامل پیش از کاربر | Blue-green | تست Production و تعویض فوری به قبلی |
| ترافیک بالا و Deploy مکرر | Canary تدریجی با Argo Rollouts / Flagger | گسترهٔ اثر کوچک و Abort خودکار |
| سرویس کمترافیک | Blue-green یا Header canary با بررسی مصنوعی | Canary وزنی سیگنال کافی ندارد |
| سؤال محصول: B تبدیل بهتری دارد؟ | A/B با Flag | کاربر ثابت و سنجهٔ محصول |
| Backend تازه با بار نامعلوم | Shadow traffic، سپس Canary | سنجش بار بدون اثر بر کاربر |
| قابلیت ناتمام در main ادغام شده | Feature flag برای Release | توسعهٔ Trunk-based |
| برنامهٔ PHP روی VM | Symlink و Reload یا ASGهای Blue-green | بازگشت چندثانیهای |
کدام لایهٔ ترافیک؟ (Which traffic layer)
| آنچه دارید | انتخاب |
|---|---|
| فقط Service | Canary با نسبت Replica یا Blue-green با Service selector |
| Ingress-NGINX قدیمی | فعلاً Annotation قناری و برنامهٔ مهاجرت Gateway API |
| پیادهسازی Gateway API | وزن HTTPRoute و Header match |
| Mesh مانند Istio یا Linkerd | Routeهای Mesh برای ترافیک داخلی؛ HTTPRoute در صورت پشتیبانی |
| VM پشت Cloud LB | Target group وزنی یا دو ASG |
کدام کنترلگر؟ (Which controller)
| وضعیت | انتخاب |
|---|---|
| تیم Argo CD، نیازمند فهرست گام صریح و UI | Argo Rollouts |
| تیم Flux، حفظ Deployment معمولی | Flagger |
| سرویس کم و چند Deploy در هفته | Rolling و Canary دستی با PRهای HTTPRoute |
| آزمایش با Baseline و Canary کنار هم | experiment در Argo Rollouts |
کدام سامانهٔ Flag؟ (Which flag system)
| وضعیت | انتخاب |
|---|---|
| پرهیز از وابستگی کد به فروشنده | OpenFeature API و هر Provider |
| برنامهٔ فقط Laravel با Rollout ساده | Pennant و Kill switch با Cache key |
| خودمیزبان، متنباز، چند تیم | Unleash یا Flagsmith یا flagd |
| Experiment، Audit و هدفگیری سازمانی | LaunchDarkly |
| استفادهٔ فعلی از GitLab | Feature flag سازگار با Unleash در GitLab |
در معماری: از یک پردازه تا سیستم توزیعشده (In architecture: from a single process to a distributed system)
راهبرد استقرار ویژگی کل سیستم است. دو نسخه در هر رابط، از DB و صف تا API، Cache و Asset مرورگر، همزیستی دارند؛ راهبرد تعیین میکند این وضعیت چقدر و برای چه کسانی ادامه یابد.
یکپارچه: یک برنامه، یک پایگاه داده (Monolith)
یکپارچه (Monolith) لاراول روی دو VM: Deploy با Symlink، Migration فقط افزایشی، php-fpm reload و queue:restart، Smoke test و Flag قابلیتها. وقتی Release به تأیید کامل نیاز دارد، گام بعد Blue-green در Load balancer است. بخش سخت، DB واحد است؛ هر Release یا سازگار با N-1 است یا به بازهٔ نگهداری نیاز دارد.
یکپارچهٔ ماژولار: یک واحد استقرار، چند تیم (Modular monolith)
در یکپارچهٔ ماژولار (Modular monolith)، یک Artifact قابلیت چند تیم را دارد. Deploy نباید منتظر تمامشدن همه بماند؛ کار ناتمام پشت Release flag پنهان میرسد و هر ماژول مالک Flag و پاکسازی آن است. کل Artifact را Canary کنید و ماژولها را با Flag منتشر کنید.
ریزخدمتها: چند سرویس و چند نسخه (Microservices)
بیست ریزخدمت (Microservice) مستقل Deploy میشوند؛ سرویس A با نسخهٔ N ممکن است با B در N یا N-1 حرف بزند. سازگاری API، با فیلد افزایشی، Reader تحملپذیر و Endpoint نسخهدار، همان قاعدهٔ N-1 برای شبکه است. Progressive delivery برای هر سرویس با کتابخانهٔ مشترک AnalysisTemplate و ClusterAnalysisTemplate، مسیریابی Mesh یا Gateway برای Canary داخلی، repoِ GitOps برای هر محیط و مسیر استاندارد متعلق به Platform لازم میشود. Terraform، Gateway و Prometheus و کنترلگرها را میسازد؛ GitHub Actions یا GitLab CI، Digest تولید میکند؛ Argo CD اعمال و Helm یا Kustomize بستهبندی میکند.
1 service A: CI builds digest D, opens PR in env repo (staging), auto-merge after tests
2 Argo CD syncs staging; Rollout runs short steps; smoke + contract tests
3 promotion PR to production (GitHub Actions environment: required reviewer, freeze check)
4 Argo CD syncs prod; Rollout 5 -> 20 -> 50 -> 100 with ClusterAnalysisTemplate gates
5 any abort: Degraded alert to the owning team; revert PR prepared automaticallyدادهٔ توزیعشده: Cache، صف و منطقه (Distributed data)
وضعیت مشترک از هر نسخه بیشتر عمر میکند. Cache نوشتهشده توسط N پس از Rollback به دست N-1 خوانده میشود؛ کلید را نسخهدار یا قالب را سازگار کنید. پیام صف تولیدشده توسط N به Workerِ N-1 میرسد؛ قواعد تکامل Schema مانند Kafka یا protobuf لازماند. Deploy چندمنطقهای، منطقهبهمنطقه است؛ نخست یک منطقه، زمان مشاهده و سپس بقیه، یعنی Canary در مقیاس منطقه. سرویس Feature flag باید در همهٔ مناطق در دسترس باشد یا از Snapshot دریافتشده با Stream بهشکل محلی ارزیابی شود؛ LaunchDarkly، Proxyهای Unleash و flagd این الگو را دارند. در نبود دسترسی، پیشفرض امن لازم است.
مسیر رشد: یک، ده و صد برابر (Scaling path)
| مقیاس | راهبرد | تأیید | Rollback |
|---|---|---|---|
| 1x؛ یک تیم و برنامه | Rolling یا Symlink؛ Flag داخل برنامه با Pennant | Smoke test و داشبورد | Symlink به قبلی، kubectl rollout undo |
| 10x؛ چند تیم و یک Cluster | Canary با Gateway API؛ Blue-green برای پرخطر؛ OpenFeature و یک Provider | دروازهٔ Prometheus و بررسی مصنوعی | Abort، Git revert، خاموشی Flag |
| 100x؛ Cluster و منطقهٔ زیاد | Progressive delivery همهجا، موج منطقهای، تقویم Freeze بهشکل کد | SLO-based promotion، Analysis خودکار، ردیابی DORA | Abort خودکار، PR برگشت خودکار، Kill switch سراسری |
آزمایشگاه (Lab)
برچسب اجرا: در محیط ساخت، Cluster Kubernetes، Argo Rollouts، Flagger، Mesh، PHP-FPM یا برنامهٔ Laravel وجود ندارد. تمام فرمانهای kubectl، kubectl argo rollouts، helm، argocd و aws زیر مورد انتظارند؛ اجرا نشدهاند. رفتار مستند نشان داده شده و خروجی ساختگی نیست. گامهای اجراشده روی میزبان روی macOS با Go 1.27.4 و darwin/arm64، Ruby 2.6 و PHP 8.5 CLI اجرا و خروجی واقعی آنها در pipeline/sources/deployment-strategies/lab-host-output.txt ثبت شده است.
۱. تست Go: Flag، تخلیه و Smoke؛ اجراشده روی میزبان
cd docs/snippets/platform/deployment-strategies/go
gofmt -l . ; go vet ./... ; go test -race -count=1 -v ./...
# --- PASS: TestPercentageRolloutIsStickyAndMonotonic (0.28s)
# flags_test.go:121: 10%: 2010 users, 50%: 10040 users of 20000
# ok academy/deployment-strategies/flags 1.729s
# --- PASS: TestDrainFailsReadinessThenFinishesInFlight (0.59s)
# --- PASS: TestShutdownTimeoutReportsStuckRequests (0.10s)
# ok academy/deployment-strategies/server 2.122s
# ok academy/deployment-strategies/smoke 1.461s۲. سرویس، Flag و تخلیهٔ آن؛ اجراشده روی میزبان
همهٔ فرمانهای آزمایشگاه از ریشهٔ repo آغاز میشوند.
cd docs/snippets/platform/deployment-strategies/go
go build -ldflags "-X main.version=1.5.0" -o /tmp/orders-api ./cmd/orders-api
PORT=18082 /tmp/orders-api &
curl -si localhost:18082/version
# HTTP/1.1 200 OK
# X-App-Version: 1.5.0
# {"version":"1.5.0"}
curl -s -X POST -H "X-User-ID: staff-1" -H "X-Plan: internal" localhost:18082/checkout
# {"flow":"v2","recommendations":["sku-42"]} (targeting rule)
n=0; for i in $(seq 1 1000); do
curl -s -X POST -H "X-User-ID: user-$i" localhost:18082/checkout | grep -q '"v2"' && n=$((n+1)); done; echo "v2 for $n of 1000 users"
# v2 for 49 of 1000 users (5 % rollout)
kill -TERM %1; sleep 1; curl -s -o /dev/null -w 'readyz during drain %{http_code}\n' localhost:18082/readyz
# readyz during drain 503
sleep 6; curl -s -o /dev/null -w 'after drain %{http_code}\n' localhost:18082/readyz
# after drain 000 (connection refused: process exited)
# server log:
# {"level":"INFO","msg":"serving","addr":"[::]:18082","version":"1.5.0"}
# {"level":"INFO","msg":"draining","delay":5000000000}
# {"level":"INFO","msg":"stopped"}۳. Manifest در برابر Schema واقعی؛ اجراشده روی میزبان
cd docs/snippets/platform/deployment-strategies/k8s # from the repository root
ruby check-manifests.rb ../../../../../pipeline/sources/deployment-strategies */*.yaml
# 8 files, 22 objects, 104 schemas loaded
# manifests ok
# Negative test (copies with injected typos) is caught:
# Rollout.spec.strategy.canary.steps[0]: unknown field 'setWeigth'
# Canary.spec.analysis: unknown field 'stepWeigt'
# HTTPRoute.spec.rules[1].backendRefs[0].weight: expected integer, got String
# VirtualService.spec.http[1].route[0].destination: unknown field 'subst'
# canaryService orders-api-canry not definedفرمان kubectl apply --dry-run=client امتحان شده ولی به کشف API از سرور نیاز دارد و پیام couldn't get current server API group list میدهد؛ بررسی Schema بالا جایگزین آن است.
۴. تعویض Blue-green و Deploy لاراول با Stub؛ اجراشده روی میزبان
cd docs/snippets/platform/deployment-strategies # from the repository root
bash tests/blue-green-switch-test.sh
# ok - preview was patched before live
# ok - second run is a no-op (idempotent)
# ok - wrong version on preview aborts with 4 before the switch
# ok - failing live path after the switch rolls back with 5
# log: switch: request 6 answered 'error'; rolling back to blue
# ok - VERIFY_N=3 with a failing live path still rolls back with 5
# log: switch: verification ended with 'error' (0/3 requests on 1.5.0); rolling back to blue
# 10 passed, 0 failed
bash tests/laravel-deploy-test.sh
# php releases/1.1.0/artisan migrate --force --no-interaction (current=1.0.0)
# php releases/1.1.0/artisan optimize (current=1.0.0)
# systemctl reload php8.4-fpm (current=1.1.0)
# php current/artisan queue:restart (current=1.1.0)
# ok - rollback did not run migrate:rollback (forward-only)
# ok - --maintenance + failed smoke test exits 6 and does NOT switch code back
# log: deploy: smoke test failed after a maintenance-mode (incompatible) release; NOT switching code back.
# ok - --maintenance + failing migrate exits 7, stays down, no switch, no up
# log: deploy: FAILED while in maintenance mode (exit 1): the app stays DOWN; current -> root/releases/1.5.0
# 20 passed, 0 failed۵. Canary در Argo Rollouts همراه Abort؛ مورد انتظار، اجرا نشده
kubectl argo rollouts set image orders-api orders-api=ghcr.io/acme/orders-api@sha256:<new> # or a Git commit
kubectl argo rollouts get rollout orders-api --watch
# expected: Status Progressing, Step 1/8, SetWeight 5, ActualWeight 5; AnalysisRun created at step 2
kubectl get httproute orders-api -o jsonpath='{.spec.rules[0].backendRefs[*].weight}'
# expected: 95 5 while at step 0
kubectl argo rollouts abort orders-api
# expected: weights back to 100 0, Status Degraded; spec.template still the new image (fix in Git)
kubectl argo rollouts promote orders-api --full # emergency only: skips analysis, pauses and steps۶. Rollback در Deployment معمولی و Helm؛ مورد انتظار، اجرا نشده
kubectl annotate deployment/shop-web kubernetes.io/change-cause="image 1.5.0"
kubectl rollout history deployment/shop-web # REVISION CHANGE-CAUSE
kubectl rollout undo deployment/shop-web --to-revision=3 # pod template only
kubectl rollout undo --dry-run=server deployment/shop-web # preview, documented flag
helm history shop -n shop
helm rollback shop 0 -n shop --wait # 0 or omitted = previous release۷. مسیریابی Canary در Ingress-NGINX؛ مورد انتظار، اجرا نشده
for i in $(seq 1 1000); do curl -s -o /dev/null -w '%header{x-app-version}\n' https://shop.example/; done | sort | uniq -c
# expected with canary-weight "10": roughly 900 stable / 100 canary (random per request, not exact)
curl -s -H 'X-Canary: always' https://shop.example/ -o /dev/null -w '%header{x-app-version}\n' # always canary
curl -s --cookie 'canary=never' https://shop.example/ -o /dev/null -w '%header{x-app-version}\n' # always stableبدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
| Rollback همیشه امن است | فقط اگر قبلی روی Schema فعلی کار کند؛ rollout undo فقط Pod template را تغییر میدهد |
| Canary با 10 % یعنی 10 % کاربران | وزن برای درخواست است؛ Stickiness به Cookie، Header یا Flag با کلید کاربر نیاز دارد |
| Blue-green تغییر DB را حل میکند | معمولاً DB مشترک است و Schema باید هر دو رنگ را پاسخ دهد |
| Abort در Argo Rollouts، Git را برمیگرداند | "doesn't read/write anything to Git"؛ خودتان Commit را برگردانید |
| وزن Gateway API درصد است | نسبت به جمع وزنهاست؛ Backend تنها فقط با وزن > 0 همهٔ ترافیک را میگیرد |
| Feature flag جای Canary را میگیرد | Flag فقط کد پوششدادهشده را محافظت میکند؛ Crash، Leak و خطای وابستگی راهبرد ترافیکی میخواهند |
| قطعی Flag برنامه را میشکند | OpenFeature پیشفرض کد را میدهد؛ برای هر Flag پیشفرض درست انتخاب کنید |
kubectl rollout undo زیر GitOps ماندگار است | کنترلگر Git را دوباره اعمال میکند؛ در Git برگردانید |
| Recreate هرگز پذیرفتنی نیست | وقتی نسخهها همزیستی ندارند انتخاب صادقانه است |
php artisan down یعنی Deploy بدون قطعی | قطعی عمدی است؛ پوشهٔ Release و Reload استفاده کنید |
| تعویض Symlink، PHP را Reload میکند | php-fpm/OPcache، Octane و Worker صف تا Reload یا Restart کد قبلی را دارند |
| Down migration همان Rollback پایگاه داده است | Forward-only و Expand/Contract راه امناند؛ Down migration داده از دست میدهد |
| میانگین تأخیر دروازهٔ خوبی است | p99 یا p95 مربوط به Canary و SLO مطلق را بسنجید |
| Canary بدون داده قبول شده | نبود داده باید شکست باشد؛ len(result) > 0 را الزام کنید |
| Ingress-NGINX ابزار پیشفرض Canary است | مارس 2026 بازنشسته شده؛ Gateway API استفاده کنید |
چکیده (Cheat sheet)
| موضوع | آنچه باید به خاطر بسپارید |
|---|---|
| واژگان | Deploy یعنی اجرا در Production؛ Release یعنی دسترسی کاربر؛ Rollout یعنی مسیر کنترلشده |
| Rolling | پیشفرض؛ نیازمند Readiness و N-1؛ سازوکار در فصل Workload |
| Recreate | همهٔ Podها ابتدا پایان مییابند؛ قطعی؛ برای نسخهٔ ناسازگار |
| Blue-green | دو محیط؛ تعویض Selector، Route یا LB؛ هزینهٔ 2x؛ بازگشت چندثانیهای |
| Canary | وزن، Header، Cookie؛ مقایسه با Control و SLO |
| Ingress-NGINX | canary: "true"؛ اول by-header، بعد by-cookie، سپس weight؛ یک Canary در هر Rule؛ بازنشسته در 2026 |
| Gateway API | backendRefs[].weight نسبی؛ Header rule برای تستکننده |
| Argo Rollouts | Rollout CRD؛ setWeight، pause، analysis؛ Failed یعنی Abort، Inconclusive یعنی Pause؛ Git دستنخورده |
| Flagger | حفظ Deployment و ساخت -primary؛ Promotion >= interval x maxWeight/stepWeight؛ Rollback = interval x threshold |
| سلامت | نرخ موفقیت و p99 فقط Canary؛ داده الزامی؛ Burn rate از SLO |
| Flag | OpenFeature و Provider؛ پیشفرض هنگام خطا؛ Bucket ثابت Hash؛ Kill switch در خطا روشن؛ حذف پس از 100 % |
| ترتیب بازگشت | خاموشی Flag، Abort، تعویض معکوس، استقرار Digest قبلی از Git، سپس Roll forward |
| Digest | استقرار @sha256:؛ حفظ revisionHistoryLimit و تاریخچهٔ Helm |
| DB | Expand پیش از تعویض، Contract یک Release بعد؛ Forward-only؛ همیشه N-1 |
| بدون قطعی | Readiness ناموفق روی SIGTERM، preStop sleep، تخلیه، Grace بزرگتر از جمع؛ Readiness gate روی AWS |
| Laravel | Build در پوشهٔ تازه، Migration افزایشی، optimize، تعویض اتمی، FPM reload / octane:reload، queue:restart، Smoke |
| VM | AMI و Instance refresh با Checkpoint و Rollback خودکار، یا Releaseهای Symlink |
| فرایند | Freeze در Config، Smoke و Synthetic check، Runbook و DORA |
خودآزمایی: پرسش و پاسخ (Self-check: questions & answers)
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — استقرار و انتشار چه فرقی دارند و چرا برای Rollback مهم است؟ حیاتی
پاسخ
پاسخ: استقرار (Deployment) مصنوع را در Production قرار میدهد؛ انتشار (Release) دسترسی کاربران به رفتار تازه است. جداسازی آنها با کد پنهان پشت Flag، محیط green بیترافیک یا Canary با وزن صفر، بازگشت Release را به تغییر Config چندثانیهای تبدیل میکند. بازگشت Deployment همچنان تغییر Artifact در حال اجراست. Deployment، Release و Rollout.
۲ — یک Migration نام ستون را عوض کرده و کد تازه خراب است؛ چرا kubectl rollout undo راهحل نیست و تغییر باید چگونه منتشر میشد؟ حیاتی
پاسخ
پاسخ: Undo فقط Pod template را برمیگرداند؛ کد قدیمی ستون قبلیِ حذفشده را میخواهد و آن هم شکست میخورد. اکنون باید اصلاح روبهجلو کنید. تغییر باید با گسترش/انقباض (Expand/Contract) میآمد: ستون تازه، Dual-write و Backfill، تعویض خواندن، توقف نوشتن قدیمی و حذف در Release بعدی؛ هر گام سازگار با N-1. انتشار سازگار.
۳ — تعویض Blue-green در Kubernetes معمولی چگونه کار میکند و چه چیزی آن را امن میکند؟ حیاتی
پاسخ
پاسخ: دو Deployment با Labelهای slot: blue و slot: green دارید و Service زنده یکی را انتخاب میکند. پس از Rollout کامل green و Smoke test از Service پیشنمایش، یک Patch روی Selector زنده ترافیک را منتقل میکند. تأیید از مسیر عمومی و Patch معکوس هنگام شکست ایمنی میدهند؛ روشنماندن blue بازگشت را فوری میکند. DB باید هر دو نسخه را پاسخ دهد. Blue-green.
۴ — در Ingress-NGINX، درخواست با X-Canary: never و Cookie برابر canary=always کجا میرود و چرا؟ مهم
پاسخ
پاسخ: به stable میرود. ترتیب ارزیابی canary-by-header، سپس canary-by-cookie و بعد canary-weight است؛ Header با never تطبیق دارد و Cookie دیگر بررسی نمیشود. Canary در Ingress-NGINX.
۵ — وزنهای سه و یک در HTTPRoute چه سهمی میدهند؟ اگر تنها Backend وزن صفر داشته باشد چه؟ مهم
پاسخ
پاسخ: هفتادوپنج و بیستوپنج درصد؛ وزنها نسبت به جمع خود تفسیر میشوند. تک Backend فقط با وزن مثبت صد درصد میگیرد. CRD برای وزن صفر میگوید "no traffic should be forwarded for this entry"؛ پس قاعده هیچ ترافیکی به آن نمیفرستد. Gateway API.
۶ — AnalysisRun در Argo Rollouts در بیست درصد شکست میخورد؛ در Cluster و Git چه رخ میدهد و مسئول کشیک چه باید بکند؟ حیاتی
پاسخ
پاسخ: Rollout، Abort میشود؛ وزن Canary صفر، همهٔ ترافیک روی stable ReplicaSet و وضعیت Rollout برابر Degraded است. چون Argo Rollouts در Git نمینویسد، Git هنوز نسخهٔ تازه را اعلام میکند و مسئول کشیک باید Commit را برگرداند یا اصلاح کند. تا آن زمان Syncهای Argo CD کاری نمیکنند، چون Git و Rollout زنده دربارهٔ نسخهٔ تازه توافق دارند؛ Cluster روی نسخهٔ قدیمی و Degraded میماند. kubectl argo rollouts retry rollout صریح یا Revision تازه، Canary خراب را دوباره آغاز میکند. Argo Rollouts و Rollback.
۷ — با interval: 1m، stepWeight: 10، maxWeight: 50 و threshold: 5 در Flagger، حداقل زمان Promotion و زمان Rollback پس از شکست بررسیها چقدر است؟ مهم
پاسخ
پاسخ: حداقل Promotion از interval x (maxWeight / stepWeight) به دست میآید؛ یک دقیقه ضرب در پنج، یعنی پنج دقیقه. Rollback پس از interval x threshold، یعنی پنج دقیقه بررسی ناموفق رخ میدهد. Flagger.
۸ — Query تحلیل بهدلیل تغییر نام سنجه دادهای ندارد؛ result[0] >= 0.99 چه مشکلی دارد و دروازهٔ امن چیست؟ مهم
پاسخ
پاسخ: Template باید نتیجهٔ خالی را صریح مدیریت کند؛ Argo Rollouts هر دو انتخابِ پذیرش یا رد را مستند کرده است. از len(result) > 0 && result[0] >= 0.99 استفاده کنید تا نبود داده اندازهگیری را ناموفق کند و Canary اندازهگیرینشده قبول نشود. سلامت انتشار.
۹ — پیشفرض Feature flag را چگونه انتخاب میکنید و OpenFeature هنگام قطعی Provider چه میکند؟ حیاتی
پاسخ
پاسخ: OpenFeature در اجرای غیرعادی پیشفرض فراخوان را برمیگرداند و Exception پرتاب نمیکند. پس پیشفرض باید حالت امن باشد: Release flag مسیر قدیمی یعنی false را انتخاب کند؛ Kill switch برای قابلیت سالم ولی پرهزینه، روشن بماند. Feature flag.
۱۰ — چرا انتشار درصدی شناسهٔ کاربر را همراه کلید Flag، Hash میکند و افزایش ده به پنجاه درصد نباید کاربری را حذف کند؟ مهم
پاسخ
پاسخ: Hash کلید هدفگیری ثابت، تصمیم را برای کاربر ثابت میکند؛ کلید Flag گروهها را میان Flagها مستقل نگه میدارد، مانند groupId در Unleash و Flag key و Salt در LaunchDarkly. با قاعدهٔ Bucket کمتر از درصد، همهٔ اعضای گروه ده درصد زیر آستانهٔ پنجاه درصد هم هستند؛ افزایش درصد فقط عضو اضافه میکند. تست Go فصل همین را اطمینانسنجی میکند. Feature flag.
۱۱ — Podها در هر جایگزینی یک ثانیه 502 میدهند؛ چه چیزی کم است؟ حیاتی
پاسخ
پاسخ: پردازه پیش از حذفشدن از Load balancer میایستد. preStop sleep یا تأخیر تخلیه اضافه کنید، Readiness با SIGTERM ناموفق شود و Shutdown زماندار کار جاری را تمام کند؛ Grace period از جمع زمانها بیشتر باشد. پشت AWS ALB، Readiness gate کنترلگر LB را هم اضافه کنید تا Pod تازه پیش از حذف قبلی در Target group، Healthy باشد. جزئیات بدون قطعی.
۱۲ — پس از Deploy لاراول با Symlink، بعضی درخواستها کد قدیمی اجرا میکنند و Job صف میشکند؛ کدام گامها و با چه ترتیبی جا افتادهاند؟ حیاتی
پاسخ
پاسخ: پس از تعویض اتمی، php-fpm را با SIGUSR2 آرام و OPcache تازه Reload کنید یا برای Octane، octane:reload بزنید. سپس php artisan queue:restart تا Worker پس از Job جاری خارج و با کد تازه شروع شود. پیش از تعویض هم Migration فقط افزایشی باید اجرا شده و php artisan optimize، Cache را داخل Release تازه ساخته باشد. Laravel بدون قطعی.
۱۳ — چه زمانی php artisan down --with-secret ابزار درستی است؟ تکمیلی
پاسخ
پاسخ: برای Release نادری که با N-1 سازگار نمیشود و پاسخ کوتاه و ازپیشاعلامشدهٔ 503 انتخاب صادقانه است. --with-secret توکن عبور برای تست تیم چاپ میکند؛ --render="errors::503" پیش از Boot چارچوب صفحه میدهد و Cache maintenance driver همهٔ سرورها را پوشش میدهد. تا برنامه پایین است Jobهای صف پردازش نمیشوند. Laravel بدون قطعی.
۱۴ — راهبرد استقرار بر کدام سنجههای DORA اثر دارد و نام تازهٔ MTTR چیست؟ تکمیلی
پاسخ
پاسخ: Deployment frequency و Change lead time برای توان تحویل، Change fail rate و Deployment rework rate برای ناپایداری و Failed deployment recovery time برای بازیابی؛ آخری در ۲۰۲۳ جای MTTR را گرفت. Canary و Flag عمدتاً نرخ شکست تغییر و زمان بازیابی را کاهش میدهند. Freeze، تأیید و Runbook.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| استقرار (Deployment؛ عمل) | قراردادن Artifact تازه در زیرساخت Production |
| انتشار (Release) | رساندن کاربر یا ترافیک به رفتار تازه |
| استقرار تدریجی (Rollout) | حرکت کنترلشده از قدیم به جدید؛ پایان با Promotion یا Rollback |
| ارتقا (Promotion) | تبدیل نسخهٔ تازه به stable |
| بازگشت (Rollback) | سرویسدهی دوبارهٔ نسخهٔ قبلی |
| اصلاح روبهجلو (Roll forward) | اصلاح انتشار خراب با انتشار تازه بهجای بازگشت |
| بازسازی (Recreate strategy) | پایان همهٔ Podهای قدیمی و سپس ایجاد تازه؛ با قطعی |
| بهروزرسانی تدریجی (Rolling update) | جایگزینی تدریجی Pod؛ مدتی هر دو نسخه پاسخ میدهند |
| استقرار آبی/سبز (Blue-green deployment) | دو محیط کامل و تعویض ترافیک میان آنها |
| تعویض محیط (Environment switch) | تغییر واحد جابهجاکنندهٔ ترافیک؛ Selector، Route، LB یا DNS |
| انتشار قناری (Canary release) | سهم کوچک ترافیک برای نسخهٔ تازه، با مقایسه با بقیه |
| گروه کنترل (Control) | بخشی از سرویس که در Canary تغییر را دریافت نمیکند |
| وزن ترافیک (Traffic weight) | سهم درخواستهای ارسالشده به Backend |
| مسیریابی بر اساس سرآیند (Header-based routing) | انتخاب مقصد با Header مانند X-Canary: always |
| مسیریابی بر اساس کوکی (Cookie-based routing) | انتخاب با Cookie؛ ثابت برای هر مرورگر |
| Annotationهای Canary در Ingress-NGINX | nginx.ingress.kubernetes.io/canary* روی Ingress دوم |
| Gateway API | API مسیریابی Kubernetes با Gateway و HTTPRoute، جانشین Ingress |
| HTTPRoute | Route در Gateway API؛ وزنهای backendRefs، Match و Filter |
| تقسیم ترافیک شبکهٔ سرویس (Service mesh traffic split) | مسیریابی وزنی میان نسخههای سرویس در Mesh |
| Istio VirtualService | شیء مسیریابی Istio؛ Match، Route وزنی و Mirror |
| DestinationRule | شیء Istio برای تعریف Subset با Label |
| SMI TrafficSplit | API تقسیم ترافیک Service Mesh Interface بایگانیشده؛ در Linkerd منسوخ |
| تحویل تدریجی (Progressive delivery) | انتشار مرحلهای خودکار با دروازهٔ سنجهای |
| Argo Rollouts | کنترلگر با CRDهای Rollout، AnalysisTemplate، AnalysisRun و Experiment |
| Rollout CRD | جایگزین Deployment با راهبرد blueGreen و canary |
| گامهای Canary (Canary steps) | setWeight، pause، analysis، setCanaryScale، setHeaderRoute، setMirrorRoute، experiment |
| AnalysisTemplate | تعریف سنجه با شرط و محدودیت |
| AnalysisRun | نمونهٔ اجرایی (Instance) از AnalysisTemplate؛ Successful، Failed یا Inconclusive |
| successCondition / failureLimit | عبارت ارزیابی هر اندازهگیری / تعداد شکست قابل تحمل |
| توقف انتشار (Abort) | توقف Rollout و بازگشت ترافیک به stable |
| بازگشت خودکار (Automatic rollback) | Abort ناشی از Analysis ناموفق |
| Flagger | Operator تحویل تدریجی از خانوادهٔ Flux با Canary CRD |
| Canary CRD در Flagger | شیء flagger.app/v1beta1 با هدف، Service، Analysis، سنجه و Webhook |
| MetricTemplate | Query سنجهٔ سفارشی Flagger |
| آزمایش A/B (A/B testing) | تقسیم ثابت کاربران برای مقایسهٔ نتیجهٔ محصول |
| ترافیک سایه (Shadow traffic) | درخواست کپیشده با پاسخ دورریختهشده |
| انتشار پنهان (Dark launch) | فراخوانی رفتار Backend تازه برای کاربر واقعی بدون اثر قابل مشاهده |
| پرچم قابلیت (Feature flag) | کلید زمان اجرا برای انتخاب مسیر کد |
| OpenFeature | API و SDKهای مستقل از فروشنده برای Flag؛ CNCF |
| ارائهدهنده (Provider) | Adapter در OpenFeature برای سامانهٔ Flag |
| زمینهٔ ارزیابی (Evaluation context) | صفتهای موضوع ارزیابی؛ کلید، Plan، کشور |
| کلید هدفگیری (Targeting key) | هویت ثابت برای هدفگیری و Bucket |
| قواعد هدفگیری (Targeting rules) | شرط روی صفتهای Context |
| انتشار درصدی (Percentage rollout) | سهم ثابت کاربران با Bucket مبتنی بر Hash |
| کلید قطع اضطراری (Kill switch) | Flag عملیاتی دائمی برای خاموشی سریع قابلیت |
| بدهی پرچم (Flag debt) | هزینهٔ Flagهای قدیمی باقیمانده در کد |
| LaunchDarkly / Unleash / Flagsmith | محصولات Flag؛ SaaS یا متنباز و میزبانیشده |
| Laravel Pennant | پکیج رسمی Feature flag در Laravel |
| تثبیت Image با Digest (Image digest pinning) | استقرار image@sha256:... بهجای Tag |
| تاریخچهٔ بازبینی (Revision history) | ReplicaSetهای قدیمی نگهداشتهشده برای Rollback با revisionHistoryLimit |
kubectl rollout undo | بازیابی Pod template قبلی |
| Helm rollback | اعمال دوبارهٔ Revision قبلی Release در Helm |
| GitOps revert | Rollback با برگرداندن Commitی که کنترلگر Sync میکند |
| پنجرهٔ بازگشت (Rollback window) | در Argo Rollouts، Revision اخیر هنگام بازگشت گامها را رد میکند |
| سازگاری N-1 (N-1 compatibility) | هر نسخه با Schema و API نسخهٔ قبلی کار میکند |
| گسترش/انقباض (Expand/Contract) | Parallel change؛ افزودن، مهاجرت، حذف |
| مهاجرت فقط روبهجلو (Forward-only migrations) | نبود Down migration در Production؛ اصلاح با Migration تازه |
| ترتیب مهاجرت (Migration ordering) | Expand پیش از تعویض کد، Contract یک Release بعد |
| سلامت انتشار (Release health) | SLIهای ارزیابیشده هنگام و پس از Rollout |
| ارتقای مبتنی بر SLO (SLO-based promotion) | Promotion فقط تا وقتی SLI داخل SLO است |
| نرخ مصرف بودجهٔ خطا (Error budget burn rate) | سرعت مصرف بودجه نسبت به SLO |
| دروازهٔ آمادگی (Readiness gate) | شرط اضافی Pod برای آمادهبودن |
| preStop | Hook کانتینر پیش از SIGTERM |
| تخلیهٔ اتصال (Connection draining) | تمامکردن درخواست جاری پیش از بستن |
| زیرساخت تغییرناپذیر (Immutable infrastructure) | جایگزینی سرور بهجای تغییر آن |
| AMI | Amazon Machine Image؛ Artifact انتشار VM |
| نوسازی نمونهها (Instance refresh) | جایگزینی Rolling در EC2 Auto Scaling با Checkpoint و Rollback |
| تعویض پیوند نمادین انتشار (Symlink release switch) | جابهجایی اتمی current میان پوشههای Release |
| Capistrano / Deployer | ابزار Deploy با پوشهٔ Release برای Ruby / PHP |
| php-fpm reload | بارگذاری مجدد آرام Workerهای FPM با SIGUSR2 |
| حالت نگهداری Laravel (Laravel maintenance mode) | artisan down؛ پاسخ 503 برای همه جز عبور با Token |
| Octane reload | octane:reload؛ شروع دوبارهٔ آرام Workerهای Octane |
queue:restart | سیگنال خروج Worker صف پس از Job جاری |
| تست سلامت اولیه (Smoke tests) | چند بررسی حیاتی بلافاصله پس از Deploy |
| پایش مصنوعی (Synthetic monitoring) | اجرای پیوستهٔ سفر کاربر با اسکریپت |
| تأیید پس از استقرار (Post-deploy verification) | Smoke test و بررسی نسخه و سنجه پس از Deploy |
| توقف استقرار / بازهٔ مجاز تغییر (Deployment freeze / Change window) | زمانهای ممنوع / مجاز Deploy |
| دستورکار عملیاتی (Runbook) | روش نوشتهشدهٔ Deploy و Rollback آن |
| سنجههای DORA (DORA metrics) | بسامد استقرار، Lead time، نرخ شکست، زمان بازیابی و نرخ دوبارهکاری |
منابع (References)
- Kubernetes: Deployments https://kubernetes.io/docs/concepts/workloads/controllers/deployment/ — workload management and canary pattern https://kubernetes.io/docs/concepts/workloads/management/ — Ingress https://kubernetes.io/docs/concepts/services-networking/ingress/ — Gateway API concept https://kubernetes.io/docs/concepts/services-networking/gateway/ — Service https://kubernetes.io/docs/concepts/services-networking/service/ — pod lifecycle (readiness gates) https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/ — container lifecycle hooks https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/ — images and digests https://kubernetes.io/docs/concepts/containers/images/ — run a stateless application https://kubernetes.io/docs/tasks/run-application/run-stateless-application-deployment/ — pods and endpoint termination flow https://kubernetes.io/docs/tutorials/services/pods-and-endpoint-termination-flow/
- kubectl rollout https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/ — undo https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_undo/ — history https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/kubectl_rollout_history/
- Kubernetes blog: Gateway API v1.0 GA https://kubernetes.io/blog/2023/10/31/gateway-api-ga/ — Ingress NGINX retirement https://kubernetes.io/blog/2025/11/11/ingress-nginx-retirement/
- Kubernetes OpenAPI v3 documents https://github.com/kubernetes/kubernetes/tree/master/api/openapi-spec/v3
- Gateway API: HTTPRoute https://gateway-api.sigs.k8s.io/reference/api-types/httproute/ — traffic splitting https://gateway-api.sigs.k8s.io/guides/traffic-splitting/ — HTTP routing https://gateway-api.sigs.k8s.io/guides/http-routing/ — request mirroring https://gateway-api.sigs.k8s.io/guides/http-request-mirroring/ — releases https://github.com/kubernetes-sigs/gateway-api/releases
- Ingress-NGINX annotations https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ — canary example https://kubernetes.github.io/ingress-nginx/examples/canary/ — repository https://github.com/kubernetes/ingress-nginx
- Argo Rollouts: overview https://argoproj.github.io/argo-rollouts/ — concepts https://argoproj.github.io/argo-rollouts/concepts/ — canary https://argoproj.github.io/argo-rollouts/features/canary/ — blue-green https://argoproj.github.io/argo-rollouts/features/bluegreen/ — analysis https://argoproj.github.io/argo-rollouts/features/analysis/ — Prometheus https://argoproj.github.io/argo-rollouts/analysis/prometheus/ — traffic management https://argoproj.github.io/argo-rollouts/features/traffic-management/ — NGINX https://argoproj.github.io/argo-rollouts/features/traffic-management/nginx/ — Istio https://argoproj.github.io/argo-rollouts/features/traffic-management/istio/ — plugins https://argoproj.github.io/argo-rollouts/features/traffic-management/plugins/ — rollback windows https://argoproj.github.io/argo-rollouts/features/rollback/ — best practices https://argoproj.github.io/argo-rollouts/best-practices/ — FAQ https://argoproj.github.io/argo-rollouts/FAQ/ — specification https://argoproj.github.io/argo-rollouts/features/specification/ — abort https://argoproj.github.io/argo-rollouts/generated/kubectl-argo-rollouts/kubectl-argo-rollouts_abort/ — promote https://argoproj.github.io/argo-rollouts/generated/kubectl-argo-rollouts/kubectl-argo-rollouts_promote/ — releases https://github.com/argoproj/argo-rollouts/releases
- Argo Rollouts Gateway API plugin https://github.com/argoproj-labs/rollouts-plugin-trafficrouter-gatewayapi — quick start https://rollouts-plugin-trafficrouter-gatewayapi.readthedocs.io/en/latest/quick-start/
- Flagger: https://docs.flagger.app/ — how it works https://docs.flagger.app/usage/how-it-works — deployment strategies https://docs.flagger.app/usage/deployment-strategies — metrics https://docs.flagger.app/usage/metrics — webhooks https://docs.flagger.app/usage/webhooks — NGINX tutorial https://docs.flagger.app/tutorials/nginx-progressive-delivery — Gateway API tutorial https://docs.flagger.app/tutorials/gatewayapi-progressive-delivery — Linkerd tutorial https://docs.flagger.app/tutorials/linkerd-progressive-delivery — releases https://github.com/fluxcd/flagger/releases
- Istio: traffic management https://istio.io/latest/docs/concepts/traffic-management/ — VirtualService https://istio.io/latest/docs/reference/config/networking/virtual-service/ — DestinationRule https://istio.io/latest/docs/reference/config/networking/destination-rule/ — traffic shifting https://istio.io/latest/docs/tasks/traffic-management/traffic-shifting/ — mirroring https://istio.io/latest/docs/tasks/traffic-management/mirroring/
- Linkerd: dynamic request routing https://linkerd.io/2-edge/tasks/configuring-dynamic-request-routing/ — HTTPRoute https://linkerd.io/2-edge/reference/httproute/ — traffic split https://linkerd.io/2-edge/features/traffic-split/ — SMI extension https://linkerd.io/2-edge/tasks/linkerd-smi/ — SMI spec (archived) https://github.com/servicemeshinterface/smi-spec
- OpenFeature: intro https://openfeature.dev/docs/reference/intro/ — evaluation API https://openfeature.dev/docs/reference/concepts/evaluation-api/ — evaluation context https://openfeature.dev/docs/reference/concepts/evaluation-context/ — providers https://openfeature.dev/docs/reference/concepts/provider/ — flag evaluation spec https://openfeature.dev/specification/sections/flag-evaluation/ — Go SDK https://openfeature.dev/docs/reference/sdks/server/go/ and https://github.com/open-feature/go-sdk — PHP SDK https://openfeature.dev/docs/reference/sdks/server/php/ — flagd https://flagd.dev/
- LaunchDarkly: percentage rollouts https://launchdarkly.com/docs/home/releases/percentage-rollouts — kill switch flags https://launchdarkly.com/docs/home/flags/killswitch — targeting https://launchdarkly.com/docs/home/flags/target
- Unleash: activation strategies https://docs.getunleash.io/reference/activation-strategies — stickiness https://docs.getunleash.io/reference/stickiness — technical debt https://docs.getunleash.io/reference/technical-debt — best practices https://docs.getunleash.io/topics/feature-flags/feature-flag-best-practices
- Flagsmith: managing features https://docs.flagsmith.com/basic-features/managing-features — segments https://docs.flagsmith.com/basic-features/segments — GitLab feature flags https://docs.gitlab.com/operations/feature_flags/
- Martin Fowler's bliki: BlueGreenDeployment https://martinfowler.com/bliki/BlueGreenDeployment.html — CanaryRelease https://martinfowler.com/bliki/CanaryRelease.html — FeatureToggle https://martinfowler.com/bliki/FeatureToggle.html — Feature Toggles article https://martinfowler.com/articles/feature-toggles.html — DarkLaunching https://martinfowler.com/bliki/DarkLaunching.html — ParallelChange https://martinfowler.com/bliki/ParallelChange.html — ImmutableServer https://martinfowler.com/bliki/ImmutableServer.html
- Helm: rollback https://helm.sh/docs/helm/helm_rollback/ — history https://helm.sh/docs/helm/helm_history/ — upgrade https://helm.sh/docs/helm/helm_upgrade/
- Argo CD: app rollback https://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app_rollback/ — automated sync https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/ — sync windows https://argo-cd.readthedocs.io/en/stable/user-guide/sync_windows/ — sync waves and hooks https://argo-cd.readthedocs.io/en/stable/user-guide/sync-waves/ — diffing https://argo-cd.readthedocs.io/en/stable/user-guide/diffing/
- AWS: instance refresh https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-overview.html — rollback https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-rollback.html — immutable infrastructure (Well-Architected) https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_tracking_change_management_immutable_infrastructure.html — blue/green whitepaper https://docs.aws.amazon.com/whitepapers/latest/overview-deployment-options/bluegreen-deployments.html — target group attributes (deregistration delay) https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html — Load Balancer Controller readiness gates https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/deploy/pod_readiness_gate/
- Terraform: aws_autoscaling_group https://github.com/hashicorp/terraform-provider-aws/blob/main/website/docs/r/autoscaling_group.html.markdown — lifecycle https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle — Packer https://developer.hashicorp.com/packer/docs/intro
- Laravel 13: deployment https://laravel.com/docs/13.x/deployment — configuration and maintenance mode https://laravel.com/docs/13.x/configuration — Octane https://laravel.com/docs/13.x/octane — queues https://laravel.com/docs/13.x/queues — migrations https://laravel.com/docs/13.x/migrations — Pennant https://laravel.com/docs/13.x/pennant — Envoy https://laravel.com/docs/13.x/envoy
- PHP: FPM installation https://www.php.net/manual/en/install.fpm.php — FPM configuration https://www.php.net/manual/en/install.fpm.configuration.php — OPcache configuration https://www.php.net/manual/en/opcache.configuration.php — FPM signal handling https://github.com/php/php-src/blob/master/sapi/fpm/fpm/fpm_events.c — Nginx core module (
$realpath_root) https://nginx.org/en/docs/http/ngx_http_core_module.html - Capistrano: structure https://capistranorb.com/documentation/getting-started/structure/ — rollbacks https://capistranorb.com/documentation/getting-started/rollbacks/ — Deployer https://deployer.org/docs/8.x/getting-started and recipes https://github.com/deployphp/deployer/blob/master/recipe/laravel.php
- Google SRE: release engineering https://sre.google/sre-book/release-engineering/ — canarying releases https://sre.google/workbook/canarying-releases/ — alerting on SLOs https://sre.google/workbook/alerting-on-slos/ — service level objectives https://sre.google/sre-book/service-level-objectives/
- DORA: metrics https://dora.dev/guides/dora-metrics-four-keys/ — history of the metrics https://dora.dev/insights/dora-metrics-history/ — continuous delivery capability https://dora.dev/capabilities/continuous-delivery/
- Go: net/http server (Shutdown, StateNew) https://go.dev/src/net/http/server.go — os/signal https://go.dev/src/os/signal/signal.go
- GitHub Actions environments https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments — GitLab deployment safety and deploy freezes https://docs.gitlab.com/ci/environments/deployment_safety/