logstash-output-swift 0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +2 -0
  3. data/CONTRIBUTORS +22 -0
  4. data/DEVELOPER.md +15 -0
  5. data/Gemfile +11 -0
  6. data/LICENSE +201 -0
  7. data/NOTICE.TXT +2 -0
  8. data/README.md +38 -0
  9. data/lib/logstash/outputs/swift.rb +360 -0
  10. data/lib/logstash/outputs/swift/file_repository.rb +121 -0
  11. data/lib/logstash/outputs/swift/path_validator.rb +18 -0
  12. data/lib/logstash/outputs/swift/size_and_time_rotation_policy.rb +24 -0
  13. data/lib/logstash/outputs/swift/size_rotation_policy.rb +26 -0
  14. data/lib/logstash/outputs/swift/temporary_file.rb +71 -0
  15. data/lib/logstash/outputs/swift/temporary_file_factory.rb +129 -0
  16. data/lib/logstash/outputs/swift/time_rotation_policy.rb +26 -0
  17. data/lib/logstash/outputs/swift/uploader.rb +64 -0
  18. data/lib/logstash/outputs/swift/writable_directory_validator.rb +17 -0
  19. data/lib/logstash/outputs/swift/write_container_permission_validator.rb +52 -0
  20. data/logstash-output-swift.gemspec +28 -0
  21. data/spec/integration/dynamic_prefix_spec.rb +92 -0
  22. data/spec/integration/gzip_file_spec.rb +62 -0
  23. data/spec/integration/gzip_size_rotation_spec.rb +63 -0
  24. data/spec/integration/restore_from_crash_spec.rb +39 -0
  25. data/spec/integration/size_rotation_spec.rb +59 -0
  26. data/spec/integration/stress_test_spec.rb +60 -0
  27. data/spec/integration/time_based_rotation_with_constant_write_spec.rb +60 -0
  28. data/spec/integration/time_based_rotation_with_stale_write_spec.rb +64 -0
  29. data/spec/integration/upload_current_file_on_shutdown_spec.rb +51 -0
  30. data/spec/outputs/swift/file_repository_spec.rb +143 -0
  31. data/spec/outputs/swift/size_and_time_rotation_policy_spec.rb +77 -0
  32. data/spec/outputs/swift/size_rotation_policy_spec.rb +41 -0
  33. data/spec/outputs/swift/temporary_file_factory_spec.rb +89 -0
  34. data/spec/outputs/swift/temporary_file_spec.rb +47 -0
  35. data/spec/outputs/swift/time_rotation_policy_spec.rb +60 -0
  36. data/spec/outputs/swift/uploader_spec.rb +49 -0
  37. data/spec/outputs/swift/writable_directory_validator_spec.rb +40 -0
  38. data/spec/outputs/swift/write_container_permission_validator_spec.rb +38 -0
  39. data/spec/outputs/swift_spec.rb +76 -0
  40. data/spec/spec_helper.rb +48 -0
  41. data/spec/supports/helpers.rb +38 -0
  42. metadata +212 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a53de853bb7f7f97356dab1053131195d5f83e56
