author | Mahlon E. Smith <mahlon@martini.nu> |
Tue, 06 Nov 2018 15:54:05 -0800 | |
changeset 16 | fce5b4150c09 |
parent 15 | ed87882bb7f0 |
child 17 | 96b8799a565a |
permissions | -rw-r--r-- |
8 | 1 |
# vim: set et nosta sw=4 ts=4 : |
0 | 2 |
# |
3 |
# Copyright (c) 2018, Mahlon E. Smith <mahlon@martini.nu> |
|
4 |
# All rights reserved. |
|
5 |
# Redistribution and use in source and binary forms, with or without |
|
6 |
# modification, are permitted provided that the following conditions are met: |
|
7 |
# |
|
8 |
# * Redistributions of source code must retain the above copyright |
|
9 |
# notice, this list of conditions and the following disclaimer. |
|
10 |
# |
|
11 |
# * Redistributions in binary form must reproduce the above copyright |
|
12 |
# notice, this list of conditions and the following disclaimer in the |
|
13 |
# documentation and/or other materials provided with the distribution. |
|
14 |
# |
|
15 |
# * Neither the name of Mahlon E. Smith nor the names of his |
|
16 |
# contributors may be used to endorse or promote products derived |
|
17 |
# from this software without specific prior written permission. |
|
18 |
# |
|
19 |
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY |
|
20 |
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
21 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
|
22 |
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY |
|
23 |
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
|
24 |
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
|
25 |
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
|
26 |
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
|
27 |
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
|
28 |
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
|
29 |
||
30 |
||
31 |
import |
|
32 |
db_postgres, |
|
33 |
json, |
|
5 | 34 |
math, |
0 | 35 |
nativesockets, |
36 |
net, |
|
5 | 37 |
os, |
16 | 38 |
parseopt, |
8 | 39 |
posix, |
0 | 40 |
strutils, |
41 |
tables, |
|
5 | 42 |
terminal, |
8 | 43 |
times |
0 | 44 |
|
45 |
||
46 |
const |
|
16 | 47 |
VERSION = "v0.2.0" |
0 | 48 |
USAGE = """ |
5 | 49 |
./netdata_tsrelay [-q][-v][-h] --dbopts="[PostgreSQL connection string]" --listen-port=14866 --listen-addr=0.0.0.0 |
50 |
||
51 |
-q: Quiet mode. No output at all. Ignored if -d is supplied. |
|
52 |
-d: Debug: Show incoming and parsed data. |
|
53 |
-v: Display version number. |
|
11 | 54 |
-T: Change the destination table name from the default 'netdata'. |
55 |
-t: Alter the maximum time (in ms) an open socket waits for data. Default: 500ms. |
|
5 | 56 |
-h: Help. You're lookin' at it. |
0 | 57 |
|
58 |
The default connection string is: |
|
13
e1777929ba15
Remove port and user from the default dbopts, so they instead use the postgresql behavioral default.
Mahlon E. Smith <mahlon@laika.com>
parents:
11
diff
changeset
|
59 |
"host=localhost dbname=netdata application_name=netdata-tsrelay" |
0 | 60 |
""" |
61 |
INSERT_SQL = """ |
|
11 | 62 |
INSERT INTO $1 |
0 | 63 |
( time, host, metrics ) |
64 |
VALUES |
|
65 |
( 'epoch'::timestamptz + ? * '1 second'::interval, ?, ? ) |
|
66 |
""" |
|
67 |
||
68 |
||
5 | 69 |
type |
70 |
Config = object of RootObj |
|
71 |
dbopts: string # The postgresql connection parameters. (See https://www.postgresql.org/docs/current/static/libpq-connect.html) |
|
11 | 72 |
dbtable: string # The name of the table to write to. |
73 |
listen_port: int # The port to listen for incoming connections. |
|
5 | 74 |
listen_addr: string # The IP address listen for incoming connections. Defaults to inaddr_any. |
75 |
verbose: bool # Be informative |
|
76 |
debug: bool # Spew out raw data |
|
11 | 77 |
insertsql: string # The SQL insert string after interpolating the table name. |
78 |
timeout: int # How long to block, waiting on connection data. |
|
0 | 79 |
|
8 | 80 |
# Global configuration |
81 |
var conf: Config |
|
0 | 82 |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
83 |
|
5 | 84 |
proc hl( msg: string, fg: ForegroundColor, bright=false ): string = |
85 |
## Quick wrapper for color formatting a string, since the 'terminal' |
|
86 |
## module only deals with stdout directly. |
|
8 | 87 |
if not isatty(stdout): return msg |
5 | 88 |
|
89 |
var color: BiggestInt = ord( fg ) |
|
90 |
if bright: inc( color, 60 ) |
|
91 |
result = "\e[" & $color & 'm' & msg & "\e[0m" |
|
92 |
||
93 |
||
0 | 94 |
proc fetch_data( client: Socket ): string = |
95 |
## Netdata JSON backend doesn't send a length, so we read line by |
|
96 |
## line and wait for stream timeout to determine a "sample". |
|
16 | 97 |
var buf: string = "" |
0 | 98 |
try: |
11 | 99 |
result = client.recv_line( timeout=conf.timeout ) |
16 | 100 |
if result != "": result = result & "\n" |
8 | 101 |
while buf != "": |
11 | 102 |
buf = client.recv_line( timeout=conf.timeout ) |
16 | 103 |
if buf != "": result = result & buf & "\n" |
0 | 104 |
except TimeoutError: |
105 |
discard |
|
106 |
||
107 |
||
8 | 108 |
proc parse_data( data: string ): seq[ JsonNode ] = |
109 |
## Given a raw +data+ string, parse JSON and return a sequence |
|
110 |
## of JSON samples. Netdata can buffer multiple samples in one batch. |
|
111 |
result = @[] |
|
16 | 112 |
if data == "": return |
0 | 113 |
|
114 |
# Hash of sample timeperiods to pivoted json data |
|
8 | 115 |
var pivoted_data = init_table[ BiggestInt, JsonNode ]() |
0 | 116 |
|
117 |
for sample in split_lines( data ): |
|
16 | 118 |
if sample == "": continue |
11 | 119 |
if conf.debug: echo sample.hl( fgBlack, bright=true ) |
0 | 120 |
|
121 |
var parsed: JsonNode |
|
122 |
try: |
|
123 |
parsed = sample.parse_json |
|
124 |
except JsonParsingError: |
|
5 | 125 |
if conf.debug: echo hl( "Unable to parse sample line: " & sample.hl(fgRed, bright=true), fgRed ) |
8 | 126 |
continue |
127 |
if parsed.kind != JObject: return |
|
0 | 128 |
|
129 |
# Create or use existing Json object for modded data. |
|
130 |
# |
|
131 |
var pivot: JsonNode |
|
8 | 132 |
try: |
16 | 133 |
let key = parsed[ "timestamp" ].get_int |
8 | 134 |
|
135 |
if pivoted_data.has_key( key ): |
|
136 |
pivot = pivoted_data[ key ] |
|
137 |
else: |
|
138 |
pivot = newJObject() |
|
139 |
pivoted_data[ key ] = pivot |
|
0 | 140 |
|
8 | 141 |
var name = parsed[ "chart_id" ].get_str & "." & parsed[ "id" ].get_str |
142 |
pivot[ "hostname" ] = parsed[ "hostname" ] |
|
143 |
pivot[ "timestamp" ] = parsed[ "timestamp" ] |
|
144 |
pivot[ name ] = parsed[ "value" ] |
|
145 |
except: |
|
146 |
continue |
|
0 | 147 |
|
8 | 148 |
for timestamp, sample in pivoted_data: |
149 |
result.add( sample ) |
|
0 | 150 |
|
151 |
||
8 | 152 |
proc write_to_database( samples: seq[ JsonNode ] ): void = |
153 |
## Given a sequence of json samples, write them to database. |
|
154 |
if samples.len == 0: return |
|
155 |
||
156 |
let db = open( "", "", "", conf.dbopts ) |
|
157 |
||
158 |
try: |
|
159 |
db.exec sql( "BEGIN" ) |
|
160 |
for sample in samples: |
|
161 |
var |
|
16 | 162 |
timestamp = sample[ "timestamp" ].get_int |
15
ed87882bb7f0
Lowercase all hostnames before sending to the database.
Mahlon E. Smith <mahlon@martini.nu>
parents:
13
diff
changeset
|
163 |
host = sample[ "hostname" ].get_str.to_lowerascii |
8 | 164 |
sample.delete( "timestamp" ) |
165 |
sample.delete( "hostname" ) |
|
11 | 166 |
db.exec sql( conf.insertsql ), timestamp, host, sample |
8 | 167 |
db.exec sql( "COMMIT" ) |
168 |
except: |
|
169 |
let |
|
170 |
e = getCurrentException() |
|
171 |
msg = getCurrentExceptionMsg() |
|
172 |
echo "Got exception ", repr(e), " while writing to DB: ", msg |
|
173 |
discard |
|
174 |
||
175 |
db.close |
|
176 |
||
177 |
||
178 |
proc process( client: Socket, address: string ): void = |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
179 |
## Do the work for a connected client within child process. |
8 | 180 |
let t0 = cpu_time() |
0 | 181 |
var raw_data = client.fetch_data |
182 |
||
5 | 183 |
# Done with the socket, netdata will automatically |
184 |
# reconnect. Save local resources/file descriptors |
|
185 |
# by closing after the send is considered complete. |
|
186 |
# |
|
0 | 187 |
try: |
188 |
client.close |
|
189 |
except OSError: |
|
190 |
return |
|
191 |
||
8 | 192 |
# Pivot the parsed data to a single JSON blob per sample time. |
193 |
var samples = parse_data( raw_data ) |
|
194 |
write_to_database( samples ) |
|
5 | 195 |
|
196 |
if conf.verbose: |
|
197 |
echo( |
|
8 | 198 |
hl( $(epochTime().to_int), fgMagenta, bright=true ), |
199 |
" ", |
|
200 |
hl( $(samples.len), fgWhite, bright=true ), |
|
5 | 201 |
" sample(s) parsed from ", |
202 |
address.hl( fgYellow, bright=true ), |
|
203 |
" in ", hl($( round(cpu_time() - t0, 3) ), fgWhite, bright=true), " seconds." |
|
204 |
# " ", hl($(round((get_occupied_mem()/1024/1024),1)), fgWhite, bright=true), "MB memory used." |
|
205 |
) |
|
206 |
||
0 | 207 |
|
8 | 208 |
proc serverloop( conf: Config ): void = |
0 | 209 |
## Open a database connection, bind to the listening socket, |
210 |
## and start serving incoming netdata streams. |
|
211 |
let db = open( "", "", "", conf.dbopts ) |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
212 |
db.close |
8 | 213 |
if conf.verbose: echo( "Successfully tested connection to the backend database.".hl( fgGreen ) ) |
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
214 |
|
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
215 |
# Ensure children are properly reaped. |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
216 |
# |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
217 |
var sa: Sigaction |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
218 |
sa.sa_handler = SIG_IGN |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
219 |
discard sigaction( SIGCHLD, sa ) |
5 | 220 |
|
8 | 221 |
# Setup listening socket. |
222 |
# |
|
223 |
var server = newSocket() |
|
0 | 224 |
server.set_sock_opt( OptReuseAddr, true ) |
5 | 225 |
server.bind_addr( Port(conf.listen_port), conf.listen_addr ) |
0 | 226 |
server.listen() |
227 |
||
5 | 228 |
if conf.verbose: |
229 |
echo( |
|
230 |
"Listening for incoming connections on ".hl( fgGreen, bright=true ), |
|
231 |
hl( (if conf.listen_addr == "0.0.0.0": "*" else: conf.listen_addr) , fgBlue, bright=true ), |
|
232 |
":", |
|
233 |
hl( $conf.listen_port, fgBlue, bright=true ), |
|
234 |
) |
|
235 |
echo "" |
|
236 |
||
8 | 237 |
# Wait for incoming connections, fork for each client. |
238 |
# |
|
0 | 239 |
while true: |
8 | 240 |
var |
241 |
client = new Socket |
|
242 |
address = "" |
|
6
1f366fc61592
Each incoming connection requires its own client socket.
Mahlon E. Smith <mahlon@laika.com>
parents:
5
diff
changeset
|
243 |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
244 |
# Block, waiting for new connections. |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
245 |
server.acceptAddr( client, address ) |
8 | 246 |
|
247 |
if fork() == 0: |
|
248 |
server.close |
|
249 |
client.process( address ) |
|
250 |
quit( 0 ) |
|
7
c0bcf3bea772
Force a GC pass after 25 cycles. Don't bother with sync() at exit, unnecessary.
Mahlon E. Smith <mahlon@laika.com>
parents:
6
diff
changeset
|
251 |
|
6
1f366fc61592
Each incoming connection requires its own client socket.
Mahlon E. Smith <mahlon@laika.com>
parents:
5
diff
changeset
|
252 |
client.close |
7
c0bcf3bea772
Force a GC pass after 25 cycles. Don't bother with sync() at exit, unnecessary.
Mahlon E. Smith <mahlon@laika.com>
parents:
6
diff
changeset
|
253 |
when defined( testing ): dumpNumberOfInstances() |
0 | 254 |
|
255 |
||
8 | 256 |
proc parse_cmdline: Config = |
0 | 257 |
## Populate the config object with the user's preferences. |
5 | 258 |
|
8 | 259 |
# Config object defaults. |
260 |
# |
|
261 |
result = Config( |
|
13
e1777929ba15
Remove port and user from the default dbopts, so they instead use the postgresql behavioral default.
Mahlon E. Smith <mahlon@laika.com>
parents:
11
diff
changeset
|
262 |
dbopts: "host=localhost dbname=netdata application_name=netdata-tsrelay", |
11 | 263 |
dbtable: "netdata", |
8 | 264 |
listen_port: 14866, |
265 |
listen_addr: "0.0.0.0", |
|
266 |
verbose: true, |
|
11 | 267 |
debug: false, |
268 |
timeout: 500, |
|
269 |
insertsql: INSERT_SQL % [ "netdata" ] |
|
8 | 270 |
) |
271 |
||
5 | 272 |
# always set debug mode if development build. |
8 | 273 |
result.debug = defined( testing ) |
5 | 274 |
|
0 | 275 |
for kind, key, val in getopt(): |
276 |
case kind |
|
277 |
||
278 |
of cmdArgument: |
|
279 |
discard |
|
280 |
||
281 |
of cmdLongOption, cmdShortOption: |
|
282 |
case key |
|
5 | 283 |
of "debug", "d": |
8 | 284 |
result.debug = true |
5 | 285 |
|
0 | 286 |
of "help", "h": |
287 |
echo USAGE |
|
288 |
quit( 0 ) |
|
5 | 289 |
|
290 |
of "quiet", "q": |
|
8 | 291 |
result.verbose = false |
11 | 292 |
|
0 | 293 |
of "version", "v": |
5 | 294 |
echo hl( "netdata_tsrelay " & VERSION, fgWhite, bright=true ) |
0 | 295 |
quit( 0 ) |
11 | 296 |
|
297 |
of "timeout", "t": result.timeout = val.parse_int |
|
298 |
||
299 |
of "dbtable", "T": |
|
300 |
result.insertsql = INSERT_SQL % [ val ] |
|
8 | 301 |
of "dbopts": result.dbopts = val |
11 | 302 |
|
8 | 303 |
of "listen-addr", "a": result.listen_addr = val |
304 |
of "listen-port", "p": result.listen_port = val.parse_int |
|
0 | 305 |
|
306 |
else: discard |
|
307 |
||
308 |
of cmdEnd: assert( false ) # shouldn't reach here ever |
|
309 |
||
310 |
||
311 |
when isMainModule: |
|
5 | 312 |
system.addQuitProc( resetAttributes ) |
8 | 313 |
conf = parse_cmdline() |
7
c0bcf3bea772
Force a GC pass after 25 cycles. Don't bother with sync() at exit, unnecessary.
Mahlon E. Smith <mahlon@laika.com>
parents:
6
diff
changeset
|
314 |
if conf.debug: echo hl( $conf, fgYellow ) |
8 | 315 |
serverloop( conf ) |
0 | 316 |