Kube State 指標

このドキュメントでは、Google Cloud Managed Service for Prometheus を使用して Kube State 指標から指標を収集できるように、Google Kubernetes Engine のデプロイを構成する方法について説明します。このドキュメントでは、次の方法について説明します。

  • 指標を報告するように Kube 状態指標を設定する。
  • エクスポートされた指標を収集するために、Managed Service for Prometheus の PodMonitoring リソースを構成する。
  • Cloud Monitoring のダッシュボードにアクセスして指標を表示する。
  • 指標をモニタリングするようにアラートルールを構成する。

以下の手順は、Managed Service for Prometheus でマネージド コレクションを使用している場合にのみ適用されます。セルフデプロイ コレクションを使用している場合は、Kube State 指標のソース リポジトリでインストール情報をご覧ください。

以下の手順は一例であり、ほとんどの Kubernetes 環境で機能します。セキュリティ ポリシーや組織のポリシーの制限により、アプリケーションやエクスポータのインストールに問題がある場合は、オープンソース ドキュメントでサポートを確認することをおすすめします。

前提条件

Managed Service for Prometheus とマネージド コレクションを使用して Kube State 指標から指標を収集するには、デプロイが次の要件を満たしている必要があります。

  • クラスタで Google Kubernetes Engine バージョン 1.21.4-gke.300 以降を実行している必要があります。
  • マネージド コレクションを有効にして、Managed Service for Prometheus を実行する必要があります。詳細については、マネージド コレクションを使ってみるをご覧ください。

  • インテグレーションで Cloud Monitoring で利用可能なダッシュボードを使用するには、kube-state-metrics バージョン 2.4.2 以降を使用する必要があります。

    利用可能なダッシュボードの詳細については、ダッシュボードをインストールするをご覧ください。

マネージド Kube 状態指標

GKE では、この統合を構成する代わりに、kube 状態指標のフルマネージド デプロイを使用できます。インストール可能なパッケージを使用すると、セットアップが簡単な独自のキュレートされた kube 状態指標のセットを利用できます。詳細については、パッケージ: Kube 状態指標をご覧ください。

Kube 状態指標をインストールする

Kube 状態指標のインストールには、次の構成を使用します。

# 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
# limitations under the License.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
  namespace: gmp-public
  name: kube-state-metrics
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  serviceName: kube-state-metrics
  template:
    metadata:
      labels:
        app.kubernetes.io/name: kube-state-metrics
        app.kubernetes.io/version: 2.8.2
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/arch
                operator: In
                values:
                - arm64
                - amd64
              - key: kubernetes.io/os
                operator: In
                values:
                - linux
      containers:
      - name: kube-state-metric
        image: k8s.gcr.io/kube-state-metrics/kube-state-metrics:v2.8.2
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        args:
        - --pod=$(POD_NAME)
        - --pod-namespace=$(POD_NAMESPACE)
        - --port=8080
        - --telemetry-port=8081
        ports:
        - name: metrics
          containerPort: 8080
        - name: metrics-self
          containerPort: 8081
        resources:
          requests:
            cpu: 100m
            memory: 190Mi
          limits:
            memory: 250Mi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          capabilities:
            drop:
            - all
          runAsUser: 1000
          runAsGroup: 1000
        livenessProbe:
          httpGet:
            path: /healthz
            port: 8080
          initialDelaySeconds: 5
          timeoutSeconds: 5
        readinessProbe:
          httpGet:
            path: /
            port: 8081
          initialDelaySeconds: 5
          timeoutSeconds: 5
      serviceAccountName: kube-state-metrics
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
  namespace: gmp-public
  name: kube-state-metrics
spec:
  clusterIP: None
  ports:
  - name: metrics
    port: 8080
    targetPort: metrics
  - name: metrics-self
    port: 8081
    targetPort: metrics-self
  selector:
    app.kubernetes.io/name: kube-state-metrics
