Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d546033

Browse files
author
Gimi Liang
committedFeb 15, 2018
Initial commit.
1 parent f961e40 commit d546033

28 files changed

+5562
-1
lines changed
 

‎.gitignore

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
/.bundle/
2+
/.yardoc
3+
/_yardoc/
4+
/coverage/
5+
/doc/
6+
/pkg/
7+
/spec/reports/
8+
/tmp/
9+
*.gem

‎.travis.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
language: ruby
2+
rvm:
3+
- 2.5
4+
- 2.4
5+
- 2.3

‎CODE_OF_CONDUCT.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Contributor Covenant Code of Conduct
2+
3+
## Our Pledge
4+
5+
In the interest of fostering an open and welcoming environment, we as
6+
contributors and maintainers pledge to making participation in our project and
7+
our community a harassment-free experience for everyone, regardless of age, body
8+
size, disability, ethnicity, gender identity and expression, level of experience,
9+
nationality, personal appearance, race, religion, or sexual identity and
10+
orientation.
11+
12+
## Our Standards
13+
14+
Examples of behavior that contributes to creating a positive environment
15+
include:
16+
17+
* Using welcoming and inclusive language
18+
* Being respectful of differing viewpoints and experiences
19+
* Gracefully accepting constructive criticism
20+
* Focusing on what is best for the community
21+
* Showing empathy towards other community members
22+
23+
Examples of unacceptable behavior by participants include:
24+
25+
* The use of sexualized language or imagery and unwelcome sexual attention or
26+
advances
27+
* Trolling, insulting/derogatory comments, and personal or political attacks
28+
* Public or private harassment
29+
* Publishing others' private information, such as a physical or electronic
30+
address, without explicit permission
31+
* Other conduct which could reasonably be considered inappropriate in a
32+
professional setting
33+
34+
## Our Responsibilities
35+
36+
Project maintainers are responsible for clarifying the standards of acceptable
37+
behavior and are expected to take appropriate and fair corrective action in
38+
response to any instances of unacceptable behavior.
39+
40+
Project maintainers have the right and responsibility to remove, edit, or
41+
reject comments, commits, code, wiki edits, issues, and other contributions
42+
that are not aligned to this Code of Conduct, or to ban temporarily or
43+
permanently any contributor for other behaviors that they deem inappropriate,
44+
threatening, offensive, or harmful.
45+
46+
## Scope
47+
48+
This Code of Conduct applies both within project spaces and in public spaces
49+
when an individual is representing the project or its community. Examples of
50+
representing a project or community include using an official project e-mail
51+
address, posting via an official social media account, or acting as an appointed
52+
representative at an online or offline event. Representation of a project may be
53+
further defined and clarified by project maintainers.
54+
55+
## Enforcement
56+
57+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
58+
reported by contacting the project team at zliang@splunk.com. All
59+
complaints will be reviewed and investigated and will result in a response that
60+
is deemed necessary and appropriate to the circumstances. The project team is
61+
obligated to maintain confidentiality with regard to the reporter of an incident.
62+
Further details of specific enforcement policies may be posted separately.
63+
64+
Project maintainers who do not follow or enforce the Code of Conduct in good
65+
faith may face temporary or permanent repercussions as determined by other
66+
members of the project's leadership.
67+
68+
## Attribution
69+
70+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71+
available at [http://contributor-covenant.org/version/1/4][version]
72+
73+
[homepage]: http://contributor-covenant.org
74+
[version]: http://contributor-covenant.org/version/1/4/

‎Gemfile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
source "https://rubygems.org"
2+
3+
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4+
5+
# Specify your gem's dependencies in fluent-plugin-kubernetes_objects_input.gemspec
6+
gemspec

‎Gemfile.lock

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
PATH
2+
remote: .
3+
specs:
4+
fluent-plugin-kubernetes-objects (1.0.0.pre.alpha.1)
5+
fluentd (~> 1.0)
6+
kubeclient (~> 3.0)
7+
8+
GEM
9+
remote: https://rubygems.org/
10+
specs:
11+
addressable (2.5.2)
12+
public_suffix (>= 2.0.2, < 4.0)
13+
cool.io (1.5.3)
14+
crack (0.4.3)
15+
safe_yaml (~> 1.0.0)
16+
dig_rb (1.0.1)
17+
domain_name (0.5.20170404)
18+
unf (>= 0.0.5, < 1.0.0)
19+
fluentd (1.1.0)
20+
cool.io (>= 1.4.5, < 2.0.0)
21+
dig_rb (~> 1.0.0)
22+
http_parser.rb (>= 0.5.1, < 0.7.0)
23+
msgpack (>= 0.7.0, < 2.0.0)
24+
serverengine (>= 2.0.4, < 3.0.0)
25+
sigdump (~> 0.2.2)
26+
strptime (>= 0.2.2, < 1.0.0)
27+
tzinfo (~> 1.0)
28+
tzinfo-data (~> 1.0)
29+
yajl-ruby (~> 1.0)
30+
hashdiff (0.3.7)
31+
http (2.2.2)
32+
addressable (~> 2.3)
33+
http-cookie (~> 1.0)
34+
http-form_data (~> 1.0.1)
35+
http_parser.rb (~> 0.6.0)
36+
http-cookie (1.0.3)
37+
domain_name (~> 0.5)
38+
http-form_data (1.0.3)
39+
http_parser.rb (0.6.0)
40+
kubeclient (3.0.0)
41+
http (~> 2.2.2)
42+
recursive-open-struct (~> 1.0.4)
43+
rest-client (~> 2.0)
44+
mime-types (3.1)
45+
mime-types-data (~> 3.2015)
46+
mime-types-data (3.2016.0521)
47+
minitest (5.11.3)
48+
msgpack (1.2.2)
49+
netrc (0.11.0)
50+
power_assert (1.1.1)
51+
public_suffix (3.0.2)
52+
rake (10.5.0)
53+
recursive-open-struct (1.0.5)
54+
rest-client (2.0.2)
55+
http-cookie (>= 1.0.2, < 2.0)
56+
mime-types (>= 1.16, < 4.0)
57+
netrc (~> 0.8)
58+
safe_yaml (1.0.4)
59+
serverengine (2.0.6)
60+
sigdump (~> 0.2.2)
61+
sigdump (0.2.4)
62+
strptime (0.2.3)
63+
test-unit (3.2.7)
64+
power_assert
65+
thread_safe (0.3.6)
66+
tzinfo (1.2.5)
67+
thread_safe (~> 0.1)
68+
tzinfo-data (1.2018.3)
69+
tzinfo (>= 1.0.0)
70+
unf (0.1.4)
71+
unf_ext
72+
unf_ext (0.0.7.5)
73+
webmock (3.3.0)
74+
addressable (>= 2.3.6)
75+
crack (>= 0.3.2)
76+
hashdiff
77+
yajl-ruby (1.3.1)
78+
79+
PLATFORMS
80+
ruby
81+
82+
DEPENDENCIES
83+
bundler (~> 1.16)
84+
fluent-plugin-kubernetes-objects!
85+
minitest (~> 5.0)
86+
rake (~> 10.0)
87+
test-unit (~> 3.0)
88+
webmock (~> 3.2)
89+
90+
BUNDLED WITH
91+
1.16.1

‎LICENSE.txt

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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 [2018] [Gimi Liang @ Splunk Inc.]
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.

‎README.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,43 @@
11
# fluent-plugin-kubernetes-objects
2-
This is the Fluentd input plugin which queries Kubernetes API to collect Kubernetes objects (like Nodes, Namespaces, Pods, etc.)
2+
3+
[Fluentd](https://fluentd.org/) input plugin to collect all kinds of objects in a kubernetes cluster.
4+
5+
TODO: write description for your plugin.
6+
7+
## Installation
8+
9+
### RubyGems
10+
11+
```
12+
$ gem install fluent-plugin-kubernetes-objects
13+
```
14+
15+
### Bundler
16+
17+
Add following line to your Gemfile:
18+
19+
```ruby
20+
gem "fluent-plugin-kubernetes-objects"
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 kubernetes_objects
35+
```
36+
37+
You can copy and paste generated documents here.
38+
39+
## Copyright
40+
41+
* Copyright(c) 2018- Gimi Liang @ Splunk Inc.
42+
* License
43+
* Apache License, Version 2.0

‎Rakefile

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
require "bundler/gem_tasks"
2+
require "rake/testtask"
3+
4+
Rake::TestTask.new(:test) do |t|
5+
t.libs << "test"
6+
t.libs << "lib"
7+
t.test_files = FileList["test/**/*_test.rb"]
8+
end
9+
10+
task :default => :test

‎bin/console

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env ruby
2+
3+
require "bundler/setup"
4+
require "fluent/plugin/kubernetes_objects_input"
5+
6+
# You can add fixtures and/or initialization code here to make experimenting
7+
# with your gem easier. You can also use a different console, if you like.
8+
9+
# (If you use this, don't forget to add pry to your Gemfile!)
10+
# require "pry"
11+
# Pry.start
12+
13+
require "irb"
14+
IRB.start(__FILE__)

‎bin/setup

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
IFS=$'\n\t'
4+
set -vx
5+
6+
bundle install
7+
8+
# Do any other automated setup that you need to do here
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Gem::Specification.new do |spec|
2+
spec.name = "fluent-plugin-kubernetes-objects"
3+
spec.version = "1.0.0-alpha.1"
4+
spec.authors = ["Gimi Liang"]
5+
spec.email = ["zliang@splunk.com"]
6+
7+
spec.summary = %q{Fluentd plugins for collecting Kubernetes objects.}
8+
spec.description = %q{Fluentd plugins for collecting Kubernetes objects.}
9+
spec.homepage = "https://github.com/splunk/fluent-plugin-kubernetes-objects"
10+
spec.license = "Apache-2.0"
11+
12+
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
13+
# to allow pushing to a single host or delete this section to allow pushing to any host.
14+
if spec.respond_to?(:metadata)
15+
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
16+
else
17+
raise "RubyGems 2.0 or newer is required to protect against " \
18+
"public gem pushes."
19+
end
20+
21+
spec.files = `git ls-files -z`.split("\x0").reject do |f|
22+
f.match(%r{^(test|spec|features)/})
23+
end
24+
spec.bindir = "exe"
25+
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26+
spec.require_paths = ["lib"]
27+
28+
spec.required_ruby_version = '>= 2.3.0'
29+
30+
spec.add_runtime_dependency "fluentd", "~> 1.0"
31+
spec.add_runtime_dependency "kubeclient", "~> 3.0"
32+
33+
spec.add_development_dependency "bundler", "~> 1.16"
34+
spec.add_development_dependency "rake", "~> 10.0"
35+
spec.add_development_dependency "test-unit", "~> 3.0" # required by fluent/test.rb
36+
spec.add_development_dependency "minitest", "~> 5.0"
37+
spec.add_development_dependency "webmock", "~> 3.2"
38+
end
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
require "fluent/plugin/input"
2+
require 'kubeclient'
3+
4+
module Fluent::Plugin
5+
class KubernetesObjectsInput < Fluent::Plugin::Input
6+
VERSION = "1.0.0"
7+
8+
Fluent::Plugin.register_input('kubernetes_objects', self)
9+
10+
helpers :thread
11+
12+
desc 'The tag of the event.'
13+
config_param :tag, :string, default: 'kubernetes.*'
14+
15+
desc 'URL of the kubernetes API.'
16+
config_param :kubernetes_url, :string, default: nil
17+
18+
desc 'Kubernetes API version.'
19+
config_param :api_version, :string, default: 'v1'
20+
21+
desc 'Path to the certificate file for this client.'
22+
config_param :client_cert, :string, default: nil
23+
24+
desc 'Path to the private key file for this client.'
25+
config_param :client_key, :string, default: nil
26+
27+
desc 'Path to the CA file.'
28+
config_param :ca_file, :string, default: nil
29+
30+
desc "If `insecure_ssl` is set to `true`, it won't verify apiserver's certificate."
31+
config_param :insecure_ssl, :bool, default: false
32+
33+
desc 'Path to the file contains the API token. By default it reads from the file "token" in the `secret_dir`.'
34+
config_param :bearer_token_file, :string, default: nil
35+
36+
desc "Path of the location where pod's service account's credentials are stored. Usually you don't need to care about this config, the default value should work in most cases."
37+
config_param :secret_dir, :string, default: '/var/run/secrets/kubernetes.io/serviceaccount'
38+
39+
desc 'Define a resource to pull.'
40+
config_section :pull, required: false, init: false, multi: true, param_name: :pull_objects do
41+
desc 'The name of the resource, e.g. "nodes".'
42+
config_param :resource_name, :string
43+
44+
desc 'The namespace of the resource, it pulls from all namespaces if not set.'
45+
config_param :namespace, :string, default: nil
46+
47+
desc 'A selector to restrict the list of returned objects by labels.'
48+
config_param :label_selector, :string, default: nil
49+
50+
desc 'A selector to restrict the list of returned objects by fields.'
51+
config_param :field_selector, :string, default: nil
52+
53+
desc 'The interval at which the objects will be pulled, default 15m.'
54+
config_param :interval, :time, default: 15 * 60
55+
end
56+
57+
desc 'Define a resource to watch.'
58+
config_section :watch, required: false, init: false, multi: true, param_name: :watch_objects do
59+
desc 'The name of the resource, e.g. "events".'
60+
config_param :resource_name, :string
61+
62+
desc 'The namespace of the resource, it watches all namespaces if not set.'
63+
config_param :namespace, :string, default: nil
64+
65+
desc 'The name of the entity to watch, use this to watch only one entity.'
66+
config_param :entity_name, :string, default: nil
67+
68+
desc 'A selector to restrict the list of returned objects by labels.'
69+
config_param :label_selector, :string, default: nil
70+
71+
desc 'A selector to restrict the list of returned objects by fields.'
72+
config_param :field_selector, :string, default: nil
73+
end
74+
75+
def configure(conf)
76+
super
77+
raise Fluent::ConfigError, "At least one <pull> or <watch> is required, but found none." if @pull_objects.empty? && @watch_objects.empty?
78+
79+
parse_tag
80+
initialize_client
81+
initialize_watchers
82+
end
83+
84+
def start
85+
super
86+
@pull_objects.each(&method(:create_pull_thread))
87+
@watchers.each(&method(:create_watcher_thread))
88+
end
89+
90+
def close
91+
@watchers.each_value &:finish
92+
super
93+
end
94+
95+
private
96+
97+
def parse_tag
98+
@tag_prefix, @tag_suffix = @tag.split('*') if @tag.include?('*')
99+
end
100+
101+
def generate_tag(item_name)
102+
return @tag unless @tag_prefix
103+
104+
[@tag_prefix, item_name, @tag_suffix].join
105+
end
106+
107+
def initialize_client
108+
# mostly borrowed from Fluentd Kubernetes Metadata Filter Plugin
109+
if @kubernetes_url.nil?
110+
# Use Kubernetes default service account if we're in a pod.
111+
env_host = ENV['KUBERNETES_SERVICE_HOST']
112+
env_port = ENV['KUBERNETES_SERVICE_PORT']
113+
@kubernetes_url = "https://#{env_host}:#{env_port}/api" if env_host && env_port
114+
end
115+
116+
raise Fluent::ConfigError, "kubernetes url is not set" unless @kubernetes_url
117+
118+
# Use SSL certificate and bearer token from Kubernetes service account.
119+
if Dir.exist?(@secret_dir)
120+
secret_ca_file = File.join(@secret_dir, 'ca.cert')
121+
secret_token_file = File.join(@secret_dir, 'token')
122+
123+
if @ca_file.nil? and File.exist?(secret_ca_file)
124+
@ca_file = secret_ca_file
125+
end
126+
127+
if @bearer_token_file.nil? and File.exist?(secret_token_file)
128+
@bearer_token_file = secret_token_file
129+
end
130+
end
131+
132+
ssl_options = {
133+
client_cert: @client_cert && OpenSSL::X509::Certificate.new(File.read(@client_cert)),
134+
client_key: @client_key && OpenSSL::PKey::RSA.new(File.read(@client_key)),
135+
ca_file: @ca_file,
136+
verify_ssl: @insecure_ssl ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER
137+
}
138+
139+
auth_options = {}
140+
auth_options[:bearer_token] = File.read(@bearer_token_file) if @bearer_token_file
141+
142+
@client = Kubeclient::Client.new(
143+
@kubernetes_url, @api_version,
144+
ssl_options: ssl_options,
145+
auth_options: auth_options
146+
)
147+
148+
begin
149+
@client.api_valid?
150+
rescue KubeException => kube_error
151+
raise Fluent::ConfigError, "Invalid Kubernetes API #{@api_version} endpoint #{@kubernetes_url}: #{kube_error.message}"
152+
end
153+
end
154+
155+
def initialize_watchers
156+
# TODO use checkpoint (resourceVersion)
157+
@watchers = @watch_objects.inject({}) { |h, o|
158+
o = o.to_h.dup
159+
o[:as] = :raw
160+
resource_name = o.delete(:resource_name)
161+
h[resource_name] = @client.public_send "watch_#{resource_name}", o
162+
h
163+
}
164+
end
165+
166+
def create_pull_thread(conf)
167+
options = conf.to_h.dup
168+
options[:as] = :raw
169+
resource_name = options.delete :resource_name
170+
pull_interval = options.delete :interval
171+
172+
thread_create :"pull_#{resource_name}" do
173+
tag = generate_tag resource_name
174+
while thread_current_running?
175+
log.debug "Going to pull #{resource_name}"
176+
response = @client.public_send "get_#{resource_name}", options
177+
now = Fluent::Engine.now
178+
es = Fluent::MultiEventStream.new
179+
180+
# code copied from kubeclient
181+
# kubeclient will create one open struct object for each item in the response,
182+
# but this is totally unecessary in this plugin, thus we use as: :raw.
183+
result = JSON.parse(response)
184+
185+
resource_version = result.fetch('resourceVersion') {
186+
result.fetch('metadata', {})['resourceVersion']
187+
}
188+
189+
update_op = if resource_version
190+
->(item) { item['metadata'].update requestResourceVersion: resource_version }
191+
else
192+
->(item) {}
193+
end
194+
195+
# result['items'] might be nil due to https://github.com/kubernetes/kubernetes/issues/13096
196+
items = result['items'].to_a
197+
log.debug { "Received #{items.size} #{resource_name}" }
198+
items.each { |item| es.add now, item.tap(&update_op) }
199+
router.emit_stream(tag, es)
200+
201+
sleep(pull_interval)
202+
end
203+
end
204+
end
205+
206+
def create_watcher_thread(object_name, watcher)
207+
thread_create(:"watch_#{object_name}") {
208+
tag = generate_tag object_name
209+
watcher.each { |entity|
210+
log.trace { "Received new object from watching #{object_name}"}
211+
router.emit tag, Fluent::Engine.now, JSON.parse(entity)
212+
}
213+
}
214+
end
215+
end
216+
end

‎test/api.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"kind": "APIVersions",
3+
"versions": ["v1"],
4+
"serverAddressByClientCIDRs": [{
5+
"clientCIDR": "0.0.0.0/0",
6+
"serverAddress": "10.240.255.5:443"
7+
}]
8+
}

‎test/events.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"type":"ADDED","object":{"kind":"Event","apiVersion":"v1","metadata":{"name":"counter.150b2bf03f8963dd","namespace":"default","selfLink":"/api/v1/namespaces/default/events/counter.150b2bf03f8963dd","uid":"e0effe55-fcfa-11e7-95cd-000d3af99127","resourceVersion":"6621683","creationTimestamp":"2018-01-19T09:26:50Z"},"involvedObject":{"kind":"Pod","namespace":"default","name":"counter","uid":"dec534aa-fcfa-11e7-95cd-000d3af99127","apiVersion":"v1","resourceVersion":"6621674","fieldPath":"spec.containers{count}"},"reason":"Created","message":"Created container","source":{"component":"kubelet","host":"k8s-agentpool1-10851795-1"},"firstTimestamp":"2018-01-19T09:26:50Z","lastTimestamp":"2018-01-19T09:26:50Z","count":1,"type":"Normal"}}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
require "test_helper"
2+
3+
describe Fluent::Plugin::KubernetesObjectsInput do
4+
include Fluent::Test::Helpers
5+
include PluginTestHelper
6+
7+
before {
8+
Fluent::Test.setup # setup router and others
9+
stub_k8s_requests
10+
}
11+
12+
it { expect(::Fluent::Plugin::KubernetesObjectsInput::VERSION).wont_be_nil }
13+
14+
it "should require at least one <pull> or <watch> section" do
15+
expect{create_input_driver("kubernetes_url #{k8s_url}")}.must_raise Fluent::ConfigError
16+
expect(create_input_driver(<<~CONF)).wont_be_nil
17+
kubernetes_url #{k8s_url}
18+
<pull>
19+
resource_name nodes
20+
</pull>
21+
CONF
22+
expect(create_input_driver(<<~CONF)).wont_be_nil
23+
kubernetes_url #{k8s_url}
24+
<watch>
25+
resource_name nodes
26+
</watch>
27+
CONF
28+
end
29+
30+
describe "config: kubernetes_url" do
31+
it "should read from environment variables by default" do
32+
ENV['KUBERNETES_SERVICE_HOST'] = k8s_host
33+
ENV['KUBERNETES_SERVICE_PORT'] = k8s_port
34+
expect(create_input_driver(<<~CONF).instance.kubernetes_url).must_equal k8s_url
35+
<pull>
36+
resource_name nodes
37+
</pull>
38+
CONF
39+
end
40+
41+
it "should panic if not set" do
42+
ENV['KUBERNETES_SERVICE_HOST'] = nil
43+
ENV['KUBERNETES_SERVICE_PORT'] = nil
44+
expect{ create_input_driver(<<~CONF) }.must_raise Fluent::ConfigError
45+
<pull>
46+
resource_name nodes
47+
</pull>
48+
CONF
49+
end
50+
end
51+
52+
describe "emit events" do
53+
it "can pull one resource" do
54+
d = create_input_driver(<<~CONF)
55+
kubernetes_url #{k8s_url}
56+
<pull>
57+
resource_name nodes
58+
</pull>
59+
CONF
60+
61+
d.run expect_emits: 1, timeout: 3
62+
events = d.events
63+
64+
expect(events[0][0]).must_equal 'kubernetes.nodes'
65+
end
66+
67+
it "can pull multiple resources" do
68+
d = create_input_driver(<<~CONF)
69+
kubernetes_url #{k8s_url}
70+
<pull>
71+
resource_name namespaces
72+
</pull>
73+
<pull>
74+
resource_name pods
75+
</pull>
76+
CONF
77+
78+
d.run expect_emits: 2, timeout: 3
79+
events = d.events
80+
81+
expect(events.any? { |e| e[0] == 'kubernetes.pods'}).must_equal true
82+
expect(events.any? { |e| e[0] == 'kubernetes.namespaces'}).must_equal true
83+
end
84+
85+
it "can watch resources" do
86+
d = create_input_driver(<<~CONF)
87+
kubernetes_url #{k8s_url}
88+
<watch>
89+
resource_name events
90+
</watch>
91+
CONF
92+
93+
d.run expect_emits: 1, timeout: 3
94+
events = d.events
95+
expect(events.all? { |e| e[0] == 'kubernetes.events'}).must_equal true
96+
end
97+
end
98+
end

