fluent-plugin-google-cloud 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.rdoc ADDED
@@ -0,0 +1,35 @@
1
+ = Google Cloud Platform plugin for {fluentd}[http://github.com/fluent/fluentd]
2
+
3
+ fluent-plugin-google-cloud sends logs to the Google Cloud Platform logging API.
4
+
5
+ == Installation
6
+
7
+ The gem is hosted at {RubyGems.org}[http://rubygems.org]. You can install the gem as follows:
8
+
9
+ $ gem install fluent-plugin-google-cloud
10
+
11
+ == Configuration
12
+
13
+ <match **>
14
+ type google_cloud
15
+ auth_method <method>
16
+ private_key_email <address>
17
+ private_key_path <path>
18
+ </match>
19
+
20
+ Supported options:
21
+ * auth_method: either 'compute_engine_service_account' or 'private_key' (default: compute_engine_service_account)
22
+ * private_key_email: email address of your project's service account.
23
+ * private_key_path: path to a file containing service account credentials.
24
+
25
+ private_key_email and private_key_path are required if auth_method is
26
+ 'private_key', otherwise they are ignored.
27
+
28
+ == Caveats
29
+
30
+ This plugin currently only supports being run on a Google Compute Engine VM because it grabs its authentication token as well as important metadata from the VM metadata server.
31
+
32
+ == Copyright
33
+
34
+ Copyright:: Copyright 2014 Google Inc. All rights reserved.
35
+ License:: Apache License, Version 2.0
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env rake
2
+
3
+ require 'bundler'
4
+ Bundler::GemHelper.install_tasks
5
+
6
+ require 'rake/testtask'
7
+
8
+ Rake::TestTask.new(:test) do |test|
9
+ test.libs << 'lib' << 'test'
10
+ test.test_files = FileList['test/plugin/*.rb']
11
+ test.verbose = true
12
+ end
@@ -0,0 +1,19 @@
1
+ Gem::Specification.new do |gem|
2
+ gem.name = 'fluent-plugin-google-cloud'
3
+ gem.description = %q{Fluentd plugin to stream logs to the Google Cloud Platform's logs API, which will make them viewable in the Developer Console's log viewer and can optionally store them in Google Cloud Storage and/or BigQuery. This is an official Google Ruby gem.}
4
+ gem.summary = %q{Fluentd plugin to stream logs to the Google Cloud Platform's logs API}
5
+ gem.homepage = 'https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud'
6
+ gem.license = 'Apache 2.0'
7
+ gem.version = '0.1.1'
8
+ gem.authors = ['Todd Derr', 'Alex Robinson']
9
+ gem.email = ['salty@google.com']
10
+
11
+ gem.files = Dir['**/*'].keep_if { |file| File.file?(file) }
12
+ gem.test_files = gem.files.grep(%r{^(test)})
13
+ gem.require_paths = ['lib']
14
+
15
+ gem.add_runtime_dependency 'fluentd', '~> 0.10'
16
+ gem.add_runtime_dependency 'google-api-client', '~> 0.7'
17
+ gem.add_development_dependency "rake", '>= 10.3.2'
18
+ gem.add_development_dependency "webmock", '>= 1.17.0'
19
+ end
@@ -0,0 +1,243 @@
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ module Fluent
16
+ class GoogleCloudOutput < BufferedOutput
17
+ Fluent::Plugin.register_output('google_cloud', self)
18
+
19
+ # Constants for Google service names.
20
+ APPENGINE_SERVICE = 'appengine.googleapis.com'
21
+ COMPUTE_SERVICE = 'compute.googleapis.com'
22
+
23
+ # Legal values:
24
+ # 'compute_engine_service_account' - Use the service account automatically
25
+ # available on Google Compute Engine VMs. Note that this requires that
26
+ # the logs.writeonly API scope is enabled on the VM, and scopes can
27
+ # only be enabled at the time that a VM is created.
28
+ # 'private_key' - Use the service account credentials (email, private key
29
+ # local file path, and file passphrase) provided below.
30
+ config_param :auth_method, :string,
31
+ :default => 'compute_engine_service_account'
32
+
33
+ # Parameters necessary to use the private_key auth_method.
34
+ config_param :private_key_email, :string, :default => nil
35
+ config_param :private_key_path, :string, :default => nil
36
+ config_param :private_key_passphrase, :string, :default => 'notasecret'
37
+
38
+ # TODO: Add a log_name config option rather than just using the tag?
39
+
40
+ # Expose attr_readers to make testing of metadata more direct than only
41
+ # testing it indirectly through metadata sent with logs.
42
+ attr_reader :project_id
43
+ attr_reader :zone
44
+ attr_reader :vm_id
45
+ attr_reader :running_on_managed_vm
46
+ attr_reader :gae_backend_name
47
+ attr_reader :gae_backend_version
48
+ attr_reader :service_name
49
+ attr_reader :common_labels
50
+
51
+ def initialize
52
+ super
53
+ require 'cgi'
54
+ require 'google/api_client'
55
+ require 'google/api_client/auth/compute_service_account'
56
+ require 'open-uri'
57
+ end
58
+
59
+ def configure(conf)
60
+ super
61
+
62
+ case @auth_method
63
+ when 'private_key'
64
+ if !@private_key_email
65
+ raise Fluent::ConfigError, ('"private_key_email" must be ' +
66
+ 'specified if auth_method is "private_key"')
67
+ elsif !@private_key_path
68
+ raise Fluent::ConfigError, ('"private_key_path" must be ' +
69
+ 'specified if auth_method is "private_key"')
70
+ elsif !@private_key_passphrase
71
+ raise Fluent::ConfigError, ('"private_key_passphrase" must be ' +
72
+ 'specified if auth_method is "private_key"')
73
+ end
74
+ when 'compute_engine_service_account'
75
+ # pass
76
+ else
77
+ raise Fluent::ConfigError,
78
+ ('Unrecognized "auth_method" parameter. Please specify either ' +
79
+ '"compute_engine_service_account" or "private_key".')
80
+ end
81
+ end
82
+
83
+ def start
84
+ super
85
+
86
+ init_api_client()
87
+
88
+ # Grab metadata about the Google Compute Engine instance that we're on.
89
+ @project_id = fetch_metadata('project/project-id')
90
+ fully_qualified_zone = fetch_metadata('instance/zone')
91
+ @zone = fully_qualified_zone.rpartition('/')[2]
92
+ @vm_id = fetch_metadata('instance/id')
93
+ # TODO: Send instance tags and/or hostname with the logs as well?
94
+ @common_labels = []
95
+ add_label(common_labels, "#{COMPUTE_SERVICE}/resource_type",
96
+ 'strValue', 'instance')
97
+ add_label(common_labels, "#{COMPUTE_SERVICE}/resource_id",
98
+ 'strValue', @vm_id)
99
+
100
+ # If this is running on a Managed VM, grab the relevant App Engine
101
+ # metadata as well.
102
+ # TODO: Add config options for these to allow for running outside GCE?
103
+ attributes_string = fetch_metadata('instance/attributes/')
104
+ attributes = attributes_string.split
105
+ if (attributes.include?('gae_backend_name') &&
106
+ attributes.include?('gae_backend_version'))
107
+ @running_on_managed_vm = true
108
+ @gae_backend_name =
109
+ fetch_metadata('instance/attributes/gae_backend_name')
110
+ @gae_backend_version =
111
+ fetch_metadata('instance/attributes/gae_backend_version')
112
+ @service_name = APPENGINE_SERVICE
113
+ add_label(common_labels, "#{APPENGINE_SERVICE}/module_id",
114
+ 'strValue', @gae_backend_name)
115
+ add_label(common_labels, "#{APPENGINE_SERVICE}/version_id",
116
+ 'strValue', @gae_backend_version)
117
+ else
118
+ @running_on_managed_vm = false
119
+ @service_name = COMPUTE_SERVICE
120
+ end
121
+ end
122
+
123
+ def shutdown
124
+ super
125
+ end
126
+
127
+ def format(tag, time, record)
128
+ [tag, time, record].to_msgpack
129
+ end
130
+
131
+ def add_label(labels, key, type, value)
132
+ labels.push({'key' => key, type => value})
133
+ end
134
+
135
+ def write(chunk)
136
+ # Group the entries since we have to make one call per tag.
137
+ grouped_entries = {}
138
+ chunk.msgpack_each do |tag, *arr|
139
+ if !grouped_entries.has_key?(tag)
140
+ grouped_entries[tag] = []
141
+ end
142
+ grouped_entries[tag].push(arr)
143
+ end
144
+
145
+ grouped_entries.each do |tag, arr|
146
+ write_log_entries_request = {
147
+ 'commonLabels' => @common_labels,
148
+ 'entries' => [],
149
+ }
150
+ arr.each do |time, record|
151
+ if (record.has_key?('timeNanos'))
152
+ ts_secs = (record['timeNanos'] / 1000000000).to_i
153
+ ts_nanos = record['timeNanos'] % 1000000000
154
+ else
155
+ timestamp = Time.at(time)
156
+ ts_secs = timestamp.tv_sec
157
+ ts_nanos = timestamp.tv_nsec
158
+ end
159
+ entry = {
160
+ 'metadata' => {
161
+ 'serviceName' => @service_name,
162
+ 'projectId' => @project_id,
163
+ 'zone' => @zone,
164
+ 'timestamp' => {
165
+ 'seconds' => ts_secs,
166
+ 'nanos' => ts_nanos
167
+ },
168
+ },
169
+ 'textPayload' => record['message']
170
+ # TODO: default severity?
171
+ }
172
+ if record.has_key?('severity')
173
+ entry['metadata']['severity'] = record['severity']
174
+ end
175
+ write_log_entries_request['entries'].push(entry)
176
+ end
177
+
178
+ # Add a prefix to VMEngines logs to prevent namespace collisions,
179
+ # and also escape the log name.
180
+ log_name = CGI::escape(@running_on_managed_vm ?
181
+ "#{APPENGINE_SERVICE}/#{tag}" : tag)
182
+ url = ('https://www.googleapis.com/logging/v1beta/projects/' +
183
+ "#{@project_id}/logs/#{log_name}/entries:write")
184
+ begin
185
+ client = api_client()
186
+ request = client.generate_request({
187
+ :uri => url,
188
+ :body_object => write_log_entries_request,
189
+ :http_method => 'POST',
190
+ :authenticated => true
191
+ })
192
+ client.execute!(request)
193
+ # Allow most exceptions to propagate, which will cause fluentd to
194
+ # retry (with backoff). However, most ClientErrors indicate a problem
195
+ # with the request itself and should not be retried - the exception
196
+ # is 'Invalid Credentials' which we can retry.
197
+ rescue Google::APIClient::ClientError => error
198
+ if (error.message == 'Invalid Credentials')
199
+ raise error
200
+ end
201
+ dropped = write_log_entries_request['entries'].length
202
+ $log.warn "Dropping #{dropped} log message(s)",
203
+ :error_class=>error.class.to_s, :error=>error.to_s
204
+ end
205
+ end
206
+ end
207
+
208
+ private
209
+
210
+ def fetch_metadata(metadata_path)
211
+ open('http://metadata/computeMetadata/v1/' + metadata_path,
212
+ {'Metadata-Flavor' => 'Google'}) do |f|
213
+ f.read
214
+ end
215
+ end
216
+
217
+ def init_api_client
218
+ @client = Google::APIClient.new(
219
+ :application_name => 'Fluentd Google Cloud Logging plugin',
220
+ :application_version => '0.1.1',
221
+ :retries => 1)
222
+
223
+ if @auth_method == 'private_key'
224
+ key = Google::APIClient::PKCS12.load_key(@private_key_path,
225
+ @private_key_passphrase)
226
+ jwt_asserter = Google::APIClient::JWTAsserter.new(
227
+ @private_key_email, 'https://www.googleapis.com/auth/logging.write',
228
+ key)
229
+ @client.authorization = jwt_asserter.to_authorization
230
+ @client.authorization.expiry = 3600 # 3600s is the max allowed value
231
+ else
232
+ @client.authorization = Google::APIClient::ComputeServiceAccount.new
233
+ end
234
+ end
235
+
236
+ def api_client
237
+ if !@client.authorization.expired?
238
+ @client.authorization.fetch_access_token!
239
+ end
240
+ return @client
241
+ end
242
+ end
243
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,42 @@
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'rubygems'
16
+ require 'bundler'
17
+ begin
18
+ Bundler.setup(:default, :development)
19
+ rescue Bundler::BundlerError => e
20
+ $stderr.puts e.message
21
+ $stderr.puts "Run `bundle install` to install missing gems"
22
+ exit e.status_code
23
+ end
24
+ require 'test/unit'
25
+
26
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
27
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
28
+ require 'fluent/test'
29
+ unless ENV.has_key?('VERBOSE')
30
+ nulllogger = Object.new
31
+ nulllogger.instance_eval {|obj|
32
+ def method_missing(method, *args)
33
+ # pass
34
+ end
35
+ }
36
+ $log = nulllogger
37
+ end
38
+
39
+ require 'fluent/plugin/out_google_cloud'
40
+
41
+ class Test::Unit::TestCase
42
+ end
@@ -0,0 +1,349 @@
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'helper'
16
+ require 'json'
17
+ require 'webmock/test_unit'
18
+
19
+ class GoogleCloudOutputTest < Test::Unit::TestCase
20
+ def setup
21
+ Fluent::Test.setup
22
+
23
+ # Create stubs for all the GCE metadata lookups the agent needs to make.
24
+ stub_metadata_request('project/project-id', PROJECT_ID)
25
+ stub_metadata_request('instance/zone', FULLY_QUALIFIED_ZONE)
26
+ stub_metadata_request('instance/id', VM_ID)
27
+ stub_metadata_request('instance/attributes/',
28
+ "attribute1\nattribute2\nattribute3")
29
+
30
+ stub_request(:post, 'https://accounts.google.com/o/oauth2/token').
31
+ with(:body => hash_including({:grant_type => AUTH_GRANT_TYPE})).
32
+ to_return(:body => "{\"access_token\": \"#{FAKE_AUTH_TOKEN}\"}",
33
+ :status => 200,
34
+ :headers => {'Content-Length' => FAKE_AUTH_TOKEN})
35
+
36
+ @logs_sent = []
37
+ end
38
+
39
+ def setup_logging_stubs
40
+ [COMPUTE_PARAMS, VMENGINE_PARAMS].each do |params|
41
+ stub_request(:post, uri_for_log(params)).to_return do |request|
42
+ @logs_sent << JSON.parse(request.body)
43
+ {:body => ''}
44
+ end
45
+ end
46
+ end
47
+
48
+ PROJECT_ID = 'test-project-id'
49
+ ZONE = 'us-central1-b'
50
+ FULLY_QUALIFIED_ZONE = 'projects/' + PROJECT_ID + '/zones/' + ZONE
51
+ VM_ID = '9876543210'
52
+
53
+ MANAGED_VM_BACKEND_NAME = 'default'
54
+ MANAGED_VM_BACKEND_VERSION = 'guestbook2.0'
55
+
56
+ AUTH_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
57
+ FAKE_AUTH_TOKEN = 'abc123'
58
+
59
+ COMPUTE_ENGINE_SERVICE_ACCOUNT_CONFIG = %[
60
+ ]
61
+
62
+ PRIVATE_KEY_CONFIG = %[
63
+ auth_method private_key
64
+ private_key_email 271661262351-ft99kc9kjro9rrihq3k2n3s2inbplu0q@developer.gserviceaccount.com
65
+ private_key_path test/plugin/data/c31e573fd7f62ed495c9ca3821a5a85cb036dee1-privatekey.p12
66
+ ]
67
+
68
+ INVALID_CONFIG1 = %[
69
+ auth_method private_key
70
+ private_key_email nobody@example.com
71
+ ]
72
+ INVALID_CONFIG2 = %[
73
+ auth_method private_key
74
+ private_key_path /fake/path/to/key
75
+ ]
76
+ INVALID_CONFIG3 = %[
77
+ auth_method service_account
78
+ ]
79
+
80
+ COMPUTE_SERVICE_NAME = 'compute.googleapis.com'
81
+ APPENGINE_SERVICE_NAME = 'appengine.googleapis.com'
82
+
83
+ COMPUTE_PARAMS = {
84
+ 'service_name' => COMPUTE_SERVICE_NAME,
85
+ 'log_name' => 'test',
86
+ 'labels' => {
87
+ "#{COMPUTE_SERVICE_NAME}/resource_type" => ['strValue', 'instance'],
88
+ "#{COMPUTE_SERVICE_NAME}/resource_id" => ['strValue', VM_ID]
89
+ }
90
+ }
91
+
92
+ VMENGINE_PARAMS = {
93
+ 'service_name' => APPENGINE_SERVICE_NAME,
94
+ 'log_name' => "#{APPENGINE_SERVICE_NAME}%2Ftest",
95
+ 'labels' => {
96
+ "#{APPENGINE_SERVICE_NAME}/module_id" => [
97
+ 'strValue', MANAGED_VM_BACKEND_NAME],
98
+ "#{APPENGINE_SERVICE_NAME}/version_id" => [
99
+ 'strValue', MANAGED_VM_BACKEND_VERSION],
100
+ "#{COMPUTE_SERVICE_NAME}/resource_type" => ['strValue', 'instance'],
101
+ "#{COMPUTE_SERVICE_NAME}/resource_id" => ['strValue', VM_ID]
102
+ }
103
+ }
104
+
105
+ def create_driver(conf=PRIVATE_KEY_CONFIG)
106
+ Fluent::Test::BufferedOutputTestDriver.new(
107
+ Fluent::GoogleCloudOutput).configure(conf)
108
+ end
109
+
110
+ def test_configure_service_account
111
+ d = create_driver(COMPUTE_ENGINE_SERVICE_ACCOUNT_CONFIG)
112
+ assert_equal 'compute_engine_service_account', d.instance.auth_method
113
+ end
114
+
115
+ def test_configure_service_account
116
+ d = create_driver(PRIVATE_KEY_CONFIG)
117
+ assert_equal 'private_key', d.instance.auth_method
118
+ end
119
+
120
+ def test_configure_invalid_configs
121
+ begin
122
+ d = create_driver(INVALID_CONFIG1)
123
+ assert_false
124
+ rescue Fluent::ConfigError => error
125
+ assert error.message.include? 'private_key_path'
126
+ end
127
+ begin
128
+ d = create_driver(INVALID_CONFIG2)
129
+ assert_false
130
+ rescue Fluent::ConfigError => error
131
+ assert error.message.include? 'private_key_email'
132
+ end
133
+ begin
134
+ d = create_driver(INVALID_CONFIG3)
135
+ assert_false
136
+ rescue Fluent::ConfigError => error
137
+ assert error.message.include? 'auth_method'
138
+ end
139
+ end
140
+
141
+ def test_metadata_loading
142
+ d = create_driver(PRIVATE_KEY_CONFIG)
143
+ d.run
144
+ assert_equal PROJECT_ID, d.instance.project_id
145
+ assert_equal ZONE, d.instance.zone
146
+ assert_equal VM_ID, d.instance.vm_id
147
+ assert_equal false, d.instance.running_on_managed_vm
148
+ end
149
+
150
+ def test_managed_vm_metadata_loading
151
+ setup_managed_vm_metadata_stubs
152
+ d = create_driver(PRIVATE_KEY_CONFIG)
153
+ d.run
154
+ assert_equal PROJECT_ID, d.instance.project_id
155
+ assert_equal ZONE, d.instance.zone
156
+ assert_equal VM_ID, d.instance.vm_id
157
+ assert_equal true, d.instance.running_on_managed_vm
158
+ assert_equal MANAGED_VM_BACKEND_NAME, d.instance.gae_backend_name
159
+ assert_equal MANAGED_VM_BACKEND_VERSION, d.instance.gae_backend_version
160
+ end
161
+
162
+ def test_one_log
163
+ setup_logging_stubs
164
+ d = create_driver(PRIVATE_KEY_CONFIG)
165
+ d.emit({'message' => log_entry(0)})
166
+ d.run
167
+ verify_log_entries(1, COMPUTE_PARAMS)
168
+ end
169
+
170
+ def test_timestamps
171
+ setup_logging_stubs
172
+ d = create_driver(PRIVATE_KEY_CONFIG)
173
+ expected_ts = []
174
+ emit_index = 0
175
+ [Time.at(123456.789), Time.at(0), Time.now].each do |ts|
176
+ # Test both the "native" fluentd timestamp and timeNanos.
177
+ d.emit({'message' => log_entry(emit_index)}, ts.to_f)
178
+ # The native timestamp currently only supports second granularity
179
+ # (fluentd issue #461), so strip nanoseconds from the expected value.
180
+ expected_ts.push(Time.at(ts.tv_sec))
181
+ emit_index += 1
182
+ d.emit({'message' => log_entry(emit_index),
183
+ 'timeNanos' => ts.tv_sec * 1000000000 + ts.tv_nsec})
184
+ expected_ts.push(ts)
185
+ emit_index += 1
186
+ end
187
+ d.run
188
+ verify_index = 0
189
+ verify_log_entries(emit_index, COMPUTE_PARAMS) do |entry|
190
+ assert_equal expected_ts[verify_index].tv_sec,
191
+ entry['metadata']['timestamp']['seconds'], entry
192
+ assert_equal expected_ts[verify_index].tv_nsec,
193
+ entry['metadata']['timestamp']['nanos'], entry
194
+ verify_index += 1
195
+ end
196
+ end
197
+
198
+ def test_multiple_logs
199
+ setup_logging_stubs
200
+ d = create_driver(PRIVATE_KEY_CONFIG)
201
+ # Only test a few values because otherwise the test can take minutes.
202
+ [2, 3, 5, 11, 50].each do |n|
203
+ # The test driver doesn't clear its buffer of entries after running, so
204
+ # do it manually here.
205
+ d.instance_variable_get('@entries').clear
206
+ @logs_sent = []
207
+ n.times { |i| d.emit({'message' => log_entry(i)}) }
208
+ d.run
209
+ verify_log_entries(n, COMPUTE_PARAMS)
210
+ end
211
+ end
212
+
213
+ def test_client_error
214
+ # The API Client should not retry this and the plugin should consume
215
+ # the exception.
216
+ # Note that the current release of the API client (0.7-1) does actually
217
+ # retry the request; this appears to be due to a bug which has since been
218
+ # fixed but not released (see below).
219
+ stub_request(:post, uri_for_log(COMPUTE_PARAMS)).to_return(
220
+ :status => 400, :body => "Bad Request")
221
+ d = create_driver(PRIVATE_KEY_CONFIG)
222
+ d.emit({'message' => log_entry(0)})
223
+ d.run
224
+ # TODO(salty) times should be 1, change it when the API client is fixed.
225
+ assert_requested(:post, uri_for_log(COMPUTE_PARAMS), :times => 2)
226
+ end
227
+
228
+ def test_client_error_invalid_credentials
229
+ # we expect this to retry once, then throw the error.
230
+ stub_request(:post, uri_for_log(COMPUTE_PARAMS)).to_return(
231
+ :status => 401, :body => "Invalid Credentials")
232
+ d = create_driver(PRIVATE_KEY_CONFIG)
233
+ d.emit({'message' => log_entry(0)})
234
+ exception_count = 0
235
+ begin
236
+ d.run
237
+ rescue Google::APIClient::ClientError => error
238
+ assert_equal 'Invalid Credentials', error.message
239
+ exception_count += 1
240
+ end
241
+ assert_requested(:post, uri_for_log(COMPUTE_PARAMS), :times => 2)
242
+ assert_equal 1, exception_count
243
+ end
244
+
245
+ def test_server_error
246
+ # The API client should retry this once, then throw an exception which
247
+ # gets propagated through the plugin.
248
+ stub_request(:post, uri_for_log(COMPUTE_PARAMS)).to_return(
249
+ :status => 500, :body => "Server Error")
250
+ d = create_driver(PRIVATE_KEY_CONFIG)
251
+ d.emit({'message' => log_entry(0)})
252
+ exception_count = 0
253
+ begin
254
+ d.run
255
+ rescue Google::APIClient::ServerError => error
256
+ assert_equal 'Server Error', error.message
257
+ exception_count += 1
258
+ end
259
+ assert_requested(:post, uri_for_log(COMPUTE_PARAMS), :times => 2)
260
+ assert_equal 1, exception_count
261
+ end
262
+
263
+ def test_one_managed_vm_log
264
+ setup_managed_vm_metadata_stubs
265
+ setup_logging_stubs
266
+ d = create_driver(PRIVATE_KEY_CONFIG)
267
+ d.emit({'message' => log_entry(0)})
268
+ d.run
269
+ verify_log_entries(1, VMENGINE_PARAMS)
270
+ end
271
+
272
+ def test_multiple_managed_vm_logs
273
+ setup_managed_vm_metadata_stubs
274
+ setup_logging_stubs
275
+ d = create_driver(PRIVATE_KEY_CONFIG)
276
+ [2, 3, 5, 11, 50].each do |n|
277
+ # The test driver doesn't clear its buffer of entries after running, so
278
+ # do it manually here.
279
+ d.instance_variable_get('@entries').clear
280
+ @logs_sent = []
281
+ n.times { |i| d.emit({'message' => log_entry(i)}) }
282
+ d.run
283
+ verify_log_entries(n, VMENGINE_PARAMS)
284
+ end
285
+ end
286
+
287
+ private
288
+
289
+ def uri_for_log(config)
290
+ 'https://www.googleapis.com/logging/v1beta/projects/' + PROJECT_ID +
291
+ '/logs/' + config['log_name'] + '/entries:write'
292
+ end
293
+
294
+ def stub_metadata_request(metadata_path, response_body)
295
+ stub_request(:get, 'http://metadata/computeMetadata/v1/' + metadata_path).
296
+ to_return(:body => response_body, :status => 200,
297
+ :headers => {'Content-Length' => response_body.length})
298
+ end
299
+
300
+ def setup_managed_vm_metadata_stubs
301
+ stub_metadata_request(
302
+ 'instance/attributes/',
303
+ "attribute1\ngae_backend_name\ngae_backend_version\nlast_attribute")
304
+ stub_metadata_request('instance/attributes/gae_backend_name', 'default')
305
+ stub_metadata_request('instance/attributes/gae_backend_version',
306
+ 'guestbook2.0')
307
+ end
308
+
309
+ def log_entry(i)
310
+ 'test log entry ' + i.to_s
311
+ end
312
+
313
+ def check_labels(entry, common_labels, expected_labels)
314
+ # TODO(salty) test/handle overlap between common_labels and entry labels
315
+ all_labels = common_labels.to_a + entry['metadata']['labels'].to_a
316
+ all_labels.each do |label|
317
+ key = label['key']
318
+ assert expected_labels.has_key?(key), "Unexpected label #{label}"
319
+ expected_type = expected_labels[key][0]
320
+ expected_value = expected_labels[key][1]
321
+ assert label.has_key?(expected_type),
322
+ "Type mismatch - expected #{expected_type} in #{label}"
323
+ assert_equal label[expected_type], expected_value,
324
+ "Value mismatch - expected #{expected_value} in #{label}"
325
+ end
326
+ assert_equal expected_labels.length, all_labels.length,
327
+ ("Expected #{expected_labels.length} labels, got " +
328
+ "#{all_labels.length}")
329
+ end
330
+
331
+ # The caller can optionally provide a block which is called for each entry.
332
+ def verify_log_entries(n, params)
333
+ i = 0
334
+ @logs_sent.each do |batch|
335
+ batch['entries'].each do |entry|
336
+ assert_equal "test log entry #{i}", entry['textPayload'], batch
337
+ assert_equal ZONE, entry['metadata']['zone']
338
+ assert_equal params['service_name'], entry['metadata']['serviceName']
339
+ check_labels entry, batch['commonLabels'], params['labels']
340
+ if (block_given?)
341
+ yield(entry)
342
+ end
343
+ i += 1
344
+ assert i <= n, "Number of entries #{i} exceeds expected number #{n}"
345
+ end
346
+ end
347
+ assert i == n, "Number of entries #{i} does not match expected number #{n}"
348
+ end
349
+ end
metadata ADDED
@@ -0,0 +1,126 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fluent-plugin-google-cloud
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Todd Derr
9
+ - Alex Robinson
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2014-11-12 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: fluentd
17
+ requirement: !ruby/object:Gem::Requirement
18
+ none: false
19
+ requirements:
20
+ - - ~>
21
+ - !ruby/object:Gem::Version
22
+ version: '0.10'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ none: false
27
+ requirements:
28
+ - - ~>
29
+ - !ruby/object:Gem::Version
30
+ version: '0.10'
31
+ - !ruby/object:Gem::Dependency
32
+ name: google-api-client
33
+ requirement: !ruby/object:Gem::Requirement
34
+ none: false
35
+ requirements:
36
+ - - ~>
37
+ - !ruby/object:Gem::Version
38
+ version: '0.7'
39
+ type: :runtime
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ none: false
43
+ requirements:
44
+ - - ~>
45
+ - !ruby/object:Gem::Version
46
+ version: '0.7'
47
+ - !ruby/object:Gem::Dependency
48
+ name: rake
49
+ requirement: !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ! '>='
53
+ - !ruby/object:Gem::Version
54
+ version: 10.3.2
55
+ type: :development
56
+ prerelease: false
57
+ version_requirements: !ruby/object:Gem::Requirement
58
+ none: false
59
+ requirements:
60
+ - - ! '>='
61
+ - !ruby/object:Gem::Version
62
+ version: 10.3.2
63
+ - !ruby/object:Gem::Dependency
64
+ name: webmock
65
+ requirement: !ruby/object:Gem::Requirement
66
+ none: false
67
+ requirements:
68
+ - - ! '>='
69
+ - !ruby/object:Gem::Version
70
+ version: 1.17.0
71
+ type: :development
72
+ prerelease: false
73
+ version_requirements: !ruby/object:Gem::Requirement
74
+ none: false
75
+ requirements:
76
+ - - ! '>='
77
+ - !ruby/object:Gem::Version
78
+ version: 1.17.0
79
+ description: Fluentd plugin to stream logs to the Google Cloud Platform's logs API,
80
+ which will make them viewable in the Developer Console's log viewer and can optionally
81
+ store them in Google Cloud Storage and/or BigQuery. This is an official Google Ruby
82
+ gem.
83
+ email:
84
+ - salty@google.com
85
+ executables: []
86
+ extensions: []
87
+ extra_rdoc_files: []
88
+ files:
89
+ - test/helper.rb
90
+ - test/plugin/data/c31e573fd7f62ed495c9ca3821a5a85cb036dee1-privatekey.p12
91
+ - test/plugin/test_out_google_cloud.rb
92
+ - LICENSE
93
+ - Rakefile
94
+ - fluent-plugin-google-cloud.gemspec
95
+ - lib/fluent/plugin/out_google_cloud.rb
96
+ - Gemfile
97
+ - README.rdoc
98
+ homepage: https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud
99
+ licenses:
100
+ - Apache 2.0
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ none: false
107
+ requirements:
108
+ - - ! '>='
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ required_rubygems_version: !ruby/object:Gem::Requirement
112
+ none: false
113
+ requirements:
114
+ - - ! '>='
115
+ - !ruby/object:Gem::Version
116
+ version: '0'
117
+ requirements: []
118
+ rubyforge_project:
119
+ rubygems_version: 1.8.23
120
+ signing_key:
121
+ specification_version: 3
122
+ summary: Fluentd plugin to stream logs to the Google Cloud Platform's logs API
123
+ test_files:
124
+ - test/helper.rb
125
+ - test/plugin/data/c31e573fd7f62ed495c9ca3821a5a85cb036dee1-privatekey.p12
126
+ - test/plugin/test_out_google_cloud.rb