---
apiVersion: v1
kind: ServiceAccount
metadata:
  namespace: gmp-public
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: gmp-public:kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: gmp-public:kube-state-metrics
subjects:
- kind: ServiceAccount
  namespace: gmp-public
  name: kube-state-metrics
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: gmp-public:kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/version: 2.8.2
rules:
- apiGroups:
  - ""
  resources:
  - configmaps
  - secrets
  - nodes
  - pods
  - services
  - resourcequotas
  - replicationcontrollers
  - limitranges
  - persistentvolumeclaims
  - persistentvolumes
  - namespaces
  - endpoints
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
- apiGroups:
  - extensions
  resources:
  - daemonsets
  - deployments
  - replicasets
  - ingresses
  verbs:
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - statefulsets
  - daemonsets
  - deployments
  - replicasets
  verbs:
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - statefulsets
  verbs:
  - get
- apiGroups:
  - batch
  resources:
  - cronjobs
  - jobs
  verbs:
  - list
  - watch
- apiGroups:
  - autoscaling
  resources:
  - horizontalpodautoscalers
  verbs:
  - list
  - watch
- apiGroups:
  - authentication.k8s.io
  resources:
  - tokenreviews
  verbs:
  - create
- apiGroups:
  - authorization.k8s.io
  resources:
  - subjectaccessreviews
  verbs:
  - create
- apiGroups:
  - policy
  resources:
  - poddisruptionbudgets
  verbs:
  - list
  - watch
- apiGroups:
  - certificates.k8s.io
  resources:
  - certificatesigningrequests
  verbs:
  - list
  - watch
- apiGroups:
  - storage.k8s.io
  resources:
  - storageclasses
  - volumeattachments
  verbs:
  - list
  - watch
- apiGroups:
  - admissionregistration.k8s.io
  resources:
  - mutatingwebhookconfigurations
  - validatingwebhookconfigurations
  verbs:
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - networkpolicies
  - ingresses
  verbs:
  - list
  - watch
- apiGroups:
  - coordination.k8s.io
  resources:
  - leases
  verbs:
  - list
  - watch
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: kube-state-metrics
  namespace: gmp-public
spec:
  maxReplicas: 10
  minReplicas: 1
  scaleTargetRef:
    apiVersion: apps/v1
    kind: StatefulSet
    name: kube-state-metrics
  metrics:
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 60
  behavior:
    scaleDown:
      policies:
      - type: Pods
        value: 1
        # Under-utilization needs to persist for `periodSeconds` before any action can be taken.
        # Current supported max from https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2beta2/.
        periodSeconds: 1800
      # Current supported max from https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2beta2/.
      stabilizationWindowSeconds: 3600
---
apiVersion: monitoring.googleapis.com/v1
kind: ClusterPodMonitoring
metadata:
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: metrics
    interval: 30s
    metricRelabeling:
    - action: keep
      # Curated subset of metrics to reduce costs while populating default set of sample dashboards at
      # https://github.com/GoogleCloudPlatform/monitoring-dashboard-samples/tree/master/dashboards/kubernetes
      # Change this regex to fit your needs for which objects you want to monitor
      regex: kube_(daemonset|deployment|replicaset|pod|namespace|node|statefulset|persistentvolume|horizontalpodautoscaler|job_created)(_.+)?
      sourceLabels: [__name__]
  targetLabels:
    metadata: [] # explicitly empty so the metric labels are respected
---
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  namespace: gmp-public
  name: kube-state-metrics
  labels:
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: metrics-self
    interval: 30s

構成の変更内容をローカル ファイルから適用するには、次のコマンドを実行します。

kubectl apply -f FILE_NAME

Terraform を使用して構成を管理することもできます。

ルールとアラートを定義する

次の Rules 構成を使用して、指標に関するアラートを定義できます。

# 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: monitoring.googleapis.com/v1
kind: Rules
metadata:
  namespace: gmp-public
  name: kube-state-metrics-rules
  labels:
    app.kubernetes.io/component: rules
    app.kubernetes.io/name: kube-state-metrics
    app.kubernetes.io/part-of: google-cloud-managed-prometheus
