5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

InfluxDBV2メモ

Last updated at Posted at 2021-12-01

これはInfluxDB V2(Windows版)のメモです。

InfluxDB(時系列DB)

時系列DBはリレーショナルDBではない。リレーショナルDBに1億件ぐらいの多量データを入れると、めちゃくちゃ遅くなる。IoTでは、多量のデータを取り扱うのでリレーショナルDBは使いづらい。IoTのセンサーでは、データの更新はほぼなく、時系列で順々にデータが蓄積されて行っているので、検索とかでその特徴を生かされていると思う。

ダウンロード&インストール方法

からダウンロードして、展開して、C:\Program Files\InfluxData\influxdb\ に移動する(管理者権限が必要、フォルダを作成する必要あります。)下記のスクリプトをPowerShellで動かしても同じことができます。

wget https://dl.influxdata.com/influxdb/releases/influxdb2-2.0.8-windows-amd64.zip -UseBasicParsing -OutFile influxdb2-2.0.8-windows-amd64.zip
Expand-Archive .\influxdb2-2.0.8-windows-amd64.zip -DestinationPath 'C:\Program Files\InfluxData\'
mv 'C:\Program Files\InfluxData\influxdb2-2.0.8-windows-amd64' 'C:\Program Files\InfluxData\influxdb'

Telegrafのインストール(オプション)

https://dl.influxdata.com/telegraf/releases/telegraf-1.20.2_windows_amd64.zip からダウンロードし、展開して C:\Program Files\InfluxData\Telegraf\ に移動する。(ドキュメントのスクリプトが間違っているので、注意)

フォルダ構成

フォルダ構成はこんな感じになります。

c:\Program Files\InfluxData\influxdb\influx.exe
                      \influxd.exe
                                     (他2つ)
                            \telegraf\telegraf.exe
                                      telegraf.conf

設定ファイル

設定は3種類の方法で出来るみたいです。

  1. influxd flags
  2. Environment variables
  3. Configuration file settings
    ここでは、設定ファイルに(json)よる設定を記します。config.jsonファイルを、influxd.exe と同じフォルダに置きます。
    bolt Pathとengine Pathを変更しました。変更しなければ"ユーザフォルダ\.influxdbv2"に保存されるみたいです。
config.json
{
  "bolt-path": "~/.influxdbv2/influxd.bolt",
  "engine-path": "~/.influxdbv2/engine",
  "http-read-timeout": "2s",
  "http-write-timeout": "2s"
}

InfluxDB configuration options

必要性は個人的な意見です

必要性 key 内容 備考
assets-path Override the default InfluxDB user interface (UI) assets by serving assets from the specified directory. Typically, InfluxData internal use only.
指定したディレクトリからアセットを提供することで、既定のInfluxDB ユーザー インターフェイス (UI) アセットをオーバーライドします。‎‎一般的に、内部InfluxDB使用のみ利用します。
bolt-path Path to the BoltDB database. BoltDB is a key value store written in Go. InfluxDB uses BoltDB to store data including organization and user information, UI data, REST resources, and other key value data.
‎BoltDB databaseのパス。BoltDBはGoで書かれたkey value storeです。InfluxDBは、BoltDBを使用して、組織情報やユーザー情報、UIデータ、RESTリソース、およびその他のキー値データを含むデータを保存します。
保存場所を変更します。
Default: ~/.influxdbv2/influxd.bolt
e2e-testing Add a /debug/flush endpoint to the InfluxDB HTTP API to clear stores. InfluxData uses this endpoint in end-to-end testing.
ストアをクリアするために、エンドポイント /debug/flush をInfluxDB HTTP API に追加します。InfluxDataは、エンドツーエンドのテストでこのエンドポイントを使用します。‎
engine-path Path to persistent storage engine files where InfluxDB stores all Time-Structure Merge Tree (TSM) data on disk.
‎InfluxDB の時間構造マージ ツリー (TSM) データをディスクに格納する永続的なストレージ エンジン ファイルへのパス。‎
保存領域の場所を変更します。
Default: ~/.influxdbv2/engine
feature-flags Enable, disable, or override default values for feature flags.Feature flags are used to develop and test experimental features and are intended for internal use only.
‎feature機能フラグを有効、無効、または上書きします。‎Feature flagsは、実験機能の開発とテストに使用され、内部使用のみを目的としています。‎
flux-log-enabled Include option to show detailed logs for Flux queries, including the following log fields:
‎Flux クエリの詳細ログを表示するオプションを含めます。‎
Default: false
http-bind-address Bind address for the InfluxDB HTTP API. Customize the URL and port for the InfluxDB API and UI.
‎InfluxDB HTTP API のバインド アドレス。InfluxDB API と UI の URL とポートをカスタマイズします。
Default: :8086
http-idle-timeout Maximum duration the server should keep established connections alive while waiting for new requests. Set to 0 for no timeout.
新しい要求を待機している間、サーバーが確立された接続を存続させる最大期間。0指定でタイムアウトなしに設定します。‎
Default: 3m0s
http-read-header-timeout Maximum duration the server should try to read HTTP headers for new requests. Set to 0 for no timeout.
‎サーバーが新しい要求の HTTP ヘッダーを読み取ろうとする最大期間。0でタイムアウトなしに設定します。‎
Default: 10s
http-read-timeout Maximum duration the server should try to read the entirety of new requests. Set to 0 for no timeout.
‎サーバーが新しい要求全体を読み取ろうとする最大期間。0でタイムアウトなしに設定します。‎

