マルチターゲットエクスポーターパターンを理解し、使用する

このガイドでは、マルチターゲットエクスポーターパターンについて紹介します。そのために、以下を行います。

  • マルチターゲットエクスポーターパターンとそれが使用される理由を説明します。
  • このパターンの例として、blackboxエクスポーターを実行します。
  • blackboxエクスポーター用のカスタムクエリモジュールを設定します。
  • blackboxエクスポーターにPrometheusのウェブサイトに対して基本的なメトリクスクエリを実行させます。
  • リラベルを使ってエクスポーターをスクレイプするようにPrometheusを設定する一般的なパターンを検証します。

マルチターゲットエクスポーターパターンとは?

マルチターゲットエクスポーターパターンとは、特定の設計を指します。そこでは、

  • エクスポーターはネットワークプロトコルを介してターゲットのメトリクスを取得します。
  • エクスポーターはメトリクスが取得されるマシン上で実行する必要はありません。
  • エクスポーターは、PrometheusのGETリクエストのパラメータとして、ターゲットとクエリ設定文字列を取得します。
  • エクスポーターは、PrometheusのGETリクエストを受け取るとスクレイプを開始し、完了した時点で結果を返します。
  • エクスポーターは複数のターゲットをクエリできます。

このパターンは、blackboxSNMPエクスポーターなどの特定のエクスポーターでのみ使用されます。

その理由は、SNMPを使用するネットワーク機器のようにターゲット上でエクスポーターを実行できない場合や、ネットワーク外部の特定地点からウェブサイトへのレイテンシーや到達性など、距離に明確に関心がある場合(これはblackboxエクスポーターの一般的なユースケースです)にあります。

マルチターゲットエクスポーターの実行

マルチターゲットエクスポーターは環境に対して柔軟で、様々な方法で実行できます。通常のプログラムとして、コンテナ内、バックグラウンドサービスとして、ベアメタル上、仮想マシン上などです。ネットワーク経由でクエリされ、またクエリを行うため、適切なオープンポートが必要です。それ以外は簡素です。

それでは、ご自身で試してみましょう!

ターミナルでこれを実行して、Dockerを使ってblackboxエクスポーターコンテナを起動します。システム設定によっては、コマンドの前にsudoを付加する必要があるかもしれません。

docker run -p 9115:9115 prom/blackbox-exporter

いくつかのログ行が表示されるはずです。すべてうまくいけば、最後にはmsg="Listening on address"と報告されるでしょう。こちらで確認できます。

level=info ts=2018-10-17T15:41:35.4997596Z caller=main.go:324 msg="Listening on address" address=:9115

マルチターゲットエクスポーターの基本的なクエリ

クエリ方法には2つあります。

  1. エクスポーター自体をクエリする方法。エクスポーターは独自のメトリクスを持っており、通常/metricsで利用可能です。
  2. エクスポーターに別のターゲットをスクレイプさせる方法。通常、例えば/probeのような「記述的な」エンドポイントで利用可能です。マルチターゲットエクスポーターを使用する場合、これに最も関心があるでしょう。

別のターミナルでcurlを使って最初のクエリタイプを手動で試すか、このリンクを使用できます。

curl 'localhost:9115/metrics'

レスポンスは以下のようになるはずです。

# HELP blackbox_exporter_build_info A metric with a constant '1' value labeled by version, revision, branch, and goversion from which blackbox_exporter was built.
# TYPE blackbox_exporter_build_info gauge
blackbox_exporter_build_info{branch="HEAD",goversion="go1.10",revision="4a22506cf0cf139d9b2f9cde099f0012d9fcabde",version="0.12.0"} 1
# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0
go_gc_duration_seconds{quantile="0.25"} 0
go_gc_duration_seconds{quantile="0.5"} 0
go_gc_duration_seconds{quantile="0.75"} 0
go_gc_duration_seconds{quantile="1"} 0
go_gc_duration_seconds_sum 0
go_gc_duration_seconds_count 0
# HELP go_goroutines Number of goroutines that currently exist.
# TYPE go_goroutines gauge
go_goroutines 9

[…]

# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
# TYPE process_cpu_seconds_total counter
process_cpu_seconds_total 0.05
# HELP process_max_fds Maximum number of open file descriptors.
# TYPE process_max_fds gauge
process_max_fds 1.048576e+06
# HELP process_open_fds Number of open file descriptors.
# TYPE process_open_fds gauge
process_open_fds 7
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 7.8848e+06
# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.
# TYPE process_start_time_seconds gauge
process_start_time_seconds 1.54115492874e+09
# HELP process_virtual_memory_bytes Virtual memory size in bytes.
# TYPE process_virtual_memory_bytes gauge
process_virtual_memory_bytes 1.5609856e+07

これらはPrometheusの形式のメトリクスです。これらはエクスポーターの計測から得られ、エクスポーター自身の実行中の状態を教えてくれます。これはホワイトボックスモニタリングと呼ばれ、日常の運用において非常に役立ちます。もし興味があれば、独自のアプリケーションを計測する方法に関する私たちのガイドを試してみてください。

2番目のクエリタイプでは、HTTP GETリクエストのパラメータとしてターゲットとモジュールを提供する必要があります。ターゲットはURIまたはIPであり、モジュールはエクスポーターの設定で定義されている必要があります。blackboxエクスポーターコンテナには、意味のあるデフォルト設定が付属しています。
ターゲットprometheus.ioと、事前に定義されたモジュールhttp_2xxを使用します。これは、prometheus.ioにアクセスしたときにブラウザが行うようにGETリクエストを作成し、200 OKレスポンスを期待するようにエクスポーターに指示します。

これで、ターミナルでcurlを使って、blackboxエクスポーターにprometheus.ioをクエリするように指示できます。

curl 'localhost:9115/probe?target=prometheus.io&module=http_2xx'

これにより、多くのメトリクスが返されます。

# HELP probe_dns_lookup_time_seconds Returns the time taken for probe dns lookup in seconds
# TYPE probe_dns_lookup_time_seconds gauge
probe_dns_lookup_time_seconds 0.061087943
# HELP probe_duration_seconds Returns how long the probe took to complete in seconds
# TYPE probe_duration_seconds gauge
probe_duration_seconds 0.065580871
# HELP probe_failed_due_to_regex Indicates if probe failed due to regex
# TYPE probe_failed_due_to_regex gauge
probe_failed_due_to_regex 0
# HELP probe_http_content_length Length of http content response
# TYPE probe_http_content_length gauge
probe_http_content_length 0
# HELP probe_http_duration_seconds Duration of http request by phase, summed over all redirects
# TYPE probe_http_duration_seconds gauge
probe_http_duration_seconds{phase="connect"} 0
probe_http_duration_seconds{phase="processing"} 0
probe_http_duration_seconds{phase="resolve"} 0.061087943
probe_http_duration_seconds{phase="tls"} 0
probe_http_duration_seconds{phase="transfer"} 0
# HELP probe_http_redirects The number of redirects
# TYPE probe_http_redirects gauge
probe_http_redirects 0
# HELP probe_http_ssl Indicates if SSL was used for the final redirect
# TYPE probe_http_ssl gauge
probe_http_ssl 0
# HELP probe_http_status_code Response HTTP status code
# TYPE probe_http_status_code gauge
probe_http_status_code 0
# HELP probe_http_version Returns the version of HTTP of the probe response
# TYPE probe_http_version gauge
probe_http_version 0
# HELP probe_ip_protocol Specifies whether probe ip protocol is IP4 or IP6
# TYPE probe_ip_protocol gauge
probe_ip_protocol 6
# HELP probe_success Displays whether or not the probe was a success
# TYPE probe_success gauge
probe_success 0

ほとんどすべてのメトリクスが0の値を持っていることに注目してください。最後のメトリクスはprobe_success 0と読み取れます。これは、プローバーがprometheus.ioに正常に到達できなかったことを意味します。その理由は、値6を持つメトリクスprobe_ip_protocolに隠されています。デフォルトでは、別途指示がない限り、プローバーはIPv6を使用します。しかし、Dockerデーモンは別途指示がない限りIPv6をブロックします。そのため、Dockerコンテナ内で実行されているblackboxエクスポーターはIPv6経由で接続できません。

