-
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
Changes from 10 commits
933bdaa
c4e0452
6b5a9d3
6e79135
a0cb608
121d71f
ac9e653
e9d3870
cf08b56
2f36631
2dee84d
13c4f95
7c17468
5866acd
bb09363
6da73de
7843c3a
4b424a2
4a812b0
51215b5
0eebee9
2d460d7
f715c17
54385d0
739e0af
bbeb5ae
d660903
142818a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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" | ||
``` |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
package http_listener | ||
|
||
import ( | ||
"log" | ||
"net" | ||
"net/http" | ||
"sync" | ||
"time" | ||
|
||
"github.com/influxdata/telegraf" | ||
"github.com/influxdata/telegraf/plugins/inputs" | ||
"github.com/influxdata/telegraf/plugins/parsers" | ||
"io/ioutil" | ||
|
||
"github.com/hydrogen18/stoppableListener" | ||
"strconv" | ||
) | ||
|
||
type HttpListener struct { | ||
ServiceAddress string | ||
ReadTimeout string | ||
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. Type of timeout fields should be time.Duration |
||
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) | ||
t.listener, err = stoppableListener.New(rawListener) | ||
|
||
go t.httpListen() | ||
|
||
log.Printf("Started HTTP listener service on %s\n", t.ServiceAddress) | ||
|
||
return err | ||
} | ||
|
||
// 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) | ||
writeTimeout, err := strconv.ParseInt(t.WriteTimeout, 10, 32) | ||
|
||
var server = http.Server{ | ||
Handler: t, | ||
ReadTimeout: time.Duration(readTimeout) * time.Second, | ||
WriteTimeout: time.Duration(writeTimeout) * time.Second, | ||
} | ||
|
||
err = server.Serve(t.listener) | ||
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. return server.Serve(t.listener) |
||
|
||
return err | ||
} | ||
|
||
func (t *HttpListener) ServeHTTP(res http.ResponseWriter, req *http.Request) { | ||
body, err := ioutil.ReadAll(req.Body) | ||
|
||
if err == nil { | ||
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. Make it err != nil and unident usual (non-error) path |
||
var path = req.URL.Path[1:] | ||
|
||
if path == "write" { | ||
var metrics []telegraf.Metric | ||
metrics, err = t.parser.Parse(body) | ||
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. Can't find where parser is initialized 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. t.parser is initialized in HttpListener.SetParser() - I copied this pattern from the existing TCP listener plugin. |
||
if err == nil { | ||
t.storeMetrics(metrics) | ||
} else { | ||
log.Printf("Problem parsing body: [%s], Error: %s\n", string(body), err) | ||
res.WriteHeader(500) | ||
res.Write([]byte("ERROR parsing metrics")) | ||
} | ||
res.WriteHeader(204) | ||
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. for these numbers you should use the 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. Fixed. |
||
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 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(200) | ||
res.Write([]byte("{\"results\":[]}")) | ||
} else { | ||
// Don't know how to respond to calls to other endpoints | ||
res.WriteHeader(404) | ||
res.Write([]byte("Not Found")) | ||
} | ||
} else { | ||
log.Printf("Problem reading request: [%s], Error: %s\n", string(body), err) | ||
res.WriteHeader(500) | ||
res.Write([]byte("ERROR reading request")) | ||
} | ||
} | ||
|
||
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{} | ||
}) | ||
} |
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) | ||
} |
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.
this is only ~40 lines of code, you should just copy it in-repo instead of as a dependency
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.
Makes sense, done!