Set timeouts specific to your workload
Although no http-read-timeout is set by default, we strongly recommend setting a timeout specific to your workload. HTTP timeouts protect against large amounts of open connections that could potentially hurt performance.
ワークロードに固有のタイムアウトを設定してください
デフォルトではhttp-read-timeoutが0(無し)に設定されていますが、ワークロードに固有のタイムアウトを設定‎‎することを強くお勧めします‎‎。HTTP タイムアウトは、パフォーマンスを低下する可能性がある大量のオープン接続を保護します。
Default: 0‎
http-write-timeout Maximum duration the server should spend processing and responding to write requests. Set to 0 for no timeout.
‎サーバーが書き込み要求の処理と応答に費やす最大期間。0でタイムアウトなしに設定します。‎

Set timeouts specific to your workload
Although no http-write-timeout is set by default, we strongly recommend setting a timeout specific to your workload. HTTP timeouts protect against large amounts of open connections that could potentially hurt performance.
ワークロードに固有のタイムアウトを設定してください
デフォルトでは http-write-timeoutに0(無し)が設定されていますが、ワークロードに固有のタイムアウトを設定‎‎することを強くお勧めします‎‎。HTTP タイムアウトは、パフォーマンスを低下する可能性がある大量のオープン接続を保護します。‎
Default: 0
influxql-max-select-buckets Maximum number of group by time buckets a SELECT statement can create. 0 allows an unlimited number of buckets.
‎SELECTステートメントが作成できるバケットごとのグループの最大数。 0でバケット数に制限はありません。‎
Default: 0
influxql-max-select-point Maximum number of points a SELECT statement can process. 0 allows an unlimited number of points. InfluxDB checks the point count every second (so queries exceeding the maximum aren’t immediately aborted).
‎SELECTステートメントが処理できるポイントの最大数。 0でポイント数に制限はありません。InfluxDBは、1 秒ごとにポイント数をチェックします (したがって、最大を超えたクエリはすぐに中止されません)。‎
Default: 0
influxql-max-select-series Maximum number of series a SELECT statement can return. 0 allows an unlimited number of series.
SELECTステートメントが返すことができるシリーズの最大数。0でシリーズの数に制限はありません。‎
Default: 0
log-level Log output level. InfluxDB outputs log entries with severity levels greater than or equal to the level specified.
‎ログ出力レベル。InfluxDBは、指定したレベル以上の重大度レベルを持つログエントリを出力します。‎
Options: debug, info, error
Default: info
metrics-disabled Disable the HTTP /metrics endpoint which exposes internal InfluxDB metrics.
‎内部のInfluxDB メトリックを公開する HTTP エンドポイント/metricsを無効にします。‎
Default: false
nats-max-payload-bytes Maximum number of bytes allowed in a NATS message payload.
‎NATS メッセージ ペイロードで許可される最大バイト数。‎
Default: 1048576
nats-port Port for the NATS streaming server. -1 selects a random port.
‎NATS ストリーミング サーバーのポート。 -1でランダムなポートを選択します。‎
Default: -1
no-tasks Disable the task scheduler. If problematic tasks prevent InfluxDB from starting, use this option to start InfluxDB without scheduling or executing tasks.
‎タスク スケジューラを無効にします。問題のあるタスクで、IninDB の起動が妨げとなる場合は、このオプションを使用して、タスクのスケジュール設定や実行を行わずに、その中から、その他のオプションを使用します。‎
Default: false
pprof-disabled Disable the /debug/pprof HTTP endpoint. This endpoint provides runtime profiling data and can be helpful when debugging.
‎HTTP エンドポイント‎/debug/pprofを無効にします。このエンドポイントは、ランタイム プロファイル データを提供し、デバッグ時に役立ちます。
Default: false
query-concurrency Number of queries allowed to execute concurrently.
‎同時に実行できるクエリの数。
Default: 10
query-initial-memory-bytes Initial bytes of memory allocated for a query.
‎クエリに割り当てられたメモリの初期バイト数。‎
Default: equal to query-memory-bytes
query-max-memory-bytes Maximum total bytes of memory allowed for queries.
‎クエリで許容されるメモリの最大合計バイト数。‎
Default: equal to query-concurrency × query-memory-bytes
query-memory-bytes Maximum bytes of memory allowed for a single query.
‎1 回のクエリで使用できるメモリの最大バイト数。‎
Default: unlimited
Must be greater than or equal to query-initial-memory-bytes.
‎クエリの初期メモリ バイト以上である‎‎必要があります。‎
query-queue-size Maximum number of queries allowed in execution queue. When queue limit is reached, new queries are rejected.
‎実行キューで許可されるクエリの最大数。キューの制限に達すると、新しいクエリは拒否されます。‎
Default: 10
reporting-disabled Disables sending telemetry data to InfluxData. The InfluxData telemetry page provides information about what data is collected and how InfluxData uses it.
‎テレメトリ データをInfluxDataに送信することを無効にします。InfluxData テレメトリ‎‎ページには、収集されるデータと、そのデータの使用方法に関する情報が表示されます。‎
Default: false
secret-store Specifies the data store for secrets such as passwords and tokens. Store secrets in either the InfluxDB internal BoltDB or in Vault.
パスワードやトークンなどのシークレットのデータ ストアを指定します。機密情報は、InfluxDB 内部‎‎のBoltDB‎‎または‎‎Vault に格納します‎‎。‎
Options: bolt, vault
Default: bolt
session-length Specifies the Time to Live (TTL) in minutes for newly created user sessions.
‎新しく作成されたユーザー セッションの稼働時間 (TTL) を‎‎分単位で‎‎指定します。‎
Default: 60
session-renew-disabled Disables automatically extending a user’s session TTL on each request. By default, every request sets the session’s expiration time to five minutes from now. When disabled, sessions expire after the specified session length and the user is redirected to the login page, even if recently active.
‎要求ごとにユーザーのセッション TTL を自動的に拡張することを無効にします。デフォルトでは、すべての要求によってセッションの有効期限が現在から 5 分後に設定されます。無効にすると、セッションは指定された‎‎セッションの長さ‎‎後に期限切れになり、最近アクティブになった場合でも、ユーザーはログイン ページにリダイレクトされます。‎
Default: false
sqlite-path Path to the SQLite database file. The SQLite database is used to store metadata for notebooks and annotations.
‎SQLite データベース ファイルへのパス。SQLite データベースは、ノートブックと注釈のメタデータを格納するために使用されます。‎
Default: influxd.sqlite in the same directory as the bolt-path.
storage-cache-max-memory-size Maximum size (in bytes) a shard’s cache can reach before it starts rejecting writes.
‎書き込みの拒否を開始する前に、共有キャッシュが到達できる最大サイズ (バイト単位)。‎
Default: 1073741824
storage-cache-snapshot-memory-size Size (in bytes) at which the storage engine will snapshot the cache and write it to a TSM file to make more memory available.
‎ストレージエンジンがキャッシュのスナップショットを作成し、TSMファイルに書き込んで、より多くのメモリを使用可能にするサイズ(バイト単位)。‎
Default: 26214400
storage-cache-snapshot-write-cold-duration Duration at which the storage engine will snapshot the cache and write it to a new TSM file if the shard hasn’t received writes or deletes.
‎シャードが書き込みまたは削除を受信していない場合、ストレージエンジンがキャッシュのスナップショットを作成し、それを新しいTSMファイルに書き込む期間。‎
Default: 10m0s
storage-compact-full-write-cold-duration Duration at which the storage engine will compact all TSM files in a shard if it hasn’t received writes or deletes.
‎書き込みまたは削除を受信していない場合、ストレージ エンジンがシャード内のすべての TSM ファイルを圧縮する期間。‎
Default: 4h0m0s
storage-compact-throughput-burst Rate limit (in bytes per second) that TSM compactions can write to disk.
‎TSM 圧縮がディスクに書き込むことができるレート制限 (1 秒あたりのバイト数)。‎
Default: 50331648
storage-max-concurrent-compactions Maximum number of full and level compactions that can run concurrently. A value of 0 results in 50% of runtime.GOMAXPROCS(0) used at runtime. Any number greater than zero limits compactions to that value. This setting does not apply to cache snapshotting.
‎同時に実行できるフルおよびレベルの圧縮の最大数。実行時に使用される値の 50% の結果。GOMAXPROCS(0)はruntimeで使用されます。0 より大きい数値は、その値に対する圧縮を制限します。‎‎この設定は、キャッシュ スナップショットには適用されません。
Default: 0
storage-max-index-log-file-size Size (in bytes) at which an index write-ahead log (WAL) file will compact into an index file. Lower sizes will cause log files to be compacted more quickly and result in lower heap usage at the expense of write throughput.
‎インデックスwrite-ahead log (WAL) ファイルがインデックス ファイルに圧縮されるサイズ (バイト単位)。サイズを小さくすると、ログ ファイルの圧縮が迅速になり、書き込みスループットが低下してヒープ使用量が減少します。‎
Default: 1048576
storage-no-validate-field-size Skip field size validation on incoming write requests.
‎write requestsに対するフィールド サイズ検証をスキップします。‎
Default: false
storage-retention-check-interval Interval of retention policy enforcement checks.
保持ポリシーの適用チェックの間隔。‎
Default: 30m0s
storage-series-file-max-concurrent-snapshot-compactions Maximum number of snapshot compactions that can run concurrently across all series partitions in a database.
‎データベース内のすべてのシリーズ パーティションで同時に実行できるスナップショット圧縮の最大数。‎
Default: 0
storage-series-id-set-cache-size Size of the internal cache used in the TSI index to store previously calculated series results. Cached results are returned quickly rather than needing to be recalculated when a subsequent query with the same tag key/value predicate is executed. Setting this value to 0 will disable the cache and may decrease query performance.
‎以前に計算された一連の結果を格納するために TSI インデックスで使用される内部キャッシュのサイズ。同じタグキー/値述語を持つ後続のクエリを実行したときに再計算する必要がなさ、キャッシュされた結果がすぐに返されます。この値を0に設定すると、キャッシュが無効になり、クエリのパフォーマンスが低下する可能性があります。‎
Default: 100
This value should only be increased if the set of regularly used tag key/value predicates across all measurements for a database is larger than 100. An increase in cache size may lead to an increase in heap usage.
‎この値は、データベースのすべての測定値で定期的に使用されるタグキー/値述語のセットが 100 を超える場合にのみ増加する必要があります。キャッシュ サイズが大きくなると、ヒープ使用量が増加する可能性があります。‎
storage-shard-precreator-advance-period The time before a shard group’s end-time that the successor shard group is created.
‎後続のシャード グループが作成されるシャード グループの終了時刻の前の時間。‎
Default: 30m0s
storage-shard-precreator-check-interval Interval of pre-create new shards check.
‎新しいシャードの事前作成チェックの間隔。‎
Default: 10m0s
storage-tsm-use-madv-willneed Inform the kernel that InfluxDB intends to page in mmap’d sections of TSM files.
‎IninDB が TSM ファイルの mmap'd セクションにページを作成しようとしていることをカーネルに通知します。‎
Default: false
storage-validate-keys Validate incoming writes to ensure keys have only valid unicode characters.
‎着信書き込みを検証して、有効な Unicode 文字のみをキーに設定します。‎
Default: false
storage-wal-fsync-delay Duration a write will wait before fsyncing. A duration greater than 0 batches multiple fsync calls. This is useful for slower disks or when WAL write contention is present.
‎書き込みの期間は、fsync の前に待機します。複数の fsync 呼び出しをバッチ処理する期間よりも長い時間。これは、低速ディスクや WAL 書き込み競合が存在する場合に役立ちます。‎
Default: 0s
storage-wal-max-concurrent-writes Maximum number writes to the WAL directory to attempt at the same time.
‎WAL ディレクトリへの書き込みの最大数を同時に試行します。‎
Default: 0 (number of processing units available × 2)
storage-wal-max-write-delay Maximum amount of time a write request to the WAL directory will wait when the the maximum number of concurrent active writes to the WAL directory has been met. Set to 0 to disable the timeout.
‎WAL ディレクトリへの書き込み要求が‎‎、WAL ディレクトリへの同時アクティブな書き込みの最大数‎‎に達した場合に待機する最大時間。タイムアウトを無効にする場合は、0に設定します。‎
Default: 10m
storage-write-timeout Maximum amount of time the storage engine will process a write request before timing out.
‎ストレージ エンジンがタイムアウト前に書き込み要求を処理する最大時間。‎
Default: 10s
store Specifies the data store for REST resources.
‎REST リソースのデータ ストアを指定します。‎

