diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5833cba --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.ci +*.gem +Gemfile.lock +.idea +.bundle diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..abfeac7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +--- +import: +- logstash-plugins/.ci:travis/travis.yml@1.x diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..28fa99c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,2 @@ +# 1.0.0 + - Support Mixin for ensuring a plugin has an `port_management` method that returns a `Manager` capable of retrieving a `Reservation` that holds a TCP port until `Reservation#convert` or `Reservation#release`. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..f41bda3 --- /dev/null +++ b/Gemfile @@ -0,0 +1,12 @@ +source 'https://rubygems.org' + +# Specify your gem's dependencies in logstash-mass_effect.gemspec +gemspec + +logstash_path = ENV["LOGSTASH_PATH"] || "../../logstash" +use_logstash_source = ENV["LOGSTASH_SOURCE"] && ENV["LOGSTASH_SOURCE"].to_s == "1" + +if Dir.exist?(logstash_path) && use_logstash_source + gem 'logstash-core', :path => "#{logstash_path}/logstash-core" + gem 'logstash-core-plugin-api', :path => "#{logstash_path}/logstash-core-plugin-api" +end diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a80a3fd --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Elastic and contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..42af3d6 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# Port Management Support Mixin + +[![Build Status](https://travis-ci.com/logstash-plugins/logstash-mixin-port_management_support.svg?branch=main)](https://travis-ci.com/logstash-plugins/logstash-mixin-port_management_support) + +This gem provides tooling for creating and using port reservations by plugins, +so that a plugin can ensure a port is available during `#register` and _remains_ +available until `#run`. + +## Usage (simple) + +1. Add version `~>1.0` of this gem as a runtime dependency of your Logstash plugin's `gemspec`: + + ~~~ ruby + Gem::Specification.new do |s| + # ... + + s.add_runtime_dependency 'logstash-mixin-port_management_support', '~>1.0' + end + ~~~ + +2. In your plugin code, require this library and include it into your plugin class + that already inherits `LogStash::Plugin`: + + ~~~ ruby + require 'logstash/plugin_mixins/ecs_compatibility_support' + + class LogStash::Inputs::Foo < Logstash::Inputs::Base + include LogStash::PluginMixins::PortManagementSupport + + # ... + end + ~~~ + +3. Use the `port_management` method to get a `PortManagementSupport::Manager` instance, and then use + that instance to reserve a port: + + ~~~ ruby + class LogStash::Inputs::Foo < Logstash::Inputs::Base + # ... + + def register + @port_reservation = port_management.reserve(port: 1234) + end + end + ~~~ + + +4. Use the `Reservation#convert` method to release the reservation and replace it with your own + service. + + ~~~ ruby + class LogStash::Inputs::Foo < Logstash::Inputs::Base + # ... + + def run(queue) + # ... + @port_reservation.convert do |addr, port| + # this block is yielded *after* unbinding from the port, + # while still holding the global PortManagementSupport lock. + end + end + end + ~~~ + +5. Be sure to hook `Reservation#release` into your plugin's cleanup code + +## Development + +This gem: + - *MUST* remain API-stable at 1.x + - *MUST NOT* introduce additional runtime dependencies diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8785fd3 --- /dev/null +++ b/Rakefile @@ -0,0 +1,3 @@ +# encoding: utf-8 + +require "logstash/devutils/rake" diff --git a/lib/logstash/plugin_mixins/port_management_support.rb b/lib/logstash/plugin_mixins/port_management_support.rb new file mode 100644 index 0000000..ac2df4c --- /dev/null +++ b/lib/logstash/plugin_mixins/port_management_support.rb @@ -0,0 +1,140 @@ +# encoding: utf-8 + +require 'logstash/namespace' +require 'logstash/plugin' + +module LogStash + module PluginMixins + module PortManagementSupport + + def self.included(base) + fail(ArgumentError, "`#{base}` must inherit LogStash::Plugin") unless base < LogStash::Plugin + + base.define_method(:port_management) { Manager::INSTANCE } + end + + class Manager + INSTANCE=new + + ## + # Reserve a port on the provided addr, binding a dummy TCP server to the + # port to ensure that nothing else can bind to it. + # @param addr [String]: the ip address to bind to (default: "0.0.0.0") + # @param port [Integer]: the port to bind to (default: 0 "any") + # @yieldparam addr [String]: the actual ip address that was bound + # @yieldparam port [Integer]: the actual ip address that was bound + # @yieldreturn [Void]: the returned value is ignored/discarded + # @return [Reservation] + def reserve(addr: '::', port: 0, &handler) + Reservation.new(addr: addr, port: port, &handler) + end + end + + ## + # A `Reservation` is a TCP server bound to the reserved port on the provided address, preventing + # anything else in the OS from binding to the same port on that address. + class Reservation + PORT_MANAGEMENT_GLOBAL_MUTEX = Monitor.new + private_constant(:PORT_MANAGEMENT_GLOBAL_MUTEX) + + attr_reader :addr + attr_reader :port + + include LogStash::Util::Loggable + + ## + # Creates a port reservation by binding a temporary TCP server + # @param addr [String]: the address to bind to + # @param port [Integer]: the port to bind to (note: 0 means "any available") + # @return [self] + # @overload initialize(addr:, port:, &handler) + # If a handler is provided, the actual addr and port will be yielded to it *outside* + # of the global lock + # @yieldparam addr [String]: the *actual* address that was bound + # @yieldparam port [Integer]: the *actual* port that was bound + # @yieldreturn [void] + def initialize(addr:, port:, &handler) + PORT_MANAGEMENT_GLOBAL_MUTEX.synchronize do + @hold = TCPServer.new(addr, port) + @addr, @port = @hold.local_address.ip_unpack + + logger.debug("RESERVED[#{addr}:#{port}]=>[#{@addr}:#{@port}]") + end + + ObjectSpace.define_finalizer(self, self.class._server_close_proc(@hold)) + + if block_given? + begin + yield(@addr, @port) + rescue => e + release + raise + end + end + end + + ## + # Convert the reservation. + # In a global lock, the reservation is released and the block is yielded, ensuring that no other plugin + # using this tooling can make a reservation until the block completes (presumably with your server bound to + # the port in place of the dummy server that was closed) + # @yieldparam addr [String]: the reserved-and-released ip address + # @yieldparam port [Integer]: the reserved-and-released ip port + # @yieldreturn [Object]: the value emitted by the block is returned by the method + # @return [Object]: the result of the provided block + def convert(&block) + fail(ArgumentError) unless block_given? + + PORT_MANAGEMENT_GLOBAL_MUTEX.synchronize do + if active? + logger.trace("converting-active[#{@addr}:#{@port}]") + release + else + logger.warn("converting-inactive[#{@addr}:#{@port}]") + end + + yield(@addr, @port).tap do + logger.debug("CONVERTED[#{@addr}:#{@port}]") + end + end + end + + ## + # Release the reservation *without* replacing it + def release + PORT_MANAGEMENT_GLOBAL_MUTEX.synchronize do + logger.trace("releasing[#{@addr}:#{@port}]") + + fail("hold is nil") if @hold.nil? + fail("hold is already closed") if @hold.closed? + + @hold.close + @hold = nil + + logger.trace("RELEASED[#{@addr}:#{@port}]") + end + end + + ## + # Determine if the reservation is still active and eligible for conversion + # @return [Boolean]: true if-and-only-if the dummy TCP server is still open + def active? + PORT_MANAGEMENT_GLOBAL_MUTEX.synchronize do + @hold && !@hold.closed? + end + end + + # returns a proc to close the provided server without holding any other refs + # https://www.mikeperham.com/2010/02/24/the-trouble-with-ruby-finalizers/ + def self._server_close_proc(server) + proc do + unless server.closed? + logger.trace("ObjectSpace::closing(#{server})") + server.close + end + end + end + end + end + end +end \ No newline at end of file diff --git a/logstash-mixin-port_management_support.gemspec b/logstash-mixin-port_management_support.gemspec new file mode 100644 index 0000000..a40431a --- /dev/null +++ b/logstash-mixin-port_management_support.gemspec @@ -0,0 +1,22 @@ +Gem::Specification.new do |s| + s.name = 'logstash-mixin-port_management_support' + s.version = '1.0.0' + s.licenses = %w(Apache-2.0) + s.summary = "Support for port management in Logstash plugins, independent of Logstash version" + s.description = "This gem is meant to be a dependency of any Logstash plugin that wishes to manage TCP ports" + s.authors = %w(Elastic) + s.email = 'info@elastic.co' + s.homepage = 'https://github.com/logstash-plugins/logstash-mixin-port_management_support' + s.require_paths = %w(lib) + + s.files = %w(lib spec vendor).flat_map{|dir| Dir.glob("#{dir}/**/*")}+Dir.glob(["*.md","LICENSE"]) + + s.test_files = s.files.grep(%r{^(test|spec|features)/}) + + s.platform = RUBY_PLATFORM + + s.add_runtime_dependency 'logstash-core', '>= 7.0.0' + + s.add_development_dependency 'logstash-devutils' + s.add_development_dependency 'rspec', '~> 3.9' +end diff --git a/spec/logstash/plugin_mixins/port_management_support_spec.rb b/spec/logstash/plugin_mixins/port_management_support_spec.rb new file mode 100644 index 0000000..a078052 --- /dev/null +++ b/spec/logstash/plugin_mixins/port_management_support_spec.rb @@ -0,0 +1,169 @@ +# encoding: utf-8 + +require 'logstash-core' + +require 'logstash/inputs/base' +require 'logstash/filters/base' +require 'logstash/codecs/base' +require 'logstash/outputs/base' + +require "logstash/plugin_mixins/port_management_support" + +describe LogStash::PluginMixins::PortManagementSupport do + let(:port_management_support) { LogStash::PluginMixins::PortManagementSupport } + + context 'included into a class' do + context 'that does not inherit from `LogStash::Plugin`' do + let(:plugin_class) { Class.new } + + it 'fails with an ArgumentError' do + expect do + plugin_class.send(:include, port_management_support) + end.to raise_error(ArgumentError, /LogStash::Plugin/) + end + end + + [ + LogStash::Inputs::Base, + LogStash::Filters::Base, + LogStash::Codecs::Base, + LogStash::Outputs::Base + ].each do |base_class| + context "that inherits from `#{base_class}`" do + + let(:plugin_base_class) { base_class } + + subject(:plugin_class) do + Class.new(plugin_base_class) do + config_name 'test' + end + end + + context 'the result' do + before(:each) { plugin_class.send(:include, port_management_support) } + + it 'has `port_management` method' do + expect(plugin_class.method_defined?(:port_management)).to be true + expect(plugin_class.new({}).port_management).to equal(port_management_support::Manager::INSTANCE) + end + end + end + end + end + + ## + # determine if the port is currently open by attempting to temporarily + # bind a TCPServer to it + # @return [Boolean] + def port_available?(ip, port) + TCPServer.new(ip, port).close + return true + rescue Errno::EADDRINUSE + return false + end + + ## + # yield the block with a port that is available + # @return [Integer]: a port that is available + def find_available_port(ip) + with_bound_port(ip, &:itself) + end + + ## + # Yields block with a port that is unavailable + # @yieldparam port [Integer] + # @yieldreturn [Object] + # @return [Object] + def with_bound_port(ip, &block) + server = TCPServer.new(ip, 0) + + return yield(server.local_address.ip_port) + ensure + server.close + end + + describe LogStash::PluginMixins::PortManagementSupport::Manager do + subject(:manager) { described_class::INSTANCE } + + let(:default_ip) { '::' } + + describe '#reserve' do + context 'port 0' do + it 'reserves an available port and yields it' do + reservation = nil + expect { |b| reservation = manager.reserve(port: 0, &b) }.to yield_with_args(default_ip, a_value > 0) + expect(reservation.addr).to eq(default_ip) + expect(reservation.port).to be > 0 + + expect(port_available?(reservation.addr, reservation.port)).to be_falsey + end + end + context 'available port' do + let(:available_port) { find_available_port(default_ip) } + + it 'reserves the port' do + reservation = nil + expect { |b| reservation = manager.reserve(port: available_port, &b) }.to yield_with_args(default_ip, available_port) + expect(reservation.addr).to eq(default_ip) + expect(reservation.port).to eq(available_port) + + expect(port_available?(reservation.addr, reservation.port)).to be_falsey + end + end + + context 'unavailable port' do + it 'fails to reserve the port' do + with_bound_port(default_ip) do |unavailable_port| + expect { manager.reserve(port: unavailable_port) }.to raise_error(Errno::EADDRINUSE) + end + end + end + end + end + + describe LogStash::PluginMixins::PortManagementSupport::Reservation do + let(:reservation) { port_management_support::Manager::INSTANCE.reserve } + + describe '#convert' do + it 'releases the reservation before yielding the block' do + expect(port_available?(reservation.addr, reservation.port)).to be_falsey + + expect do |b| + reservation.convert do |addr, port| + b.to_proc.call(addr, port) + expect(port_available?(addr, port)).to be_truthy + end + end.to yield_with_args(reservation.addr, reservation.port) + end + + context 'when already released' do + before(:each) { reservation.release } + + it 'warns, but does not error' do + expect(port_available?(reservation.addr, reservation.port)).to be_truthy + + mock_logger = double('Logger').as_null_object + allow(reservation).to receive(:logger).and_return(mock_logger) + + expect(mock_logger).to receive(:warn).with("converting-inactive[#{reservation.addr}:#{reservation.port}]") + + expect do |b| + reservation.convert do |addr, port| + b.to_proc.call(addr, port) + end + end.to yield_with_args(reservation.addr, reservation.port) + end + end + end + + describe '#release' do + it 'releases the reservation' do + expect(port_available?(reservation.addr, reservation.port)).to be_falsey + + reservation.release + + expect(port_available?(reservation.addr, reservation.port)).to be_truthy + end + end + end +end