はじめに
以前、kube-state-metrics でカスタムリソースのメトリクスを取得する方法という記事を書きました。この記事で紹介した Custom Resource State Metrics の後継として、resource-state-metrics(旧 CRDMetrics Controller)の開発が進められています。
Custom Resource State Metrics への新規機能の追加は凍結されています。また、kube-state-metrics v3 の計画では、Custom Resource State Metrics を resource-state-metrics に置き換える案が挙がっています。ただし、変更内容や実施時期はまだ確定していません。
(参考: kube-state-metrics README、v3 Plan #3118)
本記事では、resource-state-metrics の概要・仕組み・使い方を説明します。
対象コンポーネントとバージョン
| コンポーネント | バージョン | リポジトリ |
|---|---|---|
| kube-state-metrics | v2.20.0 | kubernetes/kube-state-metrics |
| resource-state-metrics | v0.1.0 | kubernetes-sigs/resource-state-metrics |
| Vertical Pod Autoscaler | v1.8.1 | kubernetes/autoscaler |
| Metrics Server | v0.9.1 | kubernetes-sigs/metrics-server |
| kind | v0.33.0 | kubernetes-sigs/kind |
| Kubernetes | v1.37.0 | kubernetes/kubernetes |
TL;DR
- resource-state-metrics は、Custom Resource State Metrics の後継として開発されている独立したコントローラーです。kube-state-metrics の native metrics とは別プロセスで動きます。
- 導入は、デプロイ・読み取り権限の付与・ResourceMetricsMonitor の作成の3ステップです。対象リソースと、メトリクスの名前・値・ラベルを ResourceMetricsMonitor に定義します。
-
処理に応じて Resolver を選ぶのが良いと思います。直接参照は
unstructured、式による変換は CEL、複数コンテナの名前と値を組にする処理は本記事では Starlark を使います。 -
VPA の recommendation をメトリクスとして取得する例を紹介します。kind 上で実行し、
kubectl port-forwardとcurlで VPA の status とメトリクスの値が一致することを確認します。
第1章: カスタムリソースのメトリクスを取得したい理由
カスタムコントローラーを開発・運用すると、管理するカスタムリソースの状態をメトリクスとして取得し、監視したくなることがあります。
例えば Vertical Pod Autoscaler(VPA)では、CPU・メモリの recommendation をメトリクスとして取得し、現在の requests と比較する用途があります。kube-state-metrics の Custom Resource State Metrics には、この用途に使えるVPA の設定サンプルが用意されています。
ほかにも、カスタムリソースに記録された次のような情報を監視に使うことが考えられます。
| 取得する情報の例 | 用途 |
|---|---|
status.conditions や status.phase
|
リソースの状態や異常の継続を確認する |
| desired replicas / ready replicas | 必要な数のレプリカが Ready になっているか確認する |
spec.version などのバージョン情報 |
利用中のバージョンを把握する |
取得するフィールドや状態の意味は、対象のカスタムリソースによって異なります。
(参考: Custom Resource State Metrics の設定例)
メトリクスを公開するには、カスタムコントローラー自身に出力処理を実装する方法や、専用の Exporter を作成する方法があります。その場合、フィールドを値やラベルに変換する処理を実装し、継続的にメンテナンスする必要があります。
この負担を減らすために、カスタムリソースのフィールドとメトリクスの対応を設定で定義する仕組みが開発されてきました。次章では、kube-state-metrics への機能追加から resource-state-metrics へと進んだ経緯を説明します。
第2章: カスタムリソースのメトリクスを取得する方法についてのコミュニティでの流れ
カスタムリソースの状態を設定からメトリクス化する機能は、まず kube-state-metrics に追加されました。その後、保守性や障害の影響範囲を見直すため、独立した resource-state-metrics の開発へ進んでいます。
kube-state-metrics の Custom Resource State Metrics
背景
標準リソースと違い、カスタムリソースのフィールドはプロジェクトごとに異なります。kube-state-metrics 側にすべてのカスタムリソースの知識を組み込む方法では、対応するリソースが増えるたびに実装を追加する必要があります。
Custom Resource State Metrics は PR #1710で追加され、2022年6月3日に v2.5.0 で Experimental な機能としてリリースされました。
概要
Custom Resource State Metrics は、対象の Group / Version / Kind と、メトリクスへ変換するフィールドを設定ファイルで指定できるようにした機能です。リソースごとのメトリクス生成処理を Go で実装し、kube-state-metrics を独自ビルドする手間を減らせます。カスタムコントローラー自身にメトリクスを実装する方法とは別に、API にすでに記録されている情報を外部からメトリクス化する選択肢ができました。
(参考: v2.5.0 CHANGELOG、Custom Resource State Metrics)
例えば Custom Resource State Metrics では、VPA のコンテナごとの minAllowed.cpu を Gauge として取得できます。これは設定の構造を示す抜粋です。
kind: CustomResourceStateMetrics
spec:
resources:
- groupVersionKind:
group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
metrics:
- name: vpa_min_allowed_cpu_cores
help: VPA minimum allowed CPU in cores
each:
type: Gauge
gauge:
path: [spec, resourcePolicy, containerPolicies]
labelsFromPath:
container: [containerName]
valueFrom: [minAllowed, cpu]
この kind: CustomResourceStateMetrics は、kube-state-metrics が読み込む設定の形式です。後述する resource-state-metrics の ResourceMetricsMonitor のように、Kubernetes API に登録して使う CR ではありません。
Custom Resource State Metrics の詳しい使い方や設定項目は、kube-state-metrics でカスタムリソースのメトリクスを取得する方法で説明しています。
課題
Custom Resource State Metrics は、単一の数値だけでなく、配列・マップ・状態の列挙・ラベルへの展開なども扱うようになりました。設定項目やその組み合わせが増えたことで、開発とメンテナンスが難しくなりました。
また、設定の不備によって kube-state-metrics 自体がエラー終了し、標準リソースのメトリクスも取得できなくなる場合があります。例えば、同じリソースに対する設定が重複すると、エラー終了する仕様です。
(参考: Custom Resource State Metrics、KEP-4785 Motivation)
resource-state-metrics(旧 CRDMetrics Controller)
背景
これらの課題を受け、KEP-4785 では、メトリクス生成を専用のコントローラーへ分離する設計が提案されました。
分離の狙いは、主に次のように整理できます。
| 課題 | 分離によって目指すこと |
|---|---|
| 設定項目の増加によって処理が複雑になる | CEL などの式を使い、独自の設定処理を減らす |
| Custom Resource State Metrics の不具合が kube-state-metrics のプロセスに影響する | native metrics とカスタムメトリクスを別プロセスで公開する |
| native metrics だけ必要な環境にも Custom Resource State Metrics の処理が存在する | カスタムメトリクスが必要な環境で resource-state-metrics を追加する |
| 両機能の変更が同じリリースに結び付く | それぞれの目的に合わせて開発・リリースする |
概要
resource-state-metrics は、ResourceMetricsMonitor というカスタムリソースの設定に従って、対象リソースのメトリクスを生成するコントローラーです。設定で監視対象の Group / Version / Kind と resource を指定し、どのフィールドを値やラベルにするかを定義します。
| 機能 | 概要 |
|---|---|
| ResourceMetricsMonitor の管理 |
ResourceMetricsMonitor を作成・更新して設定を管理する |
| 値・ラベルの評価 |
unstructured・CEL・Starlark を使ってフィールドの参照や変換を行う |
| メトリクスの公開 | 自身の HTTP エンドポイントでメトリクスを公開する |
| 処理状態の確認 | ResourceMetricsMonitor の status と、resource-state-metrics 自身のメトリクスで確認する |
| 時系列数の制御 | カーディナリティの上限を設定する |
本記事で使う v0.1.0 の ResourceMetricsMonitor API は v1alpha1 です。仕組みと設定は第3章、実行手順は第4章で説明します。
(参考: resource-state-metrics README、ResourceMetricsMonitor の定義)
Custom Resource State Metrics との違い
主な違いは、設定をカスタムリソースとして管理すること、ResourceMetricsMonitor 内で CEL などの式・スクリプトを使えること、kube-state-metrics から独立して動作することです。
| 項目 | kube-state-metrics の Custom Resource State Metrics | resource-state-metrics |
|---|---|---|
| native metrics との関係 | kube-state-metrics と同じプロセス。設定の不備などによる終了が native metrics にも影響し得る | 独立したプロセスで動き、kube-state-metrics の native metrics から分離される |
| 開発・リリース | kube-state-metrics の一機能として開発・リリースする | 専用コントローラーとして独立して開発・リリースする |
| 設定の形式 |
CustomResourceStateMetrics 形式の設定。カスタムリソースではない |
ResourceMetricsMonitor カスタムリソース |
| 設定言語の設計方針 | 独自の設定項目と、その解釈・変換処理を実装する | 既存の式言語などを使い、独自の設定解釈処理の複雑化を抑えることを目指す |
| 値・ラベルの指定 |
path / valueFrom / labelsFromPath などの専用設定を組み合わせる |
Resolver を選び、フィールドのパスや CEL 式・Starlark スクリプトで記述する |
| 変換処理の表現 | パスの参照・配列の展開・状態の列挙など、用意された設定項目で表現する | CEL の条件分岐・計算・単位変換や、Starlark のループによるサンプル生成などを記述する |
| 設定の登録 |
--custom-resource-state-config-file でファイルを指定するか、--custom-resource-state-config にインラインで渡す |
kubectl apply などで ResourceMetricsMonitor を作成する |
| 設定の追加・更新 | 読み込ませている設定ファイルなどを変更する | ResourceMetricsMonitor を個別に作成・更新する |
| 変更の反映 | ファイル指定には変更検知・再読み込み機能がある。起動引数そのものの変更はプロセスの再起動が必要 | コントローラーがリソースの作成・更新を検知して反映する |
| 操作権限の委譲 | 共有する設定ファイルや ConfigMap などへの変更権限を管理する | RBAC で ResourceMetricsMonitor の作成・更新権限をチームごとに付与できる |
KEP-4785 では、独自の DSL を拡張する代わりに、CEL や Starlark などの既存の言語を使う方針を示しています。ResourceMetricsMonitor では、各 Resolver の機能と実行制限の範囲で、条件分岐や変換処理を記述できます。
また、ResourceMetricsMonitor は個別のカスタムリソースなので、RBAC で各チームに作成・更新権限を付与できます。対象リソースを読み取るコントローラーの権限は、別に管理する必要があります。
kube-state-metrics にも設定ファイルの再読み込み機能があるため、再起動の要否だけではなく、ResourceMetricsMonitor ごとに設定と操作権限を管理できることが違いです。
(参考: KEP-4785 の Motivation / Proposal、Custom Resource State Metrics の設定方法、設定ファイルの再読み込み機能、カスタムリソースによる設定管理の要望、ResourceMetricsMonitor の定義)
これまでの流れと、現在の状態
| 時期 | 概要 |
|---|---|
| 2022年6月 | kube-state-metrics v2.5.0 で Custom Resource State Metrics をリリース |
| 2024年8月 | KEP-4785 で、専用コントローラーとしてカスタムリソースのメトリクスを生成する仕組みの議論を開始 |
| 2026年5月 | resource-state-metrics v0.1.0 を公開 |
| 2026年8月 | kube-state-metrics v2.20.0 で Custom Resource State Metrics の機能追加凍結を明記 |
| 2026年9月 | kube-state-metrics v3 の計画 Issue に、Custom Resource State Metrics を resource-state-metrics に置き換える案を記載 |
(参考: v2.5.0 CHANGELOG、Issue #4785、resource-state-metrics v0.1.0、v2.20.0 CHANGELOG、v3 Plan #3118)
第3章: resource-state-metrics の仕組み
カスタムリソースのメトリクスを取得するための設定は、次の3ステップです。
- resource-state-metrics をデプロイする:ResourceMetricsMonitor の CRD と、コントローラーなどを導入します。
-
対象のカスタムリソースの参照権限を付与する:resource-state-metrics の ServiceAccount に、対象リソースの
list/watchなどの権限を付与します。 - ResourceMetricsMonitor を作成する:対象リソースと、生成するメトリクス名・値・ラベルを定義します。
この設定により、対象リソースの状態がメトリクスとして HTTP エンドポイントに公開されます。対象のカスタムリソースの CRD とリソース自体は、存在している前提です。
以下では VPA を例に、設定と出力の対応を説明します。3ステップの実行手順は第4章で紹介します。
3.1 実際の利用イメージ
VPA のカスタムリソース VerticalPodAutoscaler を対象に、登録した ResourceMetricsMonitor からどのようにメトリクスが出力されるかを確認します。
全体の流れは次のとおりです。
- VPA Recommender が recommendation を計算し、VPA の
statusを更新する - 利用者が、対象リソースとメトリクスを定義した ResourceMetricsMonitor を作成する
- resource-state-metrics が ResourceMetricsMonitor と VPA を監視し、その設定に従ってメトリクスを生成する
- 生成したメトリクスを HTTP エンドポイントで公開する
以下では、対象の VPA、ResourceMetricsMonitor、出力されるメトリクスを順に見ていきます。
1. メトリクスにするカスタムリソースの情報
例えば、VPA Recommender が次の recommendation を生成したとします。以下は、単一コンテナの Deployment を対象とした VPA の抜粋です。この例では、CPU の target recommendation をメトリクスの値に、コンテナ名をラベルに使います。
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: cpu-demo
namespace: default
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: cpu-demo
updatePolicy:
updateMode: "Off" # recommendation を生成し、Pod の requests は自動変更しない
status:
recommendation:
containerRecommendations:
- containerName: app
target:
cpu: 247m
memory: 250Mi
2. ResourceMetricsMonitor の作成
対象のリソース、メトリクス名、値とラベルを取得する式を定義します。以下の例は、先頭コンテナの recommendation が存在する前提です。
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-recommendations
namespace: default
spec:
configuration:
stores: # Store: 監視対象のリソースと絞り込み条件
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers
resolver: cel # o は対象の VerticalPodAutoscaler オブジェクト
selectors:
field: metadata.namespace=default
families: # Family: メトリクス名と説明
- name: vpa_recommendation_target_cpu_cores # kube_customresource_ が自動で付く
help: VPA target CPU recommendation in cores
metrics: # Metric: サンプル値とラベルを取得する式
- value: quantity(o.status.recommendation.containerRecommendations[0].target.cpu)
labels:
- name: container
value: o.status.recommendation.containerRecommendations[0].containerName
ResourceMetricsMonitor は Kubernetes API に登録するカスタムリソースです。上記をファイルに保存し、kubectl apply -f <ファイル名> で登録します。resource-state-metrics の ServiceAccount には、対象の verticalpodautoscalers に対する読み取り権限も必要です。
3. メトリクスの出力
resource-state-metrics は対象の VerticalPodAutoscaler を監視し、:9999/metrics でメトリクスを公開します。上記の入力と設定から生成される出力例は次のとおりです。ラベルの表示順は整理しています。
# HELP kube_customresource_vpa_recommendation_target_cpu_cores VPA target CPU recommendation in cores
# TYPE kube_customresource_vpa_recommendation_target_cpu_cores gauge
kube_customresource_vpa_recommendation_target_cpu_cores{group="autoscaling.k8s.io",version="v1",kind="VerticalPodAutoscaler",name="cpu-demo",namespace="default",container="app"} 0.247000
quantity() によって CPU の 247m が 0.247 core に変換され、containerName の app が container ラベルになります。メトリクス名の kube_customresource_ と、対象リソースの group / version / kind / name / namespace は自動で追加されます。
この例は単一コンテナを対象に、containerRecommendations[0] を参照しています。複数コンテナを処理する場合は、第5章の移行例を参照してください。
(参考: types.go#L140-L264、metric.go#L27-L43)
3.2 設定方法
Store・Family・Metric の関係
Store の中に Family、Family の中に Metric を定義します。それぞれ「何を監視するか」「どのメトリクスを公開するか」「値とラベルをどう取得するか」を設定します。以下は3.1節の設定から、該当部分を抜粋したものです。
Store: spec.configuration.stores[]
監視対象の API リソースと、取得対象の絞り込みを定義します。
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers
resolver: cel
selectors:
field: metadata.namespace=default
# この下に families を定義する
group / version / kind で対象の種類を指定し、resource には API で使う複数形の名前を指定します。この例では default namespace の VPA を監視し、値やラベルの取得に CEL を使います。
| 設定 | 説明 |
|---|---|
group |
対象の API グループ。VPA は autoscaling.k8s.io
|
version |
対象の API バージョン。VPA は v1
|
kind |
対象の Kind。VPA は VerticalPodAutoscaler
|
resource |
API で使う複数形のリソース名。VPA は verticalpodautoscalers
|
selectors.label |
ラベルセレクターによる監視対象の絞り込み |
selectors.field |
フィールドセレクターによる絞り込み。対象 API が対応するフィールドを指定する |
resolver |
配下の Family / Metric で使う評価方法。内側の指定で上書きできる |
labels[] |
Store に共通のラベル。各要素に name と value を指定する。v0.1.0 の制約は5.1節を参照 |
cardinalityLimit |
Store 単位の時系列数の上限。0 はデフォルトを使う |
families[] |
対象リソースから生成する Family の一覧 |
Family: stores[].families[]
Store の配下に、公開するメトリクスの名前と説明を定義します。1つの Store に複数の Family を設定できます。
families:
- name: vpa_recommendation_target_cpu_cores
help: VPA target CPU recommendation in cores
# この下に metrics を定義する
name はメトリクス名、help は出力の # HELP に使われます。この例のメトリクス名は、自動で付くプレフィックスを含めて kube_customresource_vpa_recommendation_target_cpu_cores になります。メモリの recommendation も公開する場合は、別の Family を追加します。
| 設定 | 説明 |
|---|---|
name |
メトリクス名。公開時に kube_customresource_ が付く |
help |
# HELP に出力する説明 |
metrics[] |
サンプル値とラベルを定義する Metric の一覧 |
resolver |
Store から継承した評価方法を、この Family で上書きする |
labels[] |
Family に共通のラベル。各要素に name と value を指定する。Starlark ではスクリプト内で追加する |
cardinalityLimit |
Family 単位の時系列数の上限。0 はこの階層では無制限 |
starlark.script |
メトリクスを生成する Starlark スクリプト。指定すると metrics[] の処理を使わず、スクリプトで生成する |
starlark.timeout |
スクリプトの実行タイムアウト秒数 |
starlark.maxSteps |
スクリプトの実行ステップ数の上限 |
Metric: families[].metrics[]
Family の配下に、サンプル値とラベルを取得する式を定義します。
metrics:
- value: quantity(o.status.recommendation.containerRecommendations[0].target.cpu)
labels:
- name: container
value: o.status.recommendation.containerRecommendations[0].containerName
value でメトリクスの数値を取得し、labels でラベル名とその値を定義します。Store で resolver: cel を指定しているため、ここでは o で対象の VPA を参照できます。この例は先頭コンテナの CPU recommendation を core に変換し、同じコンテナの名前を container ラベルに設定します。
| 設定 | 説明 |
|---|---|
value |
メトリクスの数値を取得する式 |
labels[].name |
追加するラベル名 |
labels[].value |
ラベルの値を取得する式 |
resolver |
Store / Family から継承した評価方法を、この Metric で上書きする |
ラベルの値が変わると別の時系列になります。自由入力の文字列やエラーメッセージをラベルにする場合は、取り得る値の数も確認するのが良いと思います。
(参考: types.go#L140-L264)
値とラベルを取り出す Resolver
Resolver は、値やラベルを取得する方法を指定します。v0.1.0 では unstructured・cel・starlark が使えます。まず unstructured で対応できるかを確認し、必要な機能に応じて CEL、Starlark の順に検討すると選びやすいと思います。
- unstructured:数値フィールドをそのまま取得する場合や、文字列をラベルにする場合の候補です。
- CEL:単位変換・条件分岐・計算などが必要な場合の候補です。
- Starlark:複数サンプルの値とラベルを組にして生成するなど、CEL では扱いにくい処理の候補です。
例えば、VPA の metadata.generation は unstructured で取得できます。CPU の recommendation のような単位付きの値は、CEL の quantity() で数値に変換します。
以下に、それぞれ VPA を対象にした設定例を示します。言語の開発背景と、複数コンテナを扱う際の具体的な使い分けは、末尾の「CEL と Starlark の概要」で補足しています。
unstructured: フィールドを直接参照する
ドット区切りのパスでフィールドを指定します。次の例は、VPA の参照先の名前を target_name ラベルに設定し、値1のメトリクスを公開します。
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-unstructured-example
namespace: default
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers # VPA の API リソース名
resolver: unstructured # ドット区切りのパスでフィールドを直接参照する
selectors:
field: metadata.namespace=default # default namespace の VPA を対象にする
families:
- name: vpa_target_info # メトリクス名には kube_customresource_ が付く
help: VPA target information
metrics:
- value: "1" # 固定値1を出力する
labels:
- name: target_name # VPA の参照先の名前を付けるラベル
value: spec.targetRef.name # 対象オブジェクトのフィールドを直接参照する
3.1節の VPA では、target_name="cpu-demo" が追加されます。フィールドは spec.targetRef.name のように指定します。配列の要素の処理や値の変換には、CEL や Starlark を使います。
cel: 式で値やラベルを取得・変換する
CEL では対象オブジェクトを o として参照し、関数や条件式を使えます。次の例は、先頭コンテナの CPU recommendation を quantity() で core に変換します。
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-cel-example
namespace: default
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers # VPA の API リソース名
resolver: cel # o で対象の VPA を参照し、CEL 式を評価する
selectors:
field: metadata.namespace=default # default namespace の VPA を対象にする
families:
- name: vpa_example_target_cpu_cores
help: VPA target CPU recommendation in cores
metrics:
# [0] は先頭コンテナ。quantity() で CPU の単位を core に変換する
- value: quantity(o.status.recommendation.containerRecommendations[0].target.cpu)
labels:
- name: container
# 値を取得したコンテナと同じ要素から名前を取得する
value: o.status.recommendation.containerRecommendations[0].containerName
3.1節の入力では、container="app" と値 0.247 が生成されます。この例は containerRecommendations[0] と CPU recommendation が存在する前提です。
starlark: スクリプトで複数のサンプルを生成する
Starlark では、対象リソースの情報が dict 型の変数 obj に格納されています。metrics[] の代わりに starlark.script を指定し、スクリプト内で値とラベルを組み立てます。
次の例は全コンテナを処理し、CPU recommendation が存在するコンテナごとにサンプルを生成します。
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-starlark-example
namespace: default
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers # VPA の API リソース名
resolver: starlark # スクリプトでサンプルを生成する
selectors:
field: metadata.namespace=default # default namespace の VPA を対象にする
families:
- name: vpa_example_all_target_cpu_cores
help: VPA target CPU recommendations for all containers in cores
resolver: starlark # v0.1.0 では Family にも明示する
starlark:
script: |
# obj は対象の VPA。recommendation がなければ空の配列を使う
recommendations = obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
samples = []
# 先頭だけでなく、配列内の全コンテナを処理する
for entry in recommendations:
target = entry.get("target", {})
if "cpu" in target: # CPU recommendation がある場合だけ生成する
samples.append(metric(
labels={"container": entry["containerName"]}, # 同じ要素の名前と値を組にする
value=quantity_to_float(str(target["cpu"])), # 例: 247m → 0.247 core
))
# 生成したサンプルを Family にまとめ、結果を families に設定する
families = [family(
name="vpa_example_all_target_cpu_cores",
help="VPA target CPU recommendations for all containers in cores",
kind="gauge",
samples=samples,
)]
metric() で各サンプルを作り、families に結果を設定します。CPU の単位変換には quantity_to_float() を使います。recommendation がまだない場合は、空のサンプル一覧になります。
unstructured / CEL の Resolver は Store・Family・Metric の順に継承され、内側の指定で上書きできます。Starlark は Family の resolver: starlark と starlark.script を指定して使います。v0.1.0 では Store の指定だけでは動作しないため、Family にも明示します。
(参考: Unstructured Resolver、CEL Resolver、Starlark Resolver)
3.3 主な起動オプション
| オプション | デフォルト | 用途 |
|---|---|---|
--main-port |
9999 |
リソースメトリクスの公開ポート |
--self-port |
9998 |
resource-state-metrics 自体のメトリクスを公開するポート |
--workers |
2 |
ResourceMetricsMonitor の処理ワーカー数 |
--resource-cardinality-default |
100000 |
ResourceMetricsMonitor ごとの上限のデフォルト |
--global-cardinality-limit |
0 |
全 ResourceMetricsMonitor 合計の上限。0 は無制限 |
--cardinality-warning-ratio |
0.8 |
上限に対する警告の割合 |
--cel-cost-limit |
100000 |
CEL 評価のコスト上限 |
--cel-timeout-seconds |
5 |
CEL 評価のタイムアウト秒数 |
--starlark-max-steps |
100000 |
Starlark の実行ステップ数の上限 |
--starlark-timeout-seconds |
5 |
Starlark の実行タイムアウト秒数 |
(参考: options.go#L72-L143)
3.4 メトリクスの型と公開先
Family は、名前が _total で終わる場合は Counter、それ以外は Gauge として公開されます。メトリクス名が型の判定に使われるため、CPU recommendation のように増減する値には _total を付けないようにします。
(参考: family.go#L545-L560)
| 公開先 | 内容 |
|---|---|
:9999/metrics |
ResourceMetricsMonitor から生成したリソースメトリクス |
:9999/external |
Go で実装・登録された外部 Collector のメトリクス |
:9998/metrics |
resource-state-metrics 自体のメトリクス。処理状態、カーディナリティ、Go / プロセスの情報など |
/external は、任意の外部 URL を指定して収集する機能ではありません。リポジトリの external パッケージで実装された Collector を公開します。
(参考: server.go#L108-L209、external README)
3.5 カーディナリティと生成失敗を確認する
ResourceMetricsMonitor 全体の時系列数の上限は、spec.configuration.cardinalityLimit で指定します。Store / Family の上限と合わせて設定できます。
ResourceMetricsMonitor には Processed / Failed / CardinalityWarning / CardinalityCutoff の Conditions が定義されています。status.cardinality には、時系列数や上限超過の状態などが記録されます。
第4章のサンプルを実行し、port-forward で 9998 番ポートへ接続した後は、次のコマンドで確認できます。
kubectl get rmm vpa-recommendations -n default -o yaml
curl -s http://127.0.0.1:9998/metrics | grep resource_state_metrics_
resource-state-metrics 自体の主なメトリクスは次のとおりです。カーディナリティは時系列数を表し、Counter は処理・評価・上限超過の回数を表します。
| メトリクス | 型 | 主なラベル | 確認する内容 |
|---|---|---|---|
resource_state_metrics_resources_monitored_info |
Gauge |
namespace, name
|
監視対象の ResourceMetricsMonitor。対象 CR の個数ではない |
resource_state_metrics_events_processed_total |
Counter |
namespace, name, event_type, status
|
ResourceMetricsMonitor のイベント処理結果 |
resource_state_metrics_cel_evaluations_total |
Counter |
namespace, name, family, result
|
CEL 評価の結果 |
resource_state_metrics_resource_cardinality |
Gauge |
namespace, name
|
ResourceMetricsMonitor ごとの時系列数 |
resource_state_metrics_resource_cardinality_limit |
Gauge |
namespace, name
|
ResourceMetricsMonitor ごとの上限 |
resource_state_metrics_global_cardinality |
Gauge | なし | 全 ResourceMetricsMonitor 合計の時系列数 |
resource_state_metrics_cardinality_exceeded_total |
Counter |
namespace, name, level, entity
|
上限超過の発生回数 |
この表の namespace / name は ResourceMetricsMonitor を識別します。生成された kube_customresource_* メトリクスの同名ラベルは対象 CR を識別するため、混同しないようにします。
(参考: controller.go#L175-L265、ResourceMetricsMonitorStatus)
上限を超えるとメトリクスの生成が打ち切られる場合があります。Conditions・ログ・resource-state-metrics 自体のメトリクスから、上限による欠損も確認するのが良いと思います。
3.6 resource-state-metrics 内部の処理フロー
resource-state-metrics 内部では、設定から監視処理を作り、対象リソースの変更に合わせてメトリクスを更新します。
通常の監視・生成・公開の流れを示しています。設定の更新に伴う監視処理の再構成や、エラー処理の詳細は省略しています。
対象リソースの取得・更新時にメトリクスを生成して保持し、HTTP リクエストには保持済みの内容を返します。処理状態や時系列数の確認方法は3.5節で説明したとおりです。
(参考: events.go#L135-L161、builder.go#L123-L165、store.go#L76-L143、server.go#L178-L195)
第4章: VPA の recommendation をメトリクスとして取得する
kind に検証用クラスタを作成し、VPA が生成した CPU・メモリの recommendation を resource-state-metrics でメトリクスとして公開します。最後に kubectl port-forward で接続し、VPA の status とメトリクスの値を照合します。以下は、実際に検証した手順と出力です。
4.1 kind クラスタを作成する
作業ディレクトリを作成します。
mkdir rsm-vpa-demo
cd rsm-vpa-demo
次の設定を kind-config.yaml として保存します。control-plane ノード1台のクラスタを作成します。
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
image: kindest/node:v1.37.0
設定ファイルを指定してクラスタを作成し、ノードが Ready になったことを確認します。
kind create cluster --name rsm-vpa-demo \
--config kind-config.yaml
kubectl get nodes
4.2 Metrics Server と VPA Recommender をデプロイする
VPA Recommender が Pod の CPU・メモリ使用量を取得できるよう、Metrics Server をデプロイします。
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
# kind 検証環境の kubelet 証明書を検証できないため、証明書検証を省略する
kubectl -n kube-system patch deployment metrics-server --type=json \
-p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
続いて VPA の CRD・RBAC・Recommender をデプロイします。今回は recommendation の取得が目的なので、Pod の設定を変更する Updater と Admission Controller はデプロイしません。
# VPA とチェックポイント用の CRD を作成する
kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/vertical-pod-autoscaler-1.8.1/vertical-pod-autoscaler/deploy/vpa-v1-crd-gen.yaml
# VPA が使用する ServiceAccount と RBAC を作成する
kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/vertical-pod-autoscaler-1.8.1/vertical-pod-autoscaler/deploy/vpa-rbac.yaml
# 使用量から recommendation を計算する VPA Recommender をデプロイする
kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/vertical-pod-autoscaler-1.8.1/vertical-pod-autoscaler/deploy/recommender-deployment.yaml
(参考: VPA v1.8.1 のデプロイ用マニフェスト、Metrics Server v0.9.1)
4.3 サンプルの Deployment と VPA を作成する
次を workload.yaml として保存します。CPU を使い続ける単一コンテナの Deployment と、それを対象にした VPA です。
apiVersion: apps/v1
kind: Deployment
metadata:
name: cpu-demo
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: cpu-demo
template:
metadata:
labels:
app: cpu-demo
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "while true; do :; done"]
resources:
requests:
cpu: 100m
memory: 32Mi
limits:
cpu: 200m
memory: 64Mi
---
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: cpu-demo
namespace: default
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: cpu-demo
updatePolicy:
updateMode: "Off" # recommendation のみ生成し、Pod の requests は自動変更しない
kubectl apply -f workload.yaml
kubectl top pod -l app=cpu-demo
Recommender が使用量を収集し、recommendation を生成するまで数分かかります。
kubectl get vpa cpu-demo -o yaml
実際に得られた status の抜粋です。recommendation は、その時点の使用量や収集期間によって変わります。
status:
conditions:
- status: "True"
type: RecommendationProvided
recommendation:
containerRecommendations:
- containerName: app
target:
cpu: 247m
memory: 250Mi
4.4 resource-state-metrics をビルドしてデプロイする
registry.k8s.io/resource-state-metrics/resource-state-metrics:v0.1.0 にイメージが存在しないため、ローカルでビルドして kind にロードします。
git clone --branch v0.1.0 --depth 1 \
https://github.com/kubernetes-sigs/resource-state-metrics.git
次を resource-state-metrics/Dockerfile.local として保存します。kube-state-metrics の Dockerfile と同様に、builder ステージで Makefile を使ってビルドし、実行ステージにはバイナリだけをコピーします。
ARG GOVERSION=1.25
FROM golang:${GOVERSION} AS builder
WORKDIR /go/src/github.com/kubernetes-sigs/resource-state-metrics/
COPY . .
RUN CGO_ENABLED=0 make -B resource-state-metrics
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=builder /go/src/github.com/kubernetes-sigs/resource-state-metrics/resource-state-metrics /
USER 65534:65534
ENTRYPOINT ["/resource-state-metrics"]
EXPOSE 9998 9999
docker build -f resource-state-metrics/Dockerfile.local \
-t resource-state-metrics:v0.1.0-local resource-state-metrics
kind load docker-image resource-state-metrics:v0.1.0-local --name rsm-vpa-demo
# Deployment のイメージをローカルで変更する
kubectl set image --local -f resource-state-metrics/manifests/deployment.yaml \
resource-state-metrics=resource-state-metrics:v0.1.0-local \
-o yaml > resource-state-metrics/manifests/deployment-local.yaml
mv resource-state-metrics/manifests/deployment-local.yaml \
resource-state-metrics/manifests/deployment.yaml
# 変更済みのマニフェストを適用する
kubectl apply -f resource-state-metrics/manifests/
(参考: resource-state-metrics v0.1.0 manifests、go.mod、Distroless)
4.5 VPA の読み取り権限を付与し、ResourceMetricsMonitor を作成する
次を vpa-rbac.yaml として保存します。同梱マニフェストの集約 ClusterRole に、VPA の読み取り権限を追加します。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: resource-state-metrics-vpa
labels:
resource-state-metrics.instrumentation.k8s-sigs.io/aggregate-to-exporter: "true"
rules:
- apiGroups: [autoscaling.k8s.io]
resources: [verticalpodautoscalers]
verbs: [get, list, watch]
kubectl apply -f vpa-rbac.yaml
kubectl auth can-i list verticalpodautoscalers.autoscaling.k8s.io --all-namespaces \
--as=system:serviceaccount:default:resource-state-metrics
権限の集約後、yes になったことを確認します。続いて、次を vpa-rmm.yaml として保存します。
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-recommendations
namespace: default # ResourceMetricsMonitor を配置する namespace
spec:
configuration:
stores:
# メトリクス化する対象リソースの Group / Version / Kind と複数形のリソース名
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers
resolver: cel # 値とラベルを CEL 式で取得・変換する。o は対象の VPA オブジェクト
selectors:
field: metadata.namespace=default # default namespace の VPA に絞る
families:
# メトリクス名には kube_customresource_ が自動で付く
- name: vpa_recommendation_target_cpu_cores
help: VPA target CPU recommendation in cores # メトリクスの HELP に出力する説明
metrics:
- labels:
- name: container # コンテナ名を container ラベルとして付与する
value: o.status.recommendation.containerRecommendations[0].containerName
# 先頭コンテナの CPU recommendation を core に変換する(例: 247m → 0.247)
value: quantity(o.status.recommendation.containerRecommendations[0].target.cpu)
- name: vpa_recommendation_target_memory_bytes
help: VPA target memory recommendation in bytes
metrics:
- labels:
- name: container
value: o.status.recommendation.containerRecommendations[0].containerName
# 先頭コンテナのメモリ recommendation を byte に変換する(例: 250Mi → 262144000)
value: quantity(o.status.recommendation.containerRecommendations[0].target.memory)
3.1節の CPU の例に、メモリの Family を追加した設定です。単一コンテナのサンプルに合わせて containerRecommendations[0] を参照します。複数コンテナを扱う場合は、第5章の移行例を参照してください。
VPA の CPU・メモリは、247m や 250Mi のような Kubernetes Quantity の形式です。resource-state-metrics の CEL 拡張関数 quantity() を使い、CPU は core、メモリは byte の数値に変換します。
kubectl apply -f vpa-rmm.yaml
kubectl get rmm vpa-recommendations -o yaml
kubectl logs deployment/resource-state-metrics --tail=100
recommendation がまだない VPA では、この式で値を取得できません。今回は recommendation の生成後に ResourceMetricsMonitor を作成します。実運用では status.recommendation が存在しない場合の扱いも決めておくのが良いと思います。
(参考: CEL quantity 関数の実装、集約 ClusterRole)
4.6 port-forward でメトリクスを確認する
次のコマンドを実行したままにします。
kubectl port-forward deployment/resource-state-metrics 9999:9999 9998:9998
別のターミナルから、メトリクスを取得します。
curl -fsS http://127.0.0.1:9999/metrics | grep kube_customresource_vpa_
検証時には、次のメトリクスが出力されました。
# HELP kube_customresource_vpa_recommendation_target_cpu_cores VPA target CPU recommendation in cores
# TYPE kube_customresource_vpa_recommendation_target_cpu_cores gauge
kube_customresource_vpa_recommendation_target_cpu_cores{container="app",group="autoscaling.k8s.io",version="v1",kind="VerticalPodAutoscaler",name="cpu-demo",namespace="default"} 0.247000
# HELP kube_customresource_vpa_recommendation_target_memory_bytes VPA target memory recommendation in bytes
# TYPE kube_customresource_vpa_recommendation_target_memory_bytes gauge
kube_customresource_vpa_recommendation_target_memory_bytes{container="app",group="autoscaling.k8s.io",version="v1",kind="VerticalPodAutoscaler",name="cpu-demo",namespace="default"} 262144000.000000
VPA の status にあった CPU の 247m が 0.247000、メモリの 250Mi が 262144000.000000 として出力されています。container="app" は ResourceMetricsMonitor で設定したラベルです。group / version / kind / name / namespace は resource-state-metrics が自動で追加しています。
resource-state-metrics 自身のメトリクスは別ポートで確認できます。
curl -fsS http://127.0.0.1:9998/metrics | grep resource_state_metrics_
4.7 検証環境を片付ける
第5章の移行例も試す場合は、クラスタを残したまま次章へ進みます。確認が終わったら、port-forward を実行しているターミナルで Ctrl+C を押し、検証用クラスタを削除します。
kind delete cluster --name rsm-vpa-demo
第5章: kube-state-metrics の Custom Resource State Metrics から移行する場合
kube-state-metrics の VPA の公式サンプルを、Store・Family・Metric の単位に分けて書き換えます。各メトリクスについて、移行前と移行後の YAML を並べて説明します。
元の設定と同じく、配列内の全コンテナを対象にします。annotations・labels・更新モードには CEL、コンテナごとの設定値・recommendation には Starlark を使います。
各 YAML は抜粋です。5.1節の families に5.3節の各 Family を追加すると、1つの ResourceMetricsMonitor になります。組み立てた YAML 全体は5.5節の折りたたみにまとめています。
5.1 Store: 監視対象と共通設定
kube-state-metrics の設定
kind: "CustomResourceStateMetrics"
spec:
resources:
- groupVersionKind:
group: "autoscaling.k8s.io"
kind: "VerticalPodAutoscaler"
version: "v1"
labelsFromPath:
namespace: ["metadata", "namespace"]
target_api_version: ["spec", "targetRef", "apiVersion"]
target_kind: ["spec", "targetRef", "kind"]
target_name: ["spec", "targetRef", "name"]
verticalpodautoscaler: ["metadata", "name"]
metricNamePrefix: "kube"
groupVersionKind で VPA を選び、labelsFromPath で VPA 名・namespace・参照先を共通ラベルにします。metricNamePrefix は公開するメトリクス名のプレフィックスです。この設定は kube-state-metrics が設定ファイルとして読み込みます。
resource-state-metrics で置き換えた場合の設定例
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-migration
namespace: default
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers
resolver: cel
families: [] # 5.3節の各 Family をここに追加する
groupVersionKind は Store の group / version / kind に分かれ、API で使う resource も指定します。name / namespace / group / version / kind は自動付与されます。元の verticalpodautoscaler と target_* は、CEL では各 Metric の labels、Starlark ではスクリプト内で追加します。v0.1.0 の実機検証では Store の共通ラベルが重複出力されたため、この例では Store / Family の labels を使いません。
5.2 Family: メトリクス名と生成方法
kube-state-metrics の設定
metrics:
- name: verticalpodautoscaler_annotations
help: Kubernetes annotations converted to Prometheus labels.
# each で型と、値・ラベルの取得方法を指定する
resource-state-metrics で置き換えた場合の設定例
families:
- name: verticalpodautoscaler_annotations
help: Kubernetes annotations converted to Prometheus labels.
# metrics または starlark.script でサンプルを生成する
kube-state-metrics の metrics[].name / help は、resource-state-metrics の families[].name / help に対応します。以降ではメトリクスごとの区別を保ち、CPU / メモリや recommendation の種類を別々の Family にします。
5.3 Metric: メトリクスごとの値とラベル
kube-state-metrics より設定が長くなる理由
kube-state-metrics の each は、配列の走査・ラベルの取得・値の変換を専用の設定項目で指定できます。一方、この移行例では、複数コンテナを処理する部分を Starlark で記述するため、配列の処理、欠損フィールドの確認、サンプルの生成を明示しています。
さらに、5.1節で説明した共通ラベルの制約を避けるため、verticalpodautoscaler と target_* を各 Metric またはスクリプトに記述しています。元のメトリクスごとに Family を分けているため、この部分が繰り返されます。
フィールドの参照や単位変換は CEL で短く書けます。ただし、v0.1.0 では、値とラベルを別々の配列として返すと対応が崩れる場合があるため、この移行例では Starlark を使っています。具体例は、末尾の「resource-state-metrics での使い分け」で説明します。
kube-state-metrics の each を、CEL の metrics[] または Starlark の starlark.script に書き換えます。以下の resource-state-metrics の YAML は、それぞれ Store の families[] に入れる1要素です。
1. VPA の annotations
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_annotations"
help: "Kubernetes annotations converted to Prometheus labels."
each:
type: "Info"
info:
labelsFromPath:
annotation_*: ["metadata", "annotations"]
name: ["metadata", "name"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_annotations
help: "Kubernetes annotations converted to Prometheus labels."
metrics:
- value: "1.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- name: _annotations
value: 'labelPrefix(has(o.metadata.annotations) ? o.metadata.annotations : {}, "annotation_")'
labelPrefix() で annotation_ を付け、ラベル名が _ で始まる設定で map を展開します。値は1です。name は自動付与され、target_* なども各 Metric に指定します。
2. VPA の labels
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_labels"
help: "Kubernetes labels converted to Prometheus labels."
each:
type: "Info"
info:
labelsFromPath:
label_*: ["metadata", "labels"]
name: ["metadata", "name"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_labels
help: "Kubernetes labels converted to Prometheus labels."
metrics:
- value: "1.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- name: _labels
value: 'labelPrefix(has(o.metadata.labels) ? o.metadata.labels : {}, "label_")'
labelPrefix() で label_ を付け、ラベル名が _ で始まる設定で map を展開します。値は1です。name は自動付与され、target_* なども各 Metric に指定します。
3. VPA の更新モード
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_spec_updatepolicy_updatemode"
help: "Update mode of the VerticalPodAutoscaler."
each:
type: "StateSet"
stateSet:
labelName: "update_mode"
path: ["spec", "updatePolicy", "updateMode"]
list: ["Auto", "Initial", "Off", "Recreate"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_spec_updatepolicy_updatemode
help: "Update mode of the VerticalPodAutoscaler."
metrics:
- value: "o.spec.updatePolicy.updateMode == 'Auto' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Auto'"}
- value: "o.spec.updatePolicy.updateMode == 'Initial' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Initial'"}
- value: "o.spec.updatePolicy.updateMode == 'Off' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Off'"}
- value: "o.spec.updatePolicy.updateMode == 'Recreate' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Recreate'"}
4種類のモードを固定ラベルで指定し、一致すれば1、それ以外は0にします。配列の並び順に依存せず、元の StateSet を Gauge で表現できます。更新モードが存在する前提です。
以降の設定値・recommendation の例は、配列の全コンテナを処理します。同じ要素から containerName と値を取得し、対象フィールドがない場合はサンプルを生成しません。CPU は core、メモリは byte に変換します。
4. メモリの minAllowed
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_memory"
help: "Minimum memory resources the VerticalPodAutoscaler can set for containers matching the name."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["spec", "resourcePolicy", "containerPolicies"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["minAllowed", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_memory
help: "Minimum memory resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["minAllowed"]["memory"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "memory" in c.get("minAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_memory",
help="Minimum memory resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
各コンテナの minAllowed.memory を取得し、byte 単位の値として公開します。
5. CPU の minAllowed
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_cpu"
help: "Minimum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["spec", "resourcePolicy", "containerPolicies"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["minAllowed", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_cpu
help: "Minimum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["minAllowed"]["cpu"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "cpu" in c.get("minAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_cpu",
help="Minimum cpu resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
各コンテナの minAllowed.cpu を取得し、core 単位の値として公開します。
6. メモリの maxAllowed
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_memory"
help: "Maximum memory resources the VerticalPodAutoscaler can set for containers matching the name."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["spec", "resourcePolicy", "containerPolicies"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["maxAllowed", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_memory
help: "Maximum memory resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["maxAllowed"]["memory"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "memory" in c.get("maxAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_memory",
help="Maximum memory resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
各コンテナの maxAllowed.memory を取得し、byte 単位の値として公開します。
7. CPU の maxAllowed
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_cpu"
help: "Maximum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["spec", "resourcePolicy", "containerPolicies"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["maxAllowed", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_cpu
help: "Maximum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["maxAllowed"]["cpu"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "cpu" in c.get("maxAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_cpu",
help="Maximum cpu resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
各コンテナの maxAllowed.cpu を取得し、core 単位の値として公開します。
8. メモリの lowerBound recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_memory"
help: "Minimum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["lowerBound", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_memory
help: "Minimum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["lowerBound"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("lowerBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_memory",
help="Minimum memory resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
各コンテナの lowerBound.memory を取得し、byte 単位の値として公開します。
9. CPU の lowerBound recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_cpu"
help: "Minimum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["lowerBound", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_cpu
help: "Minimum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["lowerBound"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("lowerBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_cpu",
help="Minimum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
各コンテナの lowerBound.cpu を取得し、core 単位の値として公開します。
10. メモリの upperBound recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_memory"
help: "Maximum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["upperBound", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_memory
help: "Maximum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["upperBound"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("upperBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_memory",
help="Maximum memory resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
各コンテナの upperBound.memory を取得し、byte 単位の値として公開します。
11. CPU の upperBound recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_cpu"
help: "Maximum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["upperBound", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_cpu
help: "Maximum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["upperBound"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("upperBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_cpu",
help="Maximum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
各コンテナの upperBound.cpu を取得し、core 単位の値として公開します。
12. メモリの target recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_target_memory"
help: "Target memory resources the VerticalPodAutoscaler recommends for the container."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["target", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_target_memory
help: "Target memory resources the VerticalPodAutoscaler recommends for the container."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["target"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("target", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_target_memory",
help="Target memory resources the VerticalPodAutoscaler recommends for the container.", kind="gauge", samples=samples)]
各コンテナの target.memory を取得し、byte 単位の値として公開します。
13. CPU の target recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu"
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["target", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["target"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("target", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu",
help="Target cpu resources the VerticalPodAutoscaler recommends for the container.", kind="gauge", samples=samples)]
各コンテナの target.cpu を取得し、core 単位の値として公開します。
14. メモリの uncappedTarget recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_memory"
help: "Target memory resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
commonLabels:
unit: "byte"
resource: "memory"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["uncappedTarget", "memory"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_memory
help: "Target memory resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["uncappedTarget"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("uncappedTarget", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_memory",
help="Target memory resources the VerticalPodAutoscaler recommends for the container ignoring bounds.", kind="gauge", samples=samples)]
各コンテナの uncappedTarget.memory を取得し、byte 単位の値として公開します。
15. CPU の uncappedTarget recommendation
kube-state-metrics の設定
metrics:
- name: "verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_cpu"
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
commonLabels:
unit: "core"
resource: "cpu"
each:
type: "Gauge"
gauge:
path: ["status", "recommendation", "containerRecommendations"]
labelsFromPath:
container: ["containerName"]
valueFrom: ["uncappedTarget", "cpu"]
resource-state-metrics で置き換えた場合の設定例
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_cpu
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["uncappedTarget"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("uncappedTarget", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_cpu",
help="Target cpu resources the VerticalPodAutoscaler recommends for the container ignoring bounds.", kind="gauge", samples=samples)]
各コンテナの uncappedTarget.cpu を取得し、core 単位の値として公開します。
5.4 公開するメトリクスの違いと確認方法
各 Family 名を元の設定に揃えても、resource-state-metrics の固定プレフィックスにより、公開するメトリクス名は変わります。
| 項目 | kube-state-metrics の設定例 | resource-state-metrics の設定例 |
|---|---|---|
| プレフィックス |
metricNamePrefix: kube により kube_
|
kube_customresource_ |
| GVK のラベル |
customresource_group / customresource_version / customresource_kind
|
group / version / kind
|
| VPA 名のラベル |
verticalpodautoscaler。name は Info の例だけに追加 |
name は全メトリクスに自動付与。verticalpodautoscaler も明示的に追加 |
Info / StateSet の表現 |
each.type で指定 |
値1、または状態ごとの0/1の Gauge |
| 対象の読み取り権限 | kube-state-metrics の ServiceAccount に付与 | resource-state-metrics の ServiceAccount に付与 |
第4章のクラスタと読み取り権限を使い、5.5節の YAML を vpa-migration-rmm.yaml として保存します。
kubectl apply -f vpa-migration-rmm.yaml
# 第4章の port-forward で公開したメトリクスを確認する
curl -s http://127.0.0.1:9999/metrics | grep kube_customresource_verticalpodautoscaler_
CPU の target recommendation は、kube_customresource_verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu で取得できます。配列内の全コンテナが対象です。設定値・recommendation がまだない場合は、そのサンプルを生成しません。annotations / labels がない場合も値1のサンプルは生成され、展開するラベルだけが省略されます。
複数コンテナへの対応と単位変換は元の設定に揃えています。実機では、2コンテナを対象とした15個のメトリクス・30サンプルについて、名前とラベルの違いを揃えたうえで値が一致することを確認しました。
メトリクス名やラベル構成が変わるため、既存のクエリ・アラート・ダッシュボードへの影響も確認するのが良いと思います。Info / StateSet は設定上の表現が変わりますが、今回の HTTP 応答では移行前後とも Gauge として公開されました。
(参考: VPA の公式サンプル、CEL Resolver、Starlark Resolver、メトリクスの生成処理、自動付与するラベル)
5.5 ResourceMetricsMonitor の設定全体
分割して説明した Store と15個の Family をまとめた YAML です。
ResourceMetricsMonitor の YAML 全体を表示
apiVersion: resource-state-metrics.instrumentation.k8s-sigs.io/v1alpha1
kind: ResourceMetricsMonitor
metadata:
name: vpa-migration
namespace: default
spec:
configuration:
stores:
- group: autoscaling.k8s.io
version: v1
kind: VerticalPodAutoscaler
resource: verticalpodautoscalers
resolver: cel
families:
- name: verticalpodautoscaler_annotations
help: "Kubernetes annotations converted to Prometheus labels."
metrics:
- value: "1.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- name: _annotations
value: 'labelPrefix(has(o.metadata.annotations) ? o.metadata.annotations : {}, "annotation_")'
- name: verticalpodautoscaler_labels
help: "Kubernetes labels converted to Prometheus labels."
metrics:
- value: "1.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- name: _labels
value: 'labelPrefix(has(o.metadata.labels) ? o.metadata.labels : {}, "label_")'
- name: verticalpodautoscaler_spec_updatepolicy_updatemode
help: "Update mode of the VerticalPodAutoscaler."
metrics:
- value: "o.spec.updatePolicy.updateMode == 'Auto' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Auto'"}
- value: "o.spec.updatePolicy.updateMode == 'Initial' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Initial'"}
- value: "o.spec.updatePolicy.updateMode == 'Off' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Off'"}
- value: "o.spec.updatePolicy.updateMode == 'Recreate' ? 1.0 : 0.0"
labels:
- {name: verticalpodautoscaler, value: o.metadata.name}
- {name: target_api_version, value: o.spec.targetRef.apiVersion}
- {name: target_kind, value: o.spec.targetRef.kind}
- {name: target_name, value: o.spec.targetRef.name}
- {name: update_mode, value: "'Recreate'"}
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_memory
help: "Minimum memory resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["minAllowed"]["memory"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "memory" in c.get("minAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_memory",
help="Minimum memory resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_cpu
help: "Minimum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["minAllowed"]["cpu"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "cpu" in c.get("minAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_minallowed_cpu",
help="Minimum cpu resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_memory
help: "Maximum memory resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["maxAllowed"]["memory"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "memory" in c.get("maxAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_memory",
help="Maximum memory resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_cpu
help: "Maximum cpu resources the VerticalPodAutoscaler can set for containers matching the name."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["maxAllowed"]["cpu"])))
for c in obj.get("spec", {}).get("resourcePolicy", {}).get("containerPolicies", [])
if "cpu" in c.get("maxAllowed", {})]
families = [family(name="verticalpodautoscaler_spec_resourcepolicy_container_policies_maxallowed_cpu",
help="Maximum cpu resources the VerticalPodAutoscaler can set for containers matching the name.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_memory
help: "Minimum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["lowerBound"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("lowerBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_memory",
help="Minimum memory resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_cpu
help: "Minimum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["lowerBound"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("lowerBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_lowerbound_cpu",
help="Minimum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_memory
help: "Maximum memory resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["upperBound"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("upperBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_memory",
help="Maximum memory resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_cpu
help: "Maximum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["upperBound"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("upperBound", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_upperbound_cpu",
help="Maximum cpu resources the container can use before the VerticalPodAutoscaler updater evicts it.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_target_memory
help: "Target memory resources the VerticalPodAutoscaler recommends for the container."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["target"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("target", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_target_memory",
help="Target memory resources the VerticalPodAutoscaler recommends for the container.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["target"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("target", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_target_cpu",
help="Target cpu resources the VerticalPodAutoscaler recommends for the container.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_memory
help: "Target memory resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="memory", unit="byte"),
value=quantity_to_float(str(c["uncappedTarget"]["memory"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "memory" in c.get("uncappedTarget", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_memory",
help="Target memory resources the VerticalPodAutoscaler recommends for the container ignoring bounds.", kind="gauge", samples=samples)]
- name: verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_cpu
help: "Target cpu resources the VerticalPodAutoscaler recommends for the container ignoring bounds."
resolver: starlark
starlark:
script: |
ref = obj["spec"]["targetRef"]
common = {"verticalpodautoscaler": obj["metadata"]["name"],
"target_api_version": ref["apiVersion"],
"target_kind": ref["kind"], "target_name": ref["name"]}
samples = [metric(
labels=dict(common, container=c["containerName"], resource="cpu", unit="core"),
value=quantity_to_float(str(c["uncappedTarget"]["cpu"])))
for c in obj.get("status", {}).get("recommendation", {}).get("containerRecommendations", [])
if "cpu" in c.get("uncappedTarget", {})]
families = [family(name="verticalpodautoscaler_status_recommendation_containerrecommendations_uncappedtarget_cpu",
help="Target cpu resources the VerticalPodAutoscaler recommends for the container ignoring bounds.", kind="gauge", samples=samples)]
おわりに
kube-state-metrics から Custom Resource State Metrics を分離し、resource-state-metrics として独立して開発する方針は、それぞれの機能に合わせて開発やリリースを進めやすくなるという点で、良い流れだと思いました。
一方で、気になっていることも2点あります。
-
セキュリティへの対応
昨今のセキュリティ対応を見ていると、コミュニティが管理する OSS でも、GA に求められる水準は高くなっている印象があります。既存のプロジェクトでも対応が課題になる中で、新しいプロジェクトを安定したリリースまで持っていくのは、以前より難しくなっているように感じます。
-
CEL と Starlark の可読性
CEL や Starlark で短くまとめた処理は、Go で書かれたコードよりも読み解きにくく、Shell のワンライナーを読んでいるように感じがします。正直、AI の補助がないと、読み書きはかなり辛いなと思いました。
AI の補助を使う前提で運用するのであれば、AI で Go でメトリクスを出力するコードを実装して運用するのと、どっちがいいかは悩ましいなと思いました。
カスタムコントローラーを開発する人にとって、resource-state-metrics が GA になれば便利になると思います。一方で、Kubernetes のように広く利用されている OSS のコミュニティでも、サブプロジェクトを立ち上げ、開発・保守を続けながら GA まで進めるのは、今後はより難しくなっていくだろうなと思いました。
参考
CEL と Starlark の概要
CEL と Starlark は、どちらもアプリケーションに組み込んで使う言語ですが、開発の背景と目的が異なります。
| 項目 | CEL | Starlark |
|---|---|---|
| 正式名・旧称 | Common Expression Language | 旧称 Skylark |
| 開発の背景 | Firebase Rules の開発経験と usability testing をもとに設計 | Google の build system で、Python による build description を置き換えるために設計 |
| 主な目的 | アプリケーションやプラットフォーム間で、式の評価方法を共通化する。security policy などに利用する | Bazel の build の設定や拡張処理を、再現性を保って記述する |
| 記述の形式 | C / Java / JavaScript などに似た式 | Python に似たスクリプト |
| 主な機能 | フィールド参照、条件分岐、計算、list / map の処理、任意の事前型チェック | 変数、関数、条件分岐、for、list comprehension、list / dict の操作 |
| 設計上の特徴 | side-effect-free(入力を変更しない)、terminating(言語内の処理で無限ループしない) | deterministic evaluation(同じ入力から同じ結果を得る)、hermetic execution(言語自体はファイル・ネットワーク・時刻へのアクセスを提供しない)、parallel evaluation(並列評価) |
| resource-state-metrics での用途 | 対象リソースを o で参照し、メトリクスの値やラベルを取得・変換する |
対象リソースの情報を持つ obj を参照し、複数のサンプルの値とラベルを組み立てる |
どちらも、組み込むアプリケーションが変数や関数などを追加できます。例えば o・obj や、quantity()・metric() などは resource-state-metrics が提供するもので、言語自体の標準機能とは区別します。
(参考: CEL README、CEL Language Definition、Starlark README、Starlark Language Design)
resource-state-metrics での使い分け
まず unstructured でフィールドをそのまま取得できるか確認し、条件分岐や変換が必要なら CEL、複数サンプルの組み立てが必要なら Starlark を検討するのが良いと思います。
| Resolver | 選ぶ場面 | 例 |
|---|---|---|
unstructured |
フィールドの値をそのまま取得する |
metadata.name をラベルにする |
cel |
条件分岐・計算・変換が必要 | Ready の状態を 1 / 0 にする、CPU の quantity を数値に変換する |
starlark |
複数サンプルの値とラベルを、対応関係を保って組み立てる | VPA のコンテナごとに、コンテナ名と CPU・メモリの recommendation を出力する |
本記事の移行例では、複数コンテナの値とラベルの対応を保つために Starlark を使っています。CEL 自体は配列を扱えますが、resource-state-metrics v0.1.0 では、値とラベルを別々の配列として返した場合、ラベル側のソートによって対応が崩れるケースを検証時に確認しました。
例えば、次のように1つの Pod に複数のコンテナが存在する場合です。以下はコンテナ構成を示すサンプルで、CPU の recommendation は Pod のマニフェストではなく、VPA の status に記録されます。
apiVersion: v1
kind: Pod
metadata:
name: multi-container-demo
spec:
containers:
- name: z-app # アプリケーション用コンテナ
image: busybox:1.36
command: ["sleep", "infinity"]
- name: a-sidecar # 同じ Pod 内の補助コンテナ
image: busybox:1.36
command: ["sleep", "infinity"]
この Pod と同じコンテナ構成を持つ workload を VPA の対象とし、z-app の CPU recommendation が 0.25、a-sidecar が 0.5 になったとします。コンテナ名を ["z-app", "a-sidecar"]、CPU の値を [0.25, 0.5] として取得した後、名前だけが ["a-sidecar", "z-app"] に並び替わると、a-sidecar に 0.25 が対応してしまいます。
Starlark では、同じコンテナから取得した名前と値を metric(labels=..., value=...) で一緒に組み立て、この問題を避けています。
これは CEL の言語仕様の制約ではなく、resource-state-metrics v0.1.0 での配列の扱いによるものです。フィールドの取得や単一の値の変換など、必要な処理を unstructured や CEL で短く表現できる場合は、そちらを使う方が設定を読みやすく保てると思います。
参考リンク
本文で参照した主なドキュメントをまとめます。