Osservabilità delle applicazioni con Prometheus su GKE

Questo tutorial mostra come configurare i probe di attività per i microservizi delle applicazioni di cui è stato eseguito il deployment in Google Kubernetes Engine (GKE) utilizzando Prometheus open source Prometheus.

Questo tutorial utilizza Prometheus open source. Tuttavia, ogni cluster GKE Autopilot esegue automaticamente il deployment di Managed Service per Prometheus, Google Cloudla soluzione completamente gestita, multi-cloud e cross-project di per le metriche di Prometheus. Managed Service per Prometheus ti consente di monitorare e creare avvisi sui tuoi carichi di lavoro a livello globale utilizzando Prometheus, senza dover gestire e utilizzare manualmente Prometheus su larga scala.

Puoi anche utilizzare strumenti open source come Grafana per visualizzare le metriche raccolte da Prometheus.

Obiettivi

  • Creare un cluster.
  • Eseguire il deployment di Prometheus.
  • Eseguire il deployment dell'applicazione di esempio, Bank of Anthos.
  • Configurare i probe di attività di Prometheus.
  • Configurare gli avvisi di Prometheus.
  • Configurare Alertmanager per ricevere notifiche in un canale Slack.
  • Simulare un'interruzione del servizio per testare Prometheus.

Costi

In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:

Per generare una stima dei costi in base all'utilizzo previsto, utilizza il calcolatore prezzi.

I nuovi Google Cloud utenti potrebbero avere diritto a una prova senza costi.

Al termine delle attività descritte in questo documento, puoi evitare l'addebito di ulteriori costi eliminando le risorse che hai creato. Per saperne di più, consulta Esegui la pulizia.

Prima di iniziare

  1. Accedi al tuo Google Cloud account. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti senza costi per l'esecuzione, il test e il deployment dei workload.
  2. In the Google Cloud console, on the project selector page, click Create project to begin creating a new Google Cloud project.

    Roles required to create a project

    To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the GKE API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, click Create project to begin creating a new Google Cloud project.

    Roles required to create a project

    To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the GKE API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. Installa l' API Helm

Prepara l'ambiente

In questo tutorial utilizzerai Cloud Shell per gestire le risorse ospitate su Google Cloud.

  1. Imposta le variabili di ambiente predefinite:

    gcloud config set project PROJECT_ID
    gcloud config set compute/region CONTROL_PLANE_LOCATION
    

    Sostituisci quanto segue:

    • PROJECT_ID: il tuo Google Cloud ID progetto.
    • CONTROL_PLANE_LOCATION: la regione Compute Engine del piano di controllo del cluster. Per questo tutorial, la regione è us-central1. In genere, ti consigliamo di scegliere una regione vicina a te.
  2. Clona il repository di esempio utilizzato in questo tutorial:

    git clone https://github.com/GoogleCloudPlatform/bank-of-anthos.git
    cd bank-of-anthos/
    
  3. Crea un cluster:

    gcloud container clusters create-auto CLUSTER_NAME \
        --release-channel=CHANNEL_NAME \
        --location=CONTROL_PLANE_LOCATION
    

    Sostituisci quanto segue:

    • CLUSTER_NAME: un nome per il nuovo cluster.
    • CHANNEL_NAME: il nome di un canale di rilascio.

Esegui il deployment di Prometheus

Installa Prometheus utilizzando il grafico Helm di esempio:

helm repo add bitnami https://charts.bitnami.com/bitnami
helm install tutorial bitnami/kube-prometheus \
    --version 8.2.2 \
    --values extras/prometheus/oss/values.yaml \
    --wait

Questo comando installa Prometheus con i seguenti componenti:

  • Operatore Prometheus: un modo diffuso per eseguire il deployment e configurare Prometheus open source.
  • Alertmanager: gestisce gli avvisi inviati dal server Prometheus e li indirizza alle applicazioni, ad esempio Slack.
  • Blackbox exporter: consente a Prometheus di eseguire il probing degli endpoint utilizzando HTTP, HTTPS, DNS, TCP, ICMP e gRPC.