For backwards compatibility, this flag also acceptss bolt as a value. When using disk, REST resources are stored on disk using the bolt-path and sqlite-path.memory is meant for transient environments, such as testing environments, where data persistence does not matter. InfluxData does not recommend using memory in production.
‎下位互換性を保つために、このフラグは‎bolt値として受け入れます。diskはREST リソースは‎‎ボルトパス‎‎と‎‎sqlite パス‎‎を使用してディスクに格納されます。‎memory‎はデータの永続化が重要でないテスト環境などの一時的な環境を対象としています。InfluxDataは、運用環境での‎memoryの使用をお勧めしません。
Options: disk, memory
Default: disk
testing-always-allow-setup Ensures the /api/v2/setup endpoint always returns true to allow onboarding. This configuration option is primary used in continuous integration tests.
‎/api/v2/setup エンドポイントが常にtrueで戻ってオンボーディングを許可するようにします。この構成オプションは、継続的インテグレーション テストで使用されるプライマリです。‎
Default: false
tls-cert Path to TLS certificate file. Requires the tls-key to be set.
‎TLS 証明書ファイルへのパス。tls‎‎キーを‎‎設定する必要があります。‎
tls-key Path to TLS key file. Requires the tls-cert to be set.
‎TLS キー ファイルへのパス。tls‎‎証明書‎‎を設定する必要があります。
tls-min-version Minimum accepted TLS version.
‎最小許容 TLS バージョン。‎
Default: 1.2
tls-strict-ciphers Restrict accepted TLS ciphers to(‎受け入れられた TLS 暗号を次の範囲に制限する):
ECDHE_RSA_WITH_AES_256_GCM_SHA384
ECDHE_RSA_WITH_AES_256_CBC_SHA
RSA_WITH_AES_256_GCM_SHA384
RSA_WITH_AES_256_CBC_SHA
Default: false
tracing-type Enable tracing in InfluxDB and specifies the tracing type. Tracing is disabled by default.
‎[ InfluxDBを有効にする] を選択し、トレースの種類を指定します。トレースは既定で無効になっています。‎
Options: log, jaeger
ui-disabled Disable the InfluxDB user interface (UI). The UI is enabled by default.
‎InfluxDB ユーザー インターフェイス (UI) を無効にします。UI は既定で有効になっています。‎
Default: false
vault-addr Specifies the address of the Vault server expressed as a URL and port. For example: https://127.0.0.1:8200/.
‎URL とポートとして表現される Vault サーバのアドレスを指定します。例えばhttps://127.0.0.1:8200/
vault-cacert Specifies the path to a PEM-encoded CA certificate file on the local disk. This file is used to verify the Vault server’s SSL certificate. This setting takes precedence over the --vault-capath setting.
‎ローカル ディスク上の PEM エンコード CA 証明書ファイルへのパスを指定します。このファイルは、Vault サーバの SSL 証明書を検証するために使用されます。‎‎この設定は‎‎--vault-capath‎‎設定よりも優先されます。‎
vault-capath Specifies the path to a directory of PEM-encoded CA certificate files on the local disk. These certificates are used to verify the Vault server’s SSL certificate.
‎ローカル ディスク上の PEM エンコード CA 証明書ファイルのディレクトリへのパスを指定します。これらの証明書は、Vault サーバの SSL 証明書を検証するために使用されます。‎
vault-client-cert Specifies the path to a PEM-encoded client certificate on the local disk. This file is used for TLS communication with the Vault server.
‎ローカル ディスク上の PEM エンコードクライアント証明書へのパスを指定します。このファイルは、Vault サーバとの TLS 通信に使用されます。‎
vault-client-key Specifies the path to an unencrypted, PEM-encoded private key on disk which corresponds to the matching client certificate.
‎一致するクライアント証明書に対応する、暗号化されていない PEM エンコードされたディスク上の秘密キーへのパスを指定します。‎
vault-max-retries Specifies the maximum number of retries when encountering a 5xx error code. The default is 2 (for three attempts in total). Set this to 0 or less to disable retrying.
‎5xx エラー・コードを検出した場合の最大再試行回数を指定します。デフォルトは 2 です (合計で 3 回の試行)。再試行を無効にするには、0 以下に設定します。‎
Default: 2
vault-client-timeout Specifies the Vault client timeout.
‎Vault クライアント タイムアウトを指定します。‎
Default: 60s
vault-skip-verify Skip certificate verification when communicating with Vault. Setting this variable voids Vault’s security model and is not recommended.
‎Vault と通信する際に証明書の検証をスキップします。‎‎この変数を設定すると‎‎、Vault のセキュリティ モデル‎‎が無効になり、‎‎推奨されません‎‎。‎
Default: false
vault-tls-server-name Specifies the name to use as the Server Name Indication (SNI) host when connecting via TLS.
‎TLS 経由で接続するときに、サーバー名表示 (SNI) ホストとして使用する名前を指定します。‎
vault-token Specifies the Vault token use when authenticating with Vault.
‎Vault で認証を行う際の Vault トークンの使用を指定します。‎

