diff --git a/.circleci/config.yml b/.circleci/config.yml index 758b14dc..09c6a598 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -143,6 +143,18 @@ jobs: - run: test/e2e-contour.sh - run: test/e2e-contour-tests.sh + e2e-skipper-testing: + machine: true + steps: + - checkout + - attach_workspace: + at: /tmp/bin + - run: test/container-build.sh + - run: test/e2e-kind.sh + - run: test/e2e-skipper.sh + - run: test/e2e-skipper-tests.sh + - run: test/e2e-skipper-cleanup.sh + push-helm-charts: docker: - image: circleci/golang:1.14 @@ -212,6 +224,9 @@ workflows: - e2e-contour-testing: requires: - build-binary + - e2e-skipper-testing: + requires: + - build-binary - push-container: requires: - build-binary @@ -220,6 +235,7 @@ workflows: - e2e-gloo-testing - e2e-nginx-testing - e2e-linkerd-testing + - e2e-skipper-testing filters: branches: only: diff --git a/.gitbook.yaml b/.gitbook.yaml index bdd2977a..1d974eca 100644 --- a/.gitbook.yaml +++ b/.gitbook.yaml @@ -10,4 +10,5 @@ redirects: usage/contour-progressive-delivery: tutorials/contour-progressive-delivery.md usage/gloo-progressive-delivery: tutorials/gloo-progressive-delivery.md usage/nginx-progressive-delivery: tutorials/nginx-progressive-delivery.md + usage/skipper-progressive-delivery: tutorials/skipper-progressive-delivery.md usage/crossover-progressive-delivery: tutorials/crossover-progressive-delivery.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bc7d64c..8d36f224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,54 @@ All notable changes to this project are documented in this file. +## 1.1.0 (2020-08-18) + +Add support for Skipper ingress controller + +#### Features + +- Skipper Ingress Controller support + [#670](https://github.com/weaveworks/flagger/pull/670) +- Support per-config configTracker disable via ConfigMap/Secret annotation + [#671](https://github.com/weaveworks/flagger/pull/671) + +#### Improvements + +- Add priorityClassName and securityContext to Helm charts + [#652](https://github.com/weaveworks/flagger/pull/652) + [#668](https://github.com/weaveworks/flagger/pull/668) +- Update Kubernetes packages to v1.18.8 + [#672](https://github.com/weaveworks/flagger/pull/672) +- Update Istio, Linkerd and Contour e2e tests + [#661](https://github.com/weaveworks/flagger/pull/661) + +#### Fixes + +- Fix O(log n) bug over network in GetTargetConfigs + [#663](https://github.com/weaveworks/flagger/pull/663) +- Fix(grafana): metrics change since Kubernetes 1.16 + [#663](https://github.com/weaveworks/flagger/pull/663) + +## 1.0.1 (2020-07-18) + +Add support for App Mesh Gateway GA + +#### Improvements + +- Update App Mesh docs to v1beta2 API + [#649](https://github.com/weaveworks/flagger/pull/649) +- Add threadiness to Flagger helm chart + [#643](https://github.com/weaveworks/flagger/pull/643) +- Add Istio virtual service to loadtester helm chart + [#643](https://github.com/weaveworks/flagger/pull/643) + +#### Fixes + +- Fix multiple paths per rule on canary ingress + [#632](https://github.com/weaveworks/flagger/pull/632) +- Fix installers for kustomize >= 3.6.0 + [#646](https://github.com/weaveworks/flagger/pull/646) + ## 1.0.0 (2020-06-17) This is the GA release for Flagger v1.0.0. diff --git a/README.md b/README.md index 4c1a237e..8a931f81 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ by gradually shifting traffic to the new version while measuring metrics and run ![flagger-overview](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/diagrams/flagger-canary-overview.png) Flagger implements several deployment strategies (Canary releases, A/B testing, Blue/Green mirroring) -using a service mesh (App Mesh, Istio, Linkerd) or an ingress controller (Contour, Gloo, NGINX) for traffic routing. +using a service mesh (App Mesh, Istio, Linkerd) or an ingress controller (Contour, Gloo, NGINX, Skipper) for traffic routing. For release analysis, Flagger can query Prometheus, Datadog or CloudWatch and for alerting it uses Slack, MS Teams, Discord and Rocket. @@ -37,6 +37,7 @@ Flagger documentation can be found at [docs.flagger.app](https://docs.flagger.ap * [Contour](https://docs.flagger.app/tutorials/contour-progressive-delivery) * [Gloo](https://docs.flagger.app/tutorials/gloo-progressive-delivery) * [NGINX Ingress](https://docs.flagger.app/tutorials/nginx-progressive-delivery) + * [Skipper](https://docs.flagger.app/tutorials/skipper-progressive-delivery) * [Kubernetes Blue/Green](https://docs.flagger.app/tutorials/kubernetes-blue-green) ### Who is using Flagger @@ -71,7 +72,7 @@ metadata: namespace: test spec: # service mesh provider (optional) - # can be: kubernetes, istio, linkerd, appmesh, nginx, contour, gloo, supergloo + # can be: kubernetes, istio, linkerd, appmesh, nginx, skipper, contour, gloo, supergloo provider: istio # deployment reference targetRef: @@ -180,17 +181,32 @@ For more details on how the canary analysis and promotion works please [read the ### Features -| Feature | Istio | Linkerd | App Mesh | NGINX | Gloo | Contour | CNI | -| -------------------------------------------- | ------------------ | ------------------ |------------------ |------------------ |------------------ |------------------ |------------------ | -| Canary deployments (weighted traffic) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | -| A/B testing (headers and cookies routing) | :heavy_check_mark: | :heavy_minus_sign: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | :heavy_check_mark: | :heavy_minus_sign: | -| Blue/Green deployments (traffic switch) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Webhooks (acceptance/load testing) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Manual gating (approve/pause/resume) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Request success rate check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | -| Request duration check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | -| Custom metric checks | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Traffic policy, CORS, retries and timeouts | :heavy_check_mark: | :heavy_minus_sign: | :heavy_minus_sign: | :heavy_minus_sign: | :heavy_minus_sign: | :heavy_check_mark: | :heavy_minus_sign: | +**Service Mesh** + +| Feature | App Mesh | Istio | Linkerd | Kubernetes CNI | +| ------------------------------------------ | ------------------ | ------------------ | ------------------ | ----------------- | +| Canary deployments (weighted traffic) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | +| A/B testing (headers and cookies routing) | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | :heavy_minus_sign: | +| Blue/Green deployments (traffic switch) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Blue/Green deployments (traffic mirroring) | :heavy_minus_sign: | :heavy_check_mark: | :heavy_minus_sign: | :heavy_minus_sign: | +| Webhooks (acceptance/load testing) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Manual gating (approve/pause/resume) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Request success rate check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | +| Request duration check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | +| Custom metric checks | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | + +**Ingress** + +| Feature | Contour | Gloo | NGINX | Skipper | +| ------------------------------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| Canary deployments (weighted traffic) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| A/B testing (headers and cookies routing) | :heavy_check_mark: | :heavy_minus_sign: | :heavy_check_mark: | :heavy_minus_sign: | +| Blue/Green deployments (traffic switch) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Webhooks (acceptance/load testing) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Manual gating (approve/pause/resume) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Request success rate check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | :heavy_check_mark: | +| Request duration check (L7 metric) | :heavy_check_mark: | :heavy_check_mark: | :heavy_minus_sign: | :heavy_check_mark: | +| Custom metric checks | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | ### Roadmap diff --git a/artifacts/flagger/deployment.yaml b/artifacts/flagger/deployment.yaml index 7e783286..a82da6b8 100644 --- a/artifacts/flagger/deployment.yaml +++ b/artifacts/flagger/deployment.yaml @@ -22,7 +22,7 @@ spec: serviceAccountName: flagger containers: - name: flagger - image: weaveworks/flagger:1.0.0 + image: weaveworks/flagger:1.1.0 imagePullPolicy: IfNotPresent ports: - name: http diff --git a/charts/flagger/Chart.yaml b/charts/flagger/Chart.yaml index 42013cf3..36dd58aa 100644 --- a/charts/flagger/Chart.yaml +++ b/charts/flagger/Chart.yaml @@ -1,7 +1,7 @@ apiVersion: v1 name: flagger -version: 1.0.0 -appVersion: 1.0.0 +version: 1.1.0 +appVersion: 1.1.0 kubeVersion: ">=1.11.0-0" engine: gotpl description: Flagger is a progressive delivery operator for Kubernetes diff --git a/charts/flagger/LICENSE b/charts/flagger/LICENSE new file mode 100644 index 00000000..6e292ed2 --- /dev/null +++ b/charts/flagger/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Weaveworks. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/charts/flagger/README.md b/charts/flagger/README.md index 888c9fe2..fa5589ae 100644 --- a/charts/flagger/README.md +++ b/charts/flagger/README.md @@ -7,7 +7,7 @@ Flagger can run automated application analysis, testing, promotion and rollback * A/B Testing (HTTP headers and cookies traffic routing) * Blue/Green (traffic switching and mirroring) -Flagger works with service mesh solutions (Istio, Linkerd, AWS App Mesh) and with Kubernetes ingress controllers (NGINX, Gloo, Contour). +Flagger works with service mesh solutions (Istio, Linkerd, AWS App Mesh) and with Kubernetes ingress controllers (NGINX, Skipper, Gloo, Contour). Flagger can be configured to send alerts to various chat platforms such as Slack, Microsoft Teams, Discord and Rocket. ## Prerequisites @@ -134,11 +134,13 @@ Parameter | Description | Default `resources.limits/memory` | Pod memory limit | `512Mi` `affinity` | Node/pod affinities | None `nodeSelector` | Node labels for pod assignment | `{}` +`threadiness` | Number of controller workers | `2` `tolerations` | List of node taints to tolerate | `[]` `istio.kubeconfig.secretName` | The name of the Kubernetes secret containing the Istio shared control plane kubeconfig | None `istio.kubeconfig.key` | The name of Kubernetes secret data key that contains the Istio control plane kubeconfig | `kubeconfig` `ingressAnnotationsPrefix` | Annotations prefix for NGINX ingresses | None `ingressClass` | Ingress class used for annotating HTTPProxy objects, e.g. `contour` | None +`podPriorityClassName` | PriorityClass name for pod priority configuration | "" Specify each parameter using the `--set key=value[,key=value]` argument to `helm upgrade`. For example, diff --git a/charts/flagger/templates/deployment.yaml b/charts/flagger/templates/deployment.yaml index 9666a15f..cb6ebd58 100644 --- a/charts/flagger/templates/deployment.yaml +++ b/charts/flagger/templates/deployment.yaml @@ -48,6 +48,9 @@ spec: secret: secretName: "{{ .Values.istio.kubeconfig.secretName }}" {{- end }} + {{- if .Values.podPriorityClassName }} + priorityClassName: {{ .Values.podPriorityClassName }} + {{- end }} containers: - name: flagger {{- if .Values.securityContext.enabled }} @@ -112,6 +115,9 @@ spec: {{- if .Values.istio.kubeconfig.secretName }} - -kubeconfig-service-mesh=/tmp/istio-host/{{ .Values.istio.kubeconfig.key }} {{- end }} + {{- if .Values.threadiness }} + - -threadiness={{ .Values.threadiness }} + {{- end }} livenessProbe: exec: command: diff --git a/charts/flagger/values.yaml b/charts/flagger/values.yaml index b453a9c9..3956f5ff 100644 --- a/charts/flagger/values.yaml +++ b/charts/flagger/values.yaml @@ -2,7 +2,7 @@ image: repository: weaveworks/flagger - tag: 1.0.0 + tag: 1.1.0 pullPolicy: IfNotPresent pullSecret: @@ -14,6 +14,9 @@ podAnnotations: prometheus.io/port: "8080" appmesh.k8s.aws/sidecarInjectorWebhook: disabled +# priority class name for pod priority configuration +podPriorityClassName: "" + metricsServer: "http://prometheus:9090" # accepted values are kubernetes, istio, linkerd, appmesh, nginx, gloo or supergloo:mesh.namespace (defaults to istio) diff --git a/charts/grafana/dashboards/appmesh.json b/charts/grafana/dashboards/appmesh.json index 1544ee5b..7ced6341 100644 --- a/charts/grafana/dashboards/appmesh.json +++ b/charts/grafana/dashboards/appmesh.json @@ -602,11 +602,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -692,11 +692,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$canary.*\", pod_name!~\"$primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$canary.*\", pod!~\"$primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -782,12 +782,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -874,12 +874,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$canary.*\", pod_name!~\"$primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$canary.*\", pod!~\"$primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -975,14 +975,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", @@ -1081,14 +1081,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$canary.*\",pod_name!~\"$primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$canary.*\",pod!~\"$primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$canary.*\",pod_name!~\"$primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$canary.*\",pod!~\"$primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", diff --git a/charts/grafana/dashboards/envoy.json b/charts/grafana/dashboards/envoy.json index 46b27a66..88be8d5f 100644 --- a/charts/grafana/dashboards/envoy.json +++ b/charts/grafana/dashboards/envoy.json @@ -602,11 +602,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$target-primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$target-primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -692,11 +692,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$target.*\", pod_name!~\"$target-primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$target.*\", pod!~\"$target-primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -782,12 +782,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$target-primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$target-primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -874,12 +874,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$target.*\", pod_name!~\"$target-primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$target.*\", pod!~\"$target-primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -975,14 +975,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$target-primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$target-primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$target-primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$target-primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", @@ -1081,14 +1081,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$target.*\",pod_name!~\"$target-primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$target.*\",pod!~\"$target-primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$target.*\",pod_name!~\"$target-primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$target.*\",pod!~\"$target-primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", diff --git a/charts/grafana/dashboards/istio.json b/charts/grafana/dashboards/istio.json index 84bc0a64..c4a9579a 100644 --- a/charts/grafana/dashboards/istio.json +++ b/charts/grafana/dashboards/istio.json @@ -403,7 +403,7 @@ "steppedLine": false, "targets": [ { - "expr": "histogram_quantile(0.50, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.50, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "interval": "", "intervalFactor": 1, @@ -411,7 +411,7 @@ "refId": "A" }, { - "expr": "histogram_quantile(0.90, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.90, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "hide": false, "intervalFactor": 1, @@ -419,7 +419,7 @@ "refId": "B" }, { - "expr": "histogram_quantile(0.99, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.99, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$primary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "hide": false, "intervalFactor": 1, @@ -509,7 +509,7 @@ "steppedLine": false, "targets": [ { - "expr": "histogram_quantile(0.50, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.50, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "interval": "", "intervalFactor": 1, @@ -517,7 +517,7 @@ "refId": "A" }, { - "expr": "histogram_quantile(0.90, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.90, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "hide": false, "intervalFactor": 1, @@ -525,7 +525,7 @@ "refId": "B" }, { - "expr": "histogram_quantile(0.99, sum(irate(istio_request_duration_seconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", + "expr": "histogram_quantile(0.99, sum(irate(istio_request_duration_milliseconds_bucket{reporter=\"destination\",destination_workload=~\"$canary\", destination_workload_namespace=~\"$namespace\"}[1m])) by (le))", "format": "time_series", "hide": false, "intervalFactor": 1, @@ -630,11 +630,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -720,11 +720,11 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod_name=~\"$canary.*\", pod_name!~\"$primary.*\", container_name!~\"POD|istio-proxy\"}[1m])) by (pod_name)", + "expr": "sum(rate(container_cpu_usage_seconds_total{cpu=\"total\",namespace=\"$namespace\",pod=~\"$canary.*\", pod!~\"$primary.*\", container!~\"POD|istio-proxy\"}[1m])) by (pod)", "format": "time_series", "hide": false, "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -810,12 +810,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -902,12 +902,12 @@ "steppedLine": false, "targets": [ { - "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod_name=~\"$canary.*\", pod_name!~\"$primary.*\", container_name!~\"POD|istio-proxy\"}) by (pod_name)", + "expr": "sum(container_memory_working_set_bytes{namespace=\"$namespace\",pod=~\"$canary.*\", pod!~\"$primary.*\", container!~\"POD|istio-proxy\"}) by (pod)", "format": "time_series", "hide": false, "interval": "", "intervalFactor": 1, - "legendFormat": "{{ pod_name }}", + "legendFormat": "{{ pod }}", "refId": "B" } ], @@ -1003,14 +1003,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", @@ -1109,14 +1109,14 @@ "steppedLine": false, "targets": [ { - "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod_name=~\"$canary.*\",pod_name!~\"$primary.*\"}[1m])) ", + "expr": "sum(rate (container_network_receive_bytes_total{namespace=\"$namespace\",pod=~\"$canary.*\",pod!~\"$primary.*\"}[1m])) ", "format": "time_series", "intervalFactor": 1, "legendFormat": "received", "refId": "A" }, { - "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod_name=~\"$canary.*\",pod_name!~\"$primary.*\"}[1m]))", + "expr": "-sum (rate (container_network_transmit_bytes_total{namespace=\"$namespace\",pod=~\"$canary.*\",pod!~\"$primary.*\"}[1m]))", "format": "time_series", "intervalFactor": 1, "legendFormat": "transmited", diff --git a/charts/loadtester/Chart.yaml b/charts/loadtester/Chart.yaml index f3262924..b1fe5917 100644 --- a/charts/loadtester/Chart.yaml +++ b/charts/loadtester/Chart.yaml @@ -1,7 +1,7 @@ apiVersion: v1 name: loadtester -version: 0.17.0 -appVersion: 0.17.0 +version: 0.18.0 +appVersion: 0.18.0 kubeVersion: ">=1.11.0-0" engine: gotpl description: Flagger's load testing services based on rakyll/hey and bojand/ghz that generates traffic during canary analysis when configured as a webhook. diff --git a/charts/loadtester/README.md b/charts/loadtester/README.md index 66201207..f41b87d3 100644 --- a/charts/loadtester/README.md +++ b/charts/loadtester/README.md @@ -62,6 +62,14 @@ Parameter | Description | Default `logLevel` | Log level can be debug, info, warning, error or panic | `info` `appmesh.enabled` | Create AWS App Mesh v1beta2 virtual node | `false` `appmesh.backends` | AWS App Mesh virtual services | `none` +`istio.enabled` | Create Istio virtual service | `false` +`istio.host` | Loadtester hostname | `flagger-loadtester.flagger` +`istio.gateway.enabled` | Create Istio gateway in namespace | `false` +`istio.tls.enabled` | Enable TLS in gateway ( TLS secrets should be in namespace ) | `false` +`istio.tls.httpsRedirect` | Redirect traffic to TLS port | `false` +`podPriorityClassName` | PriorityClass name for pod priority configuration | "" +`securityContext.enabled` | Add securityContext to container | "" +`securityContext.context` | securityContext to add | "" Specify each parameter using the `--set key=value[,key=value]` argument to `helm upgrade`. For example, diff --git a/charts/loadtester/templates/deployment.yaml b/charts/loadtester/templates/deployment.yaml index 3120bb12..f9b26604 100644 --- a/charts/loadtester/templates/deployment.yaml +++ b/charts/loadtester/templates/deployment.yaml @@ -27,8 +27,15 @@ spec: {{- else if .Values.rbac.create }} serviceAccountName: {{ include "loadtester.fullname" . }} {{- end }} + {{- if .Values.podPriorityClassName }} + priorityClassName: {{ .Values.podPriorityClassName }} + {{- end }} containers: - name: {{ .Chart.Name }} + {{- if .Values.securityContext.enabled }} + securityContext: +{{ toYaml .Values.securityContext.context | indent 12 }} + {{- end }} image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} ports: diff --git a/charts/loadtester/templates/istio-gw.yaml b/charts/loadtester/templates/istio-gw.yaml new file mode 100644 index 00000000..f6b05242 --- /dev/null +++ b/charts/loadtester/templates/istio-gw.yaml @@ -0,0 +1,30 @@ +{{- if and (.Values.istio.enabled) (.Values.istio.gateway.enabled) }} +apiVersion: networking.istio.io/v1alpha3 +kind: Gateway +metadata: + name: {{ include "loadtester.fullname" . }} +spec: + selector: + istio: ingressgateway + servers: + - port: + number: 80 + name: http-default + protocol: HTTP + hosts: + - {{ .Values.istio.host }} + {{- if .Values.istio.tls.enabled }} + - port: + number: 443 + name: https-default + protocol: HTTPS + tls: + httpsRedirect: {{ .Values.istio.tls.httpsRedirect }} + mode: SIMPLE + serverCertificate: "sds" + privateKey: "sds" + credentialName: {{ include "loadtester.fullname" . }} + hosts: + - {{ .Values.istio.host }} + {{- end }} +{{- end }} diff --git a/charts/loadtester/templates/istio-vs.yaml b/charts/loadtester/templates/istio-vs.yaml new file mode 100644 index 00000000..dd3115d2 --- /dev/null +++ b/charts/loadtester/templates/istio-vs.yaml @@ -0,0 +1,17 @@ +{{- if .Values.istio.enabled }} +apiVersion: networking.istio.io/v1alpha3 +kind: VirtualService +metadata: + name: {{ include "loadtester.fullname" . }} +spec: + gateways: + - {{ include "loadtester.fullname" . }} + hosts: + - {{ .Values.istio.host }} + http: + - route: + - destination: + host: {{ include "loadtester.fullname" . }} + port: + number: {{ .Values.service.port }} +{{- end }} diff --git a/charts/loadtester/values.yaml b/charts/loadtester/values.yaml index 9b30cc3d..c089cc6d 100644 --- a/charts/loadtester/values.yaml +++ b/charts/loadtester/values.yaml @@ -2,13 +2,15 @@ replicaCount: 1 image: repository: weaveworks/flagger-loadtester - tag: 0.17.0 + tag: 0.18.0 pullPolicy: IfNotPresent podAnnotations: prometheus.io/scrape: "true" prometheus.io/port: "8080" +podPriorityClassName: "" + logLevel: info cmd: timeout: 1h @@ -59,3 +61,21 @@ appmesh: backends: - podinfo - podinfo-canary + +#Istio virtual service and gatway settings. TLS secrets should be in namespace before enbaled it. ( secret format loadtester.fullname ) +istio: + enabled: false + host: flagger-loadtester.flagger + gateway: + enabled: false + tls: + enabled: false + httpsRedirect: false + +# when enabled, it will add a security context for the loadtester pod +securityContext: + enabled: false + context: + readOnlyRootFilesystem: true + runAsUser: 100 + runAsGroup: 101 diff --git a/cmd/flagger/main.go b/cmd/flagger/main.go index 540179a8..0ce5c76c 100644 --- a/cmd/flagger/main.go +++ b/cmd/flagger/main.go @@ -78,7 +78,7 @@ func init() { flag.BoolVar(&zapReplaceGlobals, "zap-replace-globals", false, "Whether to change the logging level of the global zap logger.") flag.StringVar(&zapEncoding, "zap-encoding", "json", "Zap logger encoding.") flag.StringVar(&namespace, "namespace", "", "Namespace that flagger would watch canary object.") - flag.StringVar(&meshProvider, "mesh-provider", "istio", "Service mesh provider, can be istio, linkerd, appmesh, contour, gloo or nginx.") + flag.StringVar(&meshProvider, "mesh-provider", "istio", "Service mesh provider, can be istio, linkerd, appmesh, contour, gloo, nginx or skipper.") flag.StringVar(&selectorLabels, "selector-labels", "app,name,app.kubernetes.io/name", "List of pod labels that Flagger uses to create pod selectors.") flag.StringVar(&ingressAnnotationsPrefix, "ingress-annotations-prefix", "nginx.ingress.kubernetes.io", "Annotations prefix for NGINX ingresses.") flag.StringVar(&ingressClass, "ingress-class", "", "Ingress class used for annotating HTTPProxy objects.") diff --git a/cmd/loadtester/main.go b/cmd/loadtester/main.go index 20e2644a..8d96ad06 100644 --- a/cmd/loadtester/main.go +++ b/cmd/loadtester/main.go @@ -11,7 +11,7 @@ import ( "go.uber.org/zap" ) -var VERSION = "0.17.0" +var VERSION = "0.18.0" var ( logLevel string port string diff --git a/docs/diagrams/flagger-skipper-overview.png b/docs/diagrams/flagger-skipper-overview.png new file mode 100644 index 00000000..e2f18aec Binary files /dev/null and b/docs/diagrams/flagger-skipper-overview.png differ diff --git a/docs/gitbook/README.md b/docs/gitbook/README.md index e0361dd0..fae6f42f 100644 --- a/docs/gitbook/README.md +++ b/docs/gitbook/README.md @@ -5,7 +5,7 @@ description: Flagger is a progressive delivery Kubernetes operator # Introduction [Flagger](https://github.com/weaveworks/flagger) is a **Kubernetes** operator that automates the promotion of -canary deployments using **Istio**, **Linkerd**, **App Mesh**, **NGINX**, **Contour** or **Gloo** routing for +canary deployments using **Istio**, **Linkerd**, **App Mesh**, **NGINX**, **Skipper**, **Contour** or **Gloo** routing for traffic shifting and **Prometheus** metrics for canary analysis. The canary analysis can be extended with webhooks for running system integration/acceptance tests, load tests, or any other custom validation. @@ -39,6 +39,7 @@ After install Flagger, you can follow one of the tutorials: * [Contour](tutorials/contour-progressive-delivery.md) * [Gloo](tutorials/gloo-progressive-delivery.md) * [NGINX Ingress](tutorials/nginx-progressive-delivery.md) +* [Skipper Ingress](tutorials/skipper-progressive-delivery.md) **Hands-on GitOps workshops** diff --git a/docs/gitbook/SUMMARY.md b/docs/gitbook/SUMMARY.md index 9f565064..240d1801 100644 --- a/docs/gitbook/SUMMARY.md +++ b/docs/gitbook/SUMMARY.md @@ -24,9 +24,10 @@ * [Istio A/B Testing](tutorials/istio-ab-testing.md) * [Linkerd Canary Deployments](tutorials/linkerd-progressive-delivery.md) * [App Mesh Canary Deployments](tutorials/appmesh-progressive-delivery.md) -* [NGINX Canary Deployments](tutorials/nginx-progressive-delivery.md) -* [Gloo Canary Deployments](tutorials/gloo-progressive-delivery.md) * [Contour Canary Deployments](tutorials/contour-progressive-delivery.md) +* [Gloo Canary Deployments](tutorials/gloo-progressive-delivery.md) +* [NGINX Canary Deployments](tutorials/nginx-progressive-delivery.md) +* [Skipper Canary Deployments](tutorials/skipper-progressive-delivery.md) * [Blue/Green Deployments](tutorials/kubernetes-blue-green.md) * [Crossover Canary Deployments](tutorials/crossover-progressive-delivery.md) * [Canary analysis with Prometheus Operator](tutorials/prometheus-operator.md) @@ -37,4 +38,4 @@ * [Development Guide](dev/dev-guide.md) * [Release Guide](dev/release-guide.md) -* [Upgrade Guide](dev/upgrade-guide.md) \ No newline at end of file +* [Upgrade Guide](dev/upgrade-guide.md) diff --git a/docs/gitbook/install/flagger-install-on-eks-appmesh.md b/docs/gitbook/install/flagger-install-on-eks-appmesh.md index e4b652db..b999ad2d 100644 --- a/docs/gitbook/install/flagger-install-on-eks-appmesh.md +++ b/docs/gitbook/install/flagger-install-on-eks-appmesh.md @@ -16,7 +16,8 @@ The App Mesh integration with EKS is made out of the following components: ## Create a Kubernetes cluster -In order to create an EKS cluster you can use [eksctl](https://eksctl.io). Eksctl is an open source command-line utility made by Weaveworks in collaboration with Amazon. +In order to create an EKS cluster you can use [eksctl](https://eksctl.io). +Eksctl is an open source command-line utility made by Weaveworks in collaboration with Amazon. On MacOS you can install eksctl with Homebrew: @@ -25,7 +26,7 @@ brew tap weaveworks/tap brew install weaveworks/tap/eksctl ``` -Create an EKS cluster: +Create an EKS cluster with: ```bash eksctl create cluster --name=appmesh \ @@ -35,7 +36,9 @@ eksctl create cluster --name=appmesh \ --appmesh-access ``` -The above command will create a two nodes cluster with App Mesh [IAM policy](https://docs.aws.amazon.com/app-mesh/latest/userguide/MESH_IAM_user_policies.html) attached to the EKS node instance role. +The above command will create a two nodes cluster with +App Mesh [IAM policy](https://docs.aws.amazon.com/app-mesh/latest/userguide/MESH_IAM_user_policies.html) +attached to the EKS node instance role. Verify the install with: @@ -45,30 +48,18 @@ kubectl get nodes ## Install Helm -Install the [Helm](https://docs.helm.sh/using_helm/#installing-helm) command-line tool: +Install the [Helm](https://docs.helm.sh/using_helm/#installing-helm) v3 command-line tool: ```text -brew install kubernetes-helm +brew install helm ``` -Create a service account and a cluster role binding for Tiller: +Add the EKS repository to Helm: ```bash -kubectl -n kube-system create sa tiller - -kubectl create clusterrolebinding tiller-cluster-rule \ ---clusterrole=cluster-admin \ ---serviceaccount=kube-system:tiller +helm repo add eks https://aws.github.io/eks-charts ``` -Deploy Tiller in the `kube-system` namespace: - -```bash -helm init --service-account tiller -``` - -You should consider using SSL between Helm and Tiller, for more information on securing your Helm installation see [docs.helm.sh](https://docs.helm.sh/using_helm/#securing-your-helm-installation). - ## Enable horizontal pod auto-scaling Install the Horizontal Pod Autoscaler \(HPA\) metrics provider: @@ -87,52 +78,27 @@ kubectl -n kube-system top pods ## Install the App Mesh components +Install the App Mesh CRDs: + +```bash +kubectl apply -k github.com/aws/eks-charts/stable/appmesh-controller//crds?ref=master +``` + Create the `appmesh-system` namespace: ```bash kubectl create ns appmesh-system ``` -Apply the App Mesh CRDs: - -```bash -kubectl apply -k github.com/aws/eks-charts/stable/appmesh-controller//crds -``` - -Add the EKS repository to Helm: - -```bash -helm repo add eks https://aws.github.io/eks-charts -``` - -Install the App Mesh CRD controller: +Install the App Mesh controller: ```bash helm upgrade -i appmesh-controller eks/appmesh-controller \ --wait --namespace appmesh-system ``` -Install the App Mesh admission controller and create a mesh called `global`: - -```bash -helm upgrade -i appmesh-inject eks/appmesh-inject \ ---wait --namespace appmesh-system \ ---set mesh.create=true \ ---set mesh.name=global -``` - -Verify that the global mesh is active: - -```bash -kubectl describe mesh - -Status: - Mesh Condition: - Status: True - Type: MeshActive -``` - -In order to collect the App Mesh metrics that Flagger needs to run the canary analysis, you'll need to setup a Prometheus instance to scrape the Envoy sidecars. +In order to collect the App Mesh metrics that Flagger needs to run the canary analysis, +you'll need to setup a Prometheus instance to scrape the Envoy sidecars. Install the App Mesh Prometheus: @@ -141,7 +107,7 @@ helm upgrade -i appmesh-prometheus eks/appmesh-prometheus \ --wait --namespace appmesh-system ``` -## Install Flagger and Grafana +## Install Flagger Add Flagger Helm repository: @@ -161,34 +127,25 @@ Deploy Flagger in the _**appmesh-system**_ namespace: helm upgrade -i flagger flagger/flagger \ --namespace=appmesh-system \ --set crd.create=false \ ---set meshProvider=appmesh \ +--set meshProvider=appmesh:v1beta2 \ --set metricsServer=http://appmesh-prometheus:9090 ``` -You can enable Slack or MS Teams notifications with: +## Install Grafana + +Deploy App Mesh Grafana that comes with a dashboard for monitoring Flagger's canary releases: ```bash -helm upgrade -i flagger flagger/flagger \ ---reuse-values \ ---namespace=appmesh-system \ ---set slack.url=https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK \ ---set slack.channel=general \ ---set slack.user=flagger -``` - -Flagger comes with a Grafana dashboard made for monitoring the canary analysis. Deploy Grafana in the _**appmesh-system**_ namespace: - -```bash -helm upgrade -i flagger-grafana flagger/grafana \ ---namespace=appmesh-system \ ---set url=http://appmesh-prometheus:9090 +helm upgrade -i appmesh-grafana eks/appmesh-grafana \ +--namespace appmesh-system ``` You can access Grafana using port forwarding: ```bash -kubectl -n appmesh-system port-forward svc/flagger-grafana 3000:80 +kubectl -n appmesh-system port-forward svc/appmesh-grafana 3000:3000 ``` -Now that you have Flagger running you can try the [App Mesh canary deployments tutorial](https://docs.flagger.app/usage/appmesh-progressive-delivery). +Now that you have Flagger running, +you can try the [App Mesh canary deployments tutorial](https://docs.flagger.app/usage/appmesh-progressive-delivery). diff --git a/docs/gitbook/install/flagger-install-on-kubernetes.md b/docs/gitbook/install/flagger-install-on-kubernetes.md index fc022a22..07b040d1 100644 --- a/docs/gitbook/install/flagger-install-on-kubernetes.md +++ b/docs/gitbook/install/flagger-install-on-kubernetes.md @@ -77,6 +77,7 @@ For ingress controllers, the install instructions are: * [Contour](https://docs.flagger.app/tutorials/contour-progressive-delivery) * [Gloo](https://docs.flagger.app/tutorials/gloo-progressive-delivery) * [NGINX](https://docs.flagger.app/tutorials/nginx-progressive-delivery) +* [Skipper](https://docs.flagger.app/tutorials/skipper-progressive-delivery) Enable **Slack** notifications: @@ -171,13 +172,13 @@ As an alternative to Helm, Flagger can be installed with Kustomize **3.5.0** or Install Flagger for Istio: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/istio | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/istio | kubectl apply -f - ``` Install Flagger for AWS App Mesh: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/appmesh | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/appmesh | kubectl apply -f - ``` This deploys Flagger and sets the metrics server URL to App Mesh's Prometheus instance. @@ -185,7 +186,7 @@ This deploys Flagger and sets the metrics server URL to App Mesh's Prometheus in Install Flagger for Linkerd: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/linkerd | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/linkerd | kubectl apply -f - ``` This deploys Flagger in the `linkerd` namespace and sets the metrics server URL to Linkerd's Prometheus instance. @@ -193,15 +194,15 @@ This deploys Flagger in the `linkerd` namespace and sets the metrics server URL If you want to install a specific Flagger release, add the version number to the URL: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/linkerd?ref=0.18.0 | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/linkerd?ref=v1.0.0 | kubectl apply -f - ``` **Generic installer** -Install Flagger and Prometheus for Contour, Gloo or NGINX ingress: +Install Flagger and Prometheus for Contour, Gloo, NGINX or Skipper ingress: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/kubernetes | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/kubernetes | kubectl apply -f - ``` This deploys Flagger and Prometheus in the `flagger-system` namespace, sets the metrics server URL @@ -219,7 +220,7 @@ metadata: name: app namespace: test spec: - # can be: kubernetes, istio, linkerd, appmesh, nginx, gloo + # can be: kubernetes, istio, linkerd, appmesh, nginx, skipper, gloo # use the kubernetes provider for Blue/Green style deployments provider: nginx ``` diff --git a/docs/gitbook/tutorials/appmesh-progressive-delivery.md b/docs/gitbook/tutorials/appmesh-progressive-delivery.md index 18e20253..8b822028 100644 --- a/docs/gitbook/tutorials/appmesh-progressive-delivery.md +++ b/docs/gitbook/tutorials/appmesh-progressive-delivery.md @@ -1,21 +1,28 @@ # App Mesh Canary Deployments -This guide shows you how to use App Mesh and Flagger to automate canary deployments. You'll need an EKS cluster configured with App Mesh, you can find the install guide [here](https://docs.flagger.app/install/flagger-install-on-eks-appmesh). +This guide shows you how to use App Mesh and Flagger to automate canary deployments. +You'll need an EKS cluster configured with App Mesh, +you can find the installion guide [here](https://docs.flagger.app/install/flagger-install-on-eks-appmesh). ## Bootstrap -Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler \(HPA\), then creates a series of objects \(Kubernetes deployments, ClusterIP services, App Mesh virtual nodes and services\). These objects expose the application on the mesh and drive the canary analysis and promotion. The only App Mesh object you need to create by yourself is the mesh resource. +Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler \(HPA\), +then creates a series of objects \(Kubernetes deployments, ClusterIP services, App Mesh virtual nodes and services\). +These objects expose the application on the mesh and drive the canary analysis and promotion. +The only App Mesh object you need to create by yourself is the mesh resource. Create a mesh called `global`: ```bash cat << EOF | kubectl apply -f - -apiVersion: appmesh.k8s.aws/v1beta1 +apiVersion: appmesh.k8s.aws/v1beta2 kind: Mesh metadata: name: global spec: - serviceDiscoveryType: dns + namespaceSelector: + matchLabels: + appmesh.k8s.aws/sidecarInjectorWebhook: enabled EOF ``` @@ -43,12 +50,12 @@ Deploy the load testing service to generate traffic during the canary analysis: ```bash helm upgrade -i flagger-loadtester flagger/loadtester \ --namespace=test \ ---set meshName=global \ ---set "backends[0]=podinfo.test" \ ---set "backends[1]=podinfo-canary.test" +--set appmesh.enabled=true \ +--set "appmesh.backends[0]=podinfo" \ +--set "appmesh.backends[1]=podinfo-canary" ``` -Create a canary custom resource: +Create a canary definition: ```yaml apiVersion: flagger.app/v1beta1 @@ -57,6 +64,8 @@ metadata: name: podinfo namespace: test spec: + # App Mesh API reference + provider: appmesh:v1beta2 # deployment reference targetRef: apiVersion: apps/v1 @@ -73,24 +82,19 @@ spec: service: # container port port: 9898 - # container port name (optional) - # can be http or grpc - portName: http - # App Mesh reference - meshName: global - # App Mesh ingress (optional) - hosts: - - "*" # App Mesh ingress timeout (optional) - timeout: 5s - # App Mesh egress (optional) - backends: - - backend.test + timeout: 15s # App Mesh retry policy (optional) retries: attempts: 3 perTryTimeout: 5s retryOn: "gateway-error,client-error,stream-error" + # App Mesh URI settings + match: + - uri: + prefix: / + rewrite: + uri: / # define the canary analysis timing and KPIs analysis: # schedule interval (default 60s) @@ -155,38 +159,39 @@ service/podinfo-canary service/podinfo-primary # generated App Mesh objects -virtualnode.appmesh.k8s.aws/podinfo virtualnode.appmesh.k8s.aws/podinfo-canary virtualnode.appmesh.k8s.aws/podinfo-primary -virtualservice.appmesh.k8s.aws/podinfo.test -virtualservice.appmesh.k8s.aws/podinfo-canary.test +virtualrouter.appmesh.k8s.aws/podinfo +virtualrouter.appmesh.k8s.aws/podinfo-canary +virtualservice.appmesh.k8s.aws/podinfo +virtualservice.appmesh.k8s.aws/podinfo-canary ``` -After the boostrap, the podinfo deployment will be scaled to zero and the traffic to `podinfo.test` will be routed to the primary pods. During the canary analysis, the `podinfo-canary.test` address can be used to target directly the canary pods. +After the boostrap, the podinfo deployment will be scaled to zero and the traffic to +`podinfo.test` will be routed to the primary pods. +During the canary analysis, the `podinfo-canary.test` address can be used to target directly the canary pods. -The App Mesh specific settings are: +App Mesh blocks all egress traffic by default. +If your application needs to call another service, you have to +create an App Mesh virtual service for it and add the virtual service name to the backend list. ```yaml service: port: 9898 - meshName: global backends: - - backend1.test - - backend2.test + - backend1 + - backend2 ``` -App Mesh blocks all egress traffic by default. If your application needs to call another service, you have to create an App Mesh virtual service for it and add the virtual service name to the backend list. +## Setup App Mesh Gateway (optional) -## Setup App Mesh Gateway \(optional\) +In order to expose the podinfo app outside the mesh you can use the App Mesh Gateway. -In order to expose the podinfo app outside the mesh you'll be using an Envoy-powered ingress gateway and an AWS network load balancer. The gateway binds to an internet domain and forwards the calls into the mesh through the App Mesh sidecar. If podinfo becomes unavailable due to a cluster downscaling or a node restart, the gateway will retry the calls for a short period of time. - -Deploy the gateway behind an AWS NLB: +Deploy the App Mesh Gateway behind an AWS NLB: ```bash -helm upgrade -i appmesh-gateway flagger/appmesh-gateway \ ---namespace test \ ---set mesh.name=global +helm upgrade -i appmesh-gateway eks/appmesh-gateway \ +--namespace test ``` Find the gateway public address: @@ -202,6 +207,27 @@ Wait for the NLB to become active: watch curl -sS $URL ``` +Create a gateway route that points to the podinfo virtual service: + +```yaml +cat << EOF | kubectl apply -f - +apiVersion: appmesh.k8s.aws/v1beta2 +kind: GatewayRoute +metadata: + name: podinfo + namespace: test +spec: + httpRoute: + match: + prefix: "/" + action: + target: + virtualService: + virtualServiceRef: + name: podinfo +EOF +``` + Open your browser and navigate to the ingress address to access podinfo UI. ## Automated canary promotion @@ -251,7 +277,9 @@ When the canary analysis starts, Flagger will call the pre-rollout webhooks befo **Note** that if you apply new changes to the deployment during the canary analysis, Flagger will restart the analysis. -During the analysis the canary’s progress can be monitored with Grafana. The App Mesh dashboard URL is [http://localhost:3000/d/flagger-appmesh/appmesh-canary?refresh=10s&orgId=1&var-namespace=test&var-primary=podinfo-primary&var-canary=podinfo](http://localhost:3000/d/flagger-appmesh/appmesh-canary?refresh=10s&orgId=1&var-namespace=test&var-primary=podinfo-primary&var-canary=podinfo) +During the analysis the canary’s progress can be monitored with Grafana. +The App Mesh dashboard URL is +[http://localhost:3000/d/flagger-appmesh/appmesh-canary?refresh=10s&orgId=1&var-namespace=test&var-primary=podinfo-primary&var-canary=podinfo](http://localhost:3000/d/flagger-appmesh/appmesh-canary?refresh=10s&orgId=1&var-namespace=test&var-primary=podinfo-primary&var-canary=podinfo). ![App Mesh Canary Dashboard](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/screens/flagger-grafana-appmesh.png) @@ -260,10 +288,10 @@ You can monitor all canaries with: ```bash watch kubectl get canaries --all-namespaces -NAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIME -test podinfo Progressing 15 2019-10-02T14:05:07Z -prod frontend Succeeded 0 2019-10-02T16:15:07Z -prod backend Failed 0 2019-10-02T17:05:07Z +NAMESPACE NAME STATUS WEIGHT +test podinfo Progressing 15 +prod frontend Succeeded 0 +prod backend Failed 0 ``` If you’ve enabled the Slack notifications, you should receive the following messages: @@ -299,7 +327,8 @@ Generate latency: watch -n 1 curl http://podinfo-canary.test:9898/delay/1 ``` -When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, the canary is scaled to zero and the rollout is marked as failed. +When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, +the canary is scaled to zero and the rollout is marked as failed. ```text kubectl -n appmesh-system logs deploy/flagger -f | jq .msg @@ -318,13 +347,16 @@ Rolling back podinfo.test failed checks threshold reached 5 Canary failed! Scaling down podinfo.test ``` -If you’ve enabled the Slack notifications, you’ll receive a message if the progress deadline is exceeded, or if the analysis reached the maximum number of failed checks: +If you’ve enabled the Slack notifications, you’ll receive a message if the progress deadline is exceeded, +or if the analysis reached the maximum number of failed checks: ![Flagger Slack Notifications](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/screens/slack-canary-failed.png) ## A/B Testing -Besides weighted routing, Flagger can be configured to route traffic to the canary based on HTTP match conditions. In an A/B testing scenario, you'll be using HTTP headers or cookies to target a certain segment of your users. This is particularly useful for frontend applications that require session affinity. +Besides weighted routing, Flagger can be configured to route traffic to the canary based on HTTP match conditions. +In an A/B testing scenario, you'll be using HTTP headers or cookies to target a certain segment of your users. +This is particularly useful for frontend applications that require session affinity. ![Flagger A/B Testing Stages](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/diagrams/flagger-abtest-steps.png) diff --git a/docs/gitbook/tutorials/gloo-progressive-delivery.md b/docs/gitbook/tutorials/gloo-progressive-delivery.md index d95e434c..6ec09c4f 100644 --- a/docs/gitbook/tutorials/gloo-progressive-delivery.md +++ b/docs/gitbook/tutorials/gloo-progressive-delivery.md @@ -305,7 +305,7 @@ metadata: spec: provider: type: prometheus - address: http://flagger-promethues.gloo-system:9090 + address: http://flagger-prometheus.gloo-system:9090 query: | 100 - sum( rate( diff --git a/docs/gitbook/tutorials/kubernetes-blue-green.md b/docs/gitbook/tutorials/kubernetes-blue-green.md index 0b9cac29..59ff350c 100644 --- a/docs/gitbook/tutorials/kubernetes-blue-green.md +++ b/docs/gitbook/tutorials/kubernetes-blue-green.md @@ -272,7 +272,7 @@ metadata: spec: provider: type: prometheus - address: http://flagger-promethues.flagger:9090 + address: http://flagger-prometheus.flagger:9090 query: | 100 - sum( rate( diff --git a/docs/gitbook/tutorials/nginx-progressive-delivery.md b/docs/gitbook/tutorials/nginx-progressive-delivery.md index 0294127e..e18d91ff 100644 --- a/docs/gitbook/tutorials/nginx-progressive-delivery.md +++ b/docs/gitbook/tutorials/nginx-progressive-delivery.md @@ -305,7 +305,7 @@ metadata: spec: provider: type: prometheus - address: http://flagger-promethues.ingress-nginx:9090 + address: http://flagger-prometheus.ingress-nginx:9090 query: | histogram_quantile(0.99, sum( diff --git a/docs/gitbook/tutorials/skipper-progressive-delivery.md b/docs/gitbook/tutorials/skipper-progressive-delivery.md new file mode 100644 index 00000000..3cc3d17f --- /dev/null +++ b/docs/gitbook/tutorials/skipper-progressive-delivery.md @@ -0,0 +1,375 @@ +# Skipper Canary Deployments + +This guide shows you how to use the [Skipper ingress controller](https://opensource.zalando.com/skipper/kubernetes/ingress-controller/) and Flagger to automate canary deployments. + +![Flagger Skipper Ingress Controller](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/diagrams/flagger-skipper-overview.png) + +## Prerequisites + +Flagger requires a Kubernetes cluster **v1.14** or newer and Skipper ingress **0.11.40** or newer. + +Install Skipper ingress-controller using [upstream definition](https://opensource.zalando.com/skipper/kubernetes/ingress-controller/#install-skipper-as-ingress-controller). + +Certain arguments are relevant: + +```yaml +- -enable-connection-metrics +- -histogram-metric-buckets=.01,1,10,100 +- -kubernetes +- -kubernetes-in-cluster +- -kubernetes-path-mode=path-prefix +- -metrics-exp-decay-sample +- -metrics-flavour=prometheus +- -route-backend-metrics +- -route-backend-error-counters +- -route-response-metrics +- -serve-host-metrics +- -serve-route-metrics +- -whitelisted-healthcheck-cidr=0.0.0.0/0 # permit Kind source health checks +``` + +Install Flagger using kustomize: + +```bash +kustomize build https://github.com/weaveworks/flagger/kustomize/kubernetes | kubectl apply -f - +``` + +## Bootstrap + +Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler (HPA), +then creates a series of objects (Kubernetes deployments, ClusterIP services and canary ingress). +These objects expose the application outside the cluster and drive the canary analysis and promotion. + +Create a test namespace: + +```bash +kubectl create ns test +``` + +Create a deployment and a horizontal pod autoscaler: + +```bash +kubectl apply -k github.com/weaveworks/flagger//kustomize/podinfo +``` + +Deploy the load testing service to generate traffic during the canary analysis: + +```bash +helm upgrade -i flagger-loadtester flagger/loadtester \ +--namespace=test +``` + +Create an ingress definition \(replace `app.example.com` with your own domain\): + +```yaml +apiVersion: networking.k8s.io/v1beta1 +kind: Ingress +metadata: + name: podinfo + namespace: test + labels: + app: podinfo + annotations: + kubernetes.io/ingress.class: "skipper" +spec: + rules: + - host: app.example.com + http: + paths: + - backend: + serviceName: podinfo + servicePort: 80 +``` + +Save the above resource as podinfo-ingress.yaml and then apply it: + +```bash +kubectl apply -f ./podinfo-ingress.yaml +``` + +Create a canary custom resource \(replace `app.example.com` with your own domain\): + +```yaml +apiVersion: flagger.app/v1beta1 +kind: Canary +metadata: + name: podinfo + namespace: test +spec: + provider: skipper + # deployment reference + targetRef: + apiVersion: apps/v1 + kind: Deployment + name: podinfo + # ingress reference + ingressRef: + apiVersion: networking.k8s.io/v1beta1 + kind: Ingress + name: podinfo + # HPA reference (optional) + autoscalerRef: + apiVersion: autoscaling/v2beta1 + kind: HorizontalPodAutoscaler + name: podinfo + # the maximum time in seconds for the canary deployment + # to make progress before it is rollback (default 600s) + progressDeadlineSeconds: 60 + service: + # ClusterIP port number + port: 80 + # container port number or name + targetPort: 9898 + analysis: + # schedule interval (default 60s) + interval: 10s + # max number of failed metric checks before rollback + threshold: 10 + # max traffic percentage routed to canary + # percentage (0-100) + maxWeight: 50 + # canary increment step + # percentage (0-100) + stepWeight: 5 + # Skipper Prometheus checks + metrics: + - name: request-success-rate + interval: 1m + # minimum req success rate (non 5xx responses) + # percentage (0-100) + thresholdRange: + min: 99 + - name: request-duration + interval: 1m + # maximum req duration P99 + # milliseconds + thresholdRange: + max: 500 + webhooks: + - name: gate + type: confirm-rollout + url: http://flagger-loadtester.test/gate/approve + - name: acceptance-test + type: pre-rollout + url: http://flagger-loadtester.test/ + timeout: 10s + metadata: + type: bash + cmd: "curl -sd 'test' http://podinfo-canary/token | grep token" + - name: load-test + type: rollout + url: http://flagger-loadtester.test/ + timeout: 5s + metadata: + type: cmd + cmd: "hey -z 10m -q 10 -c 2 -host app.example.com http://skipper-ingress.kube-system" + logCmdOutput: "true" +``` + +Save the above resource as podinfo-canary.yaml and then apply it: + +```bash +kubectl apply -f ./podinfo-canary.yaml +``` + +After a couple of seconds Flagger will create the canary objects: + +```bash +# applied +deployment.apps/podinfo +horizontalpodautoscaler.autoscaling/podinfo +ingress.networking.k8s.io/podinfo-ingress +canary.flagger.app/podinfo + +# generated +deployment.apps/podinfo-primary +horizontalpodautoscaler.autoscaling/podinfo-primary +service/podinfo +service/podinfo-canary +service/podinfo-primary +ingress.networking.k8s.io/podinfo-canary +``` + +## Automated canary promotion + +Flagger implements a control loop that gradually shifts traffic to the canary while measuring +key performance indicators like HTTP requests success rate, requests average duration and pod health. +Based on analysis of the KPIs a canary is promoted or aborted, and the analysis result is published to Slack or MS Teams. + +![Flagger Canary Stages](https://raw.githubusercontent.com/weaveworks/flagger/master/docs/diagrams/flagger-canary-steps.png) + +Trigger a canary deployment by updating the container image: + +```bash +kubectl -n test set image deployment/podinfo \ +podinfod=stefanprodan/podinfo:4.0.6 +``` + +Flagger detects that the deployment revision changed and starts a new rollout: + +```text +kubectl -n test describe canary/podinfo + +Status: + Canary Weight: 0 + Failed Checks: 0 + Phase: Succeeded +Events: + New revision detected! Scaling up podinfo.test + Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available + Pre-rollout check acceptance-test passed + Advance podinfo.test canary weight 5 + Advance podinfo.test canary weight 10 + Advance podinfo.test canary weight 15 + Advance podinfo.test canary weight 20 + Advance podinfo.test canary weight 25 + Advance podinfo.test canary weight 30 + Advance podinfo.test canary weight 35 + Advance podinfo.test canary weight 40 + Advance podinfo.test canary weight 45 + Advance podinfo.test canary weight 50 + Copying podinfo.test template spec to podinfo-primary.test + Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available + Routing all traffic to primary + Promotion completed! Scaling down podinfo.test +``` + +**Note** that if you apply new changes to the deployment during the canary analysis, Flagger will restart the analysis. + +You can monitor all canaries with: + +```bash +watch kubectl get canaries --all-namespaces + +NAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIME +test podinfo-2 Progressing 30 2020-08-14T12:32:12Z +test podinfo Succeeded 0 2020-08-14T11:23:88Z +``` + +## Automated rollback + +During the canary analysis you can generate HTTP 500 errors to test if Flagger pauses and rolls back the faulted version. + +Trigger another canary deployment: + +```bash +kubectl -n test set image deployment/podinfo \ +podinfod=stefanprodan/podinfo:4.0.6 +``` + +Exec into the load tester pod with: + +```bash +kubectl -n test exec -it deploy/flagger-loadtester bash +``` + +Generate HTTP 500 errors: + +```bash +hey -z 1m -c 5 -q 5 http://app.example.com/status/500 +``` + +Generate latency: + +```bash +watch -n 1 curl http://app.example.com/delay/1 +``` + +When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, +the canary is scaled to zero and the rollout is marked as failed. + +```text +kubectl -n flagger-system logs deploy/flagger -f | jq .msg + +New revision detected! Scaling up podinfo.test +Canary deployment podinfo.test not ready: waiting for rollout to finish: 0 of 1 updated replicas are available +Starting canary analysis for podinfo.test +Pre-rollout check acceptance-test passed +Advance podinfo.test canary weight 5 +Advance podinfo.test canary weight 10 +Advance podinfo.test canary weight 15 +Advance podinfo.test canary weight 20 +Halt podinfo.test advancement success rate 53.42% < 99% +Halt podinfo.test advancement success rate 53.19% < 99% +Halt podinfo.test advancement success rate 48.05% < 99% +Rolling back podinfo.test failed checks threshold reached 3 +Canary failed! Scaling down podinfo.test +``` + +## Custom metrics + +The canary analysis can be extended with Prometheus queries. + +Create a metric template and apply it on the cluster: + +```yaml +apiVersion: flagger.app/v1beta1 +kind: MetricTemplate +metadata: + name: latency + namespace: test +spec: + provider: + type: prometheus + address: http://flagger-prometheus.flagger-system:9090 + query: | + histogram_quantile(0.99, + sum( + rate( + skipper_serve_route_duration_seconds_bucket{ + route=~"{{ printf "kube(ew)?_%s__%s_canary__.*__%s_canary(_[0-9]+)?" namespace ingress service }}", + le="+Inf" + }[1m] + ) + ) by (le) + ) +``` + +Edit the canary analysis and add the latency check: + +```yaml + analysis: + metrics: + - name: "latency" + templateRef: + name: latency + thresholdRange: + max: 0.5 + interval: 1m +``` + +The threshold is set to 500ms so if the average request duration in the last minute goes over half a second +then the analysis will fail and the canary will not be promoted. + +Trigger a canary deployment by updating the container image: + +```bash +kubectl -n test set image deployment/podinfo \ +podinfod=stefanprodan/podinfo:4.0.6 +``` + +Generate high response latency: + +```bash +watch curl http://app.exmaple.com/delay/2 +``` + +Watch Flagger logs: + +```text +kubectl -n flagger-system logs deployment/flagger -f | jq .msg + +Starting canary deployment for podinfo.test +Advance podinfo.test canary weight 5 +Advance podinfo.test canary weight 10 +Advance podinfo.test canary weight 15 +Halt podinfo.test advancement latency 1.20 > 0.5 +Halt podinfo.test advancement latency 1.45 > 0.5 +Halt podinfo.test advancement latency 1.60 > 0.5 +Halt podinfo.test advancement latency 1.69 > 0.5 +Halt podinfo.test advancement latency 1.70 > 0.5 +Rolling back podinfo.test failed checks threshold reached 5 +Canary failed! Scaling down podinfo.test +``` + +If you have alerting configured, Flagger will send a notification with the reason why the canary failed. diff --git a/docs/gitbook/usage/deployment-strategies.md b/docs/gitbook/usage/deployment-strategies.md index 4033d3cd..80af7348 100644 --- a/docs/gitbook/usage/deployment-strategies.md +++ b/docs/gitbook/usage/deployment-strategies.md @@ -2,7 +2,7 @@ Flagger can run automated application analysis, promotion and rollback for the following deployment strategies: * **Canary Release** (progressive traffic shifting) - * Istio, Linkerd, App Mesh, NGINX, Contour, Gloo + * Istio, Linkerd, App Mesh, NGINX, Skipper, Contour, Gloo * **A/B Testing** (HTTP headers and cookies traffic routing) * Istio, App Mesh, NGINX, Contour * **Blue/Green** (traffic switching) diff --git a/docs/gitbook/usage/how-it-works.md b/docs/gitbook/usage/how-it-works.md index 4aa1719d..7e44d1ef 100644 --- a/docs/gitbook/usage/how-it-works.md +++ b/docs/gitbook/usage/how-it-works.md @@ -75,16 +75,11 @@ Based on the above configuration, Flagger generates the following Kubernetes obj * `deployment/-primary` * `hpa/-primary` -The primary deployment is considered the stable release of your app, by default all traffic is routed to this version +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. Flagger will detect changes to the target deployment (including secrets and configmaps) and will perform a canary analysis before promoting the new version as primary. -If the target deployment uses secrets and/or configmaps, Flagger will create a copy of each object using the `-primary` -prefix and will reference these objects in the primary deployment. You can disable the secrets/configmaps tracking -with the `-enable-config-tracking=false` command flag in the Flagger deployment manifest under containers args -or by setting `--set configTracking.enabled=false` when installing Flagger with Helm. - **Note** that the target deployment must have a single label selector in the format `app: `: ```yaml @@ -102,11 +97,20 @@ spec: app: podinfo ``` -Besides `app` Flagger supports `name` and `app.kubernetes.io/name` selectors. +In addition to `app`, Flagger supports `name` and `app.kubernetes.io/name` selectors. If you use a different convention you can specify your label with the `-selector-labels=my-app-label` command flag in the Flagger deployment manifest under containers args or by setting `--set selectorLabels=my-app-label` when installing Flagger with Helm. +If the target deployment uses secrets and/or configmaps, Flagger will create a copy of each object using the `-primary` +suffix and will reference these objects in the primary deployment. If you annotate your ConfigMap or Secret with +`flagger.app/config-tracking: disabled`, Flagger will use the same object for the primary deployment instead of making +a primary copy. +You can disable the secrets/configmaps tracking globally with the `-enable-config-tracking=false` command flag in +the Flagger deployment manifest under containers args or by setting `--set configTracking.enabled=false` when +installing Flagger with Helm, but disabling config-tracking using the the per Secret/ConfigMap annotation may fit your +use-case better. + The autoscaler reference is optional, when specified, Flagger will pause the traffic increase while the target and primary deployments are scaled up or down. HPA can help reduce the resource usage during the canary analysis. diff --git a/docs/gitbook/usage/metrics.md b/docs/gitbook/usage/metrics.md index 4896da1b..8ba9c8e7 100644 --- a/docs/gitbook/usage/metrics.md +++ b/docs/gitbook/usage/metrics.md @@ -95,7 +95,7 @@ metadata: spec: provider: type: prometheus - address: http://promethues.istio-system:9090 + address: http://prometheus.istio-system:9090 query: | 100 - sum( rate( @@ -148,7 +148,7 @@ metadata: spec: provider: type: prometheus - address: http://flagger-promethues.flagger-system:9090 + address: http://flagger-prometheus.flagger-system:9090 query: | 100 - sum( rate( diff --git a/go.mod b/go.mod index 072fbf72..6255481b 100644 --- a/go.mod +++ b/go.mod @@ -10,11 +10,13 @@ require ( github.com/prometheus/client_golang v1.5.1 github.com/stretchr/testify v1.5.1 go.uber.org/zap v1.14.1 + golang.org/x/net v0.0.0-20200301022130-244492dfa37a // indirect + golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d // indirect gopkg.in/h2non/gock.v1 v1.0.15 - k8s.io/api v0.18.2 - k8s.io/apimachinery v0.18.2 - k8s.io/client-go v0.18.2 - k8s.io/code-generator v0.18.2 + k8s.io/api v0.18.8 + k8s.io/apimachinery v0.18.8 + k8s.io/client-go v0.18.8 + k8s.io/code-generator v0.18.8 ) replace k8s.io/klog => github.com/stefanprodan/klog v0.0.0-20190418165334-9cbb78b20423 diff --git a/go.sum b/go.sum index b0bfe8ef..01e48ac3 100644 --- a/go.sum +++ b/go.sum @@ -40,8 +40,8 @@ github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZ github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/evanphx/json-patch v4.2.0+incompatible h1:fUDGZCv/7iAN7u0puUVhvKCcsR6vRfwrJatElLBEf0I= -github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v0.0.0-20200808040245-162e5629780b h1:vCplRbYcTTeBVLjIU0KvipEeVBSxl6sakUBRmeLBTkw= +github.com/evanphx/json-patch v0.0.0-20200808040245-162e5629780b/go.mod h1:NAJj0yf/KaRKURN6nyi7A9IZydMivZEm9oQLWNjfKDc= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -114,6 +114,7 @@ github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= @@ -187,6 +188,7 @@ github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLk github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= @@ -219,6 +221,7 @@ golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 h1:/Tl7pH94bvbAAHBdZJT947M/+gp0+CqQXDtMRC0fseo= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -228,6 +231,8 @@ golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -244,6 +249,8 @@ golang.org/x/net v0.0.0-20191004110552-13f9640d40b9 h1:rjwSpXsdiK0dV8/Naq3kAw9ym golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a h1:GuSPYbZzB5/dcLNCwLQLsg3obCJtX9IJhpXkvY7kzk0= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421 h1:Wo7BWFiOk0QRFMLYMqJGFMd9CgUAcGx7V+qEg/h5IBI= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -292,7 +299,10 @@ golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64bikrLBkAgPir1TNCj3Zs= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d h1:7M9AXzLrJWWGdDYtBblPHBTnHtaN6KKQ98OYb35mLlY= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= @@ -333,20 +343,20 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -k8s.io/api v0.18.2 h1:wG5g5ZmSVgm5B+eHMIbI9EGATS2L8Z72rda19RIEgY8= -k8s.io/api v0.18.2/go.mod h1:SJCWI7OLzhZSvbY7U8zwNl9UA4o1fizoug34OV/2r78= -k8s.io/apimachinery v0.18.2 h1:44CmtbmkzVDAhCpRVSiP2R5PPrC2RtlIv/MoB8xpdRA= -k8s.io/apimachinery v0.18.2/go.mod h1:9SnR/e11v5IbyPCGbvJViimtJ0SwHG4nfZFjU77ftcA= -k8s.io/client-go v0.18.2 h1:aLB0iaD4nmwh7arT2wIn+lMnAq7OswjaejkQ8p9bBYE= -k8s.io/client-go v0.18.2/go.mod h1:Xcm5wVGXX9HAA2JJ2sSBUn3tCJ+4SVlCbl2MNNv+CIU= -k8s.io/code-generator v0.18.2 h1:C1Nn2JiMf244CvBDKVPX0W2mZFJkVBg54T8OV7/Imso= -k8s.io/code-generator v0.18.2/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRVkTc= +k8s.io/api v0.18.8 h1:aIKUzJPb96f3fKec2lxtY7acZC9gQNDLVhfSGpxBAC4= +k8s.io/api v0.18.8/go.mod h1:d/CXqwWv+Z2XEG1LgceeDmHQwpUJhROPx16SlxJgERY= +k8s.io/apimachinery v0.18.8 h1:jimPrycCqgx2QPearX3to1JePz7wSbVLq+7PdBTTwQ0= +k8s.io/apimachinery v0.18.8/go.mod h1:6sQd+iHEqmOtALqOFjSWp2KZ9F0wlU/nWm0ZgsYWMig= +k8s.io/client-go v0.18.8 h1:SdbLpIxk5j5YbFr1b7fq8S7mDgDjYmUxSbszyoesoDM= +k8s.io/client-go v0.18.8/go.mod h1:HqFqMllQ5NnQJNwjro9k5zMyfhZlOwpuTLVrxjkYSxU= +k8s.io/code-generator v0.18.8 h1:lgO1P1wjikEtzNvj7ia+x1VC4svJ28a/r0wnOLhhOTU= +k8s.io/code-generator v0.18.8/go.mod h1:TgNEVx9hCyPGpdtCWA34olQYLkh3ok9ar7XfSsr8b6c= k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6 h1:4s3/R4+OYYYUKptXPhZKjQ04WJ6EhQQVFdjOFvCazDk= k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20200114144118-36b2048a9120 h1:RPscN6KhmG54S33L+lr3GS+oD1jmchIU0ll519K6FA4= k8s.io/gengo v0.0.0-20200114144118-36b2048a9120/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= -k8s.io/kube-openapi v0.0.0-20200121204235-bf4fb3bd569c h1:/KUFqjjqAcY4Us6luF5RDNZ16KJtb49HfR3ZHB9qYXM= -k8s.io/kube-openapi v0.0.0-20200121204235-bf4fb3bd569c/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6 h1:Oh3Mzx5pJ+yIumsAD0MOECPVeXsVot0UkiaCGVyfGQY= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89 h1:d4vVOjXm687F1iLSP2q3lyPPuyvTUt3aVoBpi2DqRsU= k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= sigs.k8s.io/structured-merge-diff/v3 v3.0.0-20200116222232-67a7b8c61874/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= diff --git a/kustomize/README.md b/kustomize/README.md index ccd0750f..b50b9007 100644 --- a/kustomize/README.md +++ b/kustomize/README.md @@ -5,14 +5,14 @@ As an alternative to Helm, Flagger can be installed with [Kustomize](https://kus **Prerequisites** - Kubernetes cluster **>=1.13.0** -- Kustomize **>=3.5.0** +- Kustomize **>=3.6.0** ## Service mesh specific installers Install Flagger for Istio: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/istio | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/istio | kubectl apply -f - ``` This deploys Flagger in the `istio-system` namespace and sets the metrics server URL to Istio's Prometheus instance. @@ -20,7 +20,7 @@ This deploys Flagger in the `istio-system` namespace and sets the metrics server Install Flagger for AWS App Mesh: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/appmesh | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/appmesh | kubectl apply -f - ``` This deploys Flagger in the `appmesh-system` namespace and sets the metrics server URL to App Mesh Prometheus instance. @@ -28,7 +28,7 @@ This deploys Flagger in the `appmesh-system` namespace and sets the metrics serv Install Flagger for Linkerd: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/linkerd | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/linkerd | kubectl apply -f - ``` This deploys Flagger in the `linkerd` namespace and sets the metrics server URL to Linkerd's Prometheus instance. @@ -36,13 +36,13 @@ This deploys Flagger in the `linkerd` namespace and sets the metrics server URL If you want to install a specific Flagger release, add the version number to the URL: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/linkerd?ref=0.18.0 | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/linkerd?ref=v1.0.0 | kubectl apply -f - ``` Install Flagger for Contour: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/contour | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/contour | kubectl apply -f - ``` This deploys Flagger and Prometheus in the `projectcontour` namespace and sets Prometheus to scrape Contour's Envoy instances. @@ -52,7 +52,7 @@ This deploys Flagger and Prometheus in the `projectcontour` namespace and sets P Install Flagger and Prometheus: ```bash -kustomize build github.com/weaveworks/flagger//kustomize/kubernetes | kubectl apply -f - +kustomize build https://github.com/weaveworks/flagger/kustomize/kubernetes | kubectl apply -f - ``` This deploys Flagger and Prometheus in the `flagger-system` namespace, @@ -67,12 +67,12 @@ metadata: name: app namespace: test spec: - # can be: kubernetes, istio, linkerd, appmesh, nginx, gloo + # can be: kubernetes, istio, linkerd, appmesh, nginx, skipper, gloo # use the kubernetes provider for Blue/Green style deployments provider: nginx ``` -You'll need Prometheus when using Flagger with AWS App Mesh, Gloo or NGINX ingress controller. +You'll need Prometheus when using Flagger with AWS App Mesh, Gloo, NGINX or Skipper ingress controller. The Prometheus instance has a two hours data retention and is configured to scrape all pods in your cluster that have the `prometheus.io/scrape: "true"` annotation. diff --git a/kustomize/base/flagger/deployment.yaml b/kustomize/base/flagger/deployment.yaml index c8311943..f88be587 100644 --- a/kustomize/base/flagger/deployment.yaml +++ b/kustomize/base/flagger/deployment.yaml @@ -20,7 +20,7 @@ spec: serviceAccountName: flagger containers: - name: flagger - image: weaveworks/flagger:0.21.0 + image: weaveworks/flagger:1.0.0 imagePullPolicy: IfNotPresent ports: - name: http diff --git a/kustomize/base/flagger/kustomization.yaml b/kustomize/base/flagger/kustomization.yaml index ad9e0c45..b4859564 100644 --- a/kustomize/base/flagger/kustomization.yaml +++ b/kustomize/base/flagger/kustomization.yaml @@ -8,4 +8,4 @@ resources: - deployment.yaml images: - name: weaveworks/flagger - newTag: 1.0.0 + newTag: 1.1.0 diff --git a/kustomize/tester/deployment.yaml b/kustomize/tester/deployment.yaml index 5915fefa..b25e8150 100644 --- a/kustomize/tester/deployment.yaml +++ b/kustomize/tester/deployment.yaml @@ -18,7 +18,7 @@ spec: spec: containers: - name: loadtester - image: weaveworks/flagger-loadtester:0.17.0 + image: weaveworks/flagger-loadtester:0.18.0 imagePullPolicy: IfNotPresent ports: - name: http diff --git a/pkg/apis/flagger/v1beta1/provider.go b/pkg/apis/flagger/v1beta1/provider.go index 9dbcf017..a27bbc88 100644 --- a/pkg/apis/flagger/v1beta1/provider.go +++ b/pkg/apis/flagger/v1beta1/provider.go @@ -9,4 +9,5 @@ const ( GlooProvider string = "gloo" NGINXProvider string = "nginx" KubernetesProvider string = "kubernetes" + SkipperProvider string = "skipper" ) diff --git a/pkg/canary/config_tracker.go b/pkg/canary/config_tracker.go index 2f939be9..dffc9f3f 100644 --- a/pkg/canary/config_tracker.go +++ b/pkg/canary/config_tracker.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/json" "fmt" + "strings" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" @@ -29,6 +30,8 @@ type ConfigRefType string const ( ConfigRefMap ConfigRefType = "configmap" ConfigRefSecret ConfigRefType = "secret" + + configTrackingDisabledAnnotationKey = "flagger.app/config-tracking" ) // ConfigRef holds the reference to a tracked Kubernetes ConfigMap or Secret @@ -50,6 +53,10 @@ func checksum(data interface{}) string { return fmt.Sprintf("%x", hashBytes[:8]) } +func configIsDisabled(annotations map[string]string) bool { + return strings.HasPrefix(annotations[configTrackingDisabledAnnotationKey], "disable") +} + // getRefFromConfigMap transforms a Kubernetes ConfigMap into a ConfigRef // and computes the checksum of the ConfigMap data func (ct *ConfigTracker) getRefFromConfigMap(name string, namespace string) (*ConfigRef, error) { @@ -58,6 +65,10 @@ func (ct *ConfigTracker) getRefFromConfigMap(name string, namespace string) (*Co return nil, fmt.Errorf("configmap %s.%s get query error: %w", name, namespace, err) } + if configIsDisabled(config.GetAnnotations()) { + return nil, nil + } + return &ConfigRef{ Name: config.Name, Type: ConfigRefMap, @@ -82,6 +93,10 @@ func (ct *ConfigTracker) getRefFromSecret(name string, namespace string) (*Confi return nil, nil } + if configIsDisabled(secret.GetAnnotations()) { + return nil, nil + } + return &ConfigRef{ Name: secret.Name, Type: ConfigRefSecret, @@ -92,23 +107,22 @@ func (ct *ConfigTracker) getRefFromSecret(name string, namespace string) (*Confi // GetTargetConfigs scans the target deployment for Kubernetes ConfigMaps and Secretes // and returns a list of config references func (ct *ConfigTracker) GetTargetConfigs(cd *flaggerv1.Canary) (map[string]ConfigRef, error) { - res := make(map[string]ConfigRef) targetName := cd.Spec.TargetRef.Name - var vs []corev1.Volume var cs []corev1.Container + switch cd.Spec.TargetRef.Kind { case "Deployment": targetDep, err := ct.KubeClient.AppsV1().Deployments(cd.Namespace).Get(context.TODO(), targetName, metav1.GetOptions{}) if err != nil { - return res, fmt.Errorf("deployment %s.%s get query error: %w", targetName, cd.Namespace, err) + return nil, fmt.Errorf("deployment %s.%s get query error: %w", targetName, cd.Namespace, err) } vs = targetDep.Spec.Template.Spec.Volumes cs = targetDep.Spec.Template.Spec.Containers case "DaemonSet": targetDae, err := ct.KubeClient.AppsV1().DaemonSets(cd.Namespace).Get(context.TODO(), targetName, metav1.GetOptions{}) if err != nil { - return res, fmt.Errorf("daemonset %s.%s get query error: %w", targetName, cd.Namespace, err) + return nil, fmt.Errorf("daemonset %s.%s get query error: %w", targetName, cd.Namespace, err) } vs = targetDae.Spec.Template.Spec.Volumes cs = targetDae.Spec.Template.Spec.Containers @@ -116,48 +130,31 @@ func (ct *ConfigTracker) GetTargetConfigs(cd *flaggerv1.Canary) (map[string]Conf return nil, fmt.Errorf("TargetRef.Kind invalid: %s", cd.Spec.TargetRef.Kind) } + type void struct{} + var member void + secretNames := map[string]void{} + configMapNames := map[string]void{} + // scan volumes for _, volume := range vs { if cmv := volume.ConfigMap; cmv != nil { - config, err := ct.getRefFromConfigMap(cmv.Name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromConfigMap failed: %v", err) - continue - } - res[config.GetName()] = *config + name := cmv.Name + configMapNames[name] = member } - if sv := volume.Secret; sv != nil { - secret, err := ct.getRefFromSecret(sv.SecretName, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromSecret failed: %v", err) - continue - } - if secret != nil { - res[secret.GetName()] = *secret - } + name := sv.SecretName + secretNames[name] = member } if projected := volume.Projected; projected != nil { for _, source := range projected.Sources { if cmv := source.ConfigMap; cmv != nil { - config, err := ct.getRefFromConfigMap(cmv.Name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromConfigMap failed: %v", err) - continue - } - res[config.GetName()] = *config + name := cmv.Name + configMapNames[name] = member } - if sv := source.Secret; sv != nil { - secret, err := ct.getRefFromSecret(sv.Name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromSecret failed: %v", err) - continue - } - if secret != nil { - res[secret.GetName()] = *secret - } + name := sv.Name + secretNames[name] = member } } } @@ -170,22 +167,10 @@ func (ct *ConfigTracker) GetTargetConfigs(cd *flaggerv1.Canary) (map[string]Conf switch { case env.ValueFrom.ConfigMapKeyRef != nil: name := env.ValueFrom.ConfigMapKeyRef.LocalObjectReference.Name - config, err := ct.getRefFromConfigMap(name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromConfigMap failed: %v", err) - continue - } - res[config.GetName()] = *config + configMapNames[name] = member case env.ValueFrom.SecretKeyRef != nil: name := env.ValueFrom.SecretKeyRef.LocalObjectReference.Name - secret, err := ct.getRefFromSecret(name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromSecret failed: %v", err) - continue - } - if secret != nil { - res[secret.GetName()] = *secret - } + secretNames[name] = member } } } @@ -194,26 +179,37 @@ func (ct *ConfigTracker) GetTargetConfigs(cd *flaggerv1.Canary) (map[string]Conf switch { case envFrom.ConfigMapRef != nil: name := envFrom.ConfigMapRef.LocalObjectReference.Name - config, err := ct.getRefFromConfigMap(name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromConfigMap failed %v", err) - continue - } - res[config.GetName()] = *config + configMapNames[name] = member case envFrom.SecretRef != nil: name := envFrom.SecretRef.LocalObjectReference.Name - secret, err := ct.getRefFromSecret(name, cd.Namespace) - if err != nil { - ct.Logger.Errorf("getRefFromSecret failed %v", err) - continue - } - if secret != nil { - res[secret.GetName()] = *secret - } + secretNames[name] = member } } } + res := make(map[string]ConfigRef) + + for configMapName := range configMapNames { + config, err := ct.getRefFromConfigMap(configMapName, cd.Namespace) + if err != nil { + ct.Logger.Errorf("getRefFromConfigMap failed: %v", err) + continue + } + if config != nil { + res[config.GetName()] = *config + } + } + for secretName := range secretNames { + secret, err := ct.getRefFromSecret(secretName, cd.Namespace) + if err != nil { + ct.Logger.Errorf("getRefFromSecret failed: %v", err) + continue + } + if secret != nil { + res[secret.GetName()] = *secret + } + } + return res, nil } diff --git a/pkg/canary/config_tracker_test.go b/pkg/canary/config_tracker_test.go index fb8d0d05..d7bbae2b 100644 --- a/pkg/canary/config_tracker_test.go +++ b/pkg/canary/config_tracker_test.go @@ -10,6 +10,19 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +func TestConfigIsDisabled(t *testing.T) { + for _, c := range []struct { + annotations map[string]string + exp bool + }{ + {annotations: map[string]string{configTrackingDisabledAnnotationKey: "disable"}, exp: true}, + {annotations: map[string]string{"app": "disable"}, exp: false}, + {annotations: map[string]string{}, exp: false}, + } { + assert.Equal(t, configIsDisabled(c.annotations), c.exp) + } +} + func TestConfigTracker_ConfigMaps(t *testing.T) { t.Run("deployment", func(t *testing.T) { mocks := newDeploymentFixture() @@ -46,6 +59,33 @@ func TestConfigTracker_ConfigMaps(t *testing.T) { if assert.NoError(t, err) { assert.Equal(t, configMapProjected.Data["color"], configPrimaryProjected.Data["color"]) } + + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-enabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-enabled-primary", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-disabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-disabled-primary", metav1.GetOptions{}) + assert.Error(t, err) + + var trackedVolPresent, originalVolPresent bool + for _, vol := range depPrimary.Spec.Template.Spec.Volumes { + if vol.ConfigMap != nil { + switch vol.ConfigMap.Name { + case "podinfo-config-tracker-enabled": + assert.Fail(t, "primary Deployment does not contain a volume for config-tracked configmap %q", vol.ConfigMap.Name) + case "podinfo-config-tracker-enabled-primary": + trackedVolPresent = true + case "podinfo-config-tracker-disabled": + originalVolPresent = true + case "podinfo-config-tracker-disabled-primary": + assert.Fail(t, "primary Deployment incorrectly contains a volume for a copy of an untracked configmap %q", vol.ConfigMap.Name) + } + } + } + assert.True(t, trackedVolPresent, "Volume for primary copy of config-tracked configmap should be present") + assert.True(t, originalVolPresent, "Volume for original configmap with disabled tracking should be present") }) t.Run("daemonset", func(t *testing.T) { @@ -56,10 +96,10 @@ func TestConfigTracker_ConfigMaps(t *testing.T) { err := mocks.controller.Initialize(mocks.canary) require.NoError(t, err) - depPrimary, err := mocks.kubeClient.AppsV1().DaemonSets("default").Get(context.TODO(), "podinfo-primary", metav1.GetOptions{}) + daePrimary, err := mocks.kubeClient.AppsV1().DaemonSets("default").Get(context.TODO(), "podinfo-primary", metav1.GetOptions{}) require.NoError(t, err) - configPrimaryVolName := depPrimary.Spec.Template.Spec.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name + configPrimaryVolName := daePrimary.Spec.Template.Spec.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name assert.Equal(t, "podinfo-config-vol-primary", configPrimaryVolName) configPrimary, err := mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-env-primary", metav1.GetOptions{}) @@ -77,13 +117,40 @@ func TestConfigTracker_ConfigMaps(t *testing.T) { assert.Equal(t, configMap.Data["color"], configPrimaryVol.Data["color"]) } - configProjectedName := depPrimary.Spec.Template.Spec.Volumes[2].VolumeSource.Projected.Sources[0].ConfigMap.Name + configProjectedName := daePrimary.Spec.Template.Spec.Volumes[2].VolumeSource.Projected.Sources[0].ConfigMap.Name assert.Equal(t, "podinfo-config-projected-primary", configProjectedName) configPrimaryProjected, err := mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-vol-primary", metav1.GetOptions{}) if assert.NoError(t, err) { assert.Equal(t, configMapProjected.Data["color"], configPrimaryProjected.Data["color"]) } + + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-enabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-enabled-primary", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-disabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().ConfigMaps("default").Get(context.TODO(), "podinfo-config-tracker-disabled-primary", metav1.GetOptions{}) + assert.Error(t, err) + + var trackedVolPresent, originalVolPresent bool + for _, vol := range daePrimary.Spec.Template.Spec.Volumes { + if vol.ConfigMap != nil { + switch vol.ConfigMap.Name { + case "podinfo-config-tracker-enabled": + assert.Fail(t, "primary Deployment does not contain a volume for config-tracked configmap %q", vol.ConfigMap.Name) + case "podinfo-config-tracker-enabled-primary": + trackedVolPresent = true + case "podinfo-config-tracker-disabled": + originalVolPresent = true + case "podinfo-config-tracker-disabled-primary": + assert.Fail(t, "primary Deployment incorrectly contains a volume for a copy of an untracked configmap %q", vol.ConfigMap.Name) + } + } + } + assert.True(t, trackedVolPresent, "Volume for primary copy of config-tracked configmap should be present") + assert.True(t, originalVolPresent, "Volume for original configmap with disabled tracking should be present") }) } @@ -123,6 +190,33 @@ func TestConfigTracker_Secrets(t *testing.T) { if assert.NoError(t, err) { assert.Equal(t, string(secretProjected.Data["apiKey"]), string(secretPrimaryProjected.Data["apiKey"])) } + + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-enabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-enabled-primary", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-disabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-disabled-primary", metav1.GetOptions{}) + assert.Error(t, err) + + var trackedVolPresent, originalVolPresent bool + for _, vol := range depPrimary.Spec.Template.Spec.Volumes { + if vol.Secret != nil { + switch vol.Secret.SecretName { + case "podinfo-secret-tracker-enabled": + assert.Fail(t, "primary Deployment does not contain a volume for config-tracked secret %q", vol.Secret.SecretName) + case "podinfo-secret-tracker-enabled-primary": + trackedVolPresent = true + case "podinfo-secret-tracker-disabled": + originalVolPresent = true + case "podinfo-secret-tracker-disabled-primary": + assert.Fail(t, "primary Deployment incorrectly contains a volume for a copy of an untracked secret %q", vol.Secret.SecretName) + } + } + } + assert.True(t, trackedVolPresent, "Volume for primary copy of config-tracked secret should be present") + assert.True(t, originalVolPresent, "Volume for original secret with disabled tracking should be present") }) t.Run("daemonset", func(t *testing.T) { @@ -160,5 +254,32 @@ func TestConfigTracker_Secrets(t *testing.T) { if assert.NoError(t, err) { assert.Equal(t, string(secretProjected.Data["apiKey"]), string(secretPrimaryProjected.Data["apiKey"])) } + + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-enabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-enabled-primary", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-disabled", metav1.GetOptions{}) + assert.NoError(t, err) + _, err = mocks.kubeClient.CoreV1().Secrets("default").Get(context.TODO(), "podinfo-secret-tracker-disabled-primary", metav1.GetOptions{}) + assert.Error(t, err) + + var trackedVolPresent, originalVolPresent bool + for _, vol := range daePrimary.Spec.Template.Spec.Volumes { + if vol.Secret != nil { + switch vol.Secret.SecretName { + case "podinfo-secret-tracker-enabled": + assert.Fail(t, "primary Deployment does not contain a volume for config-tracked secret %q", vol.Secret.SecretName) + case "podinfo-secret-tracker-enabled-primary": + trackedVolPresent = true + case "podinfo-secret-tracker-disabled": + originalVolPresent = true + case "podinfo-secret-tracker-disabled-primary": + assert.Fail(t, "primary Deployment incorrectly contains a volume for a copy of an untracked secret %q", vol.Secret.SecretName) + } + } + } + assert.True(t, trackedVolPresent, "Volume for primary copy of config-tracked secret should be present") + assert.True(t, originalVolPresent, "Volume for original secret with disabled tracking should be present") }) } diff --git a/pkg/canary/daemonset_fixture_test.go b/pkg/canary/daemonset_fixture_test.go index d0919af0..4d0e8291 100644 --- a/pkg/canary/daemonset_fixture_test.go +++ b/pkg/canary/daemonset_fixture_test.go @@ -35,10 +35,14 @@ func newDaemonSetFixture() daemonSetControllerFixture { newDaemonSetControllerTestConfigMapEnv(), newDaemonSetControllerTestConfigMapVol(), newDaemonSetControllerTestConfigProjected(), + newDaemonSetControllerTestConfigMapTrackerEnabled(), + newDaemonSetControllerTestConfigMapTrackerDisabled(), newDaemonSetControllerTestSecret(), newDaemonSetControllerTestSecretEnv(), newDaemonSetControllerTestSecretVol(), newDaemonSetControllerTestSecretProjected(), + newDaemonSetControllerTestSecretTrackerEnabled(), + newDaemonSetControllerTestSecretTrackerDisabled(), ) logger, _ := logger.NewLogger("debug") @@ -130,6 +134,42 @@ func newDaemonSetControllerTestConfigMapVol() *corev1.ConfigMap { } } +func newDaemonSetControllerTestConfigMapTrackerEnabled() *corev1.ConfigMap { + return &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-config-tracker-enabled", + Annotations: map[string]string{ + "unrelated-annotation-1": ":)", + "flagger.app/config-tracking": "enabled", + "unrelated-annotation-2": "<3", + }, + }, + Data: map[string]string{ + "color": "red", + }, + } +} + +func newDaemonSetControllerTestConfigMapTrackerDisabled() *corev1.ConfigMap { + return &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-config-tracker-disabled", + Annotations: map[string]string{ + "unrelated-annotation-1": "c:", + "flagger.app/config-tracking": "disabled", + "unrelated-annotation-2": "^-^", + }, + }, + Data: map[string]string{ + "color": "red", + }, + } +} + func newDaemonSetControllerTestSecret() *corev1.Secret { return &corev1.Secret{ TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, @@ -186,6 +226,44 @@ func newDaemonSetControllerTestSecretVol() *corev1.Secret { } } +func newDaemonSetControllerTestSecretTrackerEnabled() *corev1.Secret { + return &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-secret-tracker-enabled", + Annotations: map[string]string{ + "unrelated-annotation-1": ":)", + "flagger.app/config-tracking": "enabled", + "unrelated-annotation-2": "<3", + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "apiKey": []byte("test"), + }, + } +} + +func newDaemonSetControllerTestSecretTrackerDisabled() *corev1.Secret { + return &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-secret-tracker-disabled", + Annotations: map[string]string{ + "unrelated-annotation-1": "c:", + "flagger.app/config-tracking": "disabled", + "unrelated-annotation-2": "^-^", + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "apiKey": []byte("test"), + }, + } +} + func newDaemonSetControllerTestCanary() *flaggerv1.Canary { cd := &flaggerv1.Canary{ TypeMeta: metav1.TypeMeta{APIVersion: flaggerv1.SchemeGroupVersion.String()}, @@ -297,6 +375,26 @@ func newDaemonSetControllerTestPodInfo() *appsv1.DaemonSet { MountPath: "/etc/podinfo/secret", ReadOnly: true, }, + { + Name: "config-tracker-enabled", + MountPath: "/etc/podinfo/config-tracker-enabled", + ReadOnly: true, + }, + { + Name: "config-tracker-disabled", + MountPath: "/etc/podinfo/config-tracker-disabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-enabled", + MountPath: "/etc/podinfo/secret-tracker-enabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-disabled", + MountPath: "/etc/podinfo/secret-tracker-disabled", + ReadOnly: true, + }, }, }, }, @@ -354,6 +452,42 @@ func newDaemonSetControllerTestPodInfo() *appsv1.DaemonSet { }, }, }, + { + Name: "config-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-enabled", + }, + }, + }, + }, + { + Name: "config-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-disabled", + }, + }, + }, + }, + { + Name: "secret-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-enabled", + }, + }, + }, + { + Name: "secret-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-disabled", + }, + }, + }, }, }, }, @@ -441,6 +575,26 @@ func newDaemonSetControllerTestPodInfoV2() *appsv1.DaemonSet { MountPath: "/etc/podinfo/secret", ReadOnly: true, }, + { + Name: "config-tracker-enabled", + MountPath: "/etc/podinfo/config-tracker-enabled", + ReadOnly: true, + }, + { + Name: "config-tracker-disabled", + MountPath: "/etc/podinfo/config-tracker-disabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-enabled", + MountPath: "/etc/podinfo/secret-tracker-enabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-disabled", + MountPath: "/etc/podinfo/secret-tracker-disabled", + ReadOnly: true, + }, }, }, }, @@ -498,6 +652,42 @@ func newDaemonSetControllerTestPodInfoV2() *appsv1.DaemonSet { }, }, }, + { + Name: "config-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-enabled", + }, + }, + }, + }, + { + Name: "config-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-disabled", + }, + }, + }, + }, + { + Name: "secret-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-enabled", + }, + }, + }, + { + Name: "secret-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-disabled", + }, + }, + }, }, }, }, diff --git a/pkg/canary/deployment_fixture_test.go b/pkg/canary/deployment_fixture_test.go index c8ab873d..aec070ff 100644 --- a/pkg/canary/deployment_fixture_test.go +++ b/pkg/canary/deployment_fixture_test.go @@ -64,10 +64,14 @@ func newDeploymentFixture() deploymentControllerFixture { newDeploymentControllerTestConfigMapEnv(), newDeploymentControllerTestConfigMapVol(), newDeploymentControllerTestConfigProjected(), + newDeploymentControllerTestConfigMapTrackerEnabled(), + newDeploymentControllerTestConfigMapTrackerDisabled(), newDeploymentControllerTestSecret(), newDeploymentControllerTestSecretEnv(), newDeploymentControllerTestSecretVol(), newDeploymentControllerTestSecretProjected(), + newDeploymentControllerTestSecretTrackerEnabled(), + newDeploymentControllerTestSecretTrackerDisabled(), ) logger, _ := logger.NewLogger("debug") @@ -146,6 +150,42 @@ func newDeploymentControllerTestConfigMapEnv() *corev1.ConfigMap { } } +func newDeploymentControllerTestConfigMapTrackerEnabled() *corev1.ConfigMap { + return &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-config-tracker-enabled", + Annotations: map[string]string{ + "unrelated-annotation-1": ":)", + "flagger.app/config-tracking": "enabled", + "unrelated-annotation-2": "<3", + }, + }, + Data: map[string]string{ + "color": "red", + }, + } +} + +func newDeploymentControllerTestConfigMapTrackerDisabled() *corev1.ConfigMap { + return &corev1.ConfigMap{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-config-tracker-disabled", + Annotations: map[string]string{ + "unrelated-annotation-1": "c:", + "flagger.app/config-tracking": "disabled", + "unrelated-annotation-2": "^-^", + }, + }, + Data: map[string]string{ + "color": "red", + }, + } +} + func newDeploymentControllerTestConfigMapVol() *corev1.ConfigMap { return &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, @@ -215,6 +255,44 @@ func newDeploymentControllerTestSecretVol() *corev1.Secret { } } +func newDeploymentControllerTestSecretTrackerEnabled() *corev1.Secret { + return &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-secret-tracker-enabled", + Annotations: map[string]string{ + "unrelated-annotation-1": ":)", + "flagger.app/config-tracking": "enabled", + "unrelated-annotation-2": "<3", + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "apiKey": []byte("test"), + }, + } +} + +func newDeploymentControllerTestSecretTrackerDisabled() *corev1.Secret { + return &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "podinfo-secret-tracker-disabled", + Annotations: map[string]string{ + "unrelated-annotation-1": "c:", + "flagger.app/config-tracking": "disabled", + "unrelated-annotation-2": "^-^", + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "apiKey": []byte("test"), + }, + } +} + func newDeploymentControllerTestCanary() *flaggerv1.Canary { cd := &flaggerv1.Canary{ TypeMeta: metav1.TypeMeta{APIVersion: flaggerv1.SchemeGroupVersion.String()}, @@ -337,6 +415,26 @@ func newDeploymentControllerTest() *appsv1.Deployment { MountPath: "/etc/podinfo/secret", ReadOnly: true, }, + { + Name: "config-tracker-enabled", + MountPath: "/etc/podinfo/config-tracker-enabled", + ReadOnly: true, + }, + { + Name: "config-tracker-disabled", + MountPath: "/etc/podinfo/config-tracker-disabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-enabled", + MountPath: "/etc/podinfo/secret-tracker-enabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-disabled", + MountPath: "/etc/podinfo/secret-tracker-disabled", + ReadOnly: true, + }, }, }, }, @@ -394,6 +492,42 @@ func newDeploymentControllerTest() *appsv1.Deployment { }, }, }, + { + Name: "config-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-enabled", + }, + }, + }, + }, + { + Name: "config-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-disabled", + }, + }, + }, + }, + { + Name: "secret-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-enabled", + }, + }, + }, + { + Name: "secret-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-disabled", + }, + }, + }, }, }, }, @@ -482,6 +616,26 @@ func newDeploymentControllerTestV2() *appsv1.Deployment { MountPath: "/etc/podinfo/secret", ReadOnly: true, }, + { + Name: "config-tracker-enabled", + MountPath: "/etc/podinfo/config-tracker-enabled", + ReadOnly: true, + }, + { + Name: "config-tracker-disabled", + MountPath: "/etc/podinfo/config-tracker-disabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-enabled", + MountPath: "/etc/podinfo/secret-tracker-enabled", + ReadOnly: true, + }, + { + Name: "secret-tracker-disabled", + MountPath: "/etc/podinfo/secret-tracker-disabled", + ReadOnly: true, + }, }, }, }, @@ -539,6 +693,42 @@ func newDeploymentControllerTestV2() *appsv1.Deployment { }, }, }, + { + Name: "config-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-enabled", + }, + }, + }, + }, + { + Name: "config-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "podinfo-config-tracker-disabled", + }, + }, + }, + }, + { + Name: "secret-tracker-enabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-enabled", + }, + }, + }, + { + Name: "secret-tracker-disabled", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "podinfo-secret-tracker-disabled", + }, + }, + }, }, }, }, diff --git a/pkg/metrics/observers/factory.go b/pkg/metrics/observers/factory.go index 35555c7c..ac20884d 100644 --- a/pkg/metrics/observers/factory.go +++ b/pkg/metrics/observers/factory.go @@ -56,6 +56,10 @@ func (factory Factory) Observer(provider string) Interface { return &HttpObserver{ client: factory.Client, } + case provider == flaggerv1.SkipperProvider: + return &SkipperObserver{ + client: factory.Client, + } default: return &IstioObserver{ client: factory.Client, diff --git a/pkg/metrics/observers/skipper.go b/pkg/metrics/observers/skipper.go new file mode 100644 index 00000000..9f4effea --- /dev/null +++ b/pkg/metrics/observers/skipper.go @@ -0,0 +1,82 @@ +package observers + +import ( + "fmt" + "regexp" + "time" + + flaggerv1 "github.com/weaveworks/flagger/pkg/apis/flagger/v1beta1" + "github.com/weaveworks/flagger/pkg/logger" + + "github.com/weaveworks/flagger/pkg/metrics/providers" +) + +const routePattern = `{{- $route := printf "kube(ew)?_%s__%s_canary__.*__%s_canary(_[0-9]+)?" namespace ingress service }}` + +var skipperQueries = map[string]string{ + "request-success-rate": routePattern + ` + sum(rate(skipper_response_duration_seconds_bucket{route=~"{{ $route }}",code!~"5..",le="+Inf"}[{{ interval }}])) / + sum(rate(skipper_response_duration_seconds_bucket{route=~"{{ $route }}",le="+Inf"}[{{ interval }}])) * 100`, + "request-duration": routePattern + ` + sum(rate(skipper_serve_route_duration_seconds_sum{route=~"{{ $route }}"}[{{ interval }}])) / + sum(rate(skipper_serve_route_duration_seconds_count{route=~"{{ $route }}"}[{{ interval }}])) * 1000`, +} + +// SkipperObserver Implementation for Skipper (https://github.com/zalando/skipper) +type SkipperObserver struct { + client providers.Interface +} + +// GetRequestSuccessRate return value for Skipper Request Success Rate +func (ob *SkipperObserver) GetRequestSuccessRate(model flaggerv1.MetricTemplateModel) (float64, error) { + + model = encodeModelForSkipper(model) + + query, err := RenderQuery(skipperQueries["request-success-rate"], model) + if err != nil { + return 0, fmt.Errorf("rendering query failed: %w", err) + } + logger, _ := logger.NewLoggerWithEncoding("debug", "json") + logger.Debugf("GetRequestSuccessRate: %s", query) + + value, err := ob.client.RunQuery(query) + if err != nil { + return 0, fmt.Errorf("running query failed: %w", err) + } + + return value, nil +} + +// GetRequestDuration return value for Skipper Request Duration +func (ob *SkipperObserver) GetRequestDuration(model flaggerv1.MetricTemplateModel) (time.Duration, error) { + + model = encodeModelForSkipper(model) + + query, err := RenderQuery(skipperQueries["request-duration"], model) + if err != nil { + return 0, fmt.Errorf("rendering query failed: %w", err) + } + logger, _ := logger.NewLoggerWithEncoding("debug", "json") + logger.Debugf("GetRequestDuration: %s", query) + + value, err := ob.client.RunQuery(query) + if err != nil { + return 0, fmt.Errorf("running query failed: %w", err) + } + + ms := time.Duration(int64(value)) * time.Millisecond + return ms, nil +} + +// encodeModelForSkipper replaces non word character in model with underscore to match route names +// https://github.com/zalando/skipper/blob/dd70bd65e7f99cfb5dd6b6f71885d9fe3b2707f6/dataclients/kubernetes/ingress.go#L101 +func encodeModelForSkipper(model flaggerv1.MetricTemplateModel) flaggerv1.MetricTemplateModel { + nonWord := regexp.MustCompile(`\W`) + model.Ingress = nonWord.ReplaceAllString(model.Ingress, "_") + model.Name = nonWord.ReplaceAllString(model.Name, "_") + model.Namespace = nonWord.ReplaceAllString(model.Namespace, "_") + model.Service = nonWord.ReplaceAllString(model.Service, "_") + model.Target = nonWord.ReplaceAllString(model.Target, "_") + + return model +} diff --git a/pkg/metrics/observers/skipper_test.go b/pkg/metrics/observers/skipper_test.go new file mode 100644 index 00000000..9c16243d --- /dev/null +++ b/pkg/metrics/observers/skipper_test.go @@ -0,0 +1,97 @@ +package observers + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + flaggerv1 "github.com/weaveworks/flagger/pkg/apis/flagger/v1beta1" + "github.com/weaveworks/flagger/pkg/metrics/providers" +) + +func TestSkipperObserver_GetRequestSuccessRate(t *testing.T) { + t.Run("ok", func(t *testing.T) { + expected := ` sum(rate(skipper_response_duration_seconds_bucket{route=~"kube(ew)?_skipper__skipper_ingress_canary__.*__backend_canary(_[0-9]+)?",code!~"5..",le="+Inf"}[1m])) / sum(rate(skipper_response_duration_seconds_bucket{route=~"kube(ew)?_skipper__skipper_ingress_canary__.*__backend_canary(_[0-9]+)?",le="+Inf"}[1m])) * 100` + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + promql := r.URL.Query()["query"][0] + assert.Equal(t, expected, promql) + + json := `{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1,"100"]}]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &SkipperObserver{client: client} + val, err := observer.GetRequestSuccessRate(flaggerv1.MetricTemplateModel{ + Namespace: "skipper", + Interval: "1m", + Service: "backend", + Ingress: "skipper-ingress", + }) + require.NoError(t, err) + + assert.Equal(t, float64(100), val) + }) + + t.Run("no values", func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json := `{"status":"success","data":{"resultType":"vector","result":[]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &SkipperObserver{client: client} + _, err = observer.GetRequestSuccessRate(flaggerv1.MetricTemplateModel{}) + require.True(t, errors.Is(err, providers.ErrNoValuesFound)) + }) +} + +func TestSkipperObserver_GetRequestDuration(t *testing.T) { + expected := ` sum(rate(skipper_serve_route_duration_seconds_sum{route=~"kube(ew)?_skipper__skipper_ingress_canary__.*__backend_canary(_[0-9]+)?"}[1m])) / sum(rate(skipper_serve_route_duration_seconds_count{route=~"kube(ew)?_skipper__skipper_ingress_canary__.*__backend_canary(_[0-9]+)?"}[1m])) * 1000` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + promql := r.URL.Query()["query"][0] + assert.Equal(t, expected, promql) + + json := `{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1,"100"]}]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &SkipperObserver{client: client} + val, err := observer.GetRequestDuration(flaggerv1.MetricTemplateModel{ + Namespace: "skipper", + Interval: "1m", + Service: "backend", + Ingress: "skipper-ingress", + }) + require.NoError(t, err) + + assert.Equal(t, 100*time.Millisecond, val) +} diff --git a/pkg/router/factory.go b/pkg/router/factory.go index 15df37fe..2a970c90 100644 --- a/pkg/router/factory.go +++ b/pkg/router/factory.go @@ -122,6 +122,11 @@ func (factory *Factory) MeshRouter(provider string, labelSelector string) Interf kubeClient: factory.kubeClient, annotationsPrefix: factory.ingressAnnotationsPrefix, } + case provider == flaggerv1.SkipperProvider: + return &SkipperRouter{ + logger: factory.logger, + kubeClient: factory.kubeClient, + } case provider == flaggerv1.KubernetesProvider: return &NopRouter{} default: diff --git a/pkg/router/kubernetes_default.go b/pkg/router/kubernetes_default.go index df4a8bc4..739dc4c7 100644 --- a/pkg/router/kubernetes_default.go +++ b/pkg/router/kubernetes_default.go @@ -125,9 +125,6 @@ func (c *KubernetesDefaultRouter) reconcileService(canary *flaggerv1.Canary, nam metadata.Annotations = make(map[string]string) } - c.logger.With("canary", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). - Debugw(fmt.Sprintf("Creating Service %s", name), "metadata", metadata, "service_configuration", canary.Spec.Service) - // create service if it doesn't exists svc, err := c.kubeClient.CoreV1().Services(canary.Namespace).Get(context.TODO(), name, metav1.GetOptions{}) if errors.IsNotFound(err) { diff --git a/pkg/router/skipper.go b/pkg/router/skipper.go new file mode 100644 index 00000000..6b5a8c7c --- /dev/null +++ b/pkg/router/skipper.go @@ -0,0 +1,235 @@ +package router + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/google/go-cmp/cmp" + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/kubernetes" + + flaggerv1 "github.com/weaveworks/flagger/pkg/apis/flagger/v1beta1" +) + +/* +Skipper Principles: +* if only one backend has a weight, only one backend will get 100% traffic +* if two of three or more backends have a weight, only those two should get traffic. +* if two backends don't have any weight, it's undefined and right now they get equal amount of traffic. +* weights can be int or float, but always treated as a ratio. + +Implementation: +* apex Ingress is immutable +* new canary Ingress contains two paths for primary and canary service +* canary Ingress manages weights on primary & canary service, hence no traffic to apex service + +*/ + +const ( + skipperpredicateAnnotationKey = "zalando.org/skipper-predicate" + skipperBackendWeightsAnnotationKey = "zalando.org/backend-weights" + canaryPatternf = "%s-canary" + canaryRouteWeight = "Weight(100)" + canaryRouteDisable = "False()" +) + +type SkipperRouter struct { + kubeClient kubernetes.Interface + logger *zap.SugaredLogger +} + +// Reconcile creates or updates the ingresses +func (skp *SkipperRouter) Reconcile(canary *flaggerv1.Canary) error { + if canary.Spec.IngressRef == nil || canary.Spec.IngressRef.Name == "" { + return fmt.Errorf("ingress selector is empty") + } + + apexSvcName, primarySvcName, canarySvcName := canary.GetServiceNames() + apexIngressName, canaryIngressName := skp.getIngressNames(canary.Spec.IngressRef.Name) + + // retrieving apex ingress + apexIngress, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Get( + context.TODO(), apexIngressName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("apexIngress %s.%s get query error: %w", apexIngressName, canary.Namespace, err) + } + + // building the canary ingress from apex + iClone := apexIngress.DeepCopy() + for x := range iClone.Spec.Rules { + rule := &iClone.Spec.Rules[x] // ref not value + for y := range rule.HTTP.Paths { + path := &rule.HTTP.Paths[y] // ref not value + if path.Backend.ServiceName == apexSvcName { + // flipping to primary service + path.Backend.ServiceName = primarySvcName + // adding second canary service + canaryBackend := path.DeepCopy() + canaryBackend.Backend.ServiceName = canarySvcName + rule.HTTP.Paths = append(rule.HTTP.Paths, *canaryBackend) + } + } + } + if apexIngress.DeepCopy() == iClone { + return fmt.Errorf("backend %s not found in ingress %s", apexSvcName, apexIngressName) + } + + iClone.Annotations = skp.makeAnnotations(iClone.Annotations, map[string]int{primarySvcName: 100, canarySvcName: 0}) + iClone.Name = canaryIngressName + iClone.Namespace = canary.Namespace + iClone.OwnerReferences = []metav1.OwnerReference{ + *metav1.NewControllerRef(canary, schema.GroupVersionKind{ + Group: flaggerv1.SchemeGroupVersion.Group, + Version: flaggerv1.SchemeGroupVersion.Version, + Kind: flaggerv1.CanaryKind, + }), + } + + // search for existence + canaryIngress, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Get( + context.TODO(), canaryIngressName, metav1.GetOptions{}) + + // new ingress + if errors.IsNotFound(err) { + // Let K8s set this. Otherwise K8s API complains with "resourceVersion should not be set on objects to be created" + iClone.ObjectMeta.ResourceVersion = "" + _, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Create(context.TODO(), iClone, metav1.CreateOptions{}) + if err != nil { + return fmt.Errorf("ingress %s.%s create error: %w", iClone.Name, iClone.Namespace, err) + } + skp.logger.With("canary", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Infof("Ingress %s.%s created", iClone.GetName(), canary.Namespace) + return nil + } else if err != nil { + return fmt.Errorf("ingress %s.%s query error: %w", canaryIngressName, canary.Namespace, err) + } + + // existant, updating + if cmp.Diff(iClone.Spec, canaryIngress.Spec) != "" { + ingressClone := canaryIngress.DeepCopy() + ingressClone.Spec = iClone.Spec + ingressClone.Annotations = iClone.Annotations + + _, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Update(context.TODO(), ingressClone, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("ingress %s.%s update error: %w", canaryIngressName, ingressClone.Namespace, err) + } + skp.logger.With("canary", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Infof("Ingress %s updated", canaryIngressName) + } + return nil +} + +func (skp *SkipperRouter) GetRoutes(canary *flaggerv1.Canary) (primaryWeight, canaryWeight int, mirrored bool, err error) { + _, primarySvcName, canarySvcName := canary.GetServiceNames() + + _, canaryIngressName := skp.getIngressNames(canary.Spec.IngressRef.Name) + canaryIngress, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Get(context.TODO(), canaryIngressName, metav1.GetOptions{}) + if err != nil { + err = fmt.Errorf("ingress %s.%s get query error: %w", canaryIngressName, canary.Namespace, err) + return + } + + weights, err := skp.backendWeights(canaryIngress.Annotations) + if err != nil { + err = fmt.Errorf("ingress %s.%s get backendWeights error: %w", canaryIngressName, canary.Namespace, err) + return + } + var ok bool + primaryWeight, ok = weights[primarySvcName] + if !ok { + err = fmt.Errorf("ingress %s.%s could not get weights[primarySvcName]", canaryIngressName, canary.Namespace) + return + } + canaryWeight, ok = weights[canarySvcName] + if !ok { + err = fmt.Errorf("ingress %s.%s could not get weights[canarySvcName]", canaryIngressName, canary.Namespace) + return + } + mirrored = false + skp.logger.With("GetRoutes", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Debugf("GetRoutes primaryWeight: %d, canaryWeight: %d", primaryWeight, canaryWeight) + return +} + +func (skp *SkipperRouter) SetRoutes(canary *flaggerv1.Canary, primaryWeight, canaryWeight int, _ bool) (err error) { + _, primarySvcName, canarySvcName := canary.GetServiceNames() + _, canaryIngressName := skp.getIngressNames(canary.Spec.IngressRef.Name) + canaryIngress, err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Get(context.TODO(), canaryIngressName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("ingress %s.%s get query error: %w", canaryIngressName, canary.Namespace, err) + } + + iClone := canaryIngress.DeepCopy() + + // TODO: A/B testing + + // Canary + iClone.Annotations = skp.makeAnnotations(iClone.Annotations, map[string]int{ + primarySvcName: primaryWeight, + canarySvcName: canaryWeight, + }) + + // Disable the canary-ingress route after the canary process + if canaryWeight == 0 { + iClone.Annotations[skipperpredicateAnnotationKey] = canaryRouteDisable + } + + _, err = skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Update( + context.TODO(), iClone, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("ingress %s.%s update error %w", iClone.Name, iClone.Namespace, err) + } + skp.logger.With("SetRoutes", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Debugf("primaryWeight: %d, canaryWeight: %d", primaryWeight, canaryWeight) + + return err +} + +func (skp *SkipperRouter) Finalize(canary *flaggerv1.Canary) error { + gracePeriodSeconds := int64(2) + _, canaryIngressName := skp.getIngressNames(canary.Spec.IngressRef.Name) + skp.logger.With("deleteCanaryIngress", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Debugf("Deleting Canary Ingress: %s", canaryIngressName) + + err := skp.kubeClient.NetworkingV1beta1().Ingresses(canary.Namespace).Delete( + context.TODO(), canaryIngressName, metav1.DeleteOptions{GracePeriodSeconds: &gracePeriodSeconds}) + if err != nil { + return fmt.Errorf("ingress %s.%s unable to remove canary ingress: %w", canaryIngressName, canary.Namespace, err) + } + return nil +} + +func (skp *SkipperRouter) makeAnnotations(annotations map[string]string, backendWeights map[string]int) map[string]string { + b, err := json.Marshal(backendWeights) + if err != nil { + skp.logger.Errorf("Skipper:makeAnnotations: unable to marshal backendWeights %w", err) + return annotations + } + annotations[skipperBackendWeightsAnnotationKey] = string(b) + // adding more weight to canary route solves traffic bypassing through apexIngress + annotations[skipperpredicateAnnotationKey] = canaryRouteWeight + + return annotations +} + +// parse backend-weights annotation if it exists +func (skp *SkipperRouter) backendWeights(annotation map[string]string) (backendWeights map[string]int, err error) { + backends, ok := annotation[skipperBackendWeightsAnnotationKey] + if ok { + err = json.Unmarshal([]byte(backends), &backendWeights) + } else { + err = errors.NewNotFound(schema.GroupResource{Group: "Skipper Canary Ingress", Resource: "Annotation"}, + skipperBackendWeightsAnnotationKey) + } + return +} + +// getIngressNames returns the primary and canary Kubernetes Ingress names +func (skp *SkipperRouter) getIngressNames(name string) (apexName, canaryName string) { + return name, fmt.Sprintf(canaryPatternf, name) +} diff --git a/pkg/router/skipper_test.go b/pkg/router/skipper_test.go new file mode 100644 index 00000000..e782f38e --- /dev/null +++ b/pkg/router/skipper_test.go @@ -0,0 +1,107 @@ +package router + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestSkipperRouter_Reconcile(t *testing.T) { + assert := assert.New(t) + mocks := newFixture(nil) + + for _, tt := range []struct { + name string + mocks func() fixture + wantErr bool + }{ + { + "creating new canary ingress w/ default settings", + func() fixture { return mocks }, + false, + }, { + "updating existing canary ingress", + func() fixture { + ti := newTestIngress() + ti.Annotations["something"] = "changed" + _, err := mocks.kubeClient.NetworkingV1beta1().Ingresses("default").Update( + context.TODO(), ti, metav1.UpdateOptions{}) + assert.NoError(err) + return mocks + }, + false, + }, + } { + tt := tt + t.Run(tt.name, func(t *testing.T) { + mocks := tt.mocks() + router := &SkipperRouter{ + kubeClient: mocks.kubeClient, + logger: mocks.logger, + } + assert.NoError(router.Reconcile(mocks.ingressCanary)) + canaryName := fmt.Sprintf("%s-canary", mocks.ingressCanary.Spec.IngressRef.Name) + inCanary, err := router.kubeClient.NetworkingV1beta1().Ingresses("default").Get( + context.TODO(), canaryName, metav1.GetOptions{}) + assert.NoError(err) + // test initialisation + assert.JSONEq(`{ "podinfo-primary": 100, "podinfo-canary": 0 }`, inCanary.Annotations["zalando.org/backend-weights"]) + assert.Equal("podinfo-primary", inCanary.Spec.Rules[0].HTTP.Paths[0].Backend.ServiceName, "backend flipped over") + assert.Equal("podinfo-canary", inCanary.Spec.Rules[0].HTTP.Paths[1].Backend.ServiceName, "backend flipped over") + assert.Len(inCanary.Spec.Rules[0].HTTP.Paths, 2) + inApex, err := router.kubeClient.NetworkingV1beta1().Ingresses("default").Get( + context.TODO(), mocks.ingressCanary.Spec.IngressRef.Name, metav1.GetOptions{}) + assert.NoError(err) + assert.Equal(inCanary.Spec.Rules[0].HTTP.Paths[0].Backend.ServicePort, + inApex.Spec.Rules[0].HTTP.Paths[0].Backend.ServicePort, "canary backend not cloned") + assert.Equal(inCanary.Spec.Rules[0].HTTP.Paths[0].Backend.ServicePort, + inCanary.Spec.Rules[0].HTTP.Paths[1].Backend.ServicePort, "canary backend not cloned") + }) + } +} + +func TestSkipperRouter_GetSetRoutes(t *testing.T) { + assert := assert.New(t) + mocks := newFixture(nil) + + router := &SkipperRouter{logger: mocks.logger, kubeClient: mocks.kubeClient} + assert.NoError(router.Reconcile(mocks.ingressCanary)) + + p, c, m, err := router.GetRoutes(mocks.ingressCanary) + assert.NoError(err) + assert.Equal(100, p) + assert.Equal(0, c) + assert.Equal(false, m) + + tests := []struct { + name string + primary, canary int + }{ + {name: "0%", primary: 100, canary: 0}, + {name: "10%", primary: 90, canary: 10}, + {name: "20%", primary: 80, canary: 20}, + {name: "30%", primary: 70, canary: 30}, + {name: "85%", primary: 15, canary: 85}, + {name: "100%", primary: 0, canary: 100}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert.NoError(router.SetRoutes(mocks.ingressCanary, tt.primary, tt.canary, false)) + inCanary, err := router.kubeClient.NetworkingV1beta1().Ingresses("default").Get( + context.TODO(), fmt.Sprintf("%s-canary", mocks.ingressCanary.Spec.IngressRef.Name), metav1.GetOptions{}) + assert.NoError(err) + assert.JSONEq(fmt.Sprintf(`{"podinfo-primary": %d,"podinfo-canary": %d}`, tt.primary, tt.canary), + inCanary.Annotations["zalando.org/backend-weights"]) + p, c, m, err = router.GetRoutes(mocks.ingressCanary) + assert.NoError(err) + assert.Equal(tt.primary, p) + assert.Equal(tt.canary, c) + assert.Equal(false, m) + }) + } + +} diff --git a/pkg/version/version.go b/pkg/version/version.go index b0e07769..1bd77e47 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -1,4 +1,4 @@ package version -var VERSION = "1.0.0" +var VERSION = "1.1.0" var REVISION = "unknown" diff --git a/test/README.md b/test/README.md index d595d847..cff6cd0f 100644 --- a/test/README.md +++ b/test/README.md @@ -53,4 +53,19 @@ The e2e testing infrastructure is powered by CircleCI and [Kubernetes Kind](http * test the A/B testing analysis and promotion using header filters and pre/post rollout webhooks [e2e-nginx-tests.sh](e2e-nginx-tests.sh) * cleanup test environment [e2e-nginx-cleanup.sh](e2e-nginx-cleanup.sh) * install NGINX Ingress and Flagger with custom ingress annotations prefix [e2e-nginx-custom-annotations.sh](e2e-nginx-custom-annotations.sh) -* repeat the canary and A/B testing workflow [e2e-nginx-tests.sh](e2e-nginx-tests.sh) \ No newline at end of file +* repeat the canary and A/B testing workflow [e2e-nginx-tests.sh](e2e-nginx-tests.sh) + +### CircleCI e2e Skipper ingress workflow + +* install latest stable kubectl [e2e-kind.sh](e2e-kind.sh) +* install Kubernetes Kind [e2e-kind.sh](e2e-kind.sh) +* create local Kubernetes cluster with kind [e2e-kind.sh](e2e-kind.sh) +* install Skipper ingress with Kustomize [e2e-skipper.sh](e2e-skipper.sh) +* load Flagger image onto the local cluster [e2e-skipper.sh](e2e-skipper.sh) +* install Flagger and Prometheus in the flagger-system namespace [e2e-skipper.sh](e2e-skipper.sh) +* create a test namespace [e2e-skipper-tests.sh](e2e-skipper-tests.sh) +* deploy the load tester in the test namespace [e2e-skipper-tests.sh](e2e-skipper-tests.sh) +* deploy the demo workload (podinfo) and ingress in the test namespace [e2e-skipper-tests.sh](e2e-skipper-tests.sh) +* test the canary initialization [e2e-skipper-tests.sh](e2e-skipper-tests.sh) +* test the canary analysis and promotion using weighted traffic and the load testing webhook [e2e-skipper-tests.sh]e2e-skipper-tests.sh) +* cleanup test environment [e2e-skipper-cleanup.sh](e2e-skipper-cleanup.sh) diff --git a/test/e2e-contour.sh b/test/e2e-contour.sh index 787a6cab..f32a1634 100755 --- a/test/e2e-contour.sh +++ b/test/e2e-contour.sh @@ -4,7 +4,7 @@ set -o errexit REPO_ROOT=$(git rev-parse --show-toplevel) -CONTOUR_VER="v1.5.0" +CONTOUR_VER="v1.7.0" echo '>>> Installing Contour' kubectl apply -f https://projectcontour.io/quickstart/${CONTOUR_VER}/contour.yaml diff --git a/test/e2e-istio.sh b/test/e2e-istio.sh index cfc84097..20c1c5c7 100755 --- a/test/e2e-istio.sh +++ b/test/e2e-istio.sh @@ -2,7 +2,7 @@ set -o errexit -ISTIO_VER="1.6.1" +ISTIO_VER="1.6.7" REPO_ROOT=$(git rev-parse --show-toplevel) echo ">>> Downloading Istio ${ISTIO_VER}" diff --git a/test/e2e-kind.sh b/test/e2e-kind.sh index 925597cb..bb2ba52d 100755 --- a/test/e2e-kind.sh +++ b/test/e2e-kind.sh @@ -3,7 +3,8 @@ set -o errexit REPO_ROOT=$(git rev-parse --show-toplevel) -HELM_VERSION=v3.0.3 +HELM_VERSION=v3.3.0 +KUSTOMIZE_VERSION=3.8.1 KIND_VERSION=v0.8.1 KUBE_VERSION=v1.16.9 @@ -26,6 +27,14 @@ kind create cluster --wait 5m --image kindest/node:${KUBE_VERSION} kubectl get pods --all-namespaces +cd /tmp + echo ">>> Installing Helm" curl -sSL https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz | tar xz && sudo mv linux-amd64/helm /usr/local/bin/ && rm -rf linux-amd64 helm repo add stable https://kubernetes-charts.storage.googleapis.com/ + +echo ">>> Installing Kustomize" +kustomize_url=https://github.com/kubernetes-sigs/kustomize/releases/download && \ +curl -sL ${kustomize_url}/kustomize%2Fv${KUSTOMIZE_VERSION}/kustomize_v${KUSTOMIZE_VERSION}_linux_amd64.tar.gz | tar xz +chmod +x kustomize +sudo mv kustomize /usr/local/bin/kustomize diff --git a/test/e2e-linkerd.sh b/test/e2e-linkerd.sh index 89a413cc..8d8b143e 100755 --- a/test/e2e-linkerd.sh +++ b/test/e2e-linkerd.sh @@ -2,7 +2,7 @@ set -o errexit -LINKERD_VER="stable-2.8.0" +LINKERD_VER="stable-2.8.1" REPO_ROOT=$(git rev-parse --show-toplevel) curl -SsL https://github.com/linkerd/linkerd2/releases/download/${LINKERD_VER}/linkerd2-cli-${LINKERD_VER}-linux > ${REPO_ROOT}/bin/linkerd diff --git a/test/e2e-skipper-canary.yaml b/test/e2e-skipper-canary.yaml new file mode 100644 index 00000000..7e0965e4 --- /dev/null +++ b/test/e2e-skipper-canary.yaml @@ -0,0 +1,66 @@ +apiVersion: flagger.app/v1beta1 +kind: Canary +metadata: + name: podinfo + namespace: test +spec: + provider: skipper + progressDeadlineSeconds: 120 + revertOnDeletion: true + targetRef: + apiVersion: apps/v1 + kind: Deployment + name: podinfo + ingressRef: + apiVersion: networking.k8s.io/v1beta1 + kind: Ingress + name: podinfo-ingress + service: + # service name (defaults to targetRef.name) + name: podinfo-service + # ClusterIP port number + port: 80 + # container port name or number (optional) + targetPort: http + # port name can be http or grpc (default http) + # portName: http + # add all the other container ports + # to the ClusterIP services (default false) + # portDiscovery: false + analysis: + interval: 15s + threshold: 5 + maxWeight: 100 + stepWeight: 10 + metrics: + - name: request-success-rate + interval: 15s + # minimum req success rate (non 5xx responses) + # percentage (0-100) + thresholdRange: + min: 99 + - name: request-duration + interval: 15s + # maximum req duration P99 + # milliseconds + thresholdRange: + max: 500 + webhooks: + - name: gate + type: confirm-rollout + url: http://flagger-loadtester.test/gate/approve + - name: acceptance-test + type: pre-rollout + url: http://flagger-loadtester.test/ + timeout: 10s + metadata: + type: bash + cmd: "curl -sd 'test' http://podinfo-service-canary/token | grep token" + - name: "load test" + type: rollout + url: http://flagger-loadtester.test/ + timeout: 5s + metadata: + type: cmd + cmd: "hey -z 10m -q 10 -c 2 -host app.example.com http://skipper-ingress.kube-system" + logCmdOutput: "true" diff --git a/test/e2e-skipper-cleanup.sh b/test/e2e-skipper-cleanup.sh new file mode 100755 index 00000000..b789007e --- /dev/null +++ b/test/e2e-skipper-cleanup.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +REPO_ROOT=$(git rev-parse --show-toplevel) + +echo '>>> Deleting Skipper Ingress' +kustomize build ${REPO_ROOT}/test/skipper | kubectl delete --force --wait=false -f - + +echo '>>> Deleting Flagger' +kubectl delete namespace flagger-system --ignore-not-found=true --force --wait=false + +echo '>>> Cleanup test namespace' +kubectl delete namespace test --ignore-not-found=true --force --wait=false + +exit 0 diff --git a/test/e2e-skipper-tests.sh b/test/e2e-skipper-tests.sh new file mode 100755 index 00000000..2af94271 --- /dev/null +++ b/test/e2e-skipper-tests.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash + +# This script runs e2e tests for Canary initialization, analysis and promotion +# Prerequisites: Kubernetes Kind and Skipper ingress controller + +set -o errexit + +REPO_ROOT=$(git rev-parse --show-toplevel) + +echo '>>> Creating test namespace' +kubectl create namespace test || true + +echo '>>> Initialising workload' +kubectl apply -f ${REPO_ROOT}/test/e2e-workload.yaml +kubectl apply -f ${REPO_ROOT}/test/e2e-workload-ingress.yaml + +echo '>>> Installing load tester' +kubectl apply -k ${REPO_ROOT}/kustomize/tester +kubectl -n test rollout status deployment/flagger-loadtester + +echo '>>> Create canary CRD' +kubectl apply -f ${REPO_ROOT}/test/e2e-skipper-canary.yaml +echo '>>> Waiting for primary to be ready' +retries=50 +count=0 +ok=false +until ${ok}; do + kubectl -n test get canary/podinfo | grep 'Initialized' && ok=true || ok=false + sleep 5 + count=$(($count + 1)) + if [[ ${count} -eq ${retries} ]]; then + kubectl -n flagger-system logs deployment/flagger + echo "No more retries left" + exit 1 + fi +done + +echo '✔ Canary initialization test passed' + +echo '>>> Triggering canary deployment' +kubectl -n test set image deployment/podinfo podinfod=stefanprodan/podinfo:3.1.1 + +echo '>>> Waiting for canary promotion' +retries=50 +count=0 +ok=false +failed=false +until ${ok}; do + kubectl -n test get canary/podinfo | grep 'Failed' && failed=true || failed=false + if ${failed}; then + kubectl -n flagger-system logs deployment/flagger + echo "Canary failed!" + exit 1 + fi + kubectl -n test describe deployment/podinfo-primary | grep '3.1.1' && ok=true || ok=false + sleep 10 + kubectl -n flagger-system logs deployment/flagger --tail 1 + count=$(($count + 1)) + if [[ ${count} -eq ${retries} ]]; then + kubectl -n test describe deployment/podinfo + kubectl -n test describe deployment/podinfo-primary + kubectl -n flagger-system logs deployment/flagger + echo "No more retries left" + exit 1 + fi +done + +echo '>>> Waiting for canary finalization' +retries=50 +count=0 +ok=false +until ${ok}; do + kubectl -n test get canary/podinfo | grep 'Succeeded' && ok=true || ok=false + sleep 5 + count=$(($count + 1)) + if [[ ${count} -eq ${retries} ]]; then + kubectl -n flagger-system logs deployment/flagger + echo "No more retries left" + exit 1 + fi +done + +echo '✔ Canary promotion test passed' diff --git a/test/e2e-skipper.sh b/test/e2e-skipper.sh new file mode 100755 index 00000000..f5dbe2a2 --- /dev/null +++ b/test/e2e-skipper.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +set -o errexit + +REPO_ROOT=$(git rev-parse --show-toplevel) + +echo '>>> Loading Flagger image' +kind load docker-image test/flagger:latest + +echo '>>> Installing Skipper Ingress, Flagger and Prometheus' +# use kustomize to avoid compatibility issues: +# https://github.com/kubernetes-sigs/kustomize/issues/2390 +# Skipper will throw an Prometheus warning which can be ignored: +# https://github.com/weaveworks/flagger/issues/664 +kustomize build ${REPO_ROOT}/test/skipper | kubectl apply -f - + +kubectl rollout status deployment/skipper-ingress -n kube-system +kubectl rollout status deployment/flagger-prometheus -n flagger-system + +kubectl -n flagger-system set image deployment/flagger flagger=test/flagger:latest + +kubectl -n flagger-system rollout status deployment/flagger diff --git a/test/e2e-workload-ingress.yaml b/test/e2e-workload-ingress.yaml new file mode 100644 index 00000000..b7a2c619 --- /dev/null +++ b/test/e2e-workload-ingress.yaml @@ -0,0 +1,17 @@ +apiVersion: networking.k8s.io/v1beta1 +kind: Ingress +metadata: + name: podinfo-ingress + namespace: test + labels: + app: podinfo + annotations: + kubernetes.io/ingress.class: skipper +spec: + rules: + - host: app.example.com + http: + paths: + - backend: + serviceName: podinfo-service + servicePort: 80 diff --git a/test/local/e2e-skipper.sh b/test/local/e2e-skipper.sh new file mode 100755 index 00000000..0e98d6d0 --- /dev/null +++ b/test/local/e2e-skipper.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +# This script is intended for local workstation development convenience. +# It will run the e2e tests for Skipper and leave a working setup to play with + +REPO_ROOT=$(git rev-parse --show-toplevel) +cd $REPO_ROOT + +make test +make build +docker tag weaveworks/flagger:latest test/flagger:latest +make loadtester-build +(kind get clusters && kubectl delete ns/test --force) || kind create cluster --wait 5m --image kindest/node:v1.16.9 +./test/e2e-skipper.sh +# port forward prometheus UI to localhost:9090 +kubectl port-forward $(kubectl get pods -l=app=flagger-prometheus -o name -n flagger-system | head -n 1) 9090:9090 -n flagger-system & + +./test/e2e-skipper-tests.sh diff --git a/test/skipper/kustomization.yaml b/test/skipper/kustomization.yaml new file mode 100644 index 00000000..9fb1e64d --- /dev/null +++ b/test/skipper/kustomization.yaml @@ -0,0 +1,67 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../kustomize/base/prometheus/ + - ../../kustomize/base/flagger/ + - https://raw.githubusercontent.com/zalando/skipper/v0.11.140/docs/kubernetes/deploy/deployment/rbac.yaml + - https://raw.githubusercontent.com/zalando/skipper/v0.11.140/docs/kubernetes/deploy/deployment/service.yaml + - https://raw.githubusercontent.com/zalando/skipper/v0.11.140/docs/kubernetes/deploy/deployment/deployment.yaml + - namespace.yaml +patchesStrategicMerge: + - patch.yaml +patches: + - target: + kind: Deployment + name: skipper-ingress + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: skipper-ingress + spec: + template: + metadata: + annotations: + prometheus.io/path: /metrics + prometheus.io/port: "9911" + prometheus.io/scrape: "true" + spec: + nodeSelector: + $patch: delete + affinity: + $patch: delete + containers: + - name: skipper-ingress + image: registry.opensource.zalan.do/pathfinder/skipper:v0.11.141 + ports: + - name: metrics-port + containerPort: 9911 + resources: + $patch: delete + readinessProbe: + initialDelaySeconds: 5 + args: + - skipper + - -default-filters-prepend=enableAccessLog(4,5) + - -address=:9999 + - -disable-metrics-compat + - -enable-connection-metrics + - -enable-profile + - -enable-ratelimits + - -experimental-upgrade + - -histogram-metric-buckets=.01,1,10,100 + - -kubernetes-in-cluster + - -kubernetes-path-mode=path-prefix + - -kubernetes + - -lb-healthcheck-interval=3s + - -max-audit-body=0 + - -max-idle-connection-backend=0 + - -metrics-exp-decay-sample + - -metrics-flavour=prometheus + - -proxy-preserve-host + - -route-backend-metrics + - -route-backend-error-counters + - -route-response-metrics + - -serve-host-metrics + - -serve-route-metrics + - -whitelisted-healthcheck-cidr=0.0.0.0/0 # kind uses other IP addresse diff --git a/test/skipper/namespace.yaml b/test/skipper/namespace.yaml new file mode 100644 index 00000000..1f7400c3 --- /dev/null +++ b/test/skipper/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: flagger-system diff --git a/test/skipper/patch.yaml b/test/skipper/patch.yaml new file mode 100644 index 00000000..7bb6bbc5 --- /dev/null +++ b/test/skipper/patch.yaml @@ -0,0 +1,13 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: flagger +spec: + template: + spec: + containers: + - name: flagger + args: + - -log-level=debug + - -mesh-provider=skipper + - -metrics-server=http://flagger-prometheus:9090