ここで、DockerにIPv6を許可するように指示するか、blackboxエクスポーターにIPv4を使用するように指示することができます。実際のところ、どちらも理にかなっており、よくある質問「何をすべきか?」の答えは「状況による」です。これはエクスポーターガイドであるため、エクスポーターを変更し、カスタムモジュールを設定する機会とします。

モジュールの設定

モジュールはDockerコンテナ内のconfig.ymlというファイルで事前に定義されています。これはGitHubリポジトリにあるblackbox.ymlのコピーです。

このファイルをコピーし、私たちのニーズに適応させ、コンテナに含まれている設定ファイルの代わりに、私たちの設定ファイルを使用するようにエクスポーターに指示します。

まず、curlまたはブラウザを使用してファイルをダウンロードします。

curl -o blackbox.yml https://raw.githubusercontent.com/prometheus/blackbox_exporter/master/blackbox.yml

エディタで開いてください。最初の数行は以下のようになります。

modules:
  http_2xx:
    prober: http
  http_post_2xx:
    prober: http
    http:
      method: POST

YAMLは空白インデントを使用して階層を表現するため、http_2xxhttp_post_2xxという2つのmodulesが定義されており、両方ともプローバーhttpを持ち、片方はメソッド値が明示的にPOSTに設定されていることがわかります。
ここで、モジュールhttp_2xxのプローバーhttppreferred_ip_protocolを明示的に文字列ip4に設定することで変更します。

modules:
  http_2xx:
    prober: http
    http:
      preferred_ip_protocol: "ip4"
  http_post_2xx:
    prober: http
    http:
      method: POST

利用可能なプローバーとオプションの詳細については、ドキュメントを確認してください。

次に、blackboxエクスポーターに、新しく変更したファイルを使用するように指示する必要があります。これにはフラグ--config.file="blackbox.yml"を使用できます。しかし、Dockerを使用しているため、まず--mountコマンドを使用してこのファイルをコンテナ内で利用可能にする必要があります。

注記: macOSを使用している場合、まずDockerデーモンがblackbox.ymlがあるディレクトリにアクセスできるようにする必要があります。これは、メニューバーの小さなDockerクジラをクリックし、Preferences->File Sharing->+と進むことで行えます。その後、Apply & Restartを押してください。

まず、古いコンテナのターミナルに切り替えてctrl+cを押し、停止させます。blackbox.ymlを含むディレクトリにいることを確認してください。その後、このコマンドを実行します。長いですが、説明します。

docker \
  run -p 9115:9115 \
  --mount type=bind,source="$(pwd)"/blackbox.yml,target=/blackbox.yml,readonly \
  prom/blackbox-exporter \
  --config.file="/blackbox.yml"

このコマンドで、dockerに以下のことを指示しました。

  1. コンテナ外のポート9115をコンテナ内のポート9115にマッピングしてコンテナをrunする。
  2. 現在のディレクトリ($(pwd)は現在の作業ディレクトリを表示することを意味します)からファイルblackbox.ymlをコンテナ内の/blackbox.ymlreadonlyモードでmountする。
  3. Docker Hubからイメージprom/blackbox-exporterを使用する。
  4. blackbox-exporterをフラグ--config.file付きで実行し、/blackbox.ymlを構成ファイルとして使用するように指示する。

すべてが正しければ、以下のような表示が見られるはずです。

level=info ts=2018-10-19T12:40:51.650462756Z caller=main.go:213 msg="Starting blackbox_exporter" version="(version=0.12.0, branch=HEAD, revision=4a22506cf0cf139d9b2f9cde099f0012d9fcabde)"
level=info ts=2018-10-19T12:40:51.653357722Z caller=main.go:220 msg="Loaded config file"
level=info ts=2018-10-19T12:40:51.65349635Z caller=main.go:324 msg="Listening on address" address=:9115

これで、ターミナルで新しいIPv4を使用するモジュールhttp_2xxを試すことができます。

curl 'localhost:9115/probe?target=prometheus.io&module=http_2xx'

これは、以下のようなPrometheusのメトリクスを返すはずです。