Influxdbの実行

実行はPowerShell(管理者権限)で

cd -Path 'C:\Program Files\InfluxData\influxdb'
./influxd

設定

設定はGUIとCLIがあるらしい。ここではGUIで
ブラウザで localhost:8086を開いて、[Get Startted]をクリック
image.png

userとpassword、organization name、bucket name(DB名みたいなもの?)を登録
image.png
[Quick Start]をクリック
image.png
なんか動きました。
image.png
データは c:\user\ユーザーフォルダ\.infulxdbv2 に保存されていくみたいです。

Bucketの設定

[Data]の[Buckets]タブの初期設定で作ったbucketの枠内の[Settings]をクリック
image.png
1週間で消える設定にしてみました。こういうのが出来て楽ですよね。[Save Changes]をクリック
image.png

Windowsでの常時起動

ここではタスクスケジューラで設定をしてみます。(他の方法もあるみたいです)

タスク スケジューラの設定

タスク スケジューラで検索して起動します。コンピュータの管理 のタスクスケジューラでも設定できます。
image.png
タスク スケジューラ ライブラリに移って タスクの生成を押します。
image.png
全般タブは、名前とユーザがログオンしているかどうか関わらず実行するを選択。
image.png
トリガータブは、新規でスタートアップ時にのトリガ―を作る。
image.png
操作は新規でプログラム/スクリプトにInfluxd.exeを開始にInfluxd.exeがあるフォルダを指定
image.png
条件タブは適当に
設定タブは、念のためタスクを停止するまでの時間のチェックを外す。
image.png
[OK]ボタンを押すとパスワードが要求されるので入力して終わりです。再起動すると少ししてInfluxd.exeが動きます。

