-
Notifications
You must be signed in to change notification settings - Fork 5.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add HTTP listener service input plugin #1407
Closed
Closed
Changes from 17 commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
933bdaa
initial http_listener implementation
c4e0452
fix incredibly stupid bugs
6b5a9d3
populate README
6e79135
support query endpoint and change default listen port
a0cb608
set response headers for query endpoint
121d71f
add unit tests
ac9e653
revert erroneous Godeps change
e9d3870
add plugin ref to top-level README
cf08b56
remove debug output and add empty post body test
2f36631
fix linter errors
2dee84d
move stoppableListener into repo
13c4f95
use constants for http status codes
7c17468
add CHANGELOG entry
5866acd
Merge branch 'master' of https://github.com/influxdata/telegraf
bb09363
Merge branch 'master' into master
6da73de
address code review comments re. style/structure
7843c3a
Merge branch 'master' of https://github.com/bagelswitch/telegraf
4b424a2
address further code review comments
4a812b0
Merge branch 'master' of https://github.com/influxdata/telegraf
51215b5
Merge branch 'master' into master
0eebee9
Merge branch 'master' into master
2d460d7
Merge branch 'master' of https://github.com/influxdata/telegraf
f715c17
Merge branch 'master' of https://github.com/influxdata/telegraf
54385d0
correct linter error after merge
739e0af
Merge branch 'master' of https://github.com/influxdata/telegraf
bbeb5ae
Merge branch 'master' of https://github.com/influxdata/telegraf
d660903
add note to README re. database creation calls per PR comments
142818a
Merge branch 'master' of https://github.com/influxdata/telegraf
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# HTTP listener service input plugin | ||
|
||
The HTTP listener is a service input plugin that listens for messages sent via HTTP POST. | ||
The plugin expects messages in the InfluxDB line-protocol ONLY, other Telegraf input data formats are not supported. | ||
The intent of the plugin is to allow Telegraf to serve as a proxy/router for the /write endpoint of the InfluxDB HTTP API. | ||
|
||
See: [Telegraf Input Data Formats](https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md#influx). | ||
Example: curl -i -XPOST 'http://localhost:8186/write' --data-binary 'cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000' | ||
|
||
### Configuration: | ||
|
||
This is a sample configuration for the plugin. | ||
|
||
```toml | ||
# # Influx HTTP write listener | ||
[[inputs.http_listener]] | ||
## Address and port to host HTTP listener on | ||
service_address = ":8186" | ||
|
||
## timeouts in seconds | ||
read_timeout = "10" | ||
write_timeout = "10" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
package http_listener | ||
|
||
import ( | ||
"io/ioutil" | ||
"log" | ||
"net" | ||
"net/http" | ||
"strconv" | ||
"sync" | ||
"time" | ||
|
||
"github.com/influxdata/telegraf" | ||
"github.com/influxdata/telegraf/plugins/inputs" | ||
"github.com/influxdata/telegraf/plugins/inputs/http_listener/stoppableListener" | ||
"github.com/influxdata/telegraf/plugins/parsers" | ||
) | ||
|
||
type HttpListener struct { | ||
ServiceAddress string | ||
ReadTimeout string | ||
WriteTimeout string | ||
|
||
sync.Mutex | ||
|
||
listener *stoppableListener.StoppableListener | ||
|
||
parser parsers.Parser | ||
acc telegraf.Accumulator | ||
} | ||
|
||
const sampleConfig = ` | ||
## Address and port to host HTTP listener on | ||
service_address = ":8186" | ||
|
||
## timeouts in seconds | ||
read_timeout = "10" | ||
write_timeout = "10" | ||
` | ||
|
||
func (t *HttpListener) SampleConfig() string { | ||
return sampleConfig | ||
} | ||
|
||
func (t *HttpListener) Description() string { | ||
return "Influx HTTP write listener" | ||
} | ||
|
||
func (t *HttpListener) Gather(_ telegraf.Accumulator) error { | ||
return nil | ||
} | ||
|
||
func (t *HttpListener) SetParser(parser parsers.Parser) { | ||
t.parser = parser | ||
} | ||
|
||
// Start starts the http listener service. | ||
func (t *HttpListener) Start(acc telegraf.Accumulator) error { | ||
t.Lock() | ||
defer t.Unlock() | ||
|
||
t.acc = acc | ||
|
||
var rawListener, err = net.Listen("tcp", t.ServiceAddress) | ||
if err != nil { | ||
return err | ||
} | ||
t.listener, err = stoppableListener.New(rawListener) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
go t.httpListen() | ||
|
||
log.Printf("Started HTTP listener service on %s\n", t.ServiceAddress) | ||
|
||
return nil | ||
} | ||
|
||
// Stop cleans up all resources | ||
func (t *HttpListener) Stop() { | ||
t.Lock() | ||
defer t.Unlock() | ||
|
||
t.listener.Stop() | ||
t.listener.Close() | ||
|
||
log.Println("Stopped HTTP listener service on ", t.ServiceAddress) | ||
} | ||
|
||
// httpListen listens for HTTP requests. | ||
func (t *HttpListener) httpListen() error { | ||
|
||
readTimeout, err := strconv.ParseInt(t.ReadTimeout, 10, 32) | ||
if err != nil { | ||
return err | ||
} | ||
writeTimeout, err := strconv.ParseInt(t.WriteTimeout, 10, 32) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
var server = http.Server{ | ||
Handler: t, | ||
ReadTimeout: time.Duration(readTimeout) * time.Second, | ||
WriteTimeout: time.Duration(writeTimeout) * time.Second, | ||
} | ||
|
||
return server.Serve(t.listener) | ||
} | ||
|
||
func (t *HttpListener) ServeHTTP(res http.ResponseWriter, req *http.Request) { | ||
body, err := ioutil.ReadAll(req.Body) | ||
|
||
if err != nil { | ||
log.Printf("Problem reading request: [%s], Error: %s\n", string(body), err) | ||
res.WriteHeader(http.StatusInternalServerError) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. http.Error(w. "ERROR reading request", http.StatusInternalServerError) |
||
res.Write([]byte("ERROR reading request")) | ||
} | ||
|
||
var path = req.URL.Path[1:] | ||
|
||
if path == "write" { | ||
var metrics []telegraf.Metric | ||
metrics, err = t.parser.Parse(body) | ||
if err == nil { | ||
t.storeMetrics(metrics) | ||
res.WriteHeader(http.StatusNoContent) | ||
res.Write([]byte("")) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This call does nothing. Just remove it. |
||
} else { | ||
log.Printf("Problem parsing body: [%s], Error: %s\n", string(body), err) | ||
res.WriteHeader(http.StatusInternalServerError) | ||
res.Write([]byte("ERROR parsing metrics")) | ||
} | ||
} else if path == "query" { | ||
// Deliver a dummy response to the query endpoint, as some InfluxDB clients test endpoint availability with a query | ||
res.Header().Set("Content-Type", "application/json") | ||
res.Header().Set("X-Influxdb-Version", "1.0") | ||
res.WriteHeader(http.StatusOK) | ||
res.Write([]byte("{\"results\":[]}")) | ||
} else { | ||
// Don't know how to respond to calls to other endpoints | ||
res.WriteHeader(http.StatusNotFound) | ||
res.Write([]byte("Not Found")) | ||
} | ||
} | ||
|
||
func (t *HttpListener) storeMetrics(metrics []telegraf.Metric) error { | ||
t.Lock() | ||
defer t.Unlock() | ||
|
||
for _, m := range metrics { | ||
t.acc.AddFields(m.Name(), m.Fields(), m.Tags(), m.Time()) | ||
} | ||
return nil | ||
} | ||
|
||
func init() { | ||
inputs.Add("http_listener", func() telegraf.Input { | ||
return &HttpListener{} | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
package http_listener | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/influxdata/telegraf/plugins/parsers" | ||
"github.com/influxdata/telegraf/testutil" | ||
|
||
"bytes" | ||
"github.com/stretchr/testify/require" | ||
"net/http" | ||
) | ||
|
||
const ( | ||
testMsg = "cpu_load_short,host=server01 value=12.0 1422568543702900257\n" | ||
|
||
testMsgs = `cpu_load_short,host=server02 value=12.0 1422568543702900257 | ||
cpu_load_short,host=server03 value=12.0 1422568543702900257 | ||
cpu_load_short,host=server04 value=12.0 1422568543702900257 | ||
cpu_load_short,host=server05 value=12.0 1422568543702900257 | ||
cpu_load_short,host=server06 value=12.0 1422568543702900257 | ||
` | ||
badMsg = "blahblahblah: 42\n" | ||
|
||
emptyMsg = "" | ||
) | ||
|
||
func newTestHttpListener() *HttpListener { | ||
listener := &HttpListener{ | ||
ServiceAddress: ":8186", | ||
ReadTimeout: "10", | ||
WriteTimeout: "10", | ||
} | ||
return listener | ||
} | ||
|
||
func TestWriteHTTP(t *testing.T) { | ||
listener := newTestHttpListener() | ||
listener.parser, _ = parsers.NewInfluxParser() | ||
|
||
acc := &testutil.Accumulator{} | ||
require.NoError(t, listener.Start(acc)) | ||
defer listener.Stop() | ||
|
||
time.Sleep(time.Millisecond * 25) | ||
|
||
// post single message to listener | ||
var resp, err = http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(testMsg))) | ||
require.NoError(t, err) | ||
require.EqualValues(t, 204, resp.StatusCode) | ||
|
||
time.Sleep(time.Millisecond * 15) | ||
acc.AssertContainsTaggedFields(t, "cpu_load_short", | ||
map[string]interface{}{"value": float64(12)}, | ||
map[string]string{"host": "server01"}, | ||
) | ||
|
||
// post multiple message to listener | ||
resp, err = http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(testMsgs))) | ||
require.NoError(t, err) | ||
require.EqualValues(t, 204, resp.StatusCode) | ||
|
||
time.Sleep(time.Millisecond * 15) | ||
hostTags := []string{"server02", "server03", | ||
"server04", "server05", "server06"} | ||
for _, hostTag := range hostTags { | ||
acc.AssertContainsTaggedFields(t, "cpu_load_short", | ||
map[string]interface{}{"value": float64(12)}, | ||
map[string]string{"host": hostTag}, | ||
) | ||
} | ||
} | ||
|
||
func TestWriteHTTPInvalid(t *testing.T) { | ||
time.Sleep(time.Millisecond * 250) | ||
|
||
listener := newTestHttpListener() | ||
listener.parser, _ = parsers.NewInfluxParser() | ||
|
||
acc := &testutil.Accumulator{} | ||
require.NoError(t, listener.Start(acc)) | ||
defer listener.Stop() | ||
|
||
time.Sleep(time.Millisecond * 25) | ||
|
||
// post single message to listener | ||
var resp, err = http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(badMsg))) | ||
require.NoError(t, err) | ||
require.EqualValues(t, 500, resp.StatusCode) | ||
} | ||
|
||
func TestWriteHTTPEmpty(t *testing.T) { | ||
time.Sleep(time.Millisecond * 250) | ||
|
||
listener := newTestHttpListener() | ||
listener.parser, _ = parsers.NewInfluxParser() | ||
|
||
acc := &testutil.Accumulator{} | ||
require.NoError(t, listener.Start(acc)) | ||
defer listener.Stop() | ||
|
||
time.Sleep(time.Millisecond * 25) | ||
|
||
// post single message to listener | ||
var resp, err = http.Post("http://localhost:8186/write?db=mydb", "", bytes.NewBuffer([]byte(emptyMsg))) | ||
require.NoError(t, err) | ||
require.EqualValues(t, 204, resp.StatusCode) | ||
} | ||
|
||
func TestQueryHTTP(t *testing.T) { | ||
time.Sleep(time.Millisecond * 250) | ||
|
||
listener := newTestHttpListener() | ||
listener.parser, _ = parsers.NewInfluxParser() | ||
|
||
acc := &testutil.Accumulator{} | ||
require.NoError(t, listener.Start(acc)) | ||
defer listener.Stop() | ||
|
||
time.Sleep(time.Millisecond * 25) | ||
|
||
// post query to listener | ||
var resp, err = http.Post("http://localhost:8186/query?db=&q=CREATE+DATABASE+IF+NOT+EXISTS+%22mydb%22", "", nil) | ||
require.NoError(t, err) | ||
require.EqualValues(t, 200, resp.StatusCode) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
Copyright (c) 2014, Eric Urban | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: | ||
|
||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. | ||
|
||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Type of timeout fields should be time.Duration