4
+ data.tar.gz: 98ed226c784788a9bb4510b4208f1128b14ee315
5
+ SHA512:
6
+ metadata.gz: 38d9a9e6e243e297436fa605d7e40eee0a5841f31a67617238803da04bde70f695519ec96a509fede8c331284782f992b6f6e4ce4a84d21371063a79736fa5ad
7
+ data.tar.gz: 56f10e27ce4efd6eaa2806673030cecd8bb7e39422012bbbfc656d19329f2e15fe6d56f2b28aaf81a7b13a7746d9bf90390ecb8db53bc763fe13f9b6d760a19b
@@ -0,0 +1,2 @@
1
+ ## 0.1
2
+ - First release, based on lgostash-output-s3 4.0.13
@@ -0,0 +1,22 @@
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
+ * Chad Bean (chadbean)
6
+ * Colin Surprenant (colinsurprenant)
7
+ * Helmut Duregger (hduregger)
8
+ * Jordan Sissel (jordansissel)
9
+ * Joshua Spence (joshuaspence)
10
+ * Kurt Hurtado (kurtado)
11
+ * Mattia Peterle (MattiaBeast)
12
+ * Nick Ethier (nickethier)
13
+ * Pier-Hugues Pellerin (ph)
14
+ * Richard Pijnenburg (electrical)
15
+ * Jake Landis (jakelandis)
16
+ * Armin Braun (original-brownbear)
17
+ * Karri Niemelä (kakoni)
18
+
19
+ Note: If you've sent us patches, bug reports, or otherwise contributed to
20
+ Logstash, and you aren't on the list above and want to be, please let us know
21
+ and we'll make sure you're here. Contributions from folks like you are what make
22
+ open source awesome.
@@ -0,0 +1,15 @@
1
+ [Missing the other part of the readme]
2
+
3
+ ## Running the tests
4
+
5
+ ```
6
+ bundle install
7
+ bundle exec rspec
8
+ ```
9
+
10
+ If you want to run the integration test against a real bucket you need to pass
11
+ your aws credentials to the test runner or declare it in your environment.
12
+
13
+ ```
14
+ AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=123 AWS_SECRET_ACCESS_KEY=secret AWS_LOGSTASH_TEST_BUCKET=mytest bundle exec rspec spec/integration/s3_spec.rb --tag integration
15
+ ```
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ logstash_path = ENV["LOGSTASH_PATH"] || "../../logstash"
6
+ use_logstash_source = ENV["LOGSTASH_SOURCE"] && ENV["LOGSTASH_SOURCE"].to_s == "1"
7
+
8
+ if Dir.exist?(logstash_path) && use_logstash_source
9
+ gem 'logstash-core', :path => "#{logstash_path}/logstash-core"
10
+ gem 'logstash-core-plugin-api', :path => "#{logstash_path}/logstash-core-plugin-api"
11
+ end
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.
@@ -0,0 +1,2 @@
1
+ This product includes software developed by The Apache Software
2
+ Foundation (http://www.apache.org/).
@@ -0,0 +1,38 @@
1
+ # logstash-output-swift
2
+
3
+ This plugin is provided as an external plugin and is not part of the Logstash project.
4
+ Its forked from [logstash-out-s3](https://github.com/logstash-plugins/logstash-output-s3) project.
5
+
6
+ This plugin allows you to output to Openstack swift storage.
7
+
8
+ ## Changelog
9
+ See CHANGELOG.md
10
+
11
+ ## Versions
12
+ Released versions are available via rubygems.
13
+
14
+ ## Installation
15
+ - Run `bin/logstash-plugin install logstash-output-swift` in your logstash installation directory
16
+ - Configure
17
+
18
+ ## Configuration options
19
+
20
+ | Option | Type | Description | Required? | Default |
21
+ | ------ | ---- | ----------- | --------- | ------- |
22
+ | username | String | Openstack Username | Yes | |
23
+ | api_key | String | Openstack apikey | Yes | |
24
+ | auth_url | String | Keystone server | Yes | |
25
+ | project_name | String | Project name | Yes | |
26
+ | domain_name | String | Domain name | Yes | |
27
+ | container | String | Swift container for the logs | Yes | |
28
+
29
+ ## Development and Running tests
30
+ - `bundle exec rspec`
31
+
32
+ ## Releasing
33
+ - Update Changelog
34
+ - Bump version in gemspec
35
+ - Commit
36
+ - Create tag `git tag v<version-number-in-gemspec>`
37
+ - `gem build logstash-output-swift.gemspec`
38
+ - `gem push`
@@ -0,0 +1,360 @@
1
+ # encoding: utf-8
2
+ require "logstash/outputs/base"
3
+ require "logstash/namespace"
4
+ require "stud/temporary"
5
+ require "stud/task"
6
+ require "concurrent"
7
+ require "socket"
8
+ require "thread"
9
+ require "tmpdir"
10
+ require "fileutils"
11
+ require "set"
12
+ require "pathname"
13
+ require "fog/openstack"
14
+
15
+ # INFORMATION:
16
+ #
17
+ # This plugin batches and uploads logstash events into Openstack Swift.
18
+ #
19
+ # Requirements:
20
+ # * Amazon S3 Bucket and S3 Access Permissions (Typically access_key_id and secret_access_key)
21
+ # * S3 PutObject permission
22
+ #
23
+ # Swift outputs create temporary files into the OS' temporary directory, you can specify where to save them using the `temporary_directory` option.
24
+ #
25
+ # Swift output files have the following format
26
+ #
27
+ # ls.s3.312bc026-2f5d-49bc-ae9f-5940cf4ad9a6.2013-04-18T10.00.tag_hello.part0.txt
28
+ #
29
+ #
30
+ # |=======
31
+ # | ls.s3 | indicate logstash plugin s3 |
32
+ # | 312bc026-2f5d-49bc-ae9f-5940cf4ad9a6 | a new, random uuid per file. |
33
+ # | 2013-04-18T10.00 | represents the time whenever you specify time_file. |
34
+ # | tag_hello | this indicates the event's tag. |
35
+ # | part0 | this means if you indicate size_file then it will generate more parts if you file.size > size_file. When a file is full it will be pushed to the bucket and then deleted from the temporary directory. If a file is empty, it is simply deleted. Empty files will not be pushed |
36
+ # |=======
37
+ #
38
+ # Crash Recovery:
39
+ # * This plugin will recover and upload temporary log files after crash/abnormal termination when using `restore` set to true
40
+ #
41
+ ##[Note regarding time_file and size_file] :
42
+ #
43
+ ## Both time_file and size_file settings can trigger a log "file rotation"
44
+ ## A log rotation pushes the current log "part" to s3 and deleted from local temporary storage.
45
+ #
46
+ ## If you specify BOTH size_file and time_file then it will create file for each tag (if specified).
47
+ ## When EITHER time_file minutes have elapsed OR log file size > size_file, a log rotation is triggered.
48
+ ##
49
+ ## If you ONLY specify time_file but NOT file_size, one file for each tag (if specified) will be created.
50
+ ## When time_file minutes elapses, a log rotation will be triggered.
51
+ #
52
+ ## If you ONLY specify size_file, but NOT time_file, one files for each tag (if specified) will be created.
53
+ ## When size of log file part > size_file, a log rotation will be triggered.
54
+ #
55
+ ## If NEITHER size_file nor time_file is specified, ONLY one file for each tag (if specified) will be created.
56
+ ## WARNING: Since no log rotation is triggered, S3 Upload will only occur when logstash restarts.
57
+ #
58
+ #
59
+ # #### Usage:
60
+ # This is an example of logstash config:
61
+ # [source,ruby]
62
+ # output {
63
+ # swift {
64
+ # username => "crazy_name" (required)
65
+ # api_key => "crazy_key" (required)
66
+ # auth_url => "https://auth_tokens" (required)
67
+ # project_name => "crazy project name" (required)
68
+ # domain_name => "crazy domain name" (required)
69
+ # container => "your_bucket_container" (required)
70
+ # }
71
+ #
72
+ class LogStash::Outputs::Swift < LogStash::Outputs::Base
73
+ require "logstash/outputs/swift/writable_directory_validator"
74
+ require "logstash/outputs/swift/path_validator"
75
+ require "logstash/outputs/swift/write_container_permission_validator"
76
+ require "logstash/outputs/swift/size_rotation_policy"
77
+ require "logstash/outputs/swift/time_rotation_policy"
78
+ require "logstash/outputs/swift/size_and_time_rotation_policy"
79
+ require "logstash/outputs/swift/temporary_file"
80
+ require "logstash/outputs/swift/temporary_file_factory"
81
+ require "logstash/outputs/swift/uploader"
82
+ require "logstash/outputs/swift/file_repository"
83
+
84
+ #include LogStash::PluginMixins::AwsConfig::V2
85
+
86
+ PREFIX_KEY_NORMALIZE_CHARACTER = "_"
87
+ PERIODIC_CHECK_INTERVAL_IN_SECONDS = 15
88
+ CRASH_RECOVERY_THREADPOOL = Concurrent::ThreadPoolExecutor.new({
89
+ :min_threads => 1,
90
+ :max_threads => 2,
91
+ :fallback_policy => :caller_runs
92
+ })
93
+
94
+
95
+ config_name "swift"
96
+ default :codec, "line"
97
+
98
+ concurrency :shared
99
+
100
+ # Swift container
101
+ config :container, :validate => :string, :required => true
102
+
103
+ # Set the size of file in bytes, this means that files on bucket when have dimension > file_size, they are stored in two or more file.
104
+ # If you have tags then it will generate a specific size file for every tags
105
+ ##NOTE: define size of file is the better thing, because generate a local temporary file on disk and then put it in bucket.
106
+ config :size_file, :validate => :number, :default => 1024 * 1024 * 5
107
+
108
+ # Set the time, in MINUTES, to close the current sub_time_section of bucket.
109
+ # If you define file_size you have a number of files in consideration of the section and the current tag.
110
+ # 0 stay all time on listerner, beware if you specific 0 and size_file 0, because you will not put the file on bucket,
111
+ # for now the only thing this plugin can do is to put the file when logstash restart.
112
+ config :time_file, :validate => :number, :default => 15
113
+
114
+ ## IMPORTANT: if you use multiple instance of s3, you should specify on one of them the "restore=> true" and on the others "restore => false".
115
+ ## This is hack for not destroy the new files after restoring the initial files.
116
+ ## If you do not specify "restore => true" when logstash crashes or is restarted, the files are not sent into the bucket,
117
+ ## for example if you have single Instance.
118
+ config :restore, :validate => :boolean, :default => true
119
+
120
+ # The S3 canned ACL to use when putting the file. Defaults to "private".
121
+ config :canned_acl, :validate => ["private", "public-read", "public-read-write", "authenticated-read"],
122
+ :default => "private"
123
+
124
+ # Set the directory where logstash will store the tmp files before sending it to S3
125
+ # default to the current OS temporary directory in linux /tmp/logstash
126
+ config :temporary_directory, :validate => :string, :default => File.join(Dir.tmpdir, "logstash")
127
+
128
+ # Specify a prefix to the uploaded filename, this can simulate directories on S3. Prefix does not require leading slash.
129
+ # This option support string interpolation, be warned this can created a lot of temporary local files.
130
+ config :prefix, :validate => :string, :default => ''
131
+
132
+ # Specify how many workers to use to upload the files to S3
133
+ config :upload_workers_count, :validate => :number, :default => (Concurrent.processor_count * 0.5).ceil
134
+
135
+ # Number of items we can keep in the local queue before uploading them
136
+ config :upload_queue_size, :validate => :number, :default => 2 * (Concurrent.processor_count * 0.25).ceil
137
+
138
+ # Define tags to be appended to the file on the S3 bucket.
139
+ #
140
+ # Example:
141
+ # tags => ["elasticsearch", "logstash", "kibana"]
142
+ #
143
+ # Will generate this file:
144
+ # "ls.s3.logstash.local.2015-01-01T00.00.tag_elasticsearch.logstash.kibana.part0.txt"
145
+ #
146
+ config :tags, :validate => :array, :default => []
147
+
148
+ # Specify the content encoding. Supports ("gzip"). Defaults to "none"
149
+ config :encoding, :validate => ["none", "gzip"], :default => "none"
150
+
151
+ # Define the strategy to use to decide when we need to rotate the file and push it to S3,
152
+ # The default strategy is to check for both size and time, the first one to match will rotate the file.
153
+ config :rotation_strategy, :validate => ["size_and_time", "size", "time"], :default => "size_and_time"
154
+
155
+ # The common use case is to define permission on the root bucket and give Logstash full access to write its logs.
156
+ # In some circonstances you need finer grained permission on subfolder, this allow you to disable the check at startup.
157
+ config :validate_credentials_on_root_bucket, :validate => :boolean, :default => true
158
+
159
+ #Openstack username
160
+ config :username, :validate => :string
161
+
162
+ #Openstack api_key
163
+ config :api_key, :validate => :string
164
+
165
+ #Openstack auth url
166
+ config :auth_url, :validate => :string
167
+
168
+ #Openstack project_name
169
+ config :project_name, :validate => :string
170
+
171
+ #Openstack domain_name
172
+ config :domain_name, :validate => :string
173
+
174
+ def register
175
+ # I've move the validation of the items into custom classes
176
+ # to prepare for the new config validation that will be part of the core so the core can
177
+ # be moved easily.
178
+ unless @prefix.empty?
179
+ if !PathValidator.valid?(prefix)
180
+ raise LogStash::ConfigurationError, "Prefix must not contains: #{PathValidator::INVALID_CHARACTERS}"
181
+ end
182
+ end
183
+
184
+ if !WritableDirectoryValidator.valid?(@temporary_directory)
185
+ raise LogStash::ConfigurationError, "Logstash must have the permissions to write to the temporary directory: #{@temporary_directory}"
186
+ end
187
+
188
+ if @validate_credentials_on_root_bucket && !WriteContainerPermissionValidator.new(@logger).valid?(container_resource)
189
+ raise LogStash::ConfigurationError, "Logstash must have the privileges to write to root container `#{@container}`, check your credentials or your permissions."
190
+ end
191
+
192
+ if @time_file.nil? && @size_file.nil? || @size_file == 0 && @time_file == 0
193
+ raise LogStash::ConfigurationError, "The S3 plugin must have at least one of time_file or size_file set to a value greater than 0"
194
+ end
195
+
196
+ @file_repository = FileRepository.new(@tags, @encoding, @temporary_directory)
197
+
198
+ @rotation = rotation_strategy
199
+
200
+ executor = Concurrent::ThreadPoolExecutor.new({ :min_threads => 1,
201
+ :max_threads => @upload_workers_count,
202
+ :max_queue => @upload_queue_size,
203
+ :fallback_policy => :caller_runs })
204
+
205
+ @uploader = Uploader.new(container_resource, @logger, executor)
206
+
207
+ # Restoring from crash will use a new threadpool to slowly recover
208
+ # New events should have more priority.
209
+ restore_from_crash if @restore
210
+
211
+ # If we need time based rotation we need to do periodic check on the file
212
+ # to take care of file that were not updated recently
213
+ start_periodic_check if @rotation.needs_periodic?
214
+ end
215
+
216
+ def multi_receive_encoded(events_and_encoded)
217
+ puts 'milti rrecei'
218
+ prefix_written_to = Set.new
219
+
220
+ events_and_encoded.each do |event, encoded|
221
+ prefix_key = normalize_key(event.sprintf(@prefix))
222
+ prefix_written_to << prefix_key
223
+
224
+ begin
225
+ puts 'begin'
226
+ @file_repository.get_file(prefix_key) { |file| file.write(encoded) }
227
+ # The output should stop accepting new events coming in, since it cannot do anything with them anymore.
228
+ # Log the error and rethrow it.
229
+ rescue Errno::ENOSPC => e
230
+ @logger.error("S3: No space left in temporary directory", :temporary_directory => @temporary_directory)
231
+ raise e
232
+ end
233
+ end
234
+
235
+ puts 'done'
236
+ # Groups IO calls to optimize fstat checks
237
+ rotate_if_needed(prefix_written_to)
238
+ end
239
+
240
+ def close
241
+ stop_periodic_check if @rotation.needs_periodic?
242
+
243
+ @logger.debug("Uploading current workspace")
244
+
245
+ # The plugin has stopped receiving new events, but we still have
246
+ # data on disk, lets make sure it get to S3.
247
+ # If Logstash get interrupted, the `restore_from_crash` (when set to true) method will pickup
248
+ # the content in the temporary directly and upload it.
249
+ # This will block the shutdown until all upload are done or the use force quit.
250
+ @file_repository.each_files do |file|
251
+ upload_file(file)
252
+ end
253
+
254
+ @file_repository.shutdown
255
+
256
+ @uploader.stop # wait until all the current upload are complete
257
+ @crash_uploader.stop if @restore # we might have still work to do for recovery so wait until we are done
258
+ end
259
+
260
+ def normalize_key(prefix_key)
261
+ prefix_key.gsub(PathValidator.matches_re, PREFIX_KEY_NORMALIZE_CHARACTER)
262
+ end
263
+
264
+ private
265
+ # We start a task in the background for check for stale files and make sure we rotate them to S3 if needed.
266
+ def start_periodic_check
267
+ @logger.debug("Start periodic rotation check")
268
+
269
+ @periodic_check = Concurrent::TimerTask.new(:execution_interval => PERIODIC_CHECK_INTERVAL_IN_SECONDS) do
270
+ @logger.debug("Periodic check for stale files")
271
+
272
+ rotate_if_needed(@file_repository.keys)
273
+ end
274
+
275
+ @periodic_check.execute
276
+ end
277
+
278
+ def stop_periodic_check
279
+ @periodic_check.shutdown
280
+ end
281
+
282
+ def container_resource
283
+ Excon.defaults[:ciphers] = 'DEFAULT'
284
+ service = Fog::Storage::OpenStack.new({
285
+ openstack_username: @username,
286
+ openstack_api_key: @api_key,
287
+ openstack_auth_url: @auth_url,
288
+ openstack_project_name: @project_name,
289
+ openstack_domain_name: @domain_name,
290
+ connection_options: {}
291
+ })
292
+
293
+ service.directories.get(@container)
294
+ end
295
+
296
+ def rotate_if_needed(prefixes)
297
+ puts 'rotate!'
298
+ prefixes.each do |prefix|
299
+ # Each file access is thread safe,
300
+ # until the rotation is done then only
301
+ # one thread has access to the resource.
302
+ @file_repository.get_factory(prefix) do |factory|
303
+ temp_file = factory.current
304
+
305
+ if @rotation.rotate?(temp_file)
306
+ @logger.debug("Rotate file",
307
+ :strategy => @rotation.class.name,
308
+ :key => temp_file.key,
309
+ :path => temp_file.path)
310
+
311
+ upload_file(temp_file)
312
+ factory.rotate!
313
+ end
314
+ end
315
+ end
316
+ end
317
+
318
+ def upload_file(temp_file)
319
+ puts 'upload file'
320
+ @logger.debug("Queue for upload", :path => temp_file.path)
321
+
322
+ # if the queue is full the calling thread will be used to upload
323
+ temp_file.close # make sure the content is on disk
324
+ if temp_file.size > 0
325
+ @uploader.upload_async(temp_file,
326
+ :on_complete => method(:clean_temporary_file))
327
+ end
328
+ end
329
+
330
+ def rotation_strategy
331
+ case @rotation_strategy
332
+ when "size"
333
+ SizeRotationPolicy.new(size_file)
334
+ when "time"
335
+ TimeRotationPolicy.new(time_file)
336
+ when "size_and_time"
337
+ SizeAndTimeRotationPolicy.new(size_file, time_file)
338
+ end
339
+ end
340
+
341
+ def clean_temporary_file(file)
342
+ @logger.debug("Removing temporary file", :file => file.path)
343
+ file.delete!
344
+ end
345
+
346
+ # The upload process will use a separate uploader/threadpool with less resource allocated to it.
347
+ # but it will use an unbounded queue for the work, it may take some time before all the older files get processed.
348
+ def restore_from_crash
349
+ @crash_uploader = Uploader.new(container_resource, @logger, CRASH_RECOVERY_THREADPOOL)
350
+
351
+ temp_folder_path = Pathname.new(@temporary_directory)
352
+ Dir.glob(::File.join(@temporary_directory, "**/*"))
353
+ .select { |file| ::File.file?(file) }
354
+ .each do |file|
355
+ temp_file = TemporaryFile.create_from_existing_file(file, temp_folder_path)
356
+ @logger.debug("Recovering from crash and uploading", :file => temp_file.path)
357
+ @crash_uploader.upload_async(temp_file, :on_complete => method(:clean_temporary_file))
358
+ end
359
+ end
360
+ end