TeregrafでMQTTを受信(オプション)

MQTTを受信できるように設定します。

設定

[Data]の[Sources]タブでMQTTを選択。多くの設定例が羅列しているので検索を使うと便利ですね。
image.png
ClipBoardにテンプレートをコピーし、teregraf.confをコピーしたものに書き換えます。自分はVisualSrudioCodeで編集しましたが好きなエディタを使えばよいと思います。
topicsを部分を書き換えて"M5"のTopicが受信できるようにします。

topics = [
    "M5",
  ]

[Data]の[teregraf]の[InfluxDB Output Plugin] をクリック
image.png
クリップボードにコピーし さっきの後ろに貼り付けます。
image.png
書込みにはTokenが必要なので作成します。
[Data]の[Tokens]タブの[+ Generate Taken]をクリック Read/Writeを選択します。
image.png
書込みだけでOKなのでWrite Tokenを作ります。Write側の書き込むBucketsを選択し [Save]をクリックします。
image.png

生成されたTokenをコピーし、Tokenの部分を書き換えます。日付を参考に今作ったTokenの方を選びます。この画面で名前が変更できるのでわかりやすくしておくのも手ですね。名前の部分をクリックするとTokenが見れるのでクリップボードにコピーしましょう。
image.png
image.png

Tokenを書き換えて、こんな感じのteregraf.confになります。(tokenの部分は一部書き換えています)