spec:
  groups:
    - name: kube-state-metrics
      interval: 30s
      rules:
      - alert: KubeStateMetricsListErrors
        annotations:
          description: kube-state-metrics is experiencing errors at an elevated rate in list operations. This is likely causing it to not be able to expose metrics about Kubernetes objects correctly or at all.
          summary: kube-state-metrics is experiencing errors in list operations.
        expr: |
          (sum(rate(kube_state_metrics_list_total{job="kube-state-metrics",result="error"}[5m]))
            /
          sum(rate(kube_state_metrics_list_total{job="kube-state-metrics"}[5m])))
          > 0.01
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsWatchErrors
        annotations:
          description: kube-state-metrics is experiencing errors at an elevated rate in watch operations. This is likely causing it to not be able to expose metrics about Kubernetes objects correctly or at all.
          summary: kube-state-metrics is experiencing errors in watch operations.
        expr: |
          (sum(rate(kube_state_metrics_watch_total{job="kube-state-metrics",result="error"}[5m]))
            /
          sum(rate(kube_state_metrics_watch_total{job="kube-state-metrics"}[5m])))
          > 0.01
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsShardingMismatch
        annotations:
          description: kube-state-metrics pods are running with different --total-shards configuration, some Kubernetes objects may be exposed multiple times or not exposed at all.
          summary: kube-state-metrics sharding is misconfigured.
        expr: |
          stdvar (kube_state_metrics_total_shards{job="kube-state-metrics"}) != 0
        for: 15m
        labels:
          severity: critical
      - alert: KubeStateMetricsShardsMissing
        annotations:
          description: kube-state-metrics shards are missing, some Kubernetes objects are not being exposed.
          summary: kube-state-metrics shards are missing.
        expr: |
          2^max(kube_state_metrics_total_shards{job="kube-state-metrics"}) - 1
            -
          sum( 2 ^ max by (shard_ordinal) (kube_state_metrics_shard_ordinal{job="kube-state-metrics"}) )
          != 0
        for: 15m
        labels:
          severity: critical

構成の変更内容をローカル ファイルから適用するには、次のコマンドを実行します。

kubectl apply -f FILE_NAME

Terraform を使用して構成を管理することもできます。

ルールをクラスタに適用する方法については、マネージド ルールの評価とアラートをご覧ください。

この Rules 構成は kube-state-metrics リポジトリに反映されたルールとアラートを元にしています。

構成を確認する

Metrics Explorer を使用すると、エクスポータが正しく構成されていることを確認できます。Cloud Monitoring が指標を取り込むまでに 1~2 分かかる場合があります。

指標が取り込まれていることを確認します。

  1. Google Cloud コンソールのナビゲーション パネルで [Monitoring] を選択し、次に [ Metrics Explorer] を選択します。

    Metrics Explorer に移動

  2. クエリビルダー ペインのツールバーで、[MQL] または [PROMQL] という名前のボタンを選択します。
  3. [言語] で [PromQL] が選択されていることを確認します。言語切り替えボタンは、クエリの書式設定と同じツールバーにあります。
  4. 次のクエリを入力して実行します。
    up{job="kube-state-metrics", cluster="CLUSTER_NAME", namespace="gmp-public"}
    

ダッシュボードをインストールする

Cloud Monitoring には、インテグレーション用のサンプル ダッシュボードのライブラリが用意されています。サンプル ライブラリには、[Prometheus] ダッシュボードが含まれています。このダッシュボードをインストールして、Google Cloud コンソールでデータを表示できます。

[Kubernetes Cluster Prometheus Overview] ダッシュボードを使用するには、ノード エクスポータをインストールする必要があります。[Kubernetes Pod Prometheus Overview] ダッシュボードには、ノード エクスポータcAdvisor / Kubelet をインストールする必要があります。

サンプル ライブラリからダッシュボードをインストールするには、次のように操作します。

  1. Google Cloud コンソールのナビゲーション パネルで、[Monitoring] を選択してから、[ダッシュボード] を選択します。

    [ダッシュボード] に移動

  2. [サンプル ライブラリ] タブを選択します。
  3. [Other] カテゴリを選択します。
  4. (省略可)インストールせずにダッシュボードの静的プレビューを表示するには、[プレビュー] をクリックします。
  5. インストールするダッシュボードを選択して、 [インポート] をクリックします。

ダッシュボードのインストールの詳細については、サンプル ダッシュボードのインストールをご覧ください。

トラブルシューティング

指標の取り込みに関する問題のトラブルシューティングについては、取り込み側の問題のトラブルシューティングエクスポータからの収集に関する問題をご覧ください。