Grafana

Grafana: 包括的な可視化とダッシュボード管理プラットフォーム

1. はじめに

Grafanaは、複数のデータソースから時系列データを収集し、リアルタイムのダッシュボードと高度な可視化を提供する、現代的なオブザーバビリティプラットフォームです。元々はGraphiteのダッシュボードツールとして始まりましたが、現在はPrometheus、Graphite、InfluxDB、Elasticsearch、Datadogなど、数百のデータソースに対応した統合オブザーバビリティスイートへと進化しました。

Grafanaは、インフラストラクチャ監視、アプリケーションパフォーマンス管理(APM)、ログ分析、合成監視など、複雑な環境での可視化ニーズに対応するために設計されています。

2. Grafanaの基本的な特徴

2.1 マルチソースデータ統合

Grafanaの最大の強みは、異なるベンダーやツールからのデータを一つのダッシュボードに統合できることです。

対応するデータソース(主要なもの):

  • 時系列データベース: Prometheus, Graphite, InfluxDB, TimescaleDB, Elasticsearch
  • ログ管理: Loki, Elasticsearch, Splunk, CloudWatch Logs
  • クラウドネイティブ: AWS CloudWatch, Azure Monitor, Google Cloud Monitoring
  • 外部サービス: Datadog, New Relic, Splunk, Honeycomb
  • その他: MySQL, PostgreSQL, SQLite, MongoDB (JSONドキュメントクエリ)

複数のデータソースをシームレスに組み合わせることで、単一のペイン・オブ・グラス(Single Pane of Glass)実現が可能になります。

2.2 豊富な可視化オプション

Grafanaは50以上の組み込み可視化タイプを提供し、さらにコミュニティプラグインを追加できます。

主要な可視化タイプ:

  • グラフ: 複数の軸を持つ複雑な時系列グラフ
  • ゲージ: 現在の値を視覚化する円形ゲージ
  • ステータスパネル: リソースの健全性状態をシンプルに表示
  • テーブル: 構造化データの表示と検索
  • ヒートマップ: 時間経過による強度分布の表示
  • ボックスプロット: 四分位数分布の表示
  • トポロジー: ネットワークやシステムの依存関係を図式化
  • ログ: 構造化ログの検索と表示
  • トレース: 分散トレースの視覚化
  • バー・カラムグラフ: 離散的なデータの比較表示
  • ピエ図: 全体に占める割合の表示
  • キャンドルスティック: OHLC(始値・高値・安値・終値)データの表示
  • ノード グラフ: サービス間の通信フローと依存関係

2.3 アラート機能

Grafanaはインテリジェントなアラートエンジンを備えており、複数のルールエンジンをサポートしています。

アラート機能の特徴:

  • 統一されたアラート: 単一のアラートエンジンで複数のデータソースを監視
  • 複数のルールエンジン: 古いアラート、新しいアラート(Unified Alerting)
  • 複数の通知先: Slack, Teams, PagerDuty, Webhook, メール、OpsGenie
  • ポリシーベースのルーティング: アラートをルール名や元のデータベースに基づいてルーティング
  • グループ化とテンプレート: アラート通知をカスタマイズ可能

2.4 ダッシュボード機能

Grafanaのダッシュボードは、組織内での効果的な監視とレポーティングの中核です。

ダッシュボード機能:

  • 動的パネル: 変数、テンプレートを使用した動的なダッシュボード作成
  • 共有とアクセス制御: 組織、チーム、ユーザーレベルでの細かい権限管理
  • ダッシュボードのバージョン管理: 過去のバージョンへのロールバック
  • スナップショット: ダッシュボードの固定スナップショット作成
  • 自動更新: ダッシュボードの定期的な自動更新とリフレッシュ
  • 埋め込み: 外部のWebサイトへのダッシュボード埋め込み

3. Grafanaのアーキテクチャ

3.1 全体構成