# HELP probe_dns_lookup_time_seconds Returns the time taken for probe dns lookup in seconds
# TYPE probe_dns_lookup_time_seconds gauge
probe_dns_lookup_time_seconds 0.02679421
# HELP probe_duration_seconds Returns how long the probe took to complete in seconds
# TYPE probe_duration_seconds gauge
probe_duration_seconds 0.461619124
# HELP probe_failed_due_to_regex Indicates if probe failed due to regex
# TYPE probe_failed_due_to_regex gauge
probe_failed_due_to_regex 0
# HELP probe_http_content_length Length of http content response
# TYPE probe_http_content_length gauge
probe_http_content_length -1
# HELP probe_http_duration_seconds Duration of http request by phase, summed over all redirects
# TYPE probe_http_duration_seconds gauge
probe_http_duration_seconds{phase="connect"} 0.062076202999999996
probe_http_duration_seconds{phase="processing"} 0.23481845699999998
probe_http_duration_seconds{phase="resolve"} 0.029594103
probe_http_duration_seconds{phase="tls"} 0.163420078
probe_http_duration_seconds{phase="transfer"} 0.002243199
# HELP probe_http_redirects The number of redirects
# TYPE probe_http_redirects gauge
probe_http_redirects 1
# HELP probe_http_ssl Indicates if SSL was used for the final redirect
# TYPE probe_http_ssl gauge
probe_http_ssl 1
# HELP probe_http_status_code Response HTTP status code
# TYPE probe_http_status_code gauge
probe_http_status_code 200
# HELP probe_http_uncompressed_body_length Length of uncompressed response body
# TYPE probe_http_uncompressed_body_length gauge
probe_http_uncompressed_body_length 14516
# HELP probe_http_version Returns the version of HTTP of the probe response
# TYPE probe_http_version gauge
probe_http_version 1.1
# HELP probe_ip_protocol Specifies whether probe ip protocol is IP4 or IP6
# TYPE probe_ip_protocol gauge
probe_ip_protocol 4
# HELP probe_ssl_earliest_cert_expiry Returns earliest SSL cert expiry in unixtime
# TYPE probe_ssl_earliest_cert_expiry gauge
probe_ssl_earliest_cert_expiry 1.581897599e+09
# HELP probe_success Displays whether or not the probe was a success
# TYPE probe_success gauge
probe_success 1
# HELP probe_tls_version_info Contains the TLS version used
# TYPE probe_tls_version_info gauge
probe_tls_version_info{version="TLS 1.3"} 1

プローブが成功し、フェーズごとのレイテンシー、ステータスコード、SSLステータス、Unix時間での証明書の有効期限など、多くの有用なメトリクスが得られていることがわかります。
blackboxエクスポーターは、localhost:9115で小さなウェブインターフェースも提供しており、最後の数回のプローブ、ロードされた設定、デバッグ情報を確認できます。prometheus.ioをプローブするための直接リンクも提供しています。何かがうまくいかないときに便利です。

Prometheusでマルチターゲットエクスポーターをクエリする

これまでのところ、順調です。自分を褒めてあげてください。blackboxエクスポーターは動作し、手動でリモートターゲットをクエリするように指示できます。もうすぐです。次に、Prometheusに私たちのためにクエリを実行するように指示する必要があります。

以下に、最小限のPrometheus設定を示します。これは、以前curl 'localhost:9115/metrics'を使用したのと同様に、エクスポーター自体をスクレイプするようにPrometheusに指示しています。

注記: Docker for MacまたはDocker for Windowsを使用している場合、最後の行でlocalhost:9115を使用することはできませんが、host.docker.internal:9115を使用する必要があります。これは、それらのオペレーティングシステムでDockerを実装するために使用される仮想マシンに関係しています。本番環境ではこれを使用しないでください。

Linux用prometheus.yml

global:
  scrape_interval: 5s

scrape_configs:
- job_name: blackbox # To get metrics about the exporter itself
  metrics_path: /metrics
  static_configs:
    - targets:
      - localhost:9115

macOSおよびWindows用prometheus.yml

global:
  scrape_interval: 5s

scrape_configs:
- job_name: blackbox # To get metrics about the exporter itself
  metrics_path: /metrics
  static_configs:
    - targets:
      - host.docker.internal:9115

