Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

Lab 04: Analysis and Metrics

Prometheus

  • Minimal Prometheus with pod discovery (needs RBAC for kubernetes_sd_configs)
apiVersion: v1
kind: Namespace
metadata:
  name: monitoring
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
  namespace: monitoring
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: prometheus
rules:
- apiGroups: [""]
  resources: [pods]
  verbs: [get, list, watch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
- kind: ServiceAccount
  name: prometheus
  namespace: monitoring
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: monitoring
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
    scrape_configs:
    - job_name: kubernetes-pods
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: "true"
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: $1:$2
        target_label: __address__
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: prometheus
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      serviceAccountName: prometheus
      containers:
      - name: prometheus
        image: prom/prometheus:v2.53.0
        args:
        - --config.file=/etc/prometheus/prometheus.yml
        ports:
        - containerPort: 9090
        volumeMounts:
        - name: config
          mountPath: /etc/prometheus
      volumes:
      - name: config
        configMap:
          name: prometheus-config
---
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  namespace: monitoring
spec:
  selector:
    app: prometheus
  ports:
  - port: 9090
    targetPort: 9090
kubectl apply -f prometheus.yaml
kubectl wait --for=condition=ready pod -l app=prometheus -n monitoring --timeout=120s
kubectl port-forward -n monitoring svc/prometheus 9090:9090
  • labelmap copies pod labels, so the rollouts-pod-template-hash label becomes rollouts_pod_template_hash
  • Prometheus provider address: http://prometheus.monitoring.svc.cluster.local:9090

AnalysisTemplate

kubectl create namespace analysis-demo
kubectl config set-context --current --namespace=analysis-demo
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: success-rate
spec:
  args:
  - name: pod-hash
  metrics:
  - name: success-rate
    initialDelay: 30s
    interval: 30s
    failureLimit: 3
    successCondition: result[0] >= 0.95
    provider:
      prometheus:
        address: http://prometheus.monitoring.svc.cluster.local:9090
        query: |
          sum(rate(http_requests_total{status=~"2..",rollouts_pod_template_hash="{{args.pod-hash}}"}[2m]))
          /
          sum(rate(http_requests_total{rollouts_pod_template_hash="{{args.pod-hash}}"}[2m]))
  • Args must be declared under spec.args before use as {{args.name}}
  • Prometheus provider returns a vector, so index it: result[0]
  • failureLimit: number of failed measurements tolerated (default 0); count = total measurements (omit + interval = run until rollout ends)
  • Errors (query failure) are counted separately via consecutiveErrorLimit
  • inconclusiveLimit + failureCondition give the inconclusive state, which pauses the rollout
  • The demo image does not export http_requests_total; for the queries to return data use an instrumented app (annotate pods with prometheus.io/scrape: "true", prometheus.io/port, prometheus.io/path). The failure/job/web examples below work with the stock image

Background analysis

  • Runs alongside all steps from the start of the update; failure aborts the rollout
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: analysis-demo
spec:
  replicas: 5
  selector:
    matchLabels:
      app: analysis-demo
  template:
    metadata:
      labels:
        app: analysis-demo
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
        prometheus.io/path: /metrics
    spec:
      containers:
      - name: app
        image: argoproj/rollouts-demo:blue
        ports:
        - name: http
          containerPort: 8080
  strategy:
    canary:
      analysis:
        templates:
        - templateName: success-rate
        startingStep: 1
        args:
        - name: pod-hash
          valueFrom:
            podTemplateHashValue: Latest
      steps:
      - setWeight: 20
      - pause: {duration: 2m}
      - setWeight: 50
      - pause: {duration: 2m}
kubectl argo rollouts set image analysis-demo app=argoproj/rollouts-demo:yellow
kubectl argo rollouts get rollout analysis-demo --watch
kubectl get analysisruns
kubectl argo rollouts get analysisrun <name>
  • podTemplateHashValue: Latest = canary RS hash, Stable = stable RS hash
  • startingStep delays the background run until that step

Inline analysis

  • Analysis as a step: rollout waits for the AnalysisRun to finish before the next step
  strategy:
    canary:
      steps:
      - setWeight: 20
      - analysis:
          templates:
          - templateName: success-rate
          args:
          - name: pod-hash
            valueFrom:
              podTemplateHashValue: Latest
      - setWeight: 50
      - pause: {duration: 1m}
  • Multiple templates can be listed in one step; all must pass
  • Metrics need a finite count here, otherwise the step never completes

Failing analysis

  • Always-failing template to see the automatic rollback; vector(0.5) always returns 0.5
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: always-fail
spec:
  metrics:
  - name: always-fail
    interval: 10s
    count: 3
    failureLimit: 0
    successCondition: result[0] > 1.0
    provider:
      prometheus:
        address: http://prometheus.monitoring.svc.cluster.local:9090
        query: vector(0.5)
  • Add - analysis: {templates: [{templateName: always-fail}]} as a step after setWeight: 20, then change the image
kubectl argo rollouts set image analysis-demo app=argoproj/rollouts-demo:red
kubectl argo rollouts get rollout analysis-demo --watch
  • AnalysisRun Failed -> rollout aborted -> canary scaled down, traffic back on stable, status Degraded

Other providers

  • web: HTTP GET, value pulled with jsonPath
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: web-metric
spec:
  metrics:
  - name: web
    interval: 10s
    count: 3
    successCondition: result == "Yours Truly"
    provider:
      web:
        url: https://httpbin.org/json
        jsonPath: "{$.slideshow.author}"
  • job: runs a Job, exit 0 = success
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: smoke-test
spec:
  metrics:
  - name: smoke
    provider:
      job:
        spec:
          backoffLimit: 0
          template:
            spec:
              restartPolicy: Never
              containers:
              - name: test
                image: curlimages/curl
                command: [sh, -c, "curl -sf http://analysis-demo/color"]
  • Same template for all rollouts across namespaces: ClusterAnalysisTemplate with clusterScope: true on the reference

Manual AnalysisRun

apiVersion: argoproj.io/v1alpha1
kind: AnalysisRun
metadata:
  name: manual-run
spec:
  metrics:
  - name: up
    interval: 10s
    count: 3
    successCondition: result[0] == 1
    provider:
      prometheus:
        address: http://prometheus.monitoring.svc.cluster.local:9090
        query: up{job="kubernetes-pods"}

Debug

kubectl get analysisruns
kubectl get analysisruns -o json | jq '.items[] | {name: .metadata.name, phase: .status.phase}'
kubectl get analysisrun <name> -o json | jq '.status.metricResults'
kubectl describe analysisrun <name>
  • Phases: Pending, Running, Successful, Failed, Error, Inconclusive
  • Check the query in the Prometheus UI first; empty result = no data, which errors/fails

Cleanup

kubectl delete namespace analysis-demo
kubectl delete namespace monitoring
kubectl delete clusterrole,clusterrolebinding prometheus