> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure Managed Monitoring

> Azure Monitor Workspace、Azure Managed Grafana、および Istio mTLS 経由でスクレイプを行うメッシュ内 Prometheus を使用して、AKS 上で Vantage 3.0 セルフホスト型のメトリクスを収集します。

このガイドでは、Azure マネージド監視 (Azure Monitor Workspace + Managed Grafana + `ama-metrics` エージェント) がすでに有効になっている AKS クラスターで、Vantage アプリケーションのメトリクスを収集する方法を説明します。設定が完了すると、Vantage アプリケーションのメトリクスは、Istio mTLS 経由で Vantage のエンドポイントに到達するメッシュ内 Prometheus によってスクレイプされ、同じ Azure Managed Grafana でインフラストラクチャのメトリクスとあわせて表示されます。

<Note>
  このパターンが存在する理由 (これを必要としている Istio mTLS の制約を含む) の背景については、[Monitoring Overview](/ja/vantage/self-hosted/v3.0/monitoring/overview) を参照してください。
</Note>

<div id="why-this-pattern-exists">
  ## このパターンが必要な理由
</div>

Azure によってデプロイされる `ama-metrics` エージェント は、Kubernetes のインフラストラクチャ メトリクス (kubelet、cadvisor、kube-state-metrics) を自動的に処理します。また、Istio プロキシ メトリクス (`istio_requests_total` など) は Envoy サイドカーによって平文ポートで公開されるため、pod annotation を介して自動的にスクレイプすることもできます。