┌─────────────────────────────────────────────────────────────┐
│                     Grafanaサーバー                          │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌──────────────────────────────────────────────────────┐   │
│  │         HTTP API & Web UI                             │   │
│  │  (REST API, WebSocket, GraphQL API)                   │   │
│  └──────────────────────────────────────────────────────┘   │
│                          ↓                                    │
│  ┌──────────────────────────────────────────────────────┐   │
│  │      データソースプラグインマネージャー              │   │
│  │  (複数のデータソース管理・クエリ翻訳)                 │   │
│  └──────────────────────────────────────────────────────┘   │
│          ↙         ↙          ↙           ↙                  │
│  ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────┐     │
│  │ Alerting│ │Dashboard │ │ Provisioning
│  │ Engine  │ │ Engine   │ │ Service  │ │ Plugin System │     │
│  └─────────┘ └──────────┘ └──────────┘ └─────────────┘     │
│           ↓                                                   │
│  ┌──────────────────────────────────────────────────────┐   │
│  │         メタデータ・インデックス管理                 │   │
│  │      (データベース、キャッシング層)                 │   │
│  └──────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│              バックエンドストレージ                          │
├─────────────────────────────────────────────────────────────┤
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐       │
│  │PostgreSQL│ │  SQLite  │ │ MySQL    │ │ Loki     │       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘       │
└─────────────────────────────────────────────────────────────┘
         ↓              ↓             ↓            ↓
┌─────────────────────────────────────────────────────────────┐
│            外部データソース                                  │
├─────────────────────────────────────────────────────────────┤
│ Prometheus│Graphite│InfluxDB│Datadog│CloudWatch│Elasticsearch│
│ Splunk    │Loki    │Azure Monitor │New Relic  等              │
└─────────────────────────────────────────────────────────────┘

3.2 コアコンポーネント

3.2.1 HTTPサーバー

Grafanaはポート3000(デフォルト)でHTTPサーバーを起動します。

主な機能:

  • RESTful API提供
  • Webユーザーインターフェース配信
  • WebSocket接続(リアルタイム更新)
  • CORS設定
  • リバースプロキシサポート
# 設定例: grafana.ini
[server]
protocol = http
http_addr = 0.0.0.0
http_port = 3000
domain = grafana.example.com
root_url = https://grafana.example.com/grafana
enforce_domain = true
serve_from_sub_path = true

3.2.2 データソースプラグインシステム

Grafanaはプラグインベースのアーキテクチャで複数のデータソースをサポートしています。

プラグインの種類:

  • データソースプラグイン: クエリエンジンとメタデータプロバイダーを実装
  • パネルプラグイン: カスタム可視化を提供
  • アプリプラグイン: 複雑な監視スイートを統合
  • バックエンドプラグイン: Goで実装されたサーバーサイドロジック
# プラグイン有効化の設定例
grafana.ini:
[plugins]
allow_ui_updates = true
plugin_admin_enabled = true
plugins_allow_ui_updates = true

3.2.3 アラートエンジン

Grafanaのアラート機能は複数のルールエンジンをサポートします。

アラートルール評価の流れ:

データソースからデータ取得
        ↓
アラートルール評価
        ↓
条件判定(Firing/Pending/Resolved)
        ↓
通知ポリシー適用
        ↓
グループ化・テンプレート処理
        ↓
複数の通知先へ送信

3.2.4 メタデータストア

Grafanaのメタデータはリレーショナルデータベースに保存されます。

保存される主要情報:

  • ユーザー、組織、チーム情報
  • ダッシュボード定義
  • アラートルール
  • データソース設定
  • 変数、テンプレート定義
  • 監査ログ
[database]
type = postgres
host = localhost:5432
name = grafana
user = grafana
password = ${GF_SECURITY_DB_PASSWORD}
ssl_mode = require
max_idle_conn = 2
max_open_conn = 0
conn_max_lifetime = 14400
log_queries = false

4. 主要な機能詳細

4.1 変数とテンプレート

Grafanaの変数は、ダッシュボードを動的にし、再利用性を高めます。

変数の種類:

1. クエリ変数: データソースクエリから値を取得
   - 例: SELECT DISTINCT hostname FROM metrics
   
2. テキスト変数: テキスト入力
   - 例: service_name = "payment-api"
   
3. 定数変数: 不変の値
   - 例: environment = "production"
   
4. カスタム変数: カンマ区切りのカスタム値
   - 例: regions = "us-west-1,us-west-2,us-east-1"
   
5. 正規表現変数: 正規表現マッチング

使用例:

{
  "dashboard": {
    "panels": [
      {
        "targets": [
          {
            "expr": "rate(http_requests_total{job=\"$job\", instance=\"$instance\"}[5m])"
          }
        ]
      }
    ],
    "templating": {
      "list": [
        {
          "name": "job",
          "type": "query",
          "query": "label_values(http_requests_total, job)",
          "refresh": "on-time-range-change"
        },
        {
          "name": "instance",
          "type": "query",
          "query": "label_values(http_requests_total{job=\"$job\"}, instance)",
          "refresh": "on-time-range-change"
        }
      ]
    }
  }
}