[[inputs.mqtt_consumer]]
  ## Broker URLs for the MQTT server or cluster.  To connect to multiple
  ## clusters or standalone servers, use a seperate plugin instance.
  ##   example: servers = ["tcp://localhost:1883"]
  ##            servers = ["ssl://localhost:1883"]
  ##            servers = ["ws://localhost:1883"]
  servers = ["tcp://127.0.0.1:1883"]

  ## Topics that will be subscribed to.
  topics = [
    "M5",
  ]

  ## The message topic will be stored in a tag specified by this value.  If set
  ## to the empty string no topic tag will be created.
  # topic_tag = "topic"

  ## QoS policy for messages
  ##   0 = at most once
  ##   1 = at least once
  ##   2 = exactly once
  ##
  ## When using a QoS of 1 or 2, you should enable persistent_session to allow
  ## resuming unacknowledged messages.
  # qos = 0

  ## Connection timeout for initial connection in seconds
  # connection_timeout = "30s"

  ## Maximum messages to read from the broker that have not been written by an
  ## output.  For best throughput set based on the number of metrics within
  ## each message and the size of the output's metric_batch_size.
  ##
  ## For example, if each message from the queue contains 10 metrics and the
  ## output metric_batch_size is 1000, setting this to 100 will ensure that a
  ## full batch is collected and the write is triggered immediately without
  ## waiting until the next flush_interval.
  # max_undelivered_messages = 1000

  ## Persistent session disables clearing of the client session on connection.
  ## In order for this option to work you must also set client_id to identify
  ## the client.  To receive messages that arrived while the client is offline,
  ## also set the qos option to 1 or 2 and don't forget to also set the QoS when
  ## publishing.
  # persistent_session = false

  ## If unset, a random client ID will be generated.
  # client_id = ""

  ## Username and password to connect MQTT server.
  # username = "telegraf"
  # password = "metricsmetricsmetricsmetrics"

  ## Optional TLS Config
  # tls_ca = "/etc/telegraf/ca.pem"
  # tls_cert = "/etc/telegraf/cert.pem"
  # tls_key = "/etc/telegraf/key.pem"
  ## Use TLS but skip chain & host verification
  # insecure_skip_verify = false

  ## Data format to consume.
  ## Each data format has its own unique set of configuration options, read
  ## more about them here:
  ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
  data_format = "influx"
   [[outputs.influxdb_v2]]
  ## The URLs of the InfluxDB cluster nodes.
  ##
  ## Multiple URLs can be specified for a single cluster, only ONE of the
  ## urls will be written to each interval.
  ## urls exp: http://127.0.0.1:9999
  urls = ["http://localhost:8086"]

  ## Token for authentication.
  token = "V0-Jx4VPCtZ-IIPdqqz0r6ICy-nRxGN3qA4ZWRotVWXtPD8eBTRy1DOxVcXHBVA71DeiMLOhrFu1qT-ZOh******"

  ## Organization is the name of the organization you wish to write to; must exist.
  organization = "home"

  ## Destination bucket to write into.
  bucket = "Data1"

