├── .gitignore ├── .travis.yml ├── Rakefile ├── NOTICE.TXT ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE.md └── CONTRIBUTING.md ├── Gemfile ├── .ci ├── docker-compose.yml └── docker-compose.override.yml ├── CONTRIBUTORS ├── spec ├── support │ └── client.rb ├── spec_helper.rb └── inputs │ └── udp_spec.rb ├── logstash-input-udp.gemspec ├── CHANGELOG.md ├── README.md ├── docs └── index.asciidoc ├── lib └── logstash │ └── inputs │ └── udp.rb └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | Gemfile.lock 3 | .bundle 4 | vendor 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | import: 2 | - logstash-plugins/.ci:travis/travis.yml@1.x 3 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | @files=[] 2 | 3 | task :default do 4 | system("rake -T") 5 | end 6 | 7 | require "logstash/devutils/rake" 8 | -------------------------------------------------------------------------------- /NOTICE.TXT: -------------------------------------------------------------------------------- 1 | Elasticsearch 2 | Copyright 2012-2015 Elasticsearch 3 | 4 | This product includes software developed by The Apache Software 5 | Foundation (http://www.apache.org/). -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for contributing to Logstash! If you haven't already signed our CLA, here's a handy link: https://www.elastic.co/contributor-agreement/ 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 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 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please post all product and debugging questions on our [forum](https://discuss.elastic.co/c/logstash). Your questions will reach our wider community members there, and if we confirm that there is a bug, then we can open a new issue here. 2 | 3 | For all general issues, please provide the following details for fast resolution: 4 | 5 | - Version: 6 | - Operating System: 7 | - Config File (if you have sensitive info, please remove it): 8 | - Sample Data: 9 | - Steps to Reproduce: 10 | -------------------------------------------------------------------------------- /.ci/docker-compose.yml: -------------------------------------------------------------------------------- 1 | # docker ipv6 only support in version 2.x 2 | version: '2.4' 3 | 4 | # run tests: cd ci/unit; docker-compose up --build --force-recreate 5 | # manual: cd ci/unit; docker-compose run logstash bash 6 | services: 7 | 8 | logstash: 9 | build: 10 | context: ../ 11 | dockerfile: .ci/Dockerfile 12 | args: 13 | - ELASTIC_STACK_VERSION=$ELASTIC_STACK_VERSION 14 | - DISTRIBUTION=${DISTRIBUTION:-default} 15 | #- INTEGRATION=false 16 | command: .ci/run.sh 17 | env_file: docker.env 18 | environment: 19 | - SPEC_OPTS 20 | #- JRUBY_OPTS 21 | tty: true 22 | -------------------------------------------------------------------------------- /.ci/docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | version: '2.4' 2 | 3 | services: 4 | logstash: 5 | container_name: udp_ls 6 | command: /usr/share/plugins/plugin/.ci/run.sh 7 | environment: 8 | - ELASTIC_STACK_VERSION=$ELASTIC_STACK_VERSION 9 | networks: 10 | app_net: 11 | ipv4_address: 172.16.238.10 12 | ipv6_address: 2001:3984:3989::10 13 | 14 | networks: 15 | app_net: 16 | driver: bridge 17 | enable_ipv6: true 18 | ipam: 19 | driver: default 20 | config: 21 | - subnet: 172.16.238.0/24 22 | gateway: 172.16.238.1 23 | - subnet: 2001:3984:3989::/64 24 | gateway: 2001:3984:3989::1 25 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 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 | * Aaron Mildenstein (untergeek) 6 | * Devin Christensen (quixoten) 7 | * John Arnold (johnarnold) 8 | * John E. Vincent (lusis) 9 | * Jordan Sissel (jordansissel) 10 | * Kurt Hurtado (kurtado) 11 | * Pier-Hugues Pellerin (ph) 12 | * Richard Pijnenburg (electrical) 13 | * kcrayon 14 | * Colin Surprenant (colinsurprenant) 15 | 16 | Note: If you've sent us patches, bug reports, or otherwise contributed to 17 | Logstash, and you aren't on the list above and want to be, please let us know 18 | and we'll make sure you're here. Contributions from folks like you are what make 19 | open source awesome. 20 | -------------------------------------------------------------------------------- /spec/support/client.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "socket" 3 | require "ipaddr" 4 | 5 | module LogStash::Inputs::Test 6 | 7 | class UDPClient 8 | attr_reader :host, :port, :socket 9 | 10 | def initialize(port, host = "0.0.0.0") 11 | @host = host 12 | @port = port 13 | if IPAddr.new(@host).ipv6? 14 | @socket = UDPSocket.new(Socket::AF_INET6) 15 | elsif IPAddr.new(@host).ipv4? 16 | @socket = UDPSocket.new(Socket::AF_INET) 17 | end 18 | @socket.connect(host, port) 19 | end 20 | 21 | def send(msg) 22 | begin 23 | socket.send(msg, 0) 24 | rescue => e 25 | puts("send exception, retrying", e.inspect) 26 | retry 27 | end 28 | end 29 | 30 | def close 31 | socket.close unless socket.closed? 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "logstash/devutils/rspec/spec_helper" 3 | require 'logstash/inputs/udp' 4 | 5 | # expose the udp socket so that we can assert, during 6 | # a spec, that it is open and we can start sending data 7 | class LogStash::Inputs::Udp 8 | attr_reader :udp 9 | end 10 | 11 | class UdpHelpers 12 | 13 | def input(plugin, size, &block) 14 | queue = Queue.new 15 | input_thread = Thread.new do 16 | plugin.run(queue) 17 | end 18 | # because the udp socket is created and bound during #run 19 | # we must ensure that it is open before sending data 20 | sleep 0.1 until (plugin.udp && !plugin.udp.closed?) 21 | block.call 22 | sleep 0.1 while queue.size != size 23 | result = size.times.inject([]) do |acc| 24 | acc << queue.pop 25 | end 26 | plugin.do_stop 27 | result 28 | end 29 | 30 | end 31 | -------------------------------------------------------------------------------- /logstash-input-udp.gemspec: -------------------------------------------------------------------------------- 1 | Gem::Specification.new do |s| 2 | 3 | s.name = 'logstash-input-udp' 4 | s.version = '3.5.0' 5 | s.licenses = ['Apache License (2.0)'] 6 | s.summary = "Reads events over UDP" 7 | s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" 8 | s.authors = ["Elastic"] 9 | s.email = 'info@elastic.co' 10 | s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" 11 | s.require_paths = ["lib"] 12 | 13 | # Files 14 | s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"] 15 | 16 | # Tests 17 | s.test_files = s.files.grep(%r{^(test|spec|features)/}) 18 | 19 | # Special flag to let us know this is actually a logstash plugin 20 | s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" } 21 | 22 | # Gem dependencies 23 | s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" 24 | 25 | s.add_runtime_dependency 'logstash-codec-plain' 26 | s.add_runtime_dependency 'stud', '~> 0.0.22' 27 | s.add_runtime_dependency 'logstash-mixin-ecs_compatibility_support', '~>1.2' 28 | s.add_development_dependency 'logstash-codec-line' 29 | s.add_development_dependency 'logstash-devutils' 30 | end 31 | 32 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 3.5.0 2 | - Added ECS v8 support as an alias to the ECS v1 implementation 3 | 4 | ## 3.4.1 5 | - [DOC] Fixed typo in code sample [#54](https://github.com/logstash-plugins/logstash-input-udp/pull/54) 6 | 7 | ## 3.4.0 8 | - Added ECS compatibility mode (`disabled` and `v1`) to rename ip source address in a ECS compliant name [#50](https://github.com/logstash-plugins/logstash-input-udp/pull/50) 9 | - Fixed integration tests for IPv6 downgrading Docker to version 2.4 [#51](https://github.com/logstash-plugins/logstash-input-udp/pull/51) 10 | 11 | ## 3.3.4 12 | - Fixed input workers exception handling and shutdown handling [#44](https://github.com/logstash-plugins/logstash-input-udp/pull/44) 13 | 14 | ## 3.3.3 15 | - Work around jruby/jruby#5148 by cloning messages on jruby 9k, therefore resizing the underlying byte buffer 16 | 17 | ## 3.3.2 18 | - Fix missing require for the ipaddr library. 19 | 20 | ## 3.3.1 21 | - Docs: Set the default_codec doc attribute. 22 | 23 | ## 3.3.0 24 | - Add metrics support for events, operations, connections and errors produced during execution. #34 25 | - Fix support for IPv6 #31 26 | 27 | ## 3.2.1 28 | - Code cleanup. See https://github.com/logstash-plugins/logstash-input-udp/pull/33 29 | 30 | ## 3.2.0 31 | - Clone codec per worker. See https://github.com/logstash-plugins/logstash-input-udp/pull/32 32 | 33 | ## 3.1.3 34 | - Update gemspec summary 35 | 36 | ## 3.1.2 37 | - Fix some documentation issues 38 | 39 | ## 3.1.0 40 | - Add "receive_buffer_bytes" config setting to optionally set socket receive buffer size 41 | 42 | ## 3.0.3 43 | - fix performance regression calling IO.select for every packet #21 44 | 45 | ## 3.0.2 46 | - Relax constraint on logstash-core-plugin-api to >= 1.60 <= 2.99 47 | 48 | ## 3.0.1 49 | - Republish all the gems under jruby. 50 | ## 3.0.0 51 | - Update the plugin to the version 2.0 of the plugin api, this change is required for Logstash 5.0 compatibility. See https://github.com/elastic/logstash/issues/5141 52 | # 2.0.5 53 | - Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash 54 | # 2.0.4 55 | - New dependency requirements for logstash-core for the 5.0 release 56 | ## 2.0.2 57 | - Adapt the test style to be able to run within the context of the LS 58 | core default plugins test (integration) 59 | 60 | ## 2.0.0 61 | - Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully, 62 | instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895 63 | - Dependency on logstash-core update to 2.0 64 | 65 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Logstash 2 | 3 | All contributions are welcome: ideas, patches, documentation, bug reports, 4 | complaints, etc! 5 | 6 | Programming is not a required skill, and there are many ways to help out! 7 | It is more important to us that you are able to contribute. 8 | 9 | That said, some basic guidelines, which you are free to ignore :) 10 | 11 | ## Want to learn? 12 | 13 | Want to lurk about and see what others are doing with Logstash? 14 | 15 | * The irc channel (#logstash on irc.freenode.org) is a good place for this 16 | * The [forum](https://discuss.elastic.co/c/logstash) is also 17 | great for learning from others. 18 | 19 | ## Got Questions? 20 | 21 | Have a problem you want Logstash to solve for you? 22 | 23 | * You can ask a question in the [forum](https://discuss.elastic.co/c/logstash) 24 | * Alternately, you are welcome to join the IRC channel #logstash on 25 | irc.freenode.org and ask for help there! 26 | 27 | ## Have an Idea or Feature Request? 28 | 29 | * File a ticket on [GitHub](https://github.com/elastic/logstash/issues). Please remember that GitHub is used only for issues and feature requests. If you have a general question, the [forum](https://discuss.elastic.co/c/logstash) or IRC would be the best place to ask. 30 | 31 | ## Something Not Working? Found a Bug? 32 | 33 | If you think you found a bug, it probably is a bug. 34 | 35 | * If it is a general Logstash or a pipeline issue, file it in [Logstash GitHub](https://github.com/elasticsearch/logstash/issues) 36 | * If it is specific to a plugin, please file it in the respective repository under [logstash-plugins](https://github.com/logstash-plugins) 37 | * or ask the [forum](https://discuss.elastic.co/c/logstash). 38 | 39 | # Contributing Documentation and Code Changes 40 | 41 | If you have a bugfix or new feature that you would like to contribute to 42 | logstash, and you think it will take more than a few minutes to produce the fix 43 | (ie; write code), it is worth discussing the change with the Logstash users and developers first! You can reach us via [GitHub](https://github.com/elastic/logstash/issues), the [forum](https://discuss.elastic.co/c/logstash), or via IRC (#logstash on freenode irc) 44 | Please note that Pull Requests without tests will not be merged. If you would like to contribute but do not have experience with writing tests, please ping us on IRC/forum or create a PR and ask our help. 45 | 46 | ## Contributing to plugins 47 | 48 | Check our [documentation](https://www.elastic.co/guide/en/logstash/current/contributing-to-logstash.html) on how to contribute to plugins or write your own! It is super easy! 49 | 50 | ## Contribution Steps 51 | 52 | 1. Test your changes! [Run](https://github.com/elastic/logstash#testing) the test suite 53 | 2. Please make sure you have signed our [Contributor License 54 | Agreement](https://www.elastic.co/contributor-agreement/). We are not 55 | asking you to assign copyright to us, but to give us the right to distribute 56 | your code without restriction. We ask this of all contributors in order to 57 | assure our users of the origin and continuing existence of the code. You 58 | only need to sign the CLA once. 59 | 3. Send a pull request! Push your changes to your fork of the repository and 60 | [submit a pull 61 | request](https://help.github.com/articles/using-pull-requests). In the pull 62 | request, describe what your changes do and mention any bugs/issues related 63 | to the pull request. 64 | 65 | 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Logstash Plugin 2 | 3 | [![Travis Build Status](https://travis-ci.com/logstash-plugins/logstash-input-udp.svg)](https://travis-ci.com/logstash-plugins/logstash-input-udp) 4 | 5 | This is a plugin for [Logstash](https://github.com/elastic/logstash). 6 | 7 | It is fully free and fully open source. The license is Apache 2.0, meaning you are pretty much free to use it however you want in whatever way. 8 | 9 | ## Documentation 10 | 11 | Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elastic.co/guide/en/logstash/current/). 12 | 13 | - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive 14 | - For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide 15 | 16 | ## Need Help? 17 | 18 | Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum. 19 | 20 | ## Developing 21 | 22 | ### 1. Plugin Developement and Testing 23 | 24 | #### Code 25 | - To get started, you'll need JRuby with the Bundler gem installed. 26 | 27 | - Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization. We also provide [example plugins](https://github.com/logstash-plugins?query=example). 28 | 29 | - Install dependencies 30 | ```sh 31 | bundle install 32 | ``` 33 | 34 | #### Test 35 | 36 | - Update your dependencies 37 | 38 | ```sh 39 | bundle install 40 | ``` 41 | 42 | - Run tests 43 | 44 | ```sh 45 | bundle exec rspec 46 | ``` 47 | 48 | ### 2. Running your unpublished Plugin in Logstash 49 | 50 | #### 2.1 Run in a local Logstash clone 51 | 52 | - Edit Logstash `Gemfile` and add the local plugin path, for example: 53 | ```ruby 54 | gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome" 55 | ``` 56 | - Install plugin 57 | ```sh 58 | # Logstash 2.3 and higher 59 | bin/logstash-plugin install --no-verify 60 | 61 | # Prior to Logstash 2.3 62 | bin/plugin install --no-verify 63 | 64 | ``` 65 | - Run Logstash with your plugin 66 | ```sh 67 | bin/logstash -e 'filter {awesome {}}' 68 | ``` 69 | At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash. 70 | 71 | #### 2.2 Run in an installed Logstash 72 | 73 | You can use the same **2.1** method to run your plugin in an installed Logstash by editing its `Gemfile` and pointing the `:path` to your local plugin development directory or you can build the gem and install it using: 74 | 75 | - Build your plugin gem 76 | ```sh 77 | gem build logstash-filter-awesome.gemspec 78 | ``` 79 | - Install the plugin from the Logstash home 80 | ```sh 81 | # Logstash 2.3 and higher 82 | bin/logstash-plugin install --no-verify 83 | 84 | # Prior to Logstash 2.3 85 | bin/plugin install --no-verify 86 | 87 | ``` 88 | - Start Logstash and proceed to test the plugin 89 | 90 | ## Contributing 91 | 92 | All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin. 93 | 94 | Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here. 95 | 96 | It is more important to the community that you are able to contribute. 97 | 98 | For more information about contributing, see the [CONTRIBUTING](https://github.com/elastic/logstash/blob/master/CONTRIBUTING.md) file. -------------------------------------------------------------------------------- /spec/inputs/udp_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require_relative "../spec_helper" 3 | require "logstash/devutils/rspec/shared_examples" 4 | require_relative "../support/client" 5 | require "logstash/codecs/base" 6 | 7 | 8 | class LogStash::Codecs::Crash < LogStash::Codecs::Base 9 | config_name "crash" 10 | 11 | def decode(data) 12 | raise("decode crash") if data == "crash" 13 | yield LogStash::Event.new({"message" => data }) 14 | end 15 | end 16 | 17 | describe LogStash::Inputs::Udp do 18 | before do 19 | srand(RSpec.configuration.seed) 20 | end 21 | 22 | let!(:helper) { UdpHelpers.new } 23 | let(:client) { LogStash::Inputs::Test::UDPClient.new(port) } 24 | let(:port) { rand(1024..65535) } 25 | let(:host) { "0.0.0.0" } 26 | let(:config) { { "port" => port, "host" => host } } 27 | subject { LogStash::Plugin.lookup("input","udp").new(config) } 28 | 29 | after :each do 30 | subject.close rescue nil 31 | end 32 | 33 | describe "register" do 34 | it "should register without errors" do 35 | expect { subject.register }.to_not raise_error 36 | end 37 | end 38 | 39 | describe "receive" do 40 | shared_examples "receiving" do 41 | before(:each) do 42 | subject.register 43 | end 44 | 45 | let(:nevents) { 10 } 46 | 47 | let(:events) do 48 | helper.input(subject, nevents) do 49 | nevents.times do |i| 50 | client.send("msg #{i}") 51 | end 52 | end 53 | end 54 | 55 | it "should receive events been generated" do 56 | expect(events.size).to be(nevents) 57 | messages = events.map { |event| event.get("message")} 58 | messages.each do |message| 59 | expect(message).to match(/msg \d+/) 60 | end 61 | end 62 | end 63 | 64 | context "ipv4" do 65 | let(:client) { LogStash::Inputs::Test::UDPClient.new(port, "127.0.0.1") } 66 | include_examples "receiving" 67 | end 68 | context "ipv6" do 69 | let(:host) { "::1" } 70 | let(:client) { LogStash::Inputs::Test::UDPClient.new(port, "::1") } 71 | include_examples "receiving" 72 | end 73 | end 74 | 75 | shared_examples "respects ECS compatibility setting host metadata" do |ecs_compatibility, field_name| 76 | context "when ecs_compatibility is `#{ecs_compatibility}`" do 77 | let(:config) { { "port" => port, "workers" => 1, "ecs_compatibility" => ecs_compatibility} } 78 | let(:localhost) { "127.0.0.1" } 79 | let(:client) { LogStash::Inputs::Test::UDPClient.new(port, localhost) } 80 | 81 | let(:events) do 82 | helper.input(subject, 1) do 83 | client.send("line1") 84 | end 85 | end 86 | 87 | before(:each) do 88 | subject.register 89 | end 90 | 91 | it "produces event with source_ip_fieldname as '#{field_name}'" do 92 | expect(events.size).to be(1) 93 | message = events.last 94 | expect(message.get(field_name)).to eq(client.host) 95 | end 96 | end 97 | end 98 | 99 | it_behaves_like "respects ECS compatibility setting host metadata", :disabled, "host" 100 | it_behaves_like "respects ECS compatibility setting host metadata", :v1, "[host][ip]" 101 | it_behaves_like "respects ECS compatibility setting host metadata", :v8, "[host][ip]" 102 | 103 | 104 | 105 | describe "uses custom hostname field when ECS is enabled" do 106 | let(:config) { { "port" => port, "workers" => 1, "ecs_compatibility" => :v1, "source_ip_fieldname" => "custom_host_field"} } 107 | let(:localhost) { "127.0.0.1" } 108 | let(:client) { LogStash::Inputs::Test::UDPClient.new(port, localhost) } 109 | 110 | let(:events) do 111 | helper.input(subject, 1) do 112 | client.send("line1") 113 | end 114 | end 115 | 116 | before(:each) do 117 | subject.register 118 | end 119 | 120 | it "should receive event with user defined source_ip_fieldname" do 121 | expect(events.size).to be(1) 122 | message = events.last 123 | expect(message.get(config['source_ip_fieldname'])).to eq(client.host) 124 | end 125 | end 126 | 127 | describe "multiple lines per datagram using line codec" do 128 | # 3 workers for 3 datagrams send below 129 | let(:config) { { "port" => port, "workers" => 3, "codec" => "line" } } 130 | 131 | let(:events) do 132 | helper.input(subject, 8) do 133 | client.send("line1\nline2") 134 | client.send("line3\nline4") 135 | client.send("line5\nline6\nline7\nline8") 136 | end 137 | end 138 | 139 | before(:each) do 140 | subject.register 141 | end 142 | 143 | it "should receive events been generated" do 144 | expect(events.size).to be(8) 145 | messages = events.map { |event| event.get("message") }.sort # important to sort here because order is unpredictable 146 | messages.each_index {|i| expect(messages[i]).to match("line#{i + 1}")} 147 | end 148 | end 149 | 150 | it_behaves_like "an interruptible input plugin" do 151 | # see https://github.com/elastic/logstash-devutils/blob/9c4a1fbf2b0c4547e428c5a40ed84f60aad17f97/lib/logstash/devutils/rspec/shared_examples.rb 152 | end 153 | 154 | describe "worker should ignore codec exception" do 155 | # see custom "crash" codec above which raises upon decoding the "crash" straing payload 156 | let(:config) { { "port" => port, "workers" => 1, "codec" => "crash" } } 157 | 158 | let(:events) do 159 | helper.input(subject, 3) do 160 | client.send("crash") 161 | client.send("foo") 162 | client.send("bar") 163 | client.send("crash") 164 | client.send("baz") 165 | end 166 | end 167 | 168 | before(:each) do 169 | subject.register 170 | end 171 | 172 | it "should receive events been generated" do 173 | expect(events.size).to be(3) 174 | expect(events[0].get("message")).to match("foo") 175 | expect(events[1].get("message")).to match("bar") 176 | expect(events[2].get("message")).to match("baz") 177 | end 178 | end 179 | end 180 | -------------------------------------------------------------------------------- /docs/index.asciidoc: -------------------------------------------------------------------------------- 1 | :plugin: udp 2 | :type: input 3 | :default_codec: plain 4 | 5 | /////////////////////////////////////////// 6 | START - GENERATED VARIABLES, DO NOT EDIT! 7 | /////////////////////////////////////////// 8 | :version: %VERSION% 9 | :release_date: %RELEASE_DATE% 10 | :changelog_url: %CHANGELOG_URL% 11 | :include_path: ../../../../logstash/docs/include 12 | /////////////////////////////////////////// 13 | END - GENERATED VARIABLES, DO NOT EDIT! 14 | /////////////////////////////////////////// 15 | 16 | [id="plugins-{type}s-{plugin}"] 17 | 18 | === Udp input plugin 19 | 20 | include::{include_path}/plugin_header.asciidoc[] 21 | 22 | ==== Description 23 | 24 | Read messages as events over the network via udp. The only required 25 | configuration item is `port`, which specifies the udp port logstash 26 | will listen on for event streams. 27 | 28 | 29 | [id="plugins-{type}s-{plugin}-ecs_metadata"] 30 | ===== Event Metadata and the Elastic Common Schema (ECS) 31 | 32 | This plugin adds a field containing the source IP address of the UDP packet. 33 | By default, the IP address is stored in the host field. 34 | When {ecs-ref}[Elastic Common Schema (ECS)] is enabled (in 35 | <>), the source IP address is stored 36 | in the [host][ip] field. 37 | 38 | You can customize the field name using the <>. 39 | See <> for more information. 40 | 41 | 42 | [id="plugins-{type}s-{plugin}-options"] 43 | ==== Udp Input Configuration Options 44 | 45 | This plugin supports the following configuration options plus the <> described later. 46 | 47 | [cols="<,<,<",options="header",] 48 | |======================================================================= 49 | |Setting |Input type|Required 50 | | <> |<>|No 51 | | <> | <>|No 52 | | <> |<>|No 53 | | <> |<>|Yes 54 | | <> |<>|No 55 | | <> |<>|No 56 | | <> |<>|No 57 | | <> |<>|No 58 | |======================================================================= 59 | 60 | Also see <> for a list of options supported by all 61 | input plugins. 62 | 63 |   64 | 65 | [id="plugins-{type}s-{plugin}-buffer_size"] 66 | ===== `buffer_size` 67 | 68 | * Value type is <> 69 | * Default value is `65536` 70 | 71 | The maximum packet size to read from the network 72 | 73 | [id="plugins-{type}s-{plugin}-ecs_compatibility"] 74 | ===== `ecs_compatibility` 75 | 76 | * Value type is <> 77 | * Supported values are: 78 | ** `disabled`: unstructured connection metadata added at root level 79 | ** `v1`: structured connection metadata added under ECS compliant namespaces 80 | * Default value depends on which version of Logstash is running: 81 | ** When Logstash provides a `pipeline.ecs_compatibility` setting, its value is used as the default 82 | ** Otherwise, the default value is `disabled`. 83 | 84 | Controls this plugin's compatibility with the {ecs-ref}[Elastic Common Schema (ECS)]. 85 | 86 | The value of this setting affects the placement of a TCP connection's metadata on events. 87 | 88 | .Metadata Location by `ecs_compatibility` value 89 | [cols="> 100 | * Default value is `"0.0.0.0"` 101 | 102 | The address which logstash will listen on. 103 | This plugin supports both IPv4 and IPv6. To receive data over IPv6 use an IPv6 address in this setting. 104 | 105 | Example: 106 | [source,ruby] 107 | input { 108 | udp { 109 | host => "::1" 110 | } 111 | } 112 | 113 | [id="plugins-{type}s-{plugin}-port"] 114 | ===== `port` 115 | 116 | * This is a required setting. 117 | * Value type is <> 118 | * There is no default value for this setting. 119 | 120 | The port which logstash will listen on. Remember that ports less 121 | than 1024 (privileged ports) may require root or elevated privileges to use. 122 | 123 | [id="plugins-{type}s-{plugin}-queue_size"] 124 | ===== `queue_size` 125 | 126 | * Value type is <> 127 | * Default value is `2000` 128 | 129 | This is the number of unprocessed UDP packets you can hold in memory 130 | before packets will start dropping. 131 | 132 | [id="plugins-{type}s-{plugin}-receive_buffer_bytes"] 133 | ===== `receive_buffer_bytes` 134 | 135 | * Value type is <> 136 | * There is no default value for this setting. 137 | 138 | The socket receive buffer size in bytes. 139 | If option is not set, the operating system default is used. 140 | The operating system will use the max allowed value if receive_buffer_bytes is larger than allowed. 141 | Consult your operating system documentation if you need to increase this max allowed value. 142 | 143 | [id="plugins-{type}s-{plugin}-source_ip_fieldname"] 144 | ===== `source_ip_fieldname` 145 | 146 | * Value type is <> 147 | * Default value could be `"host"` or `[host][ip]` depending on the value of <> 148 | 149 | The name of the field where the source IP address will be stored. 150 | See <> for more information on how ECS compatibility settings affect these defaults. 151 | 152 | Example: 153 | [source,ruby] 154 | input { 155 | udp { 156 | source_ip_fieldname => "[appliance][monitoring][ip]" 157 | } 158 | } 159 | 160 | [id="plugins-{type}s-{plugin}-workers"] 161 | ===== `workers` 162 | 163 | * Value type is <> 164 | * Default value is `2` 165 | 166 | Number of threads processing packets 167 | 168 | [id="plugins-{type}s-{plugin}-common-options"] 169 | include::{include_path}/{type}.asciidoc[] 170 | 171 | :default_codec!: 172 | -------------------------------------------------------------------------------- /lib/logstash/inputs/udp.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "date" 3 | require "logstash/inputs/base" 4 | require "logstash/namespace" 5 | require "socket" 6 | require "stud/interval" 7 | require "ipaddr" 8 | require "logstash/plugin_mixins/ecs_compatibility_support" 9 | 10 | # Read messages as events over the network via udp. The only required 11 | # configuration item is `port`, which specifies the udp port logstash 12 | # will listen on for event streams. 13 | # 14 | class LogStash::Inputs::Udp < LogStash::Inputs::Base 15 | # adds ecs_compatibility config which could be :disabled or :v1 16 | include LogStash::PluginMixins::ECSCompatibilitySupport(:disabled, :v1, :v8 => :v1) 17 | 18 | config_name "udp" 19 | 20 | default :codec, "plain" 21 | 22 | # The address which logstash will listen on. 23 | config :host, :validate => :string, :default => "0.0.0.0" 24 | 25 | # The port which logstash will listen on. Remember that ports less 26 | # than 1024 (privileged ports) may require root or elevated privileges to use. 27 | config :port, :validate => :number, :required => true 28 | 29 | # The maximum packet size to read from the network 30 | config :buffer_size, :validate => :number, :default => 65536 31 | 32 | # The socket receive buffer size in bytes. 33 | # If option is not set, the operating system default is used. 34 | # The operating system will use the max allowed value if receive_buffer_bytes is larger than allowed. 35 | # Consult your operating system documentation if you need to increase this max allowed value. 36 | config :receive_buffer_bytes, :validate => :number 37 | 38 | # Number of threads processing packets 39 | config :workers, :validate => :number, :default => 2 40 | 41 | # This is the number of unprocessed UDP packets you can hold in memory 42 | # before packets will start dropping. 43 | config :queue_size, :validate => :number, :default => 2000 44 | 45 | # The name of the field where the source IP address will be stored 46 | config :source_ip_fieldname, :validate => :string 47 | 48 | def initialize(params) 49 | super 50 | BasicSocket.do_not_reverse_lookup = true 51 | end 52 | 53 | def register 54 | @udp = nil 55 | @metric_errors = metric.namespace(:errors) 56 | if source_ip_fieldname.nil? 57 | # define ecs name mapping 58 | @field_source_ip = ecs_select[disabled: "host", v1: "[host][ip]"] 59 | else 60 | @field_source_ip = source_ip_fieldname 61 | if (ecs_compatibility != :disabled) 62 | @logger.warn("'source_ip_fieldname' is user customized, please check is has an ECS compatible name ") 63 | end 64 | end 65 | end # def register 66 | 67 | def run(output_queue) 68 | @output_queue = output_queue 69 | 70 | @input_to_worker = SizedQueue.new(@queue_size) 71 | metric.gauge(:queue_size, @queue_size) 72 | metric.gauge(:workers, @workers) 73 | 74 | @input_workers = (1..@workers).to_a.map do |i| 75 | @logger.debug("Starting UDP worker thread", :worker => i) 76 | Thread.new(i, @codec.clone) { |i, codec| inputworker(i, codec) } 77 | end 78 | 79 | begin 80 | # udp server 81 | udp_listener(output_queue) 82 | rescue => e 83 | @logger.error("UDP listener died", :exception => e, :backtrace => e.backtrace) 84 | @metric_errors.increment(:listener) 85 | Stud.stoppable_sleep(5) { stop? } 86 | retry unless stop? 87 | ensure 88 | # signal workers to end 89 | @input_workers.size.times { @input_to_worker.push([:END, nil]) } 90 | @input_workers.each { |thread| thread.join } 91 | end 92 | end 93 | 94 | def close 95 | if @udp && !@udp.closed? 96 | @udp.close rescue ignore_close_and_log($!) 97 | end 98 | end 99 | 100 | def stop 101 | if @udp && !@udp.closed? 102 | @udp.close rescue ignore_close_and_log($!) 103 | end 104 | end 105 | 106 | private 107 | 108 | def udp_listener(output_queue) 109 | @logger.info("Starting UDP listener", :address => "#{@host}:#{@port}") 110 | 111 | if @udp && !@udp.closed? 112 | @udp.close 113 | end 114 | 115 | if IPAddr.new(@host).ipv6? 116 | @udp = UDPSocket.new(Socket::AF_INET6) 117 | elsif IPAddr.new(@host).ipv4? 118 | @udp = UDPSocket.new(Socket::AF_INET) 119 | end 120 | # set socket receive buffer size if configured 121 | if @receive_buffer_bytes 122 | @udp.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVBUF, @receive_buffer_bytes) 123 | end 124 | rcvbuf = @udp.getsockopt(Socket::SOL_SOCKET, Socket::SO_RCVBUF).unpack("i")[0] 125 | if @receive_buffer_bytes && rcvbuf != @receive_buffer_bytes 126 | @logger.warn("Unable to set receive_buffer_bytes to desired size. Requested #{@receive_buffer_bytes} but obtained #{rcvbuf} bytes.") 127 | end 128 | 129 | @udp.bind(@host, @port) 130 | @logger.info("UDP listener started", :address => "#{@host}:#{@port}", :receive_buffer_bytes => "#{rcvbuf}", :queue_size => "#{@queue_size}") 131 | 132 | 133 | while !stop? 134 | next if IO.select([@udp], [], [], 0.5).nil? 135 | # collect datagram messages and add to inputworker queue 136 | @queue_size.times do 137 | begin 138 | payload, client = @udp.recvfrom_nonblock(@buffer_size) 139 | break if payload.empty? 140 | push_data(payload, client) 141 | rescue IO::EAGAINWaitReadable 142 | break 143 | end 144 | end 145 | end 146 | ensure 147 | if @udp 148 | @udp.close_read rescue ignore_close_and_log($!) 149 | @udp.close_write rescue ignore_close_and_log($!) 150 | end 151 | end 152 | 153 | def inputworker(number, codec) 154 | LogStash::Util::set_thread_name(" e 167 | @logger.error("Exception in inputworker", "exception" => e, "backtrace" => e.backtrace) 168 | @metric_errors.increment(:worker) 169 | end 170 | end 171 | end 172 | 173 | # work around jruby/jruby#5148 174 | # For jruby 9k (ruby >= 2.x) we need to truncate the buffer 175 | # after reading from the socket otherwise each 176 | # message will use 64kb 177 | if RUBY_VERSION.match(/^2/) 178 | def push_data(payload, client) 179 | payload = payload.b.force_encoding(Encoding::UTF_8) 180 | @input_to_worker.push([payload, client]) 181 | end 182 | else 183 | def push_data(payload, client) 184 | @input_to_worker.push([payload, client]) 185 | end 186 | end 187 | 188 | def push_decoded_event(ip_address, event) 189 | decorate(event) 190 | event.set(@field_source_ip, ip_address) if event.get(@field_source_ip).nil? 191 | @output_queue.push(event) 192 | metric.increment(:events) 193 | end 194 | 195 | def ignore_close_and_log(e) 196 | @logger.debug("ignoring close exception", "exception" => e) 197 | end 198 | end 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 2020 Elastic and contributors 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. 203 | --------------------------------------------------------------------------------