4.2 アラート設定の詳細

4.2.1 新しいアラート(Unified Alerting)

Grafana 8.0以降で導入された統一されたアラートシステム。

# Prometheus互換の記法
groups:
  - name: my-alerts
    interval: 5m
    rules:
      - alert: HighErrorRate
        expr: |
          (
            sum(rate(requests_total{status=~"5.."}[5m]))
            /
            sum(rate(requests_total[5m]))
          ) > 0.05
        for: 5m
        annotations:
          summary: "High error rate detected"
          description: "Error rate is {{ $value | humanizePercentage }}"
        labels:
          severity: critical

4.2.2 通知ポリシー

global:
  resolve_timeout: 5m

route:
  receiver: default
  group_by: ['alertname', 'cluster']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 4h
  
  routes:
    - matcher:
        severity: critical
      receiver: pagerduty
      repeat_interval: 1h
      
    - matcher:
        team: platform
      receiver: slack-platform
      group_by: ['alertname', 'service']

receivers:
  - name: default
    slack_configs:
      - api_url: 'https://hooks.slack.com/services/XXX/YYY/ZZZ'
        channel: '#alerts'
        
  - name: pagerduty
    pagerduty_configs:
      - service_key: 'https://events.pagerduty.com/...'
        severity: 'critical'

4.3 ダッシュボード設定の実装例

4.3.1 基本的なダッシュボード構造

{
  "dashboard": {
    "title": "Platform Observability Dashboard",
    "uid": "platform-obs-001",
    "version": 1,
    "tags": ["platform", "production"],
    "timezone": "browser",
    "refresh": "30s",
    "time": {
      "from": "now-6h",
      "to": "now"
    },
    "panels": [
      {
        "id": 1,
        "title": "Request Rate",
        "type": "graph",
        "datasource": "Prometheus",
        "gridPos": {
          "h": 8,
          "w": 12,
          "x": 0,
          "y": 0
        },
        "targets": [
          {
            "expr": "sum(rate(http_requests_total[5m])) by (service)",
            "format": "time_series",
            "legendFormat": "{{service}}",
            "refId": "A"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "color": {
              "mode": "palette-classic"
            },
            "custom": {
              "axisLabel": "Requests/sec",
              "axisPlacement": "auto"
            },
            "unit": "reqps"
          }
        },
        "options": {
          "legend": {
            "calcs": ["mean", "max"],
            "placement": "bottom"
          }
        }
      },
      {
        "id": 2,
        "title": "Error Rate",
        "type": "gauge",
        "datasource": "Prometheus",
        "gridPos": {
          "h": 8,
          "w": 12,
          "x": 12,
          "y": 0
        },
        "targets": [
          {
            "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m]))",
            "refId": "A"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "percentunit",
            "max": 1,
            "min": 0,
            "thresholds": {
              "mode": "absolute",
              "steps": [
                {"color": "green", "value": null},
                {"color": "yellow", "value": 0.01},
                {"color": "red", "value": 0.05}
              ]
            }
          }
        }
      },
      {
        "id": 3,
        "title": "Latency Heatmap",
        "type": "heatmap",
        "datasource": "Prometheus",
        "gridPos": {
          "h": 8,
          "w": 24,
          "x": 0,
          "y": 8
        },
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
            "legendFormat": "p95",
            "refId": "A"
          },
          {
            "expr": "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))",
            "legendFormat": "p99",
            "refId": "B"
          }
        ]
      }
    ]
  }
}

4.3.2 複雑なダッシュボード例:マイクロサービスモニタリング

{
  "dashboard": {
    "title": "Microservices Health Dashboard",
    "tags": ["microservices", "platform"],
    "templating": {
      "list": [
        {
          "name": "environment",
          "type": "query",
          "query": "label_values(up, environment)",
          "current": {"value": "production"}
        },
        {
          "name": "service",
          "type": "query",
          "query": "label_values(up{environment=\"$environment\"}, service)",
          "current": {"value": ["all"]},
          "multi": true
        }
      ]
    },
    "panels": [
      {
        "title": "Service Status Overview",
        "type": "stat",
        "targets": [
          {
            "expr": "count(up{environment=\"$environment\", service=~\"$service\"} == 1)",
            "legendFormat": "Healthy"
          },
          {
            "expr": "count(up{environment=\"$environment\", service=~\"$service\"} == 0)",
            "legendFormat": "Unhealthy"
          }
        ],
        "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
      },
      {
        "title": "P95 Latency by Service",
        "type": "table",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket{environment=\"$environment\", service=~\"$service\"}[5m]))",
            "format": "table"
          }
        ],
        "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}
      }
    ]
  }
}