‎test/lib/no_webmock/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
There are two reasons why we stub out all these webmock adapter:
2+
* Requiring 'http' (by the http_rb_adapter) will trigger a circle require warning (http/client <-> http/connection)
3+
* We only need mocking the standard library `net/http`, and we don't want to load a bunch of not used libraries.

‎test/lib/no_webmock/http_lib_adapters/curb_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/em_http_request_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/excon_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/httpclient_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/manticore_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/patron_adapter.rb

Whitespace-only changes.

‎test/lib/no_webmock/http_lib_adapters/typhoeus_hydra_adapter.rb

Whitespace-only changes.

‎test/namespaces.json

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
{
2+
"kind": "NamespaceList",
3+
"apiVersion": "v1",
4+
"metadata": {
5+
"selfLink": "/api/v1/namespaces",
6+
"resourceVersion": "6619676"
7+
},
8+
"items": [
9+
{
10+
"metadata": {
11+
"name": "default",
12+
"selfLink": "/api/v1/namespaces/default",
13+
"uid": "0731343c-d150-11e7-854f-000d3af99127",
14+
"resourceVersion": "6",
15+
"creationTimestamp": "2017-11-24T19:45:30Z"
16+
},
17+
"spec": {
18+
"finalizers": [
19+
"kubernetes"
20+
]
21+
},
22+
"status": {
23+
"phase": "Active"
24+
}
25+
},
26+
{
27+
"metadata": {
28+
"name": "kube-public",
29+
"selfLink": "/api/v1/namespaces/kube-public",
30+
"uid": "0742cba1-d150-11e7-854f-000d3af99127",
31+
"resourceVersion": "27",
32+
"creationTimestamp": "2017-11-24T19:45:30Z"
33+
},
34+
"spec": {
35+
"finalizers": [
36+
"kubernetes"
37+
]
38+
},
39+
"status": {
40+
"phase": "Active"
41+
}
42+
},
43+
{
44+
"metadata": {
45+
"name": "kube-system",
46+
"selfLink": "/api/v1/namespaces/kube-system",
47+
"uid": "073eb4de-d150-11e7-854f-000d3af99127",
48+
"resourceVersion": "58",
49+
"creationTimestamp": "2017-11-24T19:45:30Z",
50+
"annotations": {
51+
"kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"annotations\":{},\"name\":\"kube-system\",\"namespace\":\"\"}}\n"
52+
}
53+
},
54+
"spec": {
55+
"finalizers": [
56+
"kubernetes"
57+
]
58+
},
59+
"status": {
60+
"phase": "Active"
61+
}
62+
}
63+
]
64+
}

