fluent-plugin-mongoでTTLをサポートした話 - 2020-09-04 - ククログ

ククログ

株式会社クリアコード > ククログ > fluent-plugin-mongoでTTLをサポートした話

fluent-plugin-mongoでTTLをサポートした話

はじめに

クリアコードはFluentdの開発に参加しています。

Fluentdにはプラグインというしくみがあり、たくさんのプラグインが開発されています。 今回は筆者畑ケがfluent-plugin-mongoというMongoDBにFluentdからログを流すプラグインでTTL(Time To Live)の機能をサポートした話を書きます。

MongoDBでのTTL

TTL(Time To Live)とは、あるデータが破棄されるまでの有効期限のことです。

MongoDBでは、このTTLはコレクションではなく、コレクションに対して貼るインデックスで設定します。

MongoDBのRuby Driverのマニュアルページを見ると、MongoDBのコレクションに対して貼るインデックスのオプションにexpire_afterパラメーターがいる事がわかります。

MongoDBのRuby DriverではMongoDBのコレクションに対して、以下のようにレコードのキーの指定とexpire_afterオプションの指定でTTLの指定ができる事がわかります。

client[:test_name].indexes.create_one(
  {"time": 1}, expire_after: 120
)

実際に組み込んでみる

fluent-plugin-mongoでは、時刻に関するキーは@inject_config.time_keyにて設定されます。 また、プラグインに組み込む時に設定ファイルでTTLの長さを設定できるとより便利です。

これらの要素を入れたパッチが以下のようになります。

diff --git a/lib/fluent/plugin/out_mongo.rb b/lib/fluent/plugin/out_mongo.rb
index fe9109f..4727762 100644
--- a/lib/fluent/plugin/out_mongo.rb
+++ b/lib/fluent/plugin/out_mongo.rb
@@ -49,6 +49,9 @@ module Fluent::Plugin
     desc "Remove tag prefix"
     config_param :remove_tag_prefix, :string, default: nil,
                  deprecated: "use @label instead for event routing."
+    # expire indexes
+    desc "Specify expire after seconds"
+    config_param :expire_after, :time, default: 0
 
     # SSL connection
     config_param :ssl, :bool, default: false
@@ -270,6 +273,13 @@ module Fluent::Plugin
       unless collection_exists?(name)
         log.trace "Create collection #{name} with options #{options}"
         @client[name, options].create
+        if @expire_after > 0 && @inject_config
+          log.trace "Create expiring index with key: \"#{@inject_config.time_key}\" and seconds: \"#{@expire_after}\""
+          @client[name].indexes.create_one(
+            {"#{@inject_config.time_key}": 1},
+            expire_after: @expire_after
+          )
+        end
       end
       @collections[name] = true
       @client[name]

このパッチを組み込み、設定ファイルを作成します。

<match **>
  @type mongo
  connection_string mongodb://localhost:27017/testDb
  collection test1
  expire_after 120
  # ...
</match>

とすると、testDbデータベースへtest1コレクションを作成し、このコレクションに入るレコードのTTLは120秒に設定されます。

まとめ

fluent-plugin-mongoを題材にして普段どのようにFluentdプラグインのメンテナンスをしているかを解説しました。

当社では、お客さまからの技術的なご質問・ご依頼に有償にて対応するFluentdサポートサービスを提供しています。Fluentd/Fluent Bitをエンタープライズ環境において導入/運用されるSIer様、サービス提供事業者様は、お問い合わせフォームよりお問い合わせください。