Esegui il deployment di Bank of Anthos

Esegui il deployment dell'applicazione di esempio Bank of Anthos:

kubectl apply -f extras/jwt/jwt-secret.yaml
kubectl apply -f kubernetes-manifests

Notifiche Slack

Per configurare le notifiche Slack, devi creare un'applicazione Slack, attivare i webhook in entrata per l'applicazione e installare l'applicazione in un workspace Slack.

Crea l'applicazione Slack

  1. Unisciti a un workspace Slack, registrandoti con la tua email o utilizzando un invito inviato da un amministratore di Workspace.

  2. Accedi a Slack utilizzando il nome del workspace e le credenziali dell'account Slack.

  3. Crea una nuova app Slack

    1. Nella finestra di dialogo Crea un'app, fai clic su Da zero.
    2. Specifica un nome app e scegli il tuo workspace Slack.
    3. Fai clic su Crea app.
    4. In Aggiungi funzionalità, fai clic su Webhook in entrata.
    5. Fai clic sul pulsante di attivazione/disattivazione Attiva webhook in entrata.
    6. Nella sezione URL webhook per il tuo workspace, fai clic su Aggiungi nuovo webhook al workspace.
    7. Nella pagina di autorizzazione che si apre, seleziona un canale per ricevere le notifiche.
    8. Fai clic su Consenti.
    9. Un webhook per l'applicazione Slack viene visualizzato nella sezione URL webhook per il tuo workspace. Salva l'URL per un utilizzo futuro.

Configura Alertmanager

Crea un secret di Kubernetes per archiviare l'URL webhook:

kubectl create secret generic alertmanager-slack-webhook --from-literal webhookURL=SLACK_WEBHOOK_URL
kubectl apply -f extras/prometheus/oss/alertmanagerconfig.yaml

Sostituisci SLACK_WEBHOOK_URL con l'URL del webhook della sezione precedente.