install&実行

teregrafのフォルダに移って、以下を実行し、動かします。

./telegraf --config telegraf.conf

確認

[Data Explorer]でデータを確認しましょう。
下の欄のデータを選択していき最後に[Submit]をクリックするとグラフが表示されます。

image.png

参考 InfluxDbのデータの書き込み

Line protocol

https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/
こんな感じで書くらしいです。
measurementName fieldKey="field string value" 1556813561098000000

// Syntax

<measurement>[,<tag_key>=<tag_value>[,<tag_key>=<tag_value>]] <field_key>=<field_value>[,<field_key>=<field_value>] [<timestamp>]

// Example
myMeasurement,tag1=value1,tag2=value2 fieldKey="fieldValue" 1556813561098000000

tag(オプション)はIndexになるもので、Fieldはデータらしいです。Tagがあればそれでグループ化できるみたいです。
改行は newline character \n で表します。 Line protocol では、スペースに気を付けましょう。
Line protocolでは、tagとFieldでは改行**\n**は使えません。

measurementName,tagKey=tagValue fieldKey="fieldValue" 1465839830100400200
--------------- --------------- --------------------- -------------------
       |               |                  |                    |
  Measurement       Tag set           Field set            Timestamp

Measurement

(必須) measurement名. InfluxDBは一つのポイントごとに1つの measurement名を付けます。 Measurement名は大文字小文字を区別されます。measurement名は_で始めることはできません。
Data type: String

Tag set

(オプション) tag keyとtag valueの組み合わせになります。 Key-value との関係は**=** で表します。 複数のtag key-value の組み合わせは","で区切ります Tag keys と tag values は大文字小文字が区別されます。Tag keys は_で始めることはできません。

Key data type: String
Value data type: String

Field set

(必須) field keyとfield valueの組み合わせになります。最低1つは必要です。Field keys と string values は大文字小文字が区別されます。 Field keys は_で始めることはできません。

Key data type: String
Value data type: Float | Integer | UInteger | String | Boolean

**"**で始まるのは string field 値です。