4.4 プロビジョニングとインフラストラクチャアズコード

Grafanaはプロビジョニングにより、ダッシュボード、データソース、アラートなどを宣言的に管理できます。

# /etc/grafana/provisioning/dashboards/dashboards.yaml
apiVersion: 1

providers:
  - name: 'default'
    orgId: 1
    folder: ''
    type: file
    disableDeletion: false
    options:
      path: /var/lib/grafana/dashboards
# /var/lib/grafana/dashboards/prometheus.yaml
apiVersion: 1
kind: ConfigMap
metadata:
  name: prometheus-datasource

data:
  prometheus.yaml: |
    apiVersion: 1
    datasources:
      - name: Prometheus
        type: prometheus
        access: proxy
        url: http://prometheus:9090
        isDefault: true
        editable: true

4.5 RBAC(ロールベースアクセス制御)

Grafana Enterpriseでは細かいアクセス制御が可能です。

# ロール定義の例
[security]
admin_user = admin
admin_password = ${GF_SECURITY_ADMIN_PASSWORD}

[auth]
# LDAP/Active Directory統合
ldap_enabled = true
ldap_config_path = /etc/grafana/ldap.toml

# SAML統合
saml_enabled = true
saml_certificate_path = /etc/grafana/certs/sp.crt
saml_key_path = /etc/grafana/certs/sp.key

# OAuth 2.0統合
oauth_auto_login = false
oauth_allow_signup = true
# ldap.toml LDAP設定
[[servers]]
host = "ldap.example.com"
port = 389
use_ssl = false
bind_dn = "cn=admin,dc=example,dc=com"
bind_password = "password"
search_base_dns = ["dc=example,dc=com"]

[servers.attributes]
name = "cn"
surname = "sn"
username = "uid"
member_of = "memberOf"
email = "mail"

[[servers.group_mappings]]
group_dn = "cn=grafana-admin,ou=groups,dc=example,dc=com"
org_role = "Admin"

[[servers.group_mappings]]
group_dn = "cn=grafana-viewer,ou=groups,dc=example,dc=com"
org_role = "Viewer"

5. Grafana Loki統合

Loki は Grafana が開発したログアグリゲーション システムで、Prometheus にインスパイアされています。

5.1 Loki アーキテクチャ

┌─────────────────────────┐
│  ログソース              │
│ (Docker、Kubernetes)    │
└────────────┬────────────┘
             │ Promtail
             ↓
┌─────────────────────────┐
│  Loki Distributor       │
│ (ラベルパース・バリデーション)
└────────────┬────────────┘
             │
      ┌──────┴──────┐
      ↓             ↓
┌──────────┐  ┌──────────┐
│ Ingester │  │ Ingester │
│(ログバッチ化)  
└────┬─────┘  └────┬─────┘
     │              │
     └──────┬───────┘
            ↓
┌─────────────────────────┐
│  Object Storage         │
│  (S3, GCS, Azure等)      │
└─────────────────────────┘

5.2 Lokiクエリ例

# ラベルクエリ
{job="api-server"}

# 複合クエリ
{job="api-server", level="error"}

# ログライン フィルタ
{job="api-server"} |= "error"

# 正規表現フィルタ
{job="api-server"} |~ "status=5\d{2}"

# メトリクス抽出
{job="api-server"} | json | status=500 | unwrap duration_ms

# 集約
{job="api-server"} | json | unwrap duration_ms | histogram_quantile(0.95)

6. Grafana Tempo(トレース管理)

Tempo は OpenTelemetry ネイティブな分散トレース管理システムです。

6.1 Tempoとの統合

# datasource設定
apiVersion: v1
kind: ConfigMap
metadata:
  name: grafana-datasources

data:
  tempo.yaml: |
    apiVersion: 1
    datasources:
      - name: Tempo
        type: tempo
        access: proxy
        url: http://tempo:3200
        jsonData:
          nodeGraph:
            enabled: true
          lokiSearch:
            datasourceUid: loki_uid

6.2 トレース可視化

トレースパネルはサービス間の呼び出しフローを可視化します。