Configura Prometheus

  1. Esamina il seguente manifest:

    # Copyright 2023 Google LLC
    #
    # 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.
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: frontend-probe
    spec:
      jobName: frontend
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - frontend:80
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: userservice-probe
    spec:
      jobName: userservice
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - userservice:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: balancereader-probe
    spec:
      jobName: balancereader
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - balancereader:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: contacts-probe
    spec:
      jobName: contacts
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - contacts:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: ledgerwriter-probe
    spec:
      jobName: ledgerwriter
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - ledgerwriter:8080/ready
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: Probe
    metadata:
      name: transactionhistory-probe
    spec:
      jobName: transactionhistory
      prober:
        url: tutorial-kube-prometheus-blackbox-exporter:19115
        path: /probe
      module: http_2xx
      interval: 60s
      scrapeTimeout: 30s
      targets:
        staticConfig:
          labels:
            app: bank-of-anthos
          static:
            - transactionhistory:8080/ready
    

    Questo manifest descrive i probe di attività di Prometheus e include i seguenti campi:

    • spec.jobName: il nome del job assegnato alle metriche di cui è stato eseguito lo scraping.
    • spec.prober.url: l'URL del servizio dell'exporter blackbox. Include la porta predefinita per l'exporter blackbox, definita nel grafico Helm.
    • spec.prober.path: il percorso di raccolta delle metriche.
    • spec.targets.staticConfig.labels: le etichette assegnate a tutte le metriche di cui è stato eseguito lo scraping dalle destinazioni.
    • spec.targets.staticConfig.static: l'elenco degli host di cui eseguire il probing.
  2. Applica il manifest al cluster:

    kubectl apply -f extras/prometheus/oss/probes.yaml
    
  3. Esamina il seguente manifest:

    # Copyright 2023 Google LLC
    #
    # 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.
    ---
    apiVersion: monitoring.coreos.com/v1
    kind: PrometheusRule
    metadata:
      name: uptime-rule
    spec:
      groups:
      - name: Micro services uptime
        interval: 60s
        rules:
        - alert: BalancereaderUnavaiable
          expr: probe_success{app="bank-of-anthos",job="balancereader"} == 0
          for: 1m
          annotations:
            summary: Balance Reader Service is unavailable
            description: Check Balance Reader pods and it's logs
          labels:
            severity: 'critical'
        - alert: ContactsUnavaiable
          expr: probe_success{app="bank-of-anthos",job="contacts"} == 0
          for: 1m
          annotations:
            summary: Contacs Service is unavailable
            description: Check Contacs pods and it's logs
          labels:
            severity: 'warning'
        - alert: FrontendUnavaiable
          expr: probe_success{app="bank-of-anthos",job="frontend"} == 0
          for: 1m
          annotations:
            summary: Frontend Service is unavailable
            description: Check Frontend pods and it's logs
          labels:
            severity: 'critical'
        - alert: LedgerwriterUnavaiable
          expr: probe_success{app="bank-of-anthos",job="ledgerwriter"} == 0
          for: 1m
          annotations:
            summary: Ledger Writer Service is unavailable
            description: Check Ledger Writer pods and it's logs
          labels:
            severity: 'critical'
        - alert: TransactionhistoryUnavaiable
          expr: probe_success{app="bank-of-anthos",job="transactionhistory"} == 0
          for: 1m
          annotations:
            summary: Transaction History Service is unavailable
            description: Check Transaction History pods and it's logs
          labels:
            severity: 'critical'
        - alert: UserserviceUnavaiable
          expr: probe_success{app="bank-of-anthos",job="userservice"} == 0
          for: 1m
          annotations:
            summary: User Service is unavailable
            description: Check User Service pods and it's logs
          labels:
            severity: 'critical'
    

    Questo manifest descrive un PrometheusRule e include i seguenti campi:

    • spec.groups.[*].name: il nome del gruppo di regole.
    • spec.groups.[*].interval: la frequenza con cui vengono valutate le regole nel gruppo.
    • spec.groups.[*].rules[*].alert: il nome dell'avviso.
    • spec.groups.[*].rules[*].expr: l'espressione PromQL da valutare.
    • spec.groups.[*].rules[*].for: il periodo di tempo in cui gli avvisi devono essere restituiti prima di essere considerati attivi.
    • spec.groups.[*].rules[*].annotations: un elenco di annotazioni da aggiungere a ogni avviso. È valido solo per le regole di avviso.
    • spec.groups.[*].rules[*].labels: le etichette da aggiungere o sovrascrivere.
  4. Applica il manifest al cluster:

    kubectl apply -f extras/prometheus/oss/rules.yaml
    

Simula un'interruzione del servizio

  1. Simula un'interruzione del servizio scalando il deployment contacts a zero:

    kubectl scale deployment contacts --replicas 0
    

    Dovresti visualizzare un messaggio di notifica nel canale del workspace Slack. GKE potrebbe impiegare fino a 5 minuti per scalare il deployment.

  2. Ripristina il deployment contacts:

    kubectl scale deployment contacts --replicas 1
    

    Dovresti visualizzare un messaggio di notifica di risoluzione dell'avviso nel canale del workspace Slack. GKE potrebbe impiegare fino a 5 minuti per scalare il deployment.

Libera spazio

Per evitare che al tuo Account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, elimina il progetto che contiene le risorse oppure mantieni il progetto ed elimina le singole risorse.

Elimina il progetto

    Elimina un Google Cloud progetto:

    gcloud projects delete PROJECT_ID

Elimina singole risorse

  1. Elimina le risorse Kubernetes:

    kubectl delete -f kubernetes-manifests
    
  2. Disinstalla Prometheus:

    helm uninstall tutorial
    
  3. Elimina il cluster GKE:

    gcloud container clusters delete CLUSTER_NAME --quiet
    

Passaggi successivi

  • Scopri di più su Google Cloud Managed Service per Prometheus, una soluzione di metriche globali completamente gestita, basata su Prometheus, di cui viene eseguito il deployment per impostazione predefinita in tutti i cluster Autopilot.
  • Esplora architetture, diagrammi e best practice di riferimento su Google Cloud. Consulta il nostro Cloud Architecture Center.