‎test/nodes.json

Lines changed: 1615 additions & 0 deletions
Large diffs are not rendered by default.

‎test/pods.json

Lines changed: 2484 additions & 0 deletions
Large diffs are not rendered by default.

‎test/test_helper.rb

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
2+
#$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
3+
4+
# suppress warning, when require the 'http' library, it shows circle require warnning,
5+
# which is pretty annoying (kubeclient depends on http for watch_stream)
6+
_verbose = $VERBOSE
7+
$VERBOSE = nil
8+
require "fluent/plugin/in_kubernetes_objects"
9+
$VERBOSE = _verbose
10+
11+
require "fluent/test"
12+
require "fluent/test/driver/input"
13+
require "fluent/test/helpers"
14+
require "minitest/autorun"
15+
require "webmock/minitest"
16+
17+
# make assertions from webmock available in minitest/spec
18+
module Minitest::Expectations
19+
infect_an_assertion :assert_requested, :must_be_requested, :reverse
20+
infect_an_assertion :assert_not_requested, :wont_be_requested, :reverse
21+
end
22+
23+
module PluginTestHelper
24+
def k8s_host() "127.0.0.1" end
25+
def k8s_port() "8001" end
26+
def k8s_url() "https://#{k8s_host}:#{k8s_port}/api" end
27+
28+
def fluentd_conf_for(*lines)
29+
basic_config = [
30+
]
31+
(basic_config + lines).join("\n")
32+
end
33+
34+
def create_input_driver(*configs)
35+
Fluent::Test::Driver::Input.new(Fluent::Plugin::KubernetesObjectsInput).tap { |d|
36+
d.configure(fluentd_conf_for(*configs))
37+
}
38+
end
39+
40+
def stub_k8s_requests
41+
# all stub response bodies are from real k8s 1.8 API calls
42+
stub_k8s_api
43+
stub_k8s_v1
44+
stub_k8s_namespaces
45+
stub_k8s_nodes
46+
stub_k8s_pods
47+
stub_k8s_events
48+
end
49+
50+
def stub_k8s_api
51+
open(File.expand_path('../api.json', __FILE__)).tap { |f|
52+
stub_request(:get, k8s_url).to_return(body: f.read)
53+
}.close
54+
end
55+
56+
def stub_k8s_v1
57+
open(File.expand_path('../v1.json', __FILE__)).tap { |f|
58+
stub_request(:get, "#{k8s_url}/v1").to_return(body: f.read)
59+
}.close
60+
end
61+
62+
def stub_k8s_namespaces
63+
open(File.expand_path('../namespaces.json', __FILE__)).tap { |f|
64+
stub_request(:get, "#{k8s_url}/v1/namespaces").to_return(body: f.read())
65+
}.close
66+
end
67+
68+
def stub_k8s_nodes
69+
open(File.expand_path('../nodes.json', __FILE__)).tap { |f|
70+
stub_request(:get, "#{k8s_url}/v1/nodes").to_return(body: f.read())
71+
}.close
72+
end
73+
74+
def stub_k8s_pods
75+
open(File.expand_path('../pods.json', __FILE__)).tap { |f|
76+
stub_request(:get, "#{k8s_url}/v1/pods").to_return(body: f.read())
77+
}.close
78+
end
79+
80+
def stub_k8s_events
81+
open(File.expand_path('../events.json', __FILE__)).tap { |f|
82+
stub_request(:get, "#{k8s_url}/v1/watch/events").
83+
to_return(body: f.read(), headers: {"Content-Type" => "application/json", "Transfer-Encoding" => "chunked"})
84+
}.close
85+
end
86+
end

‎test/v1.json

Lines changed: 488 additions & 0 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)
Please sign in to comment.