API Gateway (150ms)
    ├── Payment Service (100ms)
    │   ├── Database Query (50ms)
    │   └── Cache Lookup (5ms)
    ├── Order Service (30ms)
    │   └── Message Queue (20ms)
    └── Notification Service (15ms)
        └── Email Send (10ms)

7. Grafana Mimir(メトリクス管理)

Mimirは高スケーラビリティなメトリクスストレージです。

7.1 Mimirの特徴

  • 水平スケーラビリティ: マイクロサービスアーキテクチャ
  • 長期保存: S3などのオブジェクトストレージ対応
  • 高可用性: レプリケーション機能
  • 複数テナント対応: マルチテナント環境に対応

7.2 Mirirのコンポーネント

┌──────────────────────────┐
│  Distributor             │
│  (スケーラビリティ層)      │
└──────────┬───────────────┘
           │
    ┌──────┴──────┐
    ↓             ↓
┌──────────┐ ┌──────────┐
│ Ingester │ │ Ingester │
└────┬─────┘ └────┬─────┘
     │             │
     └──────┬──────┘
            ↓
┌──────────────────────────┐
│  Block Storage           │
│  (S3, GCS等)             │
└──────────────────────────┘

8. 運用の実践例

8.1 Docker Composeでの実装

version: '3.8'

services:
  grafana:
    image: grafana/grafana:10.0.0
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
      - GF_USERS_ALLOW_SIGN_UP=false
      - GF_SECURITY_SECRET_KEY=${GF_SECURITY_SECRET_KEY}
    volumes:
      - grafana_storage:/var/lib/grafana
      - ./provisioning:/etc/grafana/provisioning
      - ./dashboards:/var/lib/grafana/dashboards
    networks:
      - monitoring

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_storage:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
    networks:
      - monitoring

  loki:
    image: grafana/loki:2.8.0
    ports:
      - "3100:3100"
    volumes:
      - ./loki-config.yaml:/etc/loki/local-config.yaml
      - loki_storage:/loki
    command: -config.file=/etc/loki/local-config.yaml
    networks:
      - monitoring

  promtail:
    image: grafana/promtail:2.8.0
    volumes:
      - /var/log:/var/log
      - ./promtail-config.yaml:/etc/promtail/config.yml
    command: -config.file=/etc/promtail/config.yml
    networks:
      - monitoring

volumes:
  grafana_storage:
  prometheus_storage:
  loki_storage:

networks:
  monitoring:
    driver: bridge

8.2 Kubernetesでのデプロイ

# grafana-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: grafana
  namespace: monitoring

spec:
  replicas: 2
  selector:
    matchLabels:
      app: grafana
  
  template:
    metadata:
      labels:
        app: grafana
    
    spec:
      serviceAccountName: grafana
      
      containers:
      - name: grafana
        image: grafana/grafana:10.0.0
        ports:
        - containerPort: 3000
          name: web
        
        env:
        - name: GF_SECURITY_ADMIN_PASSWORD
          valueFrom:
            secretKeyRef:
              name: grafana-secret
              key: admin-password
        - name: GF_SECURITY_SECRET_KEY
          valueFrom:
            secretKeyRef:
              name: grafana-secret
              key: secret-key
        
        resources:
          requests:
            memory: "256Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        
        volumeMounts:
        - name: storage
          mountPath: /var/lib/grafana
        - name: provisioning
          mountPath: /etc/grafana/provisioning
        - name: dashboards
          mountPath: /var/lib/grafana/dashboards
        
        livenessProbe:
          httpGet:
            path: /api/health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
        
        readinessProbe:
          httpGet:
            path: /api/health
            port: 3000
          initialDelaySeconds: 10
          periodSeconds: 5
      
      volumes:
      - name: storage
        persistentVolumeClaim:
          claimName: grafana-pvc
      - name: provisioning
        configMap:
          name: grafana-provisioning
      - name: dashboards
        configMap:
          name: grafana-dashboards

---
apiVersion: v1
kind: Service
metadata:
  name: grafana
  namespace: monitoring

spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 3000
    protocol: TCP
  selector:
    app: grafana

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: grafana-pvc
  namespace: monitoring

spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

8.3 アラートルール設定例

# /etc/grafana/provisioning/alerting/alerts.yaml
apiVersion: 1