measurementName fieldKey="field string value" 1556813561098000000

Timestamp

Optional – The unix timestamp for the data point. InfluxDB accepts one timestamp per point. もしtimestampがない場合は、InfluxDB はHostマシンのsystem time (UTC)を使います。
Data type: Unix timestamp

タイムスタンプに関する注意
数値が観測された時刻 (InfluxDB によって受信されない) がデータ ポイントに含まれるようにするには、タイムスタンプを含めます。‎
‎タイムスタンプがナノ秒でない場合は、‎‎データをDBに書き込むときのタイムスタンプの精度を‎‎指定します。‎

空白(スペース)

空白はline protocolでは空白を使って値を分けます。 1つ目の空白はmeasurement名・the tag set をfield setと区別します。2つ目の空白はfield setとtimestampを区別します。

measurementName,tagKey=tagValue fieldKey="fieldValue" 1465839830100400200
                               |                     |
                           1st space             2nd space

データの形式

Type 方法
Float IEEE-754 64-bit floating-point numbers.
Default numerical type.
InfluxDB supports scientific notation in float field values.
myMeasurement fieldKey=1.0
myMeasurement fieldKey=1
myMeasurement fieldKey=-1.234456e+78
Integer 語尾にiをつける
-9223372036854775808i~
9223372036854775807i
myMeasurement fieldKey=1i
myMeasurement fieldKey=12485903i
myMeasurement fieldKey=-12485903i
UInteger 語尾にuをつける
0u~18446744073709551615u
myMeasurement fieldKey=1u
myMeasurement fieldKey=12485903u
String ダブルコーテーションでくくる
長さは最大64kb
myMeasurement fieldKey="this is a string"
Boolean 以下の表現が使える
True t, T, true, True, TRUE
False f, F, false, False, FALSE
myMeasurement fieldKey=true
myMeasurement fieldKey=false
myMeasurement fieldKey=t
myMeasurement fieldKey=f
myMeasurement fieldKey=TRUE
myMeasurement fieldKey=FALSE
Unix timestamp Unix timestamp in a specified precision. Default precision is nanoseconds (ns).
-9223372036854775806~
9223372036854775806
myMeasurementName fieldKey="fieldValue" 1556813561098000000

引用符

Line protocolは**'"**が使えます。

Element Double quotes Single quotes
Measurement Limited * Limited *
Tag key Limited * Limited *
Tag value Limited * Limited *
Field key Limited * Limited *
Field value 文字列のみ なし
Timestamp なし なし
  • ‎Line protocolは、計測名、タグキー、タグ値、およびフィールドキーで二重引用符と単一引用符を使用できますが、名前、キー、または値の一部として解釈されます。‎

特殊文字

Line protocolは特殊文字をstring elementsで使えます。**backslash ()**を使ってescapする必要があります。

Element Escape characters
Measurement Comma, Space
Tag key Comma, Equals Sign, Space
Tag value Comma, Equals Sign, Space
Field key Comma, Equals Sign, Space
Field value Double quote, Backslash

ほかの特殊文字はescape不要です。

Examples of special characters in line protocol

# Measurement name with spaces
my\ Measurement fieldKey="string value"

# Double quotes in a string field value
myMeasurement fieldKey="\"string\" within a string"

# Tag keys and values with spaces
myMeasurement,tag\ Key1=tag\ Value1,tag\ Key2=tag\ Value2 fieldKey=100

# Emojis
myMeasurement,tagKey=🍭 fieldKey="Launch 🚀" 1556813561098000000

backslashe\ のエスケープ
Line protocolは、バックスラッシュとエスケープ文字としてのバックスラッシュの両方をサポートします。連続する 2 つのバックスラッシュを使用すると、最初のバックスラッシュはエスケープ文字として解釈されます。例えば:

Backslashes 解釈
\ \
\ \
\\ \
\\ \
\\\ \\
\\\ \\

注釈行

Line protocolは行頭に#を使うとコメント行になります。

# This is a comment
myMeasurement fieldKey="string value" 1556813561098000000

名前付けの制限

Measurement names, tag keys, and field keys は最初にアンダーライン_は使えません。_ namespace は予約されています。

Duplicate points

‎ポイントは、計測名、タグセット、タイムスタンプによって一意に識別されます。同じ測定、タグセット、タイムスタンプを使用して行プロトコルを送信する場合、フィールドセットは古いフィールドセットと新しいフィールドセットの和集合となり、競合が新しいフィールドセットを優先します。‎

参考にしたところ

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?