logstash-input-flume 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c02d9533d46d3b97f0411e384c8611bff4f4cf5817a8cf9658d613d542505b2a
4
+ data.tar.gz: 54b7f68ccd862ff603c5ceb371dcb242d9a18a62d9088e409f8436975d596e39
5
+ SHA512:
6
+ metadata.gz: 434aedd32f1f30641bf0349131b70d7a86c89957d3dac06fc80b86d8e710afadbec3c8209f9ade32536b819e729a6234cc06a4bb9c181d126693dca5cdecfe6b
7
+ data.tar.gz: d5ddd7ef1acf457afbec68e9cf92907584f28c8f209628094263f17c06b313055bc824f0e35b2c5241cf6a72f6441f8ba3d164974bfaddd24ffcad3a51bcc0a2
data/CHANGELOG.md ADDED
@@ -0,0 +1,2 @@
1
+ ## 0.1.0
2
+ - Plugin created with the logstash plugin generator
data/CONTRIBUTORS ADDED
@@ -0,0 +1,10 @@
1
+ The following is a list of people who have contributed ideas, code, bug
2
+ reports, or in general have helped logstash along its way.
3
+
4
+ Contributors:
5
+ * Matthew Haugen - mhaugen@haugenapplications.com
6
+
7
+ Note: If you've sent us patches, bug reports, or otherwise contributed to
8
+ Logstash, and you aren't on the list above and want to be, please let us know
9
+ and we'll make sure you're here. Contributions from folks like you are what make
10
+ open source awesome.
data/DEVELOPER.md ADDED
@@ -0,0 +1,2 @@
1
+ # logstash-input-sensorpush
2
+ Example input plugin. This should help bootstrap your effort to write your own input plugin!
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+ gemspec
3
+
data/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Licensed under the Apache License, Version 2.0 (the "License");
2
+ you may not use this file except in compliance with the License.
3
+ You may obtain a copy of the License at
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ See the License for the specific language governing permissions and
11
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # Logstash Plugin
2
+
3
+ This is a plugin for [Logstash](https://github.com/elastic/logstash).
4
+
5
+ It is fully free and fully open source. The license is Apache 2.0, meaning you are pretty much free to use it however you want in whatever way.
6
+
7
+ ## Documentation
8
+
9
+ Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elastic.co/guide/en/logstash/current/).
10
+
11
+ - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive
12
+ - For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide
13
+
14
+ ## Need Help?
15
+
16
+ Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum.
17
+
18
+ ## Developing
19
+
20
+ ### 1. Plugin Developement and Testing
21
+
22
+ #### Code
23
+ - To get started, you'll need JRuby with the Bundler gem installed.
24
+
25
+ - Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization. We also provide [example plugins](https://github.com/logstash-plugins?query=example).
26
+
27
+ - Install dependencies
28
+ ```sh
29
+ bundle install
30
+ ```
31
+
32
+ #### Test
33
+
34
+ - Update your dependencies
35
+
36
+ ```sh
37
+ bundle install
38
+ ```
39
+
40
+ - Run tests
41
+
42
+ ```sh
43
+ bundle exec rspec
44
+ ```
45
+
46
+ ### 2. Running your unpublished Plugin in Logstash
47
+
48
+ #### 2.1 Run in a local Logstash clone
49
+
50
+ - Edit Logstash `Gemfile` and add the local plugin path, for example:
51
+ ```ruby
52
+ gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome"
53
+ ```
54
+ - Install plugin
55
+ ```sh
56
+ bin/logstash-plugin install --no-verify
57
+ ```
58
+ - Run Logstash with your plugin
59
+ ```sh
60
+ bin/logstash -e 'filter {awesome {}}'
61
+ ```
62
+ At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash.
63
+
64
+ #### 2.2 Run in an installed Logstash
65
+
66
+ You can use the same **2.1** method to run your plugin in an installed Logstash by editing its `Gemfile` and pointing the `:path` to your local plugin development directory or you can build the gem and install it using:
67
+
68
+ - Build your plugin gem
69
+ ```sh
70
+ gem build logstash-filter-awesome.gemspec
71
+ ```
72
+ - Install the plugin from the Logstash home
73
+ ```sh
74
+ bin/logstash-plugin install /your/local/plugin/logstash-filter-awesome.gem
75
+ ```
76
+ - Start Logstash and proceed to test the plugin
77
+
78
+ ## Contributing
79
+
80
+ All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin.
81
+
82
+ Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here.
83
+
84
+ It is more important to the community that you are able to contribute.
85
+
86
+ For more information about contributing, see the [CONTRIBUTING](https://github.com/elastic/logstash/blob/main/CONTRIBUTING.md) file.
@@ -0,0 +1,338 @@
1
+ # encoding: utf-8
2
+ require "logstash/inputs/base"
3
+ require "stud/interval"
4
+ require "socket" # for Socket.gethostname
5
+
6
+ # Generate a repeating message.
7
+ #
8
+ # This plugin is intented only as an example.
9
+
10
+ class OAuthClient
11
+
12
+ def get_token
13
+ raise "Not implemented!"
14
+ end
15
+ end
16
+
17
+ class ResourceOwnerOAuthClient < OAuthClient
18
+ def initialize(session, client_id, client_secret, email, password, logger)
19
+ @session = session
20
+
21
+ @logger = logger
22
+
23
+ @client_id = client_id
24
+ @client_secret = client_secret
25
+ @email = email
26
+ @password = password
27
+
28
+ @token_hash = {
29
+ expires: 0,
30
+ response: {},
31
+ claims: {}
32
+ }
33
+ end
34
+
35
+ def get_token
36
+ ret = self.get_token_hash
37
+
38
+ return ret[:response]["access_token"]
39
+ end
40
+
41
+ def get_token_claims
42
+ ret = self.get_token_hash
43
+
44
+ return ret[:claims]
45
+ end
46
+
47
+ def get_token_hash
48
+ now = Time.now.to_i
49
+
50
+ expires = @token_hash[:expires]
51
+
52
+ if expires < now
53
+ refesh_token = @token_hash[:response]["refresh_token"]
54
+
55
+ if refesh_token
56
+ @logger.debug("Getting Flume API access token (from refresh token)")
57
+ auth_body = {
58
+ grant_type: "refresh_token",
59
+
60
+ client_id: @client_id,
61
+ client_secret: @client_secret.value,
62
+
63
+ refresh_token: refresh_token
64
+ }
65
+ else
66
+ @logger.debug("Getting Flume API access token (from credentials)")
67
+
68
+ auth_body = {
69
+ grant_type: "password",
70
+
71
+ client_id: @client_id,
72
+ client_secret: @client_secret.value,
73
+
74
+ username: @email,
75
+ password: @password.value
76
+ }
77
+ end
78
+
79
+ auth_req = Net::HTTP::Post.new("/oauth/token")
80
+ auth_req.body = JSON.generate(auth_body)
81
+ auth_req["Accept"] = "application/json"
82
+ auth_req["Content-Type"] = "application/json"
83
+
84
+ auth_resp = @session.request(auth_req)
85
+
86
+ token_resp_json = JSON.parse(auth_resp.body)
87
+
88
+ puts token_resp_json
89
+
90
+ unless token_resp_json["success"]
91
+ detailed = token_resp_json["detailed"]
92
+
93
+ raise "invalid response getting access token: " + detailed[0]
94
+ end
95
+
96
+ token_data = token_resp_json["data"][0]
97
+
98
+ # @logger.debug("Getting Flume API access token")
99
+
100
+ # token_req = Net::HTTP::Post.new("/api/v1/oauth/accesstoken")
101
+ # token_req.body = JSON.generate({
102
+ # authorization: auth_resp_json["authorization"]
103
+ # })
104
+ # token_req["Accept"] = "application/json"
105
+ # token_req["Content-Type"] = "application/json"
106
+
107
+ # token_resp = @session.request(token_req)
108
+
109
+ # token_resp_json = JSON.parse(token_resp.body)
110
+
111
+ claims = self.get_token_claims_from_token(token_data["access_token"])
112
+
113
+ @token_hash = {
114
+ expires: claims["exp"] - 120,
115
+ response: token_data,
116
+ claims: claims
117
+ }
118
+ end
119
+
120
+ return @token_hash
121
+ end
122
+
123
+ def get_token_claims_from_token(token)
124
+ jwt_parts = token.split(".")
125
+
126
+ claims_part = jwt_parts[1]
127
+
128
+ claims_json = Base64.decode64(claims_part)
129
+
130
+ claims = JSON.parse(claims_json)
131
+
132
+ return claims
133
+ end
134
+ end
135
+
136
+ class FlumeApiConnection
137
+ def initialize(client_id, client_secret, email, password, logger)
138
+ @session = Net::HTTP.start("api.flumewater.com", 443, use_ssl: true)
139
+ @authenticator = ResourceOwnerOAuthClient.new(@session, client_id, client_secret, email, password, logger)
140
+
141
+ @logger = logger
142
+
143
+ @stop = false
144
+ end
145
+
146
+ def stop
147
+ @stop = true
148
+ end
149
+
150
+ def send_request(req)
151
+ req["Accept"] = "application/json"
152
+ req["Authorization"] = "Bearer " + @authenticator.get_token
153
+
154
+ resp = @session.request(req)
155
+
156
+ resp_json = JSON.parse(resp.body)
157
+
158
+ unless resp_json["success"]
159
+ puts resp.to_hash
160
+
161
+ retry_after = resp["retry-after"]
162
+
163
+ if retry_after
164
+ @logger.info("Rate limit reached. Waiting...", :retry_after => retry_after)
165
+ Stud.stoppable_sleep(Integer(retry_after)) {
166
+ @stop
167
+ }
168
+ return self.send_request(req)
169
+ end
170
+
171
+ raise "invalid response from '#{req.uri}': " + resp.body
172
+ end
173
+
174
+ return resp_json["data"]
175
+ end
176
+
177
+ def get_devices
178
+ resp = self.send_request(Net::HTTP::Get.new("/me/devices?user=false&location=true"))
179
+
180
+ return resp.select { |device|
181
+ device["type"] == 2
182
+ }
183
+ end
184
+
185
+ def get_readings_by_minute(device, to, from)
186
+ device_id = device["id"]
187
+
188
+ device_tz = TZInfo::Timezone.get(device["location"]["tz"])
189
+
190
+ body = {
191
+ queries: [
192
+ {
193
+ request_id: "by_minute",
194
+
195
+ bucket: "MIN",
196
+
197
+ units: "LITERS",
198
+
199
+ since_datetime: device_tz.to_local(from).strftime('%Y-%m-%d %H:%M:%S'),
200
+ until_datetime: device_tz.to_local(to).strftime('%Y-%m-%d %H:%M:%S')
201
+ }
202
+ ]
203
+ }
204
+
205
+ req = Net::HTTP::Post.new("/me/devices/#{device_id}/query")
206
+ req.body = JSON.generate(body)
207
+ req["Content-Type"] = "application/json"
208
+ resp = self.send_request(req)
209
+
210
+ ret = resp[0]["by_minute"]
211
+
212
+ ret.select! { |item|
213
+ item["value"] > 0
214
+ }
215
+
216
+ ret.map! { |item|
217
+ item_from = device_tz.local_to_utc(DateTime.parse(item["datetime"]))
218
+ item_to = item_from + (1.0 / (24 * 60))
219
+
220
+ {
221
+ from: item_from.to_time,
222
+ to: item_to.to_time,
223
+ value: {
224
+ perMinute: {
225
+ liters: item["value"]
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ puts ret
232
+
233
+ ret.sort_by! { |item| item[:from] }
234
+
235
+ puts ret
236
+
237
+ ret.pop
238
+
239
+ puts ret
240
+
241
+ return ret
242
+ end
243
+
244
+ def get_url(path, query_parameters = nil)
245
+ unless path.start_with?("/")
246
+ path = "/" + path
247
+ end
248
+
249
+ omadacid = self.get_omadacid
250
+
251
+ url = URI("/" + omadacid + path)
252
+
253
+ if query_parameters
254
+ url.query = URI.encode_www_form(query_parameters)
255
+ end
256
+
257
+ return url.to_s
258
+ end
259
+ end
260
+
261
+ class LogStash::Inputs::Flume < LogStash::Inputs::Base
262
+ config_name "flume"
263
+
264
+ # If undefined, Logstash will complain, even if codec is unused.
265
+ default :codec, "plain"
266
+
267
+ # The message string to use in the event.
268
+ config :client_id, :validate => :string
269
+ config :client_secret, :validate => :password
270
+
271
+ config :email, :validate => :string
272
+ config :password, :validate => :password
273
+
274
+ # Set how frequently messages should be sent.
275
+ #
276
+ # The default, `1`, means send a message every second.
277
+ config :interval, :validate => :number, :default => 10
278
+
279
+ public
280
+ def register
281
+ @logger.info("Connecting to Flume API", :client_id => @client_id, :email => @email)
282
+ @conn = FlumeApiConnection.new(@client_id, @client_secret, @email, @password, @logger)
283
+ end # def register
284
+
285
+ def run(queue)
286
+ # we can abort the loop if stop? becomes true
287
+ time_by_device = {}
288
+
289
+ while !stop?
290
+ now = DateTime.now
291
+
292
+ @logger.debug("Getting devices from Flume API")
293
+ devices = @conn.get_devices
294
+
295
+ devices.each { |device|
296
+ device_id = device["id"]
297
+
298
+ since = time_by_device[device_id]
299
+
300
+ unless since
301
+ # since = now - 0.5
302
+ since = now - 0.01
303
+ end
304
+
305
+ @logger.debug("Getting latest values from Flume API", :device_id => device_id, :since => since.iso8601)
306
+
307
+ readings_by_minute = @conn.get_readings_by_minute(device, now, since)
308
+
309
+ puts JSON.generate(readings_by_minute)
310
+
311
+ unless readings_by_minute.empty?
312
+ time_by_device[device_id] = readings_by_minute.map { |v| v[:to] }.max
313
+
314
+ readings_by_minute.each { |reading|
315
+ flume = {
316
+ device: device,
317
+ reading: reading
318
+ }
319
+
320
+ event = LogStash::Event.new("@timestamp" => reading[:to].to_time, "flume" => flume)
321
+ decorate(event)
322
+ queue << event
323
+ }
324
+ end
325
+ }
326
+
327
+ # because the sleep interval can be big, when shutdown happens
328
+ # we want to be able to abort the sleep
329
+ # Stud.stoppable_sleep will frequently evaluate the given block
330
+ # and abort the sleep(@interval) if the return value is true
331
+ Stud.stoppable_sleep(@interval) { stop? }
332
+ end # loop
333
+ end # def run
334
+
335
+ def stop
336
+ @conn.stop
337
+ end
338
+ end # class LogStash::Inputs::Airthings
@@ -0,0 +1,25 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = 'logstash-input-flume'
3
+ s.version = '0.1.1'
4
+ s.licenses = ['Apache-2.0']
5
+ s.summary = 'Connect to Flume API'
6
+ s.description = 'Connect to Flume API'
7
+ s.homepage = 'https://www.haugenapplications.com'
8
+ s.authors = ['Matthew Haugen']
9
+ s.email = 'mhaugen@haugenapplications.com'
10
+ s.require_paths = ['lib']
11
+
12
+ # Files
13
+ s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT']
14
+ # Tests
15
+ s.test_files = s.files.grep(%r{^(test|spec|features)/})
16
+
17
+ # Special flag to let us know this is actually a logstash plugin
18
+ s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" }
19
+
20
+ # Gem dependencies
21
+ s.add_runtime_dependency "logstash-core-plugin-api", "~> 2.0"
22
+ s.add_runtime_dependency 'logstash-codec-plain'
23
+ s.add_runtime_dependency 'stud', '>= 0.0.22'
24
+ s.add_development_dependency 'logstash-devutils', '>= 0.0.16'
25
+ end
@@ -0,0 +1,11 @@
1
+ # encoding: utf-8
2
+ require "logstash/devutils/rspec/spec_helper"
3
+ require "logstash/inputs/sensorpush"
4
+
5
+ describe LogStash::Inputs::SensorPush do
6
+
7
+ it_behaves_like "an interruptible input plugin" do
8
+ let(:config) { { "interval" => 100 } }
9
+ end
10
+
11
+ end
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: logstash-input-flume
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Matthew Haugen
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-07-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: logstash-core-plugin-api
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: logstash-codec-plain
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: stud
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 0.0.22
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 0.0.22
55
+ - !ruby/object:Gem::Dependency
56
+ name: logstash-devutils
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 0.0.16
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 0.0.16
69
+ description: Connect to Flume API
70
+ email: mhaugen@haugenapplications.com
71
+ executables: []
72
+ extensions: []
73
+ extra_rdoc_files: []
74
+ files:
75
+ - CHANGELOG.md
76
+ - CONTRIBUTORS
77
+ - DEVELOPER.md
78
+ - Gemfile
79
+ - LICENSE
80
+ - README.md
81
+ - lib/logstash/inputs/flume.rb
82
+ - logstash-input-flume.gemspec
83
+ - spec/inputs/flume_spec.rb
84
+ homepage: https://www.haugenapplications.com
85
+ licenses:
86
+ - Apache-2.0
87
+ metadata:
88
+ logstash_plugin: 'true'
89
+ logstash_group: input
90
+ post_install_message:
91
+ rdoc_options: []
92
+ require_paths:
93
+ - lib
94
+ required_ruby_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ required_rubygems_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ requirements: []
105
+ rubygems_version: 3.0.3.1
106
+ signing_key:
107
+ specification_version: 4
108
+ summary: Connect to Flume API
109
+ test_files:
110
+ - spec/inputs/flume_spec.rb