fluent-plugin-calyptia-monitoring 0.1.0.rc

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: efc4e7d0b11c4581475feb8c18c52a7e4366d8ada239ae16db853dc36eb886fd
4
+ data.tar.gz: 5db76c13993681bab21c389ce6d5edf2c78e03b64540a409d4bc2791e26e6b29
5
+ SHA512:
6
+ metadata.gz: e74b8aecb6b7b83dafcb999daabe7ebd64d607fb9352ca3dfa14161d612c2bf12a9c3fd6125979203d928f4b1d46676084f49c6299ce68e21f4f92fa2a73647f
7
+ data.tar.gz: 60137eaa0870327d7eb1c2485b04c0583558b375af3243ce3c11c94b6c70255d31cad86009d23e547f50dd578fd93b313a930575377c14b1cfdfcfeb01817c3f
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ *.swp
2
+ *.o
3
+ *.hi
4
+ .ruby-version
5
+ *~
6
+ .#.*
7
+ TAGS
8
+ .bundle/
9
+ vendor/bundle/
10
+ Gemfile.lock
11
+ Gemfile.local
12
+ *.conf
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")
6
+ if File.exist?(local_gemfile)
7
+ puts "Loading Gemfile.local ..." if $DEBUG # `ruby -d` or `bundle -v`
8
+ instance_eval File.read(local_gemfile)
9
+ end
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-calyptia-monitoring
2
+
3
+ [Fluentd](https://fluentd.org/) input 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-calyptia-monitoring
13
+ ```
14
+
15
+ ### Bundler
16
+
17
+ Add following line to your Gemfile:
18
+
19
+ ```ruby
20
+ gem "fluent-plugin-calyptia-monitoring"
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 input calyptia-monitoring
35
+ ```
36
+
37
+ You can copy and paste generated documents here.
38
+
39
+ ## Copyright
40
+
41
+ * Copyright(c) 2021- Hiroshi Hatake
42
+ * License
43
+ * Apache License, Version 2.0
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require "bundler"
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs.push("lib", "test")
8
+ t.test_files = FileList["test/**/test_*.rb"]
9
+ t.verbose = true
10
+ t.warning = true
11
+ end
12
+
13
+ task default: [:test]
@@ -0,0 +1,28 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+
4
+ Gem::Specification.new do |spec|
5
+ spec.name = "fluent-plugin-calyptia-monitoring"
6
+ spec.version = "0.1.0.rc"
7
+ spec.authors = ["Hiroshi Hatake"]
8
+ spec.email = ["hatake@calyptia.com"]
9
+
10
+ spec.summary = %q{Monitoring Fluentd via Calyptia Cloud}
11
+ spec.description = spec.summary
12
+ spec.homepage = "https://github.com/calyptia/fluent-plugin-calyptia-monitoring"
13
+ spec.license = "Apache-2.0"
14
+
15
+ test_files, files = `git ls-files -z`.split("\x0").partition do |f|
16
+ f.match(%r{^(test|spec|features)/})
17
+ end
18
+ spec.files = files
19
+ spec.executables = files.grep(%r{^bin/}) { |f| File.basename(f) }
20
+ spec.test_files = test_files
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency "bundler", "~> 2.2.15"
24
+ spec.add_development_dependency "rake", "~> 13.0"
25
+ spec.add_development_dependency "test-unit", "~> 3.3"
26
+ spec.add_runtime_dependency "fluentd", [">= 1.13.0", "< 2"]
27
+ spec.add_runtime_dependency "fluent-plugin-metrics-cmetrics", ">= 0.1.0.rc2"
28
+ end
@@ -0,0 +1,129 @@
1
+ #
2
+ # fluent-plugin-calyptia-monitoring
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'net/http'
17
+ require 'securerandom'
18
+ require 'socket'
19
+ require 'yajl'
20
+ require 'fluent/system_config'
21
+ require_relative 'calyptia_monitoring_machine_id'
22
+
23
+ module Fluent::Plugin
24
+ class CalyptiaAPI
25
+ class Requester
26
+ include Fluent::SystemConfig::Mixin
27
+
28
+ def initialize(endpoint, api_key, log, worker_id)
29
+ @endpoint = endpoint
30
+ @api_key = api_key
31
+ @log = log
32
+ @worker_id = worker_id
33
+ @machine_id = Fluent::Plugin::CalyptiaMonitoringMachineId.new(worker_id, log)
34
+ end
35
+
36
+ def proxies
37
+ ENV['HTTPS_PROXY'] || ENV['HTTP_PROXY'] || ENV['http_proxy'] || ENV['https_proxy']
38
+ end
39
+
40
+ def agent_metadata(current_config)
41
+ metadata = {
42
+ "name" => Socket.gethostname,
43
+ "type" => "fluentd",
44
+ "rawConfig" => current_config,
45
+ "version" => Fluent::VERSION,
46
+ "edition" => "community".freeze,
47
+ }
48
+ if system_config.workers.to_i > 1
49
+ metadata["flags"] = ["number_of_workers=#{system_config.workers}", "worker_id=#{@worker_id}"]
50
+ end
51
+ metadata
52
+ end
53
+
54
+ # POST /api/v1/agents
55
+ # Authorization: X-Project-Token
56
+ def create_agent(current_config)
57
+ url = URI("#{@endpoint}/api/v1/agents")
58
+
59
+ https = if proxy = proxies
60
+ proxy_uri = URI.parse(proxy)
61
+ Net::NTTP.new(uri.host, uri.port,
62
+ proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
63
+ else
64
+ Net::HTTP.new(url.host, url.port)
65
+ end
66
+ https.use_ssl = (url.scheme == "https")
67
+ machine_id = @machine_id.id
68
+ @log.debug "send creating agent request"
69
+ request = Net::HTTP::Post.new(url)
70
+ request["X-Project-Token"] = @api_key
71
+ request["Content-Type"] = "application/json"
72
+ request.body = Yajl.dump(agent_metadata(current_config).merge("machineID" => machine_id))
73
+ response = https.request(request)
74
+ agent = Yajl.load(response.read_body)
75
+ return [response.code, agent, machine_id]
76
+ end
77
+
78
+ # PATCH /api/v1/agents/:agent_id
79
+ # Authorization: X-Agent-Token
80
+ def update_agent(current_config, agent, machine_id)
81
+ url = URI("#{@endpoint}/api/v1/agents/#{agent['id']}")
82
+
83
+ https = if proxy = proxies
84
+ proxy_uri = URI.parse(proxy)
85
+ Net::NTTP.new(uri.host, uri.port,
86
+ proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
87
+ else
88
+ Net::HTTP.new(url.host, url.port)
89
+ end
90
+ https.use_ssl = (url.scheme == "https")
91
+
92
+ @log.debug "send updating agent request"
93
+ request = Net::HTTP::Patch.new(url)
94
+ request["X-Agent-Token"] = agent['token']
95
+ request["Content-Type"] = "application/json"
96
+
97
+ request.body = Yajl.dump(agent_metadata(current_config).merge("machineID" => machine_id))
98
+ response = https.request(request)
99
+ body = response.read_body
100
+ return [response.code, body]
101
+ end
102
+
103
+ # POST /api/v1/agents/:agent_id/metrics
104
+ # Authorization: X-Agent-Token
105
+ def add_metrics(metrics, agent_token, agent_id)
106
+ url = URI("#{@endpoint}/api/v1/agents/#{agent_id}/metrics")
107
+
108
+ https = if proxy = proxies
109
+ proxy_uri = URI.parse(proxy)
110
+ Net::NTTP.new(uri.host, uri.port,
111
+ proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
112
+ else
113
+ Net::HTTP.new(url.host, url.port)
114
+ end
115
+ https.use_ssl = (url.scheme == "https")
116
+
117
+ @log.debug "send adding agent metrics request"
118
+ request = Net::HTTP::Post.new(url)
119
+ request["X-Agent-Token"] = agent_token
120
+ request["Content-Type"] = "application/x-msgpack"
121
+
122
+ request.body = metrics
123
+
124
+ response = https.request(request)
125
+ return [response.code, Yajl.load(response.read_body)]
126
+ end
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,56 @@
1
+ #
2
+ # fluent-plugin-calyptia-monitoring
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'fluent/plugin/in_monitor_agent'
17
+
18
+ module Fluent::Plugin
19
+ class CalyptiaMonitoringExtInput < MonitorAgentInput
20
+ CALYPTIA_PLUGIN_METRIC_INFO = {
21
+ 'emit_size' => ->(){
22
+ @emit_size_metrics.cmetrics.to_msgpack
23
+ },
24
+ 'emit_records' => ->(){
25
+ @emit_records_metrics.cmetrics.to_msgpack
26
+ },
27
+ 'retry_count' => ->(){
28
+ throw(:skip) unless instance_variable_defined?(:@buffer) && !@buffer.nil? && @buffer.is_a?(::Fluent::Plugin::Buffer)
29
+ @num_errors_metrics.cmetrics.to_msgpack
30
+ },
31
+ }
32
+
33
+ def get_monitor_info(pe, opts = {})
34
+ obj = {}
35
+
36
+ obj['metrics'] = get_plugin_metric(pe)
37
+
38
+ obj
39
+ end
40
+
41
+ def get_plugin_metric(pe)
42
+ metrics = {}
43
+ CALYPTIA_PLUGIN_METRIC_INFO.each_pair { |key, code|
44
+ begin
45
+ v = pe.instance_exec(&code)
46
+ unless v.nil?
47
+ metrics[key] = v
48
+ end
49
+ rescue
50
+ end
51
+ }
52
+
53
+ metrics
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,96 @@
1
+ #
2
+ # fluent-plugin-calyptia-monitoring
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'securerandom'
17
+
18
+ module Fluent::Plugin
19
+ class CalyptiaMonitoringMachineId
20
+ def initialize(worker_id, log)
21
+ @worker_id = worker_id.to_i
22
+ @log = log
23
+ end
24
+
25
+ def macos?
26
+ RUBY_PLATFORM =~ /darwin/
27
+ end
28
+
29
+ def linux?
30
+ RUBY_PLATFORM =~ /linux/
31
+ end
32
+
33
+ def windows?
34
+ RUBY_PLATFORM =~ /mingw|mswin/
35
+ end
36
+
37
+ DBUS_MACHINE_ID_PATH = "/var/lib/dbus/machine-id".freeze
38
+ ETC_MACHINE_ID_PATH = "/etc/machine-id".freeze
39
+
40
+ def id
41
+ if linux?
42
+ linux_id
43
+ elsif windows?
44
+ windows_id
45
+ elsif macos?
46
+ macos_id
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ def macos_id
53
+ require 'open3'
54
+ o,_e, s = Open3.capture3 %q(ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}')
55
+ unless s.success?
56
+ @log.warn "MachineID is not retrived from ioreg. Using UUID instead."
57
+ "#{SecureRandom.uuid}:#{@worker_id}"
58
+ else
59
+ # TODO: The prefix should be removed?
60
+ "#{SecureRandom.hex(10)}_#{o.strip}:#{@worker_id}"
61
+ end
62
+ end
63
+
64
+ def linux_id
65
+ machine_id = ""
66
+ begin
67
+ machine_id = File.read(DBUS_MACHINE_ID_PATH).strip
68
+ rescue Errno::NOENT
69
+ machine_id = File.read(ETC_MACHINE_ID_PATH).strip rescue ""
70
+ end
71
+ if machine_id.empty?
72
+ @log.warn "MachineID is not retrived from #{DBUS_MACHINE_ID_PATH} or #{ETC_MACHINE_ID_PATH}. Using UUID instead."
73
+ "#{SecureRandom.uuid}:#{@worker_id}"
74
+ else
75
+ # TODO: The prefix should be removed?
76
+ "#{SecureRandom.hex(10)}_#{machine_id}:#{@worker_id}"
77
+ end
78
+ end
79
+
80
+ def windows_id
81
+ require 'win32/registry'
82
+
83
+ machine_id = nil
84
+ Win32::Registry::HKEY_LOCAL_MACHINE.open('SOFTWARE\\Microsoft\\Cryptography') do |key|
85
+ machine_id = key.read("MachineGuid")[1] rescue ""
86
+ end
87
+ if machine_id.empty?
88
+ @log.warn "MachineID is not retrived from Registry. Using UUID instead."
89
+ "#{SecureRandom.uuid}:#{@worker_id}"
90
+ else
91
+ # TODO: The prefix should be removed?
92
+ "#{SecureRandom.hex(10)}_#{machine_id}:#{@worker_id}"
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,231 @@
1
+ #
2
+ # fluent-plugin-calyptia-monitoring
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'net/http'
17
+ require 'monitor'
18
+ require 'time'
19
+ require 'fluent/version'
20
+ require 'fluent/config/element'
21
+ require 'fluent/plugin/metrics'
22
+ require "fluent/plugin/input"
23
+ require_relative "calyptia_monitoring_ext"
24
+ require_relative "calyptia_monitoring_calyptia_api_requester"
25
+
26
+ module Fluent
27
+ module Plugin
28
+ class CalyptiaMonitoringInput < Fluent::Plugin::Input
29
+ Fluent::Plugin.register_input("calyptia_monitoring", self)
30
+
31
+ class CreateAgentError < Fluent::ConfigError; end
32
+ class UpdateAgentError < Fluent::ConfigError; end
33
+
34
+ helpers :timer, :storage
35
+
36
+ RPC_CONFIG_DUMP_ENDPOINT = "/api/config.getDump".freeze
37
+ DEFAULT_STORAGE_TYPE = 'local'
38
+ DEFAULT_PENDING_METRICS_SIZE = 100
39
+ UNPROCESSABLE_HTTP_ERRORS = [
40
+ 422, # Invalid Metrics
41
+ 410, # Agent Gone
42
+ 401, # Unauthorized
43
+ 400, # BadRequest
44
+ ]
45
+
46
+ config_section :cloud_monitoring, multi: false do
47
+ desc 'The endpoint for Monitoring API HTTP request, e.g. http://example.com/api'
48
+ config_param :endpoint, :string, default: "https://cloud-monitoring-api-dev.fluentbit.io"
49
+ desc 'The API KEY for Monitoring API HTTP request'
50
+ config_param :api_key, :string, secret: true
51
+ desc 'Emit monitoring values interval. (minimum interval is 30 seconds.)'
52
+ config_param :rate, :time, default: 30
53
+ desc 'Setup pending metrics capacity size'
54
+ config_param :pending_metrics_size, :size, default: DEFAULT_PENDING_METRICS_SIZE
55
+ end
56
+
57
+ def multi_workers_ready?
58
+ true
59
+ end
60
+
61
+ def initialize
62
+ super
63
+ @current_config = nil
64
+ @monitor = Monitor.new
65
+ @pending = []
66
+ end
67
+
68
+ def configure(conf)
69
+ super
70
+ config = conf.elements.select{|e| e.name == 'storage' }.first
71
+ @storage_agent = storage_create(usage: 'calyptia_monitoring_agent', conf: config, default_type: DEFAULT_STORAGE_TYPE)
72
+ end
73
+
74
+ def get_current_config_from_rpc
75
+ res = retrieve_config_from_rpc
76
+ config = Yajl.load(res.body)["conf"]
77
+ conf = Fluent::Config.parse(config, '(supervisor)', '(RPC)', true)
78
+ confs = []
79
+ conf.elements.select{|e| e.name == 'ROOT' }.first.elements.each{|e|
80
+ confs << e.to_s
81
+ }
82
+ # Remove outer <ROOT> element
83
+ confs.join
84
+ end
85
+
86
+ def start
87
+ super
88
+
89
+ enabled_cmetrics = if system_config.metrics
90
+ system_config.metrics[:@type] == "cmetrics"
91
+ else
92
+ false
93
+ end
94
+ raise Fluent::ConfigError, "cmetrics plugin should be used to collect metrics on Calyptia Cloud" unless enabled_cmetrics
95
+ @monitor_agent = Fluent::Plugin::CalyptiaMonitoringExtInput.new
96
+ @api_requester = Fluent::Plugin::CalyptiaAPI::Requester.new(@cloud_monitoring.endpoint,
97
+ @cloud_monitoring.api_key,
98
+ log,
99
+ fluentd_worker_id)
100
+ if check_config_sending_usability
101
+ @current_config = get_current_config_from_rpc
102
+ end
103
+
104
+ if @cloud_monitoring.rate < 30
105
+ log.warn "High frequency events ingestion is not supported. Set up 30s as ingestion interval"
106
+ @cloud_monitoring[:rate] = 30
107
+ end
108
+ if setup_agent(@current_config)
109
+ timer_execute(:in_calyptia_monitoring_send_metrics, @cloud_monitoring.rate, &method(:on_timer_send_metrics))
110
+ else
111
+ raise UpdateAgentError, "Setup agent is failed. Something went wrong"
112
+ end
113
+ end
114
+
115
+ def create_agent(current_config)
116
+ code, agent, machine_id = @api_requester.create_agent(current_config)
117
+ if agent["error"].nil?
118
+ @storage_agent.put(:agent, agent)
119
+ @storage_agent.put(:machine_id, machine_id)
120
+ return true
121
+ else
122
+ raise CreateAgentError, "Create agent is failed. Error: `#{agent["error"]}', code: #{code}"
123
+ end
124
+ end
125
+
126
+ def setup_agent(current_config)
127
+ if agent = @storage_agent.get(:agent)
128
+ unless machine_id = @storage_agent.get(:machine_id)
129
+ return create_agent(current_config)
130
+ end
131
+ code, body = @api_requester.update_agent(current_config, agent, machine_id)
132
+ if code.to_s.start_with?("2")
133
+ return true
134
+ else
135
+ log.warn "Updating agent is failed. Error: #{Yajl.load(body)["error"]}, Code: #{code}"
136
+ return false
137
+ end
138
+ else
139
+ create_agent(current_config)
140
+ end
141
+ end
142
+
143
+ def check_config_sending_usability
144
+ unless system_config.rpc_endpoint
145
+ log.warn "This feature needs to enable RPC with `rpc_endpoint` on <system>."
146
+ return false
147
+ end
148
+
149
+ res = retrieve_config_from_rpc
150
+ if status = (res.code.to_i == 200)
151
+ return status
152
+ else
153
+ log.warn "This feature needs to enable getDump RPC endpoint with `enable_get_dump` on <system>."
154
+ return false
155
+ end
156
+ end
157
+
158
+ def retrieve_config_from_rpc
159
+ uri = URI.parse("http://#{system_config.rpc_endpoint}")
160
+ res = Net::HTTP.start(uri.host, uri.port) {|http|
161
+ http.get(RPC_CONFIG_DUMP_ENDPOINT)
162
+ }
163
+ res
164
+ end
165
+
166
+ def shutdown
167
+ super
168
+ end
169
+
170
+ def append_pendings(buffer)
171
+ @monitor.synchronize do
172
+ if @pending.empty?
173
+ @pending = [buffer]
174
+ elsif @pending.size >= DEFAULT_PENDING_METRICS_SIZE
175
+ drop_count = 1
176
+ @pending = @pending.drop(drop_count)
177
+ log.warn "pending buffer is full. Dropped the first element from the pending buffer"
178
+ @pending.concat([buffer])
179
+ else
180
+ @pending.concat([buffer])
181
+ end
182
+ end
183
+ end
184
+
185
+ def add_metrics(buffer)
186
+ return false unless agent = @storage_agent.get(:agent)
187
+
188
+ begin
189
+ code, response = if @pending.empty?
190
+ @api_requester.add_metrics(buffer, agent["token"], agent["id"])
191
+ else
192
+ @monitor.synchronize do
193
+ @pending = @pending.concat([buffer])
194
+ @api_requester.add_metrics(@pending.join, agent["token"], agent["id"])
195
+ @pending = []
196
+ end
197
+ end
198
+ if response && response["error"]
199
+ case code.to_i
200
+ when *UNPROCESSABLE_HTTP_ERRORS
201
+ log.warn "Sending metrics is failed and dropped metrics due to unprocessable on server. Error: `#{response["error"]}', Code: #{code}"
202
+ return false
203
+ end
204
+ log.warn "Failed to send metrics. Error: `#{response["error"]}', Code: #{code}"
205
+ append_pendings(buffer)
206
+ return false
207
+ end
208
+ rescue => ex
209
+ log.warn "Failed to send metrics: error = #{ex}, backtrace = #{ex.backtrace}"
210
+ append_pendings(buffer)
211
+ return false
212
+ end
213
+ return true
214
+ end
215
+
216
+ def on_timer_send_metrics
217
+ opts = {with_config: false, with_retry: false}
218
+ buffer = ""
219
+ @monitor_agent.plugins_info_all(opts).each { |record|
220
+ metrics = record["metrics"]
221
+ metrics.each_pair do |k, v|
222
+ buffer += v
223
+ end
224
+ }
225
+ unless add_metrics(buffer)
226
+ log.warn "Sending metrics is failed. Trying to send pending buffers in the next interval: #{@cloud_monitoring.rate}, next sending time: #{Time.now + @cloud_monitoring.rate}"
227
+ end
228
+ end
229
+ end
230
+ end
231
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,8 @@
1
+ $LOAD_PATH.unshift(File.expand_path("../../", __FILE__))
2
+ require "test-unit"
3
+ require "fluent/test"
4
+ require "fluent/test/driver/input"
5
+ require "fluent/test/helpers"
6
+
7
+ Test::Unit::TestCase.include(Fluent::Test::Helpers)
8
+ Test::Unit::TestCase.extend(Fluent::Test::Helpers)
@@ -0,0 +1,16 @@
1
+ require "helper"
2
+ require "logger"
3
+ require "fluent/plugin/in_calyptia_monitoring.rb"
4
+
5
+ class CalyptiaMonitoringMachineIdTest < Test::Unit::TestCase
6
+ setup do
7
+ @log = Logger.new($stdout)
8
+ worker_id = [1,2,3,4,5,6,7,8,9,10,11].sample
9
+ @machine_id = @machine_id = Fluent::Plugin::CalyptiaMonitoringMachineId.new(worker_id, @log)
10
+ end
11
+
12
+ test "Retrive machineID" do
13
+ machine_id = @machine_id.id
14
+ assert_not_nil machine_id
15
+ end
16
+ end
@@ -0,0 +1,18 @@
1
+ require "helper"
2
+ require "fluent/plugin/in_calyptia_monitoring.rb"
3
+
4
+ class CalyptiaMonitoringInputTest < Test::Unit::TestCase
5
+ setup do
6
+ Fluent::Test.setup
7
+ end
8
+
9
+ test "operate" do
10
+ omit "Not implemented for now"
11
+ end
12
+
13
+ private
14
+
15
+ def create_driver(conf)
16
+ Fluent::Test::Driver::Input.new(Fluent::Plugin::CalyptiaMonitoringInput).configure(conf)
17
+ end
18
+ end
metadata ADDED
@@ -0,0 +1,135 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fluent-plugin-calyptia-monitoring
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.rc
5
+ platform: ruby
6
+ authors:
7
+ - Hiroshi Hatake
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-07-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 2.2.15
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 2.2.15
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '13.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '13.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: test-unit
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.3'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: fluentd
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 1.13.0
62
+ - - "<"
63
+ - !ruby/object:Gem::Version
64
+ version: '2'
65
+ type: :runtime
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 1.13.0
72
+ - - "<"
73
+ - !ruby/object:Gem::Version
74
+ version: '2'
75
+ - !ruby/object:Gem::Dependency
76
+ name: fluent-plugin-metrics-cmetrics
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: 0.1.0.rc2
82
+ type: :runtime
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: 0.1.0.rc2
89
+ description: Monitoring Fluentd via Calyptia Cloud
90
+ email:
91
+ - hatake@calyptia.com
92
+ executables: []
93
+ extensions: []
94
+ extra_rdoc_files: []
95
+ files:
96
+ - ".gitignore"
97
+ - Gemfile
98
+ - LICENSE
99
+ - README.md
100
+ - Rakefile
101
+ - fluent-plugin-calyptia-monitoring.gemspec
102
+ - lib/fluent/plugin/calyptia_monitoring_calyptia_api_requester.rb
103
+ - lib/fluent/plugin/calyptia_monitoring_ext.rb
104
+ - lib/fluent/plugin/calyptia_monitoring_machine_id.rb
105
+ - lib/fluent/plugin/in_calyptia_monitoring.rb
106
+ - test/helper.rb
107
+ - test/plugin/test_calyptia_montoring_machine_id.rb
108
+ - test/plugin/test_in_calyptia_monitoring.rb
109
+ homepage: https://github.com/calyptia/fluent-plugin-calyptia-monitoring
110
+ licenses:
111
+ - Apache-2.0
112
+ metadata: {}
113
+ post_install_message:
114
+ rdoc_options: []
115
+ require_paths:
116
+ - lib
117
+ required_ruby_version: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - ">="
120
+ - !ruby/object:Gem::Version
121
+ version: '0'
122
+ required_rubygems_version: !ruby/object:Gem::Requirement
123
+ requirements:
124
+ - - ">"
125
+ - !ruby/object:Gem::Version
126
+ version: 1.3.1
127
+ requirements: []
128
+ rubygems_version: 3.0.3
129
+ signing_key:
130
+ specification_version: 4
131
+ summary: Monitoring Fluentd via Calyptia Cloud
132
+ test_files:
133
+ - test/helper.rb
134
+ - test/plugin/test_calyptia_montoring_machine_id.rb
135
+ - test/plugin/test_in_calyptia_monitoring.rb