fluent-plugin-records-merger 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5c802733686b3da60f4482bac6f209bbb8852f21a93c8adacf770c24e10cc8ab
4
+ data.tar.gz: 4c6157e2bc485d422e2debe7a988169682375af12a6e48df6a906ff361cafe77
5
+ SHA512:
6
+ metadata.gz: 0d2078ded6a41d434291ae41468fa76784c09f64a57123148c96452a7f73cc6ccfcab53e7d7e0997df12aa7bce8812236a98dccf03a37a3e2992569ffa568a97
7
+ data.tar.gz: 3ce73da1351c592ee3a7f1cb6d7a3a8c2ae598aaee31337d251331f32ccd1233c21273a87bf954fb60068aaf7e6812b3a8c7e5c62704a510c20a9b6d951c7f4e
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ .vscode/
2
+ .idea
3
+ pkg
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # fluent-plugin-records-merger
2
+
3
+ [Fluentd](https://fluentd.org/) output plugin to do something.
4
+
5
+ TODO: write description for you plugin.
6
+
7
+ ## Installation
8
+
9
+ ### RubyGems
10
+
11
+ ```
12
+ $ gem install fluent-plugin-records-merger
13
+ ```
14
+
15
+ ### Bundler
16
+
17
+ Add following line to your Gemfile:
18
+
19
+ ```ruby
20
+ gem "fluent-plugin-records-merger"
21
+ ```
22
+
23
+ And then execute:
24
+
25
+ ```
26
+ $ bundle
27
+ ```
28
+
29
+ ## Configuration
30
+
31
+ You can generate configuration template:
32
+
33
+ ```
34
+ $ fluent-plugin-config-format output records_merger
35
+ ```
36
+
37
+ You can copy and paste generated documents here.
38
+
39
+ ## Copyright
40
+
41
+ * Copyright(c) 2020- WallyNegima
42
+ * License
43
+ * Apache License, Version 2.0
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler'
4
+ Bundler::GemHelper.install_tasks
5
+
6
+ require 'rake/testtask'
7
+
8
+ Rake::TestTask.new(:test) do |t|
9
+ t.libs.push('lib', 'test')
10
+ t.test_files = FileList['test/**/test_*.rb']
11
+ t.verbose = true
12
+ t.warning = true
13
+ end
14
+
15
+ task default: [:test]
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'fluent-plugin-records-merger'
8
+ spec.version = '0.1.0'
9
+ spec.authors = ['Nobuyuki Oishi', 'WallyNegima']
10
+ spec.email = ['u.str.gm@gmail.com']
11
+
12
+ spec.summary = 'this is fluentd plugin. some records merge and out.'
13
+ spec.description = 'Parallels data is merged and out.'
14
+ spec.homepage = "https://github.com/WallyNegima/fluent-plugin-records-merger"
15
+ spec.license = 'Apache-2.0'
16
+
17
+ test_files, files = `git ls-files -z`.split("\x0").partition do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.files = files
21
+ spec.executables = files.grep(%r{^bin/}) { |f| File.basename(f) }
22
+ spec.test_files = test_files
23
+ spec.require_paths = ['lib']
24
+
25
+ spec.add_development_dependency 'bundler', '~> 1.14'
26
+ spec.add_development_dependency 'rake', '~> 12.0'
27
+ spec.add_development_dependency 'test-unit', '~> 3.0'
28
+ spec.add_runtime_dependency 'fluentd', ['>= 0.14.10', '< 2']
29
+ end
@@ -0,0 +1,461 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright 2020- WallyNegima
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ require 'fluent/plugin/output'
19
+
20
+ module Fluent
21
+ module Plugin
22
+ class RecordsMergerOutput < Fluent::Plugin::Output
23
+ Fluent::Plugin.register_output('records_merger', self)
24
+ helpers :event_emitter
25
+ PATTERN_MAX_NUM = 20
26
+
27
+ config_param :tag, :string, default: 'merged',
28
+ desc: 'Specify the output tag'
29
+ config_param :main_tag, :string,
30
+ desc: 'Specify main_tag name'
31
+ config_param :sub_tag1, :string, # string: NAME REGEXP
32
+ desc: 'Specify sub_tag name'
33
+ (2..PATTERN_MAX_NUM).each do |i|
34
+ config_param ('sub_tag' + i.to_s).to_sym, :string, default: nil, # NAME REGEXP
35
+ desc: 'Specify sub_tag name'
36
+ end
37
+ config_param :auto_typecast, :bool, default: true, # false for lower version compatibility
38
+ desc: 'Automatically cast the field types.'
39
+ config_param :merge_timing, :enum, list: %i[before after simple], default: 'before',
40
+ desc: 'Choose merge timing before/after'
41
+ # ↓ これ、なんかエラー出てるっぽい。修正する。
42
+ config_param :tolerable_time_range, :integer, default: nil,
43
+ desc: 'Specify tolerable time range for merging'
44
+ # 以下、未実装
45
+ config_param :force_emit, :bool, default: false,
46
+ desc: 'Specify to emit or not when exceeded the tolerable_time_range'
47
+
48
+ def configure(conf)
49
+ super
50
+ # p 'in configure()'
51
+ # p conf
52
+ # conf: {"@type"=>"records_merger", "tag"=>"merged1", "main_tag"=>"accesslog.1.main", "sub_tag1"=>"accesslog.1.sub1", "sub_tag2"=>"accesslog.1.sub2"}, []
53
+ @tag = conf['tag'] # これも,結局 ${tag} とかを有効にする関係で使わなくなりそう.
54
+ # set the tags set by the user
55
+ @main_tag = conf['main_tag']
56
+ @sub_tags = []
57
+ (1..PATTERN_MAX_NUM).each do |i|
58
+ next unless conf["sub_tag#{i}"]
59
+
60
+ @sub_tags.push(conf["sub_tag#{i}"])
61
+ end
62
+ if conf['merge_timing']
63
+ @merge_timing = conf['merge_timing']
64
+ p '@merge_timing is ' + @merge_timing.to_s
65
+ else
66
+ p 'Specify merge_timing before/after'
67
+ end
68
+
69
+ @tolerable_time_range = conf['tolerable_time_range'].to_i
70
+
71
+ @last_records = {} # main を流した後に削除する? (未実装)
72
+
73
+ p 'size of @sub_tags is ' + @sub_tags.size.to_s
74
+ @flags4merge = Array.new(@sub_tags.size + 1, 0)
75
+ # p @flags4merge # [0, 0,..., 0]
76
+
77
+ @force_emit = conf['force_emit']
78
+
79
+ # from out-record-reformer
80
+ map = {}
81
+ # load <record></record> directive
82
+ conf.elements.select { |element| element.name == 'record' }.each do |element|
83
+ element.each_pair do |k, v|
84
+ # p k
85
+ # p v
86
+ element.key?(k) # to suppress unread configuration warning
87
+ map[k] = parse_value(v)
88
+ end
89
+ end
90
+ # p 'print map below'
91
+ # p map
92
+
93
+ placeholder_expander_params = {
94
+ log: log,
95
+ auto_typecast: @auto_typecast
96
+ }
97
+ @placeholder_expander = PlaceholderExpander.new(placeholder_expander_params)
98
+ @map = @placeholder_expander.preprocess_map(map)
99
+ @tag = @placeholder_expander.preprocess_map(@tag)
100
+ @hostname = Socket.gethostname
101
+ end
102
+
103
+ def start
104
+ super
105
+ end
106
+
107
+ def shutdown
108
+ super
109
+ end
110
+
111
+ def process(tag, es)
112
+ # p 'in process(), merge_timing is '+@merge_timing.to_s
113
+ if @merge_timing == 'before'
114
+ # p 'merge timing is before'
115
+ if @main_tag == tag
116
+ # p 'main tag has come'
117
+ store_to_lastrecords(tag, es)
118
+ @flags4merge[0] = 1
119
+ # p 'store_to_lastrecords() seems to have no problems'
120
+ check_timegap if @tolerable_time_range > 0
121
+ # pp @flags4merge
122
+ if @flags4merge.all? { |flag| flag == 1 }
123
+ # pp 'Great! Now you can omit merged event!'
124
+ emit_new_event(es)
125
+ else
126
+ (0..@flags4merge.length - 1).each do |i|
127
+ @flags4merge[i] = 0
128
+ end
129
+ end
130
+ elsif @sub_tags.include?(tag)
131
+ store_to_lastrecords(tag, es)
132
+ @flags4merge[@sub_tags.index(tag) + 1] = 1
133
+ check_timegap if @tolerable_time_range > 0
134
+ # p @flags4merge
135
+ end
136
+ elsif @merge_timing == 'after'
137
+ # p 'merge timing is after'
138
+ if @main_tag == tag
139
+ store_to_lastrecords(tag, es)
140
+ @flags4merge[0] = 1
141
+ check_timegap if @tolerable_time_range > 0
142
+ # pp @flags4merge
143
+ elsif @sub_tags.include?(tag)
144
+ if @flags4merge[0] == 1
145
+ store_to_lastrecords(tag, es)
146
+ @flags4merge[@sub_tags.index(tag) + 1] = 1
147
+ check_timegap if @tolerable_time_range > 0
148
+ # p @flags4merge
149
+ if @flags4merge.all? { |flag| flag == 1 }
150
+ # pp 'Great! Now you can omit merged event!'
151
+ emit_new_event(es)
152
+ end
153
+ else
154
+ (0..@flags4merge.length - 1).each do |i|
155
+ @flags4merge[i] = 0
156
+ end
157
+ # p @flags4merge
158
+ end
159
+ else
160
+ p 'something else has come! check it!' + tag.to_s
161
+ end
162
+ elsif @merge_timing == 'simple'
163
+ # p 'merge timing is simple'
164
+ if @main_tag == tag
165
+ # p "main_tag_came"
166
+ store_to_lastrecords(tag, es)
167
+ # p 'after store_to_lastrecords()'
168
+ @flags4merge[0] = 1
169
+ check_timegap if @tolerable_time_range > 0
170
+ # pp @flags4merge
171
+ if @flags4merge.all? { |flag| flag == 1 }
172
+ # p 'before emit_new event()'
173
+ emit_new_event(es)
174
+ # p 'after emit_new event()'
175
+
176
+ end
177
+ elsif @sub_tags.include?(tag)
178
+ store_to_lastrecords(tag, es)
179
+ @flags4merge[@sub_tags.index(tag) + 1] = 1
180
+ # p @flags4merge
181
+ check_timegap if @tolerable_time_range > 0
182
+ emit_new_event(es) if @flags4merge.all? { |flag| flag == 1 }
183
+ else
184
+ p 'something else has come! check it!' + tag.to_s
185
+ end
186
+ end
187
+ rescue StandardError => e
188
+ log.warn "record_reformer: #{e.class} #{e.message} #{e.backtrace.first}"
189
+ log.debug "record_reformer: tag:#{@tag} map:#{@map} record:#{last_records} placeholder_values:#{placeholder_values}"
190
+ end
191
+
192
+ # そのまま持ってきてしまっているので,rewriteしたほうが良さそう?
193
+
194
+ private
195
+
196
+ def store_to_lastrecords(tag, es)
197
+ es.each do |time, record|
198
+ # p 'in store_to_lastrecords()'
199
+ # print 'time: '
200
+ # p time
201
+ # print 'record: '
202
+ # p record
203
+ record.store('time', time)
204
+ @last_records.store(tag, record)
205
+ # これで,last_recordsにはsub_tagの情報がそのまま入ってる.ちなみに,storeはkey, valueの形でハッシュに値を入れるために使う.
206
+ # ここはそのままでも問題なくて,mainが来たときにまとめて調整すれば良い.
207
+ end
208
+ end
209
+
210
+ def generate_placeholders
211
+ # here, tag can be used directly only because it is the main tag
212
+ main_tag_parts = @main_tag.split('.')
213
+ # p tag_parts
214
+ main_tag_prefix = tag_prefix(main_tag_parts)
215
+ # p tag_prefix
216
+ main_tag_suffix = tag_suffix(main_tag_parts)
217
+ # p tag_suffix
218
+
219
+ placeholder_values = {
220
+ 'main' => @last_records[@main_tag],
221
+ 'main_tag' => @main_tag,
222
+ 'main_tags' => main_tag_parts,
223
+ 'main_tag_parts' => main_tag_parts,
224
+ 'main_tag_prefix' => main_tag_prefix,
225
+ 'main_tag_suffix' => main_tag_suffix,
226
+ 'hostname' => @hostname
227
+ }
228
+
229
+ # SubTagに関する内容を追加
230
+ (1..PATTERN_MAX_NUM).each do |i|
231
+ next unless @last_records.key?(@sub_tags[i - 1])
232
+
233
+ # p @sub_tags[i-1]
234
+ sub_tag_parts = @sub_tags[i - 1].split('.')
235
+ sub_tag_prefix = tag_prefix(sub_tag_parts)
236
+ sub_tag_suffix = tag_suffix(sub_tag_parts)
237
+ placeholder_values.merge!(
238
+ "sub#{i}" => @last_records[@sub_tags[i - 1]],
239
+ "sub#{i}_tag" => @sub_tags[i - 1],
240
+ "sub#{i}_tags" => sub_tag_parts,
241
+ "sub#{i}_tag_parts" => sub_tag_parts,
242
+ "sub#{i}_tag_prefix" => sub_tag_prefix,
243
+ "sub#{i}_tag_suffix" => sub_tag_suffix
244
+ )
245
+ end
246
+
247
+ placeholder_values
248
+ end
249
+
250
+ def emit_new_event(es)
251
+ # p "in emit_new_event"
252
+ es.each do |time, _record|
253
+ placeholder_values = generate_placeholders
254
+ message = @last_records
255
+ # print "message:"
256
+ # p @last_records
257
+ next if message.keys.empty?
258
+
259
+ new_tag, new_record = reform(@tag, @last_records, placeholder_values)
260
+ next unless new_tag
261
+
262
+ router.emit(new_tag, time, new_record)
263
+ # flagの初期化
264
+ (0..@flags4merge.length - 1).each do |i|
265
+ @flags4merge[i] = 0
266
+ end
267
+ # p @flags4merge
268
+ # router.emit(@tag, time, message)
269
+ end
270
+ end
271
+
272
+ def check_timegap
273
+ p @last_records.size
274
+ tag_time_hash = {}
275
+ if @last_records.size > 1
276
+ @last_records.each do |k, v|
277
+ # p k
278
+ # p v['time'].sec
279
+ # p v['time'].nsec # ナノセカンドでの比較は余裕があったら実装する
280
+ tag_time_hash.store(k, v['time'].sec)
281
+ end
282
+ # ここでtag_nameと一緒に保持しておきたい
283
+ latest = tag_time_hash.max { |a, b| a[1] <=> b[1] }
284
+ # p latest
285
+ oldest = tag_time_hash.min { |a, b| a[1] <=> b[1] }
286
+ # p oldest
287
+ # p @last_records
288
+
289
+ if latest[1] - oldest[1] > @tolerable_time_range
290
+ p oldest[0].to_s + ' is too old! so deleted'
291
+ @last_records.delete(oldest[0])
292
+ if oldest[0] == @main_tag
293
+ @flags4merge[0] = 0
294
+ else
295
+ @flags4merge[@sub_tags.index(oldest[0]) + 1] = 0
296
+ end
297
+ end
298
+ end
299
+ end
300
+
301
+ def parse_value(value_str)
302
+ if value_str.start_with?('{', '[')
303
+ JSON.parse(value_str)
304
+ else
305
+ value_str
306
+ end
307
+ rescue StandardError => e
308
+ log.warn "failed to parse #{value_str} as json. Assuming #{value_str} is a string", error_class: e.class, error: e.message
309
+ value_str # emit as string
310
+ end
311
+
312
+ def reform(tag, _record, placeholder_values)
313
+ # p 'in reform()'
314
+ # p 'tag: '
315
+ # pp tag
316
+ # p 'record'
317
+ # pp record
318
+ placeholders = @placeholder_expander.prepare_placeholders(placeholder_values)
319
+ # p 'placeholders'
320
+ # pp placeholders
321
+
322
+ new_tag = expand_placeholders(tag, placeholders) # 新しいtagを生成してる
323
+ # p 'new_tag'
324
+ # p new_tag
325
+
326
+ # 基本的に,全部ゼロから作るからここでdupする必要はない.
327
+ # new_record = @renew_record ? {} : record.dup # dupは新しいのを作ってコピーするやつ
328
+ # @keep_keys.each {|k| new_record[k] = record[k]} if @keep_keys and @renew_record
329
+
330
+ new_record = {}
331
+ # p '@map' # ここには,<record></record>で指定したものが入ってる.
332
+ # pp @map
333
+ new_record.merge!(expand_placeholders(@map, placeholders))
334
+ # p 'new_record'
335
+ # pp new_record
336
+
337
+ [new_tag, new_record]
338
+ end
339
+
340
+ def expand_placeholders(value, placeholders)
341
+ # p 'in expand_placeholders()'
342
+ # pp value
343
+ # pp placeholders
344
+ if value.is_a?(String)
345
+ new_value = @placeholder_expander.expand(value, placeholders)
346
+ elsif value.is_a?(Hash)
347
+ # ここが<record></record>を処理してる部分
348
+ new_value = {}
349
+ # ここで分割して,再帰的に実行している感じ.
350
+ value.each_pair do |k, v|
351
+ new_key = @placeholder_expander.expand(k, placeholders, true)
352
+ new_value[new_key] = expand_placeholders(v, placeholders)
353
+ end
354
+ elsif value.is_a?(Array)
355
+ # これはvalueがArrayで与えられてたら連結するために入ってる.
356
+ new_value = []
357
+ value.each_with_index do |v, i|
358
+ new_value[i] = expand_placeholders(v, placeholders)
359
+ end
360
+ else
361
+ new_value = value
362
+ end
363
+ new_value
364
+ end
365
+
366
+ def tag_prefix(tag_parts)
367
+ return [] if tag_parts.empty?
368
+
369
+ tag_prefix = [tag_parts.first]
370
+ 1.upto(tag_parts.size - 1).each do |i|
371
+ tag_prefix[i] = "#{tag_prefix[i - 1]}.#{tag_parts[i]}"
372
+ end
373
+ tag_prefix
374
+ end
375
+
376
+ def tag_suffix(tag_parts)
377
+ return [] if tag_parts.empty?
378
+
379
+ rev_tag_parts = tag_parts.reverse
380
+ rev_tag_suffix = [rev_tag_parts.first]
381
+ 1.upto(tag_parts.size - 1).each do |i|
382
+ rev_tag_suffix[i] = "#{rev_tag_parts[i]}.#{rev_tag_suffix[i - 1]}"
383
+ end
384
+ rev_tag_suffix.reverse!
385
+ end
386
+
387
+ # THIS CLASS MUST BE THREAD-SAFE
388
+ # これを入れることで,${tag}とか使えるようになる.
389
+ class PlaceholderExpander
390
+ attr_reader :placeholders, :log
391
+
392
+ def initialize(params)
393
+ @log = params[:log]
394
+ @auto_typecast = params[:auto_typecast]
395
+ end
396
+
397
+ def time_value(time)
398
+ Time.at(time).to_s
399
+ end
400
+
401
+ def preprocess_map(value, _force_stringify = false)
402
+ value
403
+ end
404
+
405
+ def prepare_placeholders(placeholder_values)
406
+ # p 'in prepare_placeholders()'
407
+ placeholders = {}
408
+
409
+ placeholder_values.each do |key, value|
410
+ # p key
411
+ if value.is_a?(Array) # tag_parts, etc
412
+ size = value.size
413
+ value.each_with_index do |v, idx|
414
+ placeholders.store("${#{key}[#{idx}]}", v)
415
+ placeholders.store("${#{key}[#{idx - size}]}", v) # support [-1]
416
+ end
417
+ elsif value.is_a?(Hash) # record, etc
418
+ value.each do |k, v|
419
+ unless placeholder_values.key?(k) # prevent overwriting the reserved keys such as tag
420
+ placeholders.store("${#{k}}", v)
421
+ end
422
+ placeholders.store(%(${#{key}["#{k}"]}), v) # record["foo"]
423
+ end
424
+ else # string, interger, float, and others?
425
+ placeholders.store("${#{key}}", value)
426
+ end
427
+ end
428
+ # pp placeholders
429
+ # p 'end of prepare_placeholders()'
430
+ placeholders
431
+ end
432
+
433
+ # Expand string with placeholders
434
+ #
435
+ # @param [String] str
436
+ # @param [Boolean] force_stringify the value must be string, used for hash key
437
+ def expand(str, placeholders, force_stringify = false)
438
+ if @auto_typecast && !force_stringify
439
+ single_placeholder_matched = str.match(/\A(\${[^}]+}|__[A-Z_]+__)\z/)
440
+ if single_placeholder_matched
441
+ log_if_unknown_placeholder(Regexp.last_match(1), placeholders)
442
+ return placeholders[single_placeholder_matched[1]]
443
+ end
444
+ end
445
+ str.gsub(/(\${[^}]+}|__[A-Z_]+__)/) do
446
+ log_if_unknown_placeholder(Regexp.last_match(1), placeholders)
447
+ placeholders[Regexp.last_match(1)]
448
+ end
449
+ end
450
+
451
+ private
452
+
453
+ def log_if_unknown_placeholder(placeholder, placeholders)
454
+ unless placeholders.include?(placeholder)
455
+ log.warn "record_reformer: unknown placeholder `#{placeholder}` found"
456
+ end
457
+ end
458
+ end
459
+ end
460
+ end
461
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ $LOAD_PATH.unshift(File.expand_path('..', __dir__))
4
+ require 'test-unit'
5
+ require 'fluent/test'
6
+ require 'fluent/test/driver/output'
7
+ require 'fluent/test/helpers'
8
+
9
+ Test::Unit::TestCase.include(Fluent::Test::Helpers)
10
+ Test::Unit::TestCase.extend(Fluent::Test::Helpers)
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'helper'
4
+ require 'fluent/plugin/out_records_merger.rb'
5
+
6
+ class RecordsMergerOutputTest < Test::Unit::TestCase
7
+ setup do
8
+ Fluent::Test.setup
9
+ end
10
+
11
+ test 'failure' do
12
+ flunk
13
+ end
14
+
15
+ private
16
+
17
+ def create_driver(conf)
18
+ Fluent::Test::Driver::Output.new(Fluent::Plugin::RecordsMergerOutput).configure(conf)
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fluent-plugin-records-merger
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nobuyuki Oishi
8
+ - WallyNegima
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2020-02-28 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '1.14'
21
+ type: :development
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '1.14'
28
+ - !ruby/object:Gem::Dependency
29
+ name: rake
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - "~>"
33
+ - !ruby/object:Gem::Version
34
+ version: '12.0'
35
+ type: :development
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '12.0'
42
+ - !ruby/object:Gem::Dependency
43
+ name: test-unit
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '3.0'
49
+ type: :development
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '3.0'
56
+ - !ruby/object:Gem::Dependency
57
+ name: fluentd
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 0.14.10
63
+ - - "<"
64
+ - !ruby/object:Gem::Version
65
+ version: '2'
66
+ type: :runtime
67
+ prerelease: false
68
+ version_requirements: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: 0.14.10
73
+ - - "<"
74
+ - !ruby/object:Gem::Version
75
+ version: '2'
76
+ description: Parallels data is merged and out.
77
+ email:
78
+ - u.str.gm@gmail.com
79
+ executables: []
80
+ extensions: []
81
+ extra_rdoc_files: []
82
+ files:
83
+ - ".gitignore"
84
+ - Gemfile
85
+ - LICENSE
86
+ - README.md
87
+ - Rakefile
88
+ - fluent-plugin-records-merger.gemspec
89
+ - lib/fluent/plugin/out_records_merger.rb
90
+ - test/helper.rb
91
+ - test/plugin/test_out_records_merger.rb
92
+ homepage: https://github.com/WallyNegima/fluent-plugin-records-merger
93
+ licenses:
94
+ - Apache-2.0
95
+ metadata: {}
96
+ post_install_message:
97
+ rdoc_options: []
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ required_rubygems_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirements: []
111
+ rubygems_version: 3.0.3
112
+ signing_key:
113
+ specification_version: 4
114
+ summary: this is fluentd plugin. some records merge and out.
115
+ test_files:
116
+ - test/helper.rb
117
+ - test/plugin/test_out_records_merger.rb