次に、Prometheusコンテナを実行し、上記の構成ファイルをマウントするように指示します。ホスト上のネットワークがコンテナからアドレス指定できる方法のため、LinuxではmacOSやWindowsとはわずかに異なるコマンドを使用する必要があります。

LinuxでPrometheusを実行する(本番環境では--network="host"を使用しないでください)

docker \
  run --network="host"\
  --mount type=bind,source="$(pwd)"/prometheus.yml,target=/prometheus.yml,readonly \
  prom/prometheus \
  --config.file="/prometheus.yml"

macOSおよびWindowsでPrometheusを実行する

docker \
  run -p 9090:9090 \
  --mount type=bind,source="$(pwd)"/prometheus.yml,target=/prometheus.yml,readonly \
  prom/prometheus \
  --config.file="/prometheus.yml"

このコマンドは、設定ファイルを使用してblackboxエクスポーターを実行するのと同様に機能します。

すべてが機能していれば、localhost:9090/targetsにアクセスし、blackboxの下に緑色で状態がUPのエンドポイントが表示されるはずです。もし赤いDOWNが表示される場合は、上記で起動したblackboxエクスポーターがまだ実行されていることを確認してください。何も表示されない、または黄色のUNKNOWNが表示される場合は、動作が速すぎるため、ブラウザのタブを再読み込みする前に数秒待つ必要があります。

Prometheusに"localhost:9115/probe?target=prometheus.io&module=http_2xx"をクエリするように指示するには、Prometheusの設定ファイルprometheus.ymlに別のスクレイプジョブblackbox-httpを追加し、metrics_path/probeに、パラメータをparams:の下に設定します。

global:
  scrape_interval: 5s

scrape_configs:
- job_name: blackbox # To get metrics about the exporter itself
  metrics_path: /metrics
  static_configs:
    - targets:
      - localhost:9115   # For Windows and macOS replace with - host.docker.internal:9115

- job_name: blackbox-http # To get metrics about the exporter’s targets
  metrics_path: /probe
  params:
    module: [http_2xx]
    target: [prometheus.io]
  static_configs:
    - targets:
      - localhost:9115   # For Windows and macOS replace with - host.docker.internal:9115

設定ファイルを保存した後、Prometheus Dockerコンテナがあるターミナルに切り替え、ctrl+Cを押して停止し、既存のコマンドを使用して再度起動して設定をリロードします。

ターミナルは"Server is ready to receive web requests."というメッセージを返し、数秒後にはあなたのPrometheusでカラフルなグラフが見え始めるはずです。

これは機能しますが、いくつかの欠点があります。

  1. 実際のターゲットがパラメータ設定にあり、これは非常に珍しく、後で理解しにくいです。
  2. instanceラベルの値はblackboxエクスポーターのアドレスですが、これは技術的には正しいものの、私たちが関心を持っているものではありません。
  3. どのURLをプローブしたか確認できません。これは非実用的であり、複数のURLをプローブした場合に異なるメトリクスが混在してしまいます。

これを解決するため、リラベルを使用します。Prometheusの内部では多くのものが内部ラベルで設定されているため、リラベルはここで役立ちます。詳細は複雑であり、このガイドの範囲外です。したがって、必要最低限に限定します。しかし、もっと知りたい場合は、この講演を確認してください。現時点では、以下を理解していれば十分です。

  • __で始まるすべてのラベルはスクレイプ後に破棄されます。ほとんどの内部ラベルは__で始まります。
  • __param_<name>と呼ばれる内部ラベルを設定できます。これらはスクレイプリクエストのURLパラメータにキー<name>を設定します。
  • static_configsの下のtargetsによって設定される内部ラベル__address__があります。その値はスクレイプリクエストのホスト名になります。デフォルトでは、後で各メトリクスに付加され、メトリクスがどこから来たかを示すラベルinstanceの値を設定するために使用されます。

これを行うために使用する設定は以下のとおりです。一度に少し多すぎるかもしれませんが、心配しないでください、順を追って説明します。

global:
  scrape_interval: 5s

scrape_configs:
- job_name: blackbox # To get metrics about the exporter itself
  metrics_path: /metrics
  static_configs:
    - targets:
      - localhost:9115   # For Windows and macOS replace with - host.docker.internal:9115