一方、Vantage のアプリケーション メトリクスは異なります。これらはコンテナー ポート 8080 で公開されますが、このポートは Envoy サイドカーによってインターセプトされ、STRICT mTLS の適用対象になります。`ama-metrics` エージェント は `kube-system` 内で Istio サイドカーなしで実行されるため、有効な mTLS 証明書を提示できず、メッシュ化された名前空間内のアプリケーション メトリクス endpoint をスクレイプできません。Microsoft はこれを既知の制限事項として次のように文書化しています: ["現在、相互 TLS 認証を使用する Istio 構成からメトリクスを収集することはサポートされていません。"](https://learn.microsoft.com/en-us/azure/azure-monitor/containers/prometheus-istio-integration#limitations)

Vantage のアプリケーション メトリクスを収集するには、**Istio mesh 内** に Prometheus インスタンスをデプロイします。この Prometheus は Istio サイドカーとともに動作し、mesh 証明書をエクスポートして、それを使って mTLS 経由でアプリケーション endpoint をスクレイプし、`ama-metrics` と同じ Azure Monitor Workspace に remote-write します.

<div id="how-it-works">
  ## 仕組み
</div>

Vantage アプリケーションには OpenTelemetry SDK が組み込まれており、コンテナーポート 8080 の `/metrics-text` で Prometheus 形式のメトリクスを公開しています。メトリクスを公開するサービスには、ラベル `abbyy.platform.metrics.text.endpoint: "1"` が付与されています。

in-mesh Prometheus は、次のようにしてそれらのメトリクスをスクレイプします。

1. Istio サイドカー (`sidecar.istio.io/inject: "true"`) を有効にして実行します。
2. `OUTPUT_CERTS` プロキシ設定アノテーションを使用して、Istio の mTLS 証明書をエクスポートします。
3. それらの証明書を `/etc/prom-certs/` の Prometheus コンテナーにマウントします。
4. Istio の CA 証明書、クライアント証明書、およびキーを使用し、`scheme: https` 経由でスクレイプするように `ServiceMonitor` (Step 6 で `vantage-selfhosted` チャートによって作成) を設定します。

<div id="architecture">
  ## アーキテクチャ
</div>

| コンポーネント                             | 役割                                                                                                        |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------- |
| **Azure Monitor Workspace**         | すべてのメトリクスを保存する Prometheus 互換のバックエンド。                                                                      |
| **Azure Managed Grafana**           | 可視化レイヤー。データソースとして Azure Monitor Workspace にあらかじめ接続されています。                                                 |
| **`ama-metrics` エージェント** (Azure 管理) | 既定の Kubernetes インフラストラクチャ メトリクスをスクレイプします。AKS で Prometheus を有効にすると自動的にデプロイされます。                            |
| **In-mesh Prometheus** (custom)     | mTLS 経由で Vantage アプリのメトリクスをスクレイプし、Azure Monitor Workspace に remote-write する、Istio によって注入された Prometheus。   |
| **`ServiceMonitor`** (custom)       | Vantage のスクレイプ ターゲットを定義します: `abbyy.platform.metrics.text.endpoint: "1"` というラベルが付いたサービス上の `/metrics-text`。 |

<div id="prerequisites">
  ## 前提条件
</div>

* Istio service mesh アドオンが有効になっている AKS クラスター (STRICT mTLS) 。
* Azure Monitor Workspace がプロビジョニング済みで、AKS クラスターにリンクされていること。
* Azure Managed Grafana がプロビジョニング済みで、Azure Monitor Workspace にリンクされていること。
* `ama-metrics` エージェント がクラスター上で実行されていること (AKS Monitor Settings で有効化) 。
* AKS クラスターで OIDC issuer が有効になっていること (workload identity に必要) 。
* Prometheus Operator の CRD がインストールされていること (これらは `ama-metrics` に含まれます) 。

<div id="step-1-provision-azure-resources">
  ## Step 1: Azure リソースをプロビジョニングする
</div>

監視用リソースをまだ作成していない場合は、今すぐ Azure ポータルで作成してください。

1. **Azure Monitor Workspace**: Azure ポータル → "Azure Monitor workspaces" → 作成。AKS クラスターと同じリソース グループおよびリージョンを使用します。命名規則: `amw-<cluster-name>`.
2. **Azure Managed Grafana**: Azure ポータル → "Azure Managed Grafana" → 作成。同じリソース グループおよびリージョンを使用します。作成時に Azure Monitor Workspace にリンクします。命名規則: `amg-<cluster-name>`.
3. **AKS で Prometheus を有効にする**: Azure ポータル → AKS クラスター → Monitoring → Monitor Settings → "Metrics via managed Prometheus" を有効にし、Azure Monitor Workspace と Grafana インスタンスを選択します。

`ama-metrics` pod が実行中であることを確認します:

```bash theme={null}
kubectl get pods -n kube-system | grep ama-metrics
```

<div id="step-2-create-the-observability-namespace-with-istio-injection">
  ## Step 2: Istio インジェクションを有効にして observability 名前空間を作成する
</div>

> **注:** 名前空間名は任意に設定できますが、一部のオプション機能 (KEDA サポートなど) は Prometheus サービスが `observability` 名前空間にあることを前提としているため、`observability` を使用することを推奨します。

```bash theme={null}
kubectl create namespace observability
```

他のメッシュに参加している名前空間で使用されている Istio のリビジョン ラベルを確認します。

```bash theme={null}
# 必要に応じて名前空間を置き換えてください
kubectl get namespace app -o jsonpath='{.metadata.labels}' | grep istio
```

`observability` 名前空間にも同じラベルを付けます:

```bash theme={null}
kubectl label namespace observability istio.io/rev=<revision>
```

<div id="step-3-gather-azure-monitor-workspace-ingestion-details">
  ## Step 3: Azure Monitor Workspace の取り込みの詳細情報を収集する
</div>

データ収集ルールとエンドポイントのリソース ID を取得します。

```bash theme={null}
az monitor account show \
  --name <monitor-workspace-name> \
  --resource-group <resource-group> \
  --query "defaultIngestionSettings"
```

メトリクス取り込みエンドポイント URL を取得します。

```bash theme={null}
az monitor data-collection endpoint show \
  --name <monitor-workspace-name> \
  --resource-group <managed-resource-group> \
  --query "metricsIngestion.endpoint"
```

DCR の変更不可 ID を取得します:

```bash theme={null}
az monitor data-collection rule show \
  --name <monitor-workspace-name> \
  --resource-group <managed-resource-group> \
  --query "immutableId"
```

<Note>
  マネージド リソース グループは、`MA_<monitor-workspace-name>_<region>_managed` のパターンに従います。
</Note>

remote-write の完全な URL を作成します (Step 5 で使用します) :

```text theme={null}
https://<endpoint>/dataCollectionRules/<dcr-immutable-id>/streams/Microsoft-PrometheusMetrics/api/v1/write?api-version=2023-04-24
```

<div id="step-4-create-a-managed-identity-for-prometheus">
  ## 手順 4: Prometheus 用のマネージド ID を作成する
</div>

ユーザー割り当てマネージド ID を作成します。

```bash theme={null}
az identity create \
  --name <cluster-name>-prometheus \
  --resource-group <resource-group> \
  --location <region>
```

出力に表示された `clientId` と `principalId` を控えておきます。

データ収集ルールに `Monitoring Metrics Publisher` ロールを割り当てます。

```bash theme={null}
az role assignment create \
  --role "Monitoring Metrics Publisher" \
  --assignee-object-id <principalId> \
  --assignee-principal-type ServicePrincipal \
  --scope "<dataCollectionRuleResourceId>"
```

OIDC の発行元 URL を取得します:

```bash theme={null}
az aks show \
  --name <cluster-name> \
  --resource-group <resource-group> \
  --query "oidcIssuerProfile.issuerUrl" -o tsv
```

マネージド ID を Prometheus のサービス アカウントに関連付けるフェデレーション資格情報を作成します。

```bash theme={null}
az identity federated-credential create \
  --name prometheus-federated \
  --identity-name <cluster-name>-prometheus \
  --resource-group <resource-group> \
  --issuer "<oidc-issuer-url>" \
  --subject "system:serviceaccount:observability:prometheus" \
  --audiences "api://AzureADTokenExchange"
```

<div id="step-5-install-the-prometheus-operator">
  ## Step 5: Prometheus Operator をインストールする
</div>

`ama-metrics` エージェントは Prometheus CRD をインストールしますが、カスタムの Prometheus リソースをリコンサイルする Operator は実行しません。Operator のみをインストールし、それ以外はすべて無効にします:

```bash theme={null}
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install prometheus-operator prometheus-community/kube-prometheus-stack \
  --namespace observability \
  --set prometheus.enabled=false \
  --set alertmanager.enabled=false \
  --set grafana.enabled=false \
  --set defaultRules.create=false \
  --set nodeExporter.enabled=false \
  --set kubeStateMetrics.enabled=false
```

<div id="step-6-apply-the-prometheus-manifests">
  ## Step 6: Prometheus マニフェストを適用する
</div>

3 つのマニフェスト (サービス アカウント、RBAC、Prometheus インスタンス) が必要です。以下の順序で適用してください。Vantage の `ServiceMonitor` は、`vantage-selfhosted` チャートによって別途作成されます (以下を参照) 。

**`service-account.yaml`**: workload identity アノテーションを持つ Prometheus サービス アカウント:

```yaml theme={null}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
  namespace: observability
  annotations:
    azure.workload.identity/client-id: "<managed-identity-clientId>"
  labels:
    azure.workload.identity/use: "true"
```

**`rbac.yaml`**: ターゲット検出用の`ClusterRole`とバインディング：

```yaml theme={null}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: prometheus
rules:
  - apiGroups: [""]
    resources: [nodes, nodes/metrics, services, endpoints, pods]
    verbs: [get, list, watch]
  - apiGroups: ["networking.k8s.io"]
    resources: [ingresses]
    verbs: [get, list, watch]
  - nonResourceURLs: ["/metrics", "/metrics/cadvisor"]
    verbs: [get]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
  - kind: ServiceAccount
    name: prometheus
    namespace: observability
```

**`prometheus.yaml`**: Istio サイドカー インジェクション、証明書のエクスポート、Azure Monitor への remote-write を備えた Prometheus インスタンス:

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:
  name: metrics
  namespace: observability
spec:
  replicas: 1
  scrapeInterval: 60s
  logLevel: debug
  serviceAccountName: prometheus
  podMetadata:
    annotations:
      proxy.istio.io/config: |
        proxyMetadata:
          OUTPUT_CERTS: /etc/istio-output-certs
      sidecar.istio.io/userVolumeMount: '[{"name": "istio-certs", "mountPath": "/etc/istio-output-certs"}]'
    labels:
      sidecar.istio.io/inject: "true"
      azure.workload.identity/use: "true"
  volumes:
    - name: istio-certs
      emptyDir:
        medium: Memory
  volumeMounts:
    - name: istio-certs
      mountPath: /etc/prom-certs/
      readOnly: true
  resources:
    requests:
      memory: 3Gi
      cpu: 600m
    limits:
      memory: 6Gi
      cpu: 1000m
  serviceMonitorNamespaceSelector: {}
  serviceMonitorSelector: {}
  remoteWrite:
    - url: "<remote-write-url>"
      azureAd:
        cloud: AzurePublic
        sdk:
          tenantId: "<azure-tenant-id>"
  replicaExternalLabelName: "__replica__"
  externalLabels:
    cluster: "<cluster-name>"
```

<Note>
  `azureAd.sdk` 認証メソッドは `DefaultAzureCredential` を使用し、`azure.workload.identity/use: "true"` ラベルによって注入された workload identity トークンを取得します。Prometheus v3.60 以降が必要です。
</Note>

3 つすべてを適用します:

```bash theme={null}
kubectl apply -f service-account.yaml
kubectl apply -f rbac.yaml
kubectl apply -f prometheus.yaml
```

<div id="configure-the-vantage-servicemonitor">
  ### Vantage `ServiceMonitor` を設定する
</div>

Vantage の `ServiceMonitor` は手動で適用するのではなく、`vantage-selfhosted` Helm チャートによって作成されます。in-mesh Prometheus がエクスポートする証明書を使用し、Istio mTLS 経由で Vantage をスクレイプするよう `ServiceMonitor` を設定した values ファイルを使って、チャートをインストールまたはアップグレードします。

```yaml theme={null}
# values.vantage-selfhosted.yaml
observability:
  prometheus:
    serviceMonitor:
      scheme: https
      tlsConfig:
        caFile: /etc/prom-certs/root-cert.pem
        certFile: /etc/prom-certs/cert-chain.pem
        keyFile: /etc/prom-certs/key.pem
        insecureSkipVerify: true  # Prometheus は Istio のセキュリティ命名をサポートしていないため、対象の pod 証明書の検証をスキップ
      relabelings:
        - action: replace
          sourceLabels: [__meta_kubernetes_service_name]
          targetLabel: service_name
      metricRelabelings:
        - action: replace
          sourceLabels: [__meta_kubernetes_service_name]
          targetLabel: app_service
```

これらのパスで使用されている Istio mTLS 証明書の設定に関する詳しい説明は、[Prometheus を使用した監視](/ja/vantage/self-hosted/v3.0/monitoring/prometheus#istio-mtls)を参照してください。

<div id="step-7-verify">
  ## 手順 7: 確認
</div>

Prometheus pod が 3 つのコンテナー (`prometheus`、`config-reloader`、`istio-proxy`) で実行されていることを確認します。

```bash theme={null}
kubectl get pods -n observability
```

スクレイプターゲットを確認するには、ポートフォワードを実行します:

```bash theme={null}
kubectl port-forward -n observability prometheus-metrics-0 9090:9090
```

`http://localhost:9090/targets` を開きます。ターゲットが **UP** と表示され、`https` 経由で `/metrics-text:8080` をスクレイプしていることを確認します。

エラーがないか remote-write のログを確認します:

```bash theme={null}
kubectl logs -n observability prometheus-metrics-0 -c prometheus | grep -i "remote" | tail -10
```

remote-write が正常に機能している場合は、認証エラーが表示されず、"Done replaying WAL" と表示されます。

Managed Grafana では、Managed Prometheus データソースを使用して Explore ビューで `up{cluster="<cluster-name>"}` をクエリし、メトリクスが取り込まれていることを確認します。

<div id="operational-notes">
  ## 運用上の注意
</div>

* `ama-metrics` エージェント は引き続き Kubernetes のインフラストラクチャ メトリック (kubelet、cadvisor、kube-state-metrics、node-exporter) を処理します。**無効化しないでください**。
* in-mesh Prometheus が処理するのは Vantage application のメトリックのみです。どちらも同じ Azure Monitor Workspace に書き込みます。
* `azureAd.sdk` remote-write 認証では `DefaultAzureCredential` を使用します。これにより、AKS workload identity webhook によって pod に投影された workload identity トークンが取得されます。これには、サービス アカウント annotation `azure.workload.identity/client-id` と、pod label `azure.workload.identity/use: "true"` が必要です。
* `azureAd.managedIdentity` の設定は、この use case では**機能しません**。これはノード上の IMDS endpoint を呼び出しますが、ユーザー割り当て identity は VMSS の Node Pool に割り当てられていないためです。
* Prometheus の targets view に表示される `UNKNOWN` ターゲットは、通常、スクレイピングの問題ではなく、Degraded または CrashLooping 状態にある pod です。
* Prometheus CRD の `logLevel: debug` は、設定を確認した後で `info` に変更できます。
