### Deploy example application Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-unmanaged Deploy the example application to the specified Kubernetes namespace using kubectl. This application emits sample metrics. ```bash kubectl -n NAMESPACE_NAME apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/v0.17.2/examples/example-app.yaml ``` -------------------------------- ### Install Node.js modules and build the project Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/import-grafana-dashboards Install the required Node.js dependencies and build the dashboard importer project using npm. ```bash npm install && npm run build ``` -------------------------------- ### Create Kubernetes namespace Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/query-api-ui?hl=fr Create a Kubernetes namespace to organize resources for your application. It is recommended to use 'gmp-test' for the example installation. ```bash kubectl create ns NAMESPACE_NAME ``` -------------------------------- ### Verify app running with curl Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar Sends an HTTP GET request to the service URL using `curl` to verify that the sample app is running correctly. A successful response indicates the app started as expected. ```bash curl $SERVICE_URL ``` -------------------------------- ### Deploy Example Application Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed?hl=zh-CN Deploys a sample application that exposes Prometheus metrics. Ensure you replace NAMESPACE_NAME with your target namespace. ```bash kubectl -n NAMESPACE_NAME apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/v0.15.3/examples/example-app.yaml ``` -------------------------------- ### Generate HTTP Load for Example App Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa Run this command in a separate terminal to generate HTTP load against the example application, which is necessary for the HPA to scale. ```bash kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://prometheus-example-app; done" ``` -------------------------------- ### List installed gcloud CLI components Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-otel?hl=it Use this command to view the installed components of the gcloud CLI. Ensure `kubectl` is installed. ```bash gcloud components list ``` -------------------------------- ### Watch example app pods Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa?hl=es Use kubectl to monitor the pods belonging to the prometheus-example-app. This command should be run in a separate terminal session. ```bash kubectl get po -lapp.kubernetes.io/name=prometheus-example-app --watch ``` -------------------------------- ### Prometheus Rule Example Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/rules-managed?hl=pt This is an example of a Prometheus rule configuration. ```yaml groups: - name: example interval: 30s rules: - record: job:up:sum expr: sum without(instance) (up) - alert: AlwaysFiring expr: vector(1) ``` -------------------------------- ### Apply Rules to Kubernetes Cluster Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/rules-managed?hl=pt-BR Apply the example rules to your Kubernetes cluster using `kubectl apply`. Ensure you replace `NAMESPACE_NAME` with your actual namespace. ```bash kubectl apply -n NAMESPACE_NAME -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/v0.17.2/examples/rules.yaml ``` -------------------------------- ### Example Pod Status Output Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-unmanaged This is an example of the expected output when verifying Prometheus and application pods. It lists the name, readiness, status, restarts, and age of each pod. ```text NAME READY STATUS RESTARTS AGE prom-example-84c6f547f5-fglbr 1/1 Running 0 5m prom-example-84c6f547f5-jnjp4 1/1 Running 0 5m prom-example-84c6f547f5-sqdww 1/1 Running 0 5m prometheus-test-0 2/2 Running 1 3m ``` -------------------------------- ### Watch Workload Scale Up Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa Observe the scaling of pods for the example application as the Horizontal Pod Autoscaler responds to load. ```bash kubectl get po -lapp.kubernetes.io/name=prometheus-example-app --watch ``` -------------------------------- ### Verify Sample App Response Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=es-419 This is the expected output when your application starts successfully and receives a request. ```text User request received! ``` -------------------------------- ### Import Sample Grafana Dashboard Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/import-grafana-dashboards This command imports a sample Grafana dashboard located in the examples directory into your specified Google Cloud project. ```bash ./import.sh examples/k8s_cluster_example.json PROJECT_ID ``` -------------------------------- ### Example TensorFlow Serving container command with monitoring config Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/tf-serving An example of a complete TensorFlow Serving container command that includes the model name, base path, REST API port, and the monitoring configuration file path. ```yaml command: [ "tensorflow_model_server", "--model_name=$MODEL_NAME", "--model_base_path=/data/tfserve-model-repository/$MODEL_NAME", "--rest_api_port=8000", "--monitoring_config_file=$PATH_TO_MONITORING_CONFIG" ] ``` -------------------------------- ### Navigate to the sample application directory Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=es Change the current directory to the 'simple-app' directory within the 'run-gmp-sidecar' repository. ```bash pushd sample-apps/simple-app ``` -------------------------------- ### Install Tomcat Exporter as a Sidecar Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/tomcat?hl=es Install the jmx-exporter as a sidecar container within your Tomcat workload. This configuration is an example and should work in most Kubernetes environments. ```yaml # 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 # # https://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 ``` -------------------------------- ### Install ActiveMQ exporter as a sidecar Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/activemq Modify your ActiveMQ configuration to include the `jmx-exporter` as a sidecar. This setup is recommended for collecting metrics. ```yaml # Copyright 2022 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 # # https://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 ``` -------------------------------- ### Install httpd_exporter as a sidecar Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/apache Modify your Apache Web Server configuration to include the httpd_exporter as a sidecar. This example shows the basic structure for such a configuration. ```yaml # 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 # # https://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 ``` -------------------------------- ### Instalar el adaptador de Stackdriver de métricas personalizadas Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa?hl=es Aplica el manifiesto de producción para instalar el adaptador de Stackdriver de métricas personalizadas en tu clúster. ```bash kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter_new_resource_model.yaml ``` -------------------------------- ### Build and run the sample application Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=es Build the Docker image for the sample application and run it locally to test the Managed Service for Prometheus sidecar integration. ```bash cd run-gmp-sidecar docker build -t my-app . docker run -p 8080:8080 my-app ``` -------------------------------- ### Configure Flink ConfigMap for Prometheus Metrics Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/flink Add the Prometheus reporter factory class to the Flink ConfigMap when deploying Flink with official getting started manifests. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: flink-config labels: app: flink data: flink-conf.yaml: | ... + metrics.reporter.prom.factory.class: org.apache.flink.metrics.prometheus.PrometheusReporterFactory ``` -------------------------------- ### Build the sample application Docker image Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=es Build a Docker image for the 'simple-app' application. The image is tagged with the Artifact Registry path, including the region, project, and repository name. ```bash docker build -t ${REGION}-docker.pkg.dev/${GCP_PROJECT}/run-gmp/sample-app . ``` -------------------------------- ### Install Kafka exporter Deployment Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/kafka Deploy the Kafka exporter using a Kubernetes Deployment. This example assumes Kafka is available as a ClusterIP service named 'kafka' on port '9092'. ```yaml # Copyright 2022 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 # # https://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: apps/v1 kind: Deployment metadata: name: kafka-exporter labels: app.kubernetes.io/name: kafka-exporter spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: kafka-exporter template: metadata: labels: app.kubernetes.io/name: kafka-exporter spec: containers: - name: exporter image: danielqsj/kafka-exporter:v1.6.0 args: - --kafka.server=kafka:9092 ports: - containerPort: 9308 name: prometheus ``` -------------------------------- ### Create Service Account and Artifact Registry Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar Run the provided script to create a service account with necessary roles and an Artifact Registry repository for container images. This setup is required for Cloud Build. ```bash ./create-sa-and-ar.sh ``` -------------------------------- ### Habilitar la elección de líder para alta disponibilidad en Prometheus Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-unmanaged?hl=es-419 Habilita el backend de elección de líder de Kubernetes para la alta disponibilidad en Prometheus. Asegúrate de que la cuenta de servicio de Kubernetes tenga los permisos necesarios para leer y escribir recursos de asignación de tiempo. ```bash ./prometheus \ ... \ --export.ha.backend=kube \ --export.ha.kube.namespace=LEASE_NAMESPACE \ --export.ha.kube.name=LEASE_NAME ``` -------------------------------- ### Install Nginx Exporter as a Sidecar Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/nginx?hl=pt-BR Install the nginx-prometheus-exporter as a sidecar to your Nginx workload by modifying the Nginx configuration. This approach is recommended for integrating the exporter. ```yaml # Copyright 2022 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 # # https:#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 ``` -------------------------------- ### Return to the parent directory Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=es Navigate back to the 'run-gmp-sidecar' directory from the 'simple-app' directory. ```bash popd ``` -------------------------------- ### Example of Invalid Scrape Configuration Path Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting This example shows an improperly formed PodMonitoring or ClusterPodMonitoring custom resource that can lead to scraping issues. ```yaml path: /metrics/detailed?family=queue_metrics&family=queue_consumer_count ``` -------------------------------- ### Cleanup Deployed Example Resources Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa?hl=pt Remove the deployed Stackdriver custom metrics adapter and Prometheus example resources. This includes deleting the adapter, the Prometheus-to-Stackdriver configuration, and the pod monitoring. ```bash kubectl delete -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/deploy/production/adapter_new_resource_model.yaml kubectl delete -f https://raw.githubusercontent.com/GoogleCloudPlatform/k8s-stackdriver/master/custom-metrics-stackdriver-adapter/examples/prometheus-to-sd/custom-metrics-prometheus-sd.yaml kubectl delete podmonitoring/prom-example ``` -------------------------------- ### Update sample app image placeholder in service YAML Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar Replaces the placeholder '%SAMPLE_APP_IMAGE%' in the 'run-service-simple.yaml' file with the actual image path for the sample application. This ensures the correct image is deployed. ```bash sed -i s@%SAMPLE_APP_IMAGE%@${REGION}-docker.pkg.dev/${GCP_PROJECT}/run-gmp/sample-app@g run-service-simple.yaml ``` -------------------------------- ### Example Malformed Metric Names Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting These examples illustrate metric names that are not properly formatted and can lead to exceeding the metric descriptor quota. Ensure metric names do not embed dimensional information. ```text request_path_____path_to_a_resource____istio_request_duration_milliseconds ``` ```text envoy_cluster_grpc_method_name_failure ``` ```text envoy_cluster_clustername_upstream_cx_connect_ms_bucket ``` ```text vault_rollback_attempt_path_name_1700683024 ``` ```text service__________________________________________latency_bucket ``` -------------------------------- ### Prometheus Relabeling Configuration Example Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/setup-otel?hl=zh-CN This example demonstrates how to correctly escape dollar signs in the 'replacement' field of a relabel_config when using the Prometheus receiver with the OpenTelemetry Collector. This is crucial for ensuring the replacement logic functions as intended. ```yaml - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] action: replace regex: (.+):(?: \d+);(\d+) replacement: $$1:$$2 target_label: __address__ ``` -------------------------------- ### Build Monitoring Client with Options Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/manifests?hl=es Constructs a Google Cloud Monitoring client. Supports using Application Default Credentials or a service account specified via an environment variable. Ensure the account has Monitoring Editor or Admin permissions. ```go // Copyright 2024 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. package main import ( "context" "errors" "flag" "fmt" "log" "os" "regexp" "strings" "time" "unicode" monitoring "cloud.google.com/go/monitoring/apiv3/v2" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" "google.golang.org/api/iterator" "google.golang.org/api/option" ) /* This script deletes metric descriptors from the given projects (-projects flag), matching the given metric type (descriptor name) regex expression (-metric_type_regex flag). Metrics to delete will be first printed and then awaiting interactive confirmation, before the actual removal. Dry run option also exists. WARNING: All underlying time series behind each descriptor (potentially years of data) will be irreversibly removed once confirmed. Example run: 1. Setup Application Default Credentials (ADC) (https://cloud.google.com/docs/authentication/provide-credentials-adc) if you haven't yet: 1a. Make sure the account behind the ADC for chosen projects has Monitoring Editor or Monitoring Admin permissions: https://cloud.google.com/monitoring/access-control#monitoring-perms 1b. Acquire Application Default Credentials in your environment using gcloud: gcloud auth application-default login 2. Run Go script (from the same directory as the script): go run delete_metric_descriptors.go -projects projects/ -metric_type_regex "" See go run delete_metric_descriptors.go -help for all options. */ var ( cloudMonitoringEndpoint = flag.String("address", "monitoring.googleapis.com:443", "address of monitoring API") projectNames = flag.String("projects", "", "required: comma-separated project IDs of the projects on which to execute the requests. Name format is as defined in https://cloud.google.com/monitoring/api/ref_v3/rpc/google.monitoring.v3#listmetricdescriptorsrequesttarget, e.g. projects/test-project,projects/test-project2") metricTypeRegex = flag.String("metric_type_regex", "", "required: RE2 regex expression matching metric.type (anchored), so metric descriptor names to delete. Guarded with the interactive 'y' confirmation. See --dry_run to only print those") dryRun = flag.Bool("dry_run", false, "whether to dry run or not") serviceAccountEnvVar = flag.String("sa-envvar", "", "optional environment variable containing Google Service Account JSON, without it application-default flow will be used.") ) func deleteDescriptors(endpoint string, projects []string, re *regexp.Regexp, saEnvVar string, dryRun bool) error { ctx := context.Background() // Recommended way is to use auth from your environment. Use `gcloud auth application-default login` to set it up. client, err := monitoring.NewMetricClient(ctx, func() []option.ClientOption { // Optional, service account JSON in environment variable. if saEnvVar != "" { return []option.ClientOption{ option.WithEndpoint(endpoint), option.WithCredentialsJSON([]byte(os.Getenv(saEnvVar))), } } return []option.ClientOption{option.WithEndpoint(endpoint)} }()...) if err != nil { return fmt.Errorf("failed to build client for %s: %w", endpoint, err) } defer client.Close() // Find descriptors to delete. descsToDelete := map[string][]string{} toDelete := 0 checked := 0 for _, p := range projects { it := client.ListMetricDescriptors(ctx, &monitoringpb.ListMetricDescriptorsRequest{Name: p}) for { resp, err := it.Next() if errors.Is(err, iterator.Done) { break } if err != nil { return fmt.Errorf("ListMetricDescriptors iteration: %w", err) } checked++ if !re.MatchString(resp.Type) { continue } descsToDelete[p] = append(descsToDelete[p], resp.Type) toDelete++ } } // Print and perform interactive safety check. { for p, descs := range descsToDelete { fmt.Println() fmt.Printf("For project %v:\n", p) fmt.Println(descs) } fmt.Printf("After checking %v descriptors, found %v to delete across %v project(s)\n", checked, toDelete, len(projects)) fmt.Println() } if toDelete == 0 { fmt.Println("nothing to do, job done!") return nil } if dryRun { fmt.Println("-dry_run selected, job done!") return nil } if !confirmDelete() { fmt.Println("Deletion not confirmed, exiting") return nil } // Delete. deleted := 0 for p, descs := range descsToDelete { for _, d := range descs { ``` -------------------------------- ### Prometheus HTTP API Base URL and Query Example Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/query-api-ui The Managed Service for Prometheus supports the upstream Prometheus HTTP API. The base URL is `https://monitoring.googleapis.com/v1/projects/PROJECT_ID/location/global/prometheus/api/v1/`. This example shows how to perform an instant query for the 'up' metric using curl. ```APIDOC ## GET /api/v1/query ### Description Performs an instant query to retrieve time series data based on a PromQL expression. ### Method GET ### Endpoint `https://monitoring.googleapis.com/v1/projects/PROJECT_ID/location/global/prometheus/api/v1/query` ### Query Parameters - **query** (string) - Required - The PromQL expression to evaluate. ### Request Example ```bash curl https://monitoring.googleapis.com/v1/projects/PROJECT_ID/location/global/prometheus/api/v1/query \ -d "query=up" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" ``` ### Response #### Success Response (200) - **status** (string) - The status of the query execution ('success' or 'error'). - **data** (object) - Contains the query results. - **resultType** (string) - The type of the result (e.g., 'vector', 'matrix', 'scalar', 'string'). - **result** (array) - An array of time series data points or values. - **metric** (object) - Labels identifying the time series. - **value** (array) - A pair of timestamp and value for a vector result. #### Response Example ```json { "status":"success", "data":{ "resultType":"vector", "result":[ { "metric": { "__name__":"up", "cluster":"gmp-test", "instance":"prom-example-84c6f547f5-g4ljn:web", "job":"prometheus", "location":"us-central1-a", "project_id":"a-gcp-project" }, "value": [1634873239.971,"1"] } ] } } ``` ``` -------------------------------- ### ClusterRole for reading secrets Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/inference-optimized-gateway Grants permissions to get, list, and watch specific secrets. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: inference-gateway-sa-metrics-reader-secret-read rules: - resources: - secrets apiGroups: [""] verbs: ["get", "list", "watch"] resourceNames: ["inference-gateway-sa-metrics-reader-secret"] --- ``` -------------------------------- ### Executar consulta PromQL básica no Cloud Monitoring Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/query-cm?hl=pt-BR Use esta consulta PromQL simples para verificar se os dados do Prometheus estão sendo ingeridos corretamente no Cloud Monitoring. Certifique-se de que o idioma esteja definido como PromQL no Metrics Explorer. ```PromQL up ``` -------------------------------- ### Create and Download Service Account Key Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/query-api-ui Generate a JSON key file for the service account. This key will be used for authentication in non-GKE environments. ```bash gcloud iam service-accounts keys create gmp-test-sa-key.json \ --iam-account=gmp-test-sa@PROJECT_ID.iam.gserviceaccount.com ``` -------------------------------- ### ClusterRole for metrics reader Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/inference-optimized-gateway Defines RBAC permissions to get metrics from the /metrics endpoint. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: inference-gateway-metrics-reader rules: - nonResourceURLs: - /metrics verbs: - get --- ``` -------------------------------- ### Clone the run-gmp-sidecar repository Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/cloudrun-sidecar?hl=pt-BR Clone the repository to get the sample application code for the run-gmp-sidecar. ```bash git clone https://github.com/GoogleCloudPlatform/run-gmp-sidecar.git ``` -------------------------------- ### Consultar métricas de PostgreSQL con PromQL Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/postgresql?hl=es-419 Usa esta consulta PromQL en el Explorador de métricas para verificar que las métricas del exportador de PostgreSQL se estén transfiriendo correctamente. Asegúrate de reemplazar CLUSTER_NAME y NAMESPACE_NAME con tus valores específicos. ```promql up{job="postgresql", cluster="CLUSTER_NAME", namespace="NAMESPACE_NAME"} ``` -------------------------------- ### View Grafana Initialization Job Logs Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/query Retrieve logs for the Job that configures Grafana immediately after applying the datasource-syncer.yaml file. ```bash kubectl logs job.batch/datasource-syncer-init ``` -------------------------------- ### Kubernetes NetworkPolicy Example Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/exporters/kube_state_metrics This NetworkPolicy allows listing and watching specific resources. Ensure this aligns with your security requirements. ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: example-network-policy spec: podSelector: matchLabels: app: my-app policyTypes: - Ingress - Egress ingress: - from: - podSelector: matchLabels: role: frontend ports: - protocol: TCP port: 8080 egress: - to: - ipBlock: cidr: 192.168.0.0/16 ports: - protocol: TCP port: 5432 ``` -------------------------------- ### Definir recurso PodMonitoring Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/hpa?hl=es Crea un archivo YAML para definir un recurso PodMonitoring que seleccione pods con etiquetas específicas y configure la recolección de métricas. ```yaml apiVersion: monitoring.googleapis.com/v1 kind: PodMonitoring metadata: name: prom-example spec: selector: matchLabels: run: custom-metric-prometheus-sd endpoints: - port: 8080 interval: 30s ``` -------------------------------- ### Initialize Monitoring Client in Go Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/manifests?hl=de Initializes a Google Cloud Monitoring client. It supports using Application Default Credentials (ADC) or a service account specified via an environment variable. Ensure the endpoint is correctly configured. ```go // Copyright 2024 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. package main import ( "context" "errors" "flag" "fmt" "log" "os" "regexp" "strings" "time" "unicode" monitoring "cloud.google.com/go/monitoring/apiv3/v2" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" "google.golang.org/api/iterator" "google.golang.org/api/option" ) var ( cloudMonitoringEndpoint = flag.String("address", "monitoring.googleapis.com:443", "address of monitoring API") projectNames = flag.String("projects", "", "required: comma-separated project IDs of the projects on which to execute the requests. Name format is as defined in https://cloud.google.com/monitoring/api/ref_v3/rpc/google.monitoring.v3#listmetricdescriptorsrequesttarget, e.g. projects/test-project,projects/test-project2") metricTypeRegex = flag.String("metric_type_regex", "", "required: RE2 regex expression matching metric.type (anchored), so metric descriptor names to delete. Guarded with the interactive 'y' confirmation. See --dry_run to only print those") dryRun = flag.Bool("dry_run", false, "whether to dry run or not") serviceAccountEnvVar = flag.String("sa-envvar", "", "optional environment variable containing Google Service Account JSON, without it application-default flow will be used.") ) func deleteDescriptors(endpoint string, projects []string, re *regexp.Regexp, saEnvVar string, dryRun bool) error { ctx := context.Background() // Recommended way is to use auth from your environment. Use `gcloud auth application-default login` to set it up. client, err := monitoring.NewMetricClient(ctx, func() []option.ClientOption { // Optional, service account JSON in environment variable. if saEnvVar != "" { return []option.ClientOption{ option.WithEndpoint(endpoint), option.WithCredentialsJSON([]byte(os.Getenv(saEnvVar))), } } return []option.ClientOption{option.WithEndpoint(endpoint)} }()...) if err != nil { return fmt.Errorf("failed to build client for %s: %w", endpoint, err) } defer client.Close() // Find descriptors to delete. descsToDelete := map[string][]string{} toDelete := 0 checked := 0 for _, p := range projects { it := client.ListMetricDescriptors(ctx, &monitoringpb.ListMetricDescriptorsRequest{Name: p}) for { resp, err := it.Next() if errors.Is(err, iterator.Done) { break } if err != nil { return fmt.Errorf("ListMetricDescriptors iteration: %w", err) } checked++ if !re.MatchString(resp.Type) { continue } descsToDelete[p] = append(descsToDelete[p], resp.Type) toDelete++ } } // Print and perform interactive safety check. { for p, descs := range descsToDelete { fmt.Println() fmt.Printf("For project %v:\n", p) fmt.Println(descs) } fmt.Printf("After checking %v descriptors, found %v to delete across %v project(s)\n", checked, toDelete, len(projects)) fmt.Println() } if toDelete == 0 { fmt.Println("nothing to do, job done!") return nil } if dryRun { fmt.Println("-dry_run selected, job done!") return nil } if !confirmDelete() { fmt.Println("Deletion not confirmed, exiting") return nil } // Delete. deleted := 0 for p, descs := range descsToDelete { for _, d := range descs { ``` -------------------------------- ### Get Secret Data Keys Source: https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting Use this command to inspect the keys within a Kubernetes secret, useful for verifying secret contents. ```bash kubectl get secret gmp-test-sa -o json | jq '.data | keys' ```