- job_name: blackbox-http # To get metrics about the exporter’s targets
  metrics_path: /probe
  params:
    module: [http_2xx]
  static_configs:
    - targets:
      - https://prometheus.dokyumento.jp    # Target to probe with http
      - https://prometheus.dokyumento.jp   # Target to probe with https
      - http://example.com:8080 # Target to probe with http on port 8080
  relabel_configs:
    - source_labels: [__address__]
      target_label: __param_target
    - source_labels: [__param_target]
      target_label: instance
    - target_label: __address__
      replacement: localhost:9115  # The blackbox exporter’s real hostname:port. For Windows and macOS replace with - host.docker.internal:9115

では、前回の設定と比較して何が新しいのでしょうか?

paramsにはtargetが含まれなくなりました。代わりに、static configs: targetsの下に実際のターゲットを追加します。複数使用することもできます。

  params:
    module: [http_2xx]
  static_configs:
    - targets:
      - https://prometheus.dokyumento.jp    # Target to probe with http
      - https://prometheus.dokyumento.jp   # Target to probe with https
      - http://example.com:8080 # Target to probe with http on port 8080

relabel_configsには新しいリラベルルールが含まれています。

  relabel_configs:
    - source_labels: [__address__]
      target_label: __param_target
    - source_labels: [__param_target]
      target_label: instance
    - target_label: __address__
      replacement: localhost:9115  # The blackbox exporter’s real hostname:port. For Windows and macOS replace with - host.docker.internal:9115

リラベルルールを適用する前、Prometheusが作成するリクエストのURIは"https://prometheus.dokyumento.jp/probe?module=http_2xx"のようになります。リラベル後は"https://:9115/probe?target=https://prometheus.dokyumento.jp&module=http_2xx"のようになります。

次に、各ルールがどのように機能するかを見ていきましょう。

まず、ラベル__address__targetsからの値を含む)から値を取得し、それを新しいラベル__param_targetに書き込みます。これにより、Prometheusのスクレイプリクエストにパラメータtargetが追加されます。

  relabel_configs:
    - source_labels: [__address__]
      target_label: __param_target

これにより、想定されるPrometheusリクエストURIには、ターゲットパラメータが含まれるようになります: "https://prometheus.dokyumento.jp/probe?target=https://prometheus.dokyumento.jp&module=http_2xx"

次に、ラベル__param_targetから値を取得し、その値でラベルインスタンスを作成します。

  relabel_configs:
    - source_labels: [__param_target]
      target_label: instance

私たちのリクエストは変更されませんが、リクエストから返されるメトリクスには、instance="https://prometheus.dokyumento.jp"というラベルが付加されるようになります。

その後、値localhost:9115(私たちのエクスポーターのURI)をラベル__address__に書き込みます。これはPrometheusのスクレイプリクエストのホスト名とポートとして使用されます。これにより、ターゲットURIを直接クエリするのではなく、エクスポーターをクエリすることになります。

  relabel_configs:
    - target_label: __address__
      replacement: localhost:9115  # The blackbox exporter’s real hostname:port. For Windows and macOS replace with - host.docker.internal:9115

これで、リクエストは"localhost:9115/probe?target=https://prometheus.dokyumento.jp&module=http_2xx"となります。この方法により、Prometheusがblackboxエクスポーターに対してリクエストを行う間、実際のターゲットをそこに置き、それらをinstanceラベルの値として取得することができます。

多くの場合、これらを特定のサービスディスカバリと組み合わせます。詳細については、設定ドキュメントを確認してください。これらはstatic_configsの下で定義されたtargetsと同様に__address__ラベルに書き込むため、使用しても問題ありません。

以上です。Prometheus Dockerコンテナを再起動し、メトリクスを確認してください。メトリクスが実際に収集された期間を選択したことを確認してください。

概要

このガイドでは、マルチターゲットエクスポーターパターンがどのように機能するか、カスタマイズされたモジュールを使用してblackboxエクスポーターを実行する方法、およびリラベルを使用してプロバーラベル付きでメトリクスをスクレイプするようにPrometheusを設定する方法を学びました。

このドキュメントはオープンソースです。課題の提出やプルリクエストを通じて改善にご協力ください。