groups:
  - name: application_alerts
    interval: 1m
    rules:
      
      - uid: high_error_rate
        title: High Error Rate
        condition: B
        data:
          - refId: A
            queryType: ""
            relativeTimeRange:
              from: 300
              to: 0
            datasourceUid: prometheus_uid
            expression: |
              sum(rate(http_requests_total{status=~"5.."}[5m]))
              /
              sum(rate(http_requests_total[5m]))
            
          - refId: B
            expression: A
            reducer: mean
            settings:
              mode: strict
        noDataState: NoData
        execErrState: Alerting
        for: 5m
        annotations:
          description: |
            Error rate is {{ $value | humanizePercentage }}
            Please check the service logs immediately.
          runbook_url: https://wiki.example.com/runbooks/high_error_rate
          summary: High error rate detected
        labels:
          severity: critical
          team: platform
          
      - uid: high_cpu_usage
        title: High CPU Usage
        condition: B
        data:
          - refId: A
            queryType: ""
            relativeTimeRange:
              from: 300
              to: 0
            datasourceUid: prometheus_uid
            expression: |
              (100 - avg by (instance) (
                100 * (1 - rate(node_cpu_seconds_total{mode="idle"}[5m]))
              )) > 80
            
          - refId: B
            expression: A
            reducer: mean
        for: 10m
        annotations:
          description: |
            CPU usage is {{ $value }}%
            Host: {{ $labels.instance }}
          summary: High CPU usage on {{ $labels.instance }}
        labels:
          severity: warning
          team: infrastructure

9. パフォーマンス最適化

9.1 クエリ最適化

# 非効率なクエリ
rate(http_requests_total[5m])

# 最適化されたクエリ
rate(http_requests_total{environment="production"}[5m])

# さらに最適化
sum(rate(http_requests_total{environment="production", service="api"}[5m])) by (method)

9.2 リソース管理

# Grafana リソース設定
grafana:
  resources:
    requests:
      memory: 512Mi
      cpu: 250m
    limits:
      memory: 1Gi
      cpu: 500m

# Prometheus リソース設定
prometheus:
  resources:
    requests:
      memory: 2Gi
      cpu: 1000m
    limits:
      memory: 4Gi
      cpu: 2000m

10. セキュリティのベストプラクティス

10.1 認証と認可

# SAML設定
[auth.saml]
enabled = true
certificate_path = /etc/grafana/saml.crt
private_key_path = /etc/grafana/saml.key
idp_metadata_path = /etc/grafana/idp-metadata.xml
assertion_attribute_login = "email"
assertion_attribute_email = "email"
assertion_attribute_name = "name"

10.2 通信のセキュアに設定

[server]
protocol = https
cert_file = /etc/grafana/certs/server.crt
cert_key = /etc/grafana/certs/server.key
min_tls_version = TLSv1.2

[security]
admin_user = admin
admin_password = ${GF_SECURITY_ADMIN_PASSWORD}
secret_key = ${GF_SECURITY_SECRET_KEY}
cookie_secure = true
cookie_samesite = lax

10.3 監査ログ

[audit]
enabled = true
log_path = /var/log/grafana/audit.log
console = false

[log]
level = info
format = json

11. トラブルシューティング

11.1 一般的な問題と解決策

問題: ダッシュボードが遅い

解決策:

  1. クエリを最適化(範囲を絞る、ラベルで絞り込む)
  2. パネル数を減らす
  3. リフレッシュ間隔を長くする
  4. キャッシング層を追加

問題: アラートが通知されない

解決策:

  1. アラートルール評価を確認: Administration > Alerting > Alert Rules
  2. 通知チャネル設定を確認
  3. ポリシーベースのルーティングを確認
  4. ログファイルを確認

11.2 デバッグ方法

# ログレベルを上げる
docker logs -f grafana --tail=100

# Grafana CLI でデータソース接続テスト
grafana-cli admin reset-admin-password newpassword

# メトリクスエンドポイント
curl http://localhost:3000/metrics

12. まとめ

Grafanaは包括的なオブザーバビリティプラットフォームへと進化しており、以下の特徴を持っています:

  1. 柔軟なデータソース統合: 100以上のデータソースをサポート
  2. 豊富な可視化: 50以上の組み込みパネルタイプ
  3. 統一されたアラート: 複数のデータソースに対応
  4. プラグインエコシステム: コミュニティ主導の拡張
  5. エンタープライズ機能: RBAC、SSO、監査ログ
  6. オープンソース: 活発なコミュニティと定期的なアップデート

組織の規模や要件に応じて、Grafanaはスタートアップから大規模エンタープライズまで対応できる、スケーラブルで拡張性の高いプラットフォームです。

参考資料