author | Mahlon E. Smith <mahlon@laika.com> |
Sun, 18 Feb 2018 23:40:34 -0800 | |
changeset 10 | 252cdb26f76b |
parent 9 | aa9d537f7067 |
child 11 | 475c9942eb15 |
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, |
0 | 38 |
parseopt2, |
8 | 39 |
posix, |
0 | 40 |
strutils, |
41 |
tables, |
|
5 | 42 |
terminal, |
8 | 43 |
times |
0 | 44 |
|
45 |
||
46 |
const |
|
47 |
VERSION = "v0.1.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. |
|
54 |
-h: Help. You're lookin' at it. |
|
0 | 55 |
|
56 |
The default connection string is: |
|
57 |
"host=localhost port=5432 dbname=netdata user=netdata application_name=netdata-tsrelay" |
|
58 |
""" |
|
59 |
INSERT_SQL = """ |
|
60 |
INSERT INTO netdata |
|
61 |
( time, host, metrics ) |
|
62 |
VALUES |
|
63 |
( 'epoch'::timestamptz + ? * '1 second'::interval, ?, ? ) |
|
64 |
""" |
|
65 |
||
66 |
||
5 | 67 |
type |
68 |
Config = object of RootObj |
|
69 |
dbopts: string # The postgresql connection parameters. (See https://www.postgresql.org/docs/current/static/libpq-connect.html) |
|
70 |
listen_port: int # The port to listen for incoming connections |
|
71 |
listen_addr: string # The IP address listen for incoming connections. Defaults to inaddr_any. |
|
72 |
verbose: bool # Be informative |
|
73 |
debug: bool # Spew out raw data |
|
0 | 74 |
|
8 | 75 |
# Global configuration |
76 |
var conf: Config |
|
0 | 77 |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
78 |
|
5 | 79 |
proc hl( msg: string, fg: ForegroundColor, bright=false ): string = |
80 |
## Quick wrapper for color formatting a string, since the 'terminal' |
|
81 |
## module only deals with stdout directly. |
|
8 | 82 |
if not isatty(stdout): return msg |
5 | 83 |
|
84 |
var color: BiggestInt = ord( fg ) |
|
85 |
if bright: inc( color, 60 ) |
|
86 |
result = "\e[" & $color & 'm' & msg & "\e[0m" |
|
87 |
||
88 |
||
0 | 89 |
proc fetch_data( client: Socket ): string = |
90 |
## Netdata JSON backend doesn't send a length, so we read line by |
|
91 |
## line and wait for stream timeout to determine a "sample". |
|
8 | 92 |
var buf: string = nil |
0 | 93 |
try: |
8 | 94 |
result = client.recv_line( timeout=500 ) |
95 |
if result != "" and not result.is_nil: result = result & "\n" |
|
96 |
while buf != "": |
|
97 |
buf = client.recv_line( timeout=500 ) |
|
98 |
if buf != "" and not buf.is_nil: result = result & buf & "\n" |
|
0 | 99 |
except TimeoutError: |
100 |
discard |
|
101 |
||
102 |
||
8 | 103 |
proc parse_data( data: string ): seq[ JsonNode ] = |
104 |
## Given a raw +data+ string, parse JSON and return a sequence |
|
105 |
## of JSON samples. Netdata can buffer multiple samples in one batch. |
|
106 |
result = @[] |
|
107 |
if data == "" or data.is_nil: return |
|
0 | 108 |
|
109 |
# Hash of sample timeperiods to pivoted json data |
|
8 | 110 |
var pivoted_data = init_table[ BiggestInt, JsonNode ]() |
0 | 111 |
|
112 |
for sample in split_lines( data ): |
|
8 | 113 |
if sample == "" or sample.is_nil: continue |
114 |
#if conf.debug: echo sample.hl( fgBlack, bright=true ) |
|
0 | 115 |
|
116 |
var parsed: JsonNode |
|
117 |
try: |
|
118 |
parsed = sample.parse_json |
|
119 |
except JsonParsingError: |
|
5 | 120 |
if conf.debug: echo hl( "Unable to parse sample line: " & sample.hl(fgRed, bright=true), fgRed ) |
8 | 121 |
continue |
122 |
if parsed.kind != JObject: return |
|
0 | 123 |
|
124 |
# Create or use existing Json object for modded data. |
|
125 |
# |
|
126 |
var pivot: JsonNode |
|
8 | 127 |
try: |
128 |
let key = parsed["timestamp"].get_num |
|
129 |
||
130 |
if pivoted_data.has_key( key ): |
|
131 |
pivot = pivoted_data[ key ] |
|
132 |
else: |
|
133 |
pivot = newJObject() |
|
134 |
pivoted_data[ key ] = pivot |
|
0 | 135 |
|
8 | 136 |
var name = parsed[ "chart_id" ].get_str & "." & parsed[ "id" ].get_str |
137 |
pivot[ "hostname" ] = parsed[ "hostname" ] |
|
138 |
pivot[ "timestamp" ] = parsed[ "timestamp" ] |
|
139 |
pivot[ name ] = parsed[ "value" ] |
|
140 |
except: |
|
141 |
continue |
|
0 | 142 |
|
8 | 143 |
for timestamp, sample in pivoted_data: |
144 |
result.add( sample ) |
|
0 | 145 |
|
146 |
||
8 | 147 |
proc write_to_database( samples: seq[ JsonNode ] ): void = |
148 |
## Given a sequence of json samples, write them to database. |
|
149 |
if samples.len == 0: return |
|
150 |
||
151 |
let db = open( "", "", "", conf.dbopts ) |
|
152 |
||
153 |
try: |
|
154 |
db.exec sql( "BEGIN" ) |
|
155 |
for sample in samples: |
|
156 |
var |
|
157 |
timestamp = sample[ "timestamp" ].get_num |
|
158 |
host = sample[ "hostname" ].get_str |
|
159 |
sample.delete( "timestamp" ) |
|
160 |
sample.delete( "hostname" ) |
|
161 |
db.exec sql( INSERT_SQL ), timestamp, host, sample |
|
162 |
db.exec sql( "COMMIT" ) |
|
163 |
except: |
|
164 |
let |
|
165 |
e = getCurrentException() |
|
166 |
msg = getCurrentExceptionMsg() |
|
167 |
echo "Got exception ", repr(e), " while writing to DB: ", msg |
|
168 |
discard |
|
169 |
||
170 |
db.close |
|
171 |
||
172 |
||
173 |
proc process( client: Socket, address: string ): void = |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
174 |
## Do the work for a connected client within child process. |
8 | 175 |
let t0 = cpu_time() |
0 | 176 |
var raw_data = client.fetch_data |
177 |
||
5 | 178 |
# Done with the socket, netdata will automatically |
179 |
# reconnect. Save local resources/file descriptors |
|
180 |
# by closing after the send is considered complete. |
|
181 |
# |
|
0 | 182 |
try: |
183 |
client.close |
|
184 |
except OSError: |
|
185 |
return |
|
186 |
||
8 | 187 |
# Pivot the parsed data to a single JSON blob per sample time. |
188 |
var samples = parse_data( raw_data ) |
|
189 |
write_to_database( samples ) |
|
5 | 190 |
|
191 |
if conf.verbose: |
|
192 |
echo( |
|
8 | 193 |
hl( $(epochTime().to_int), fgMagenta, bright=true ), |
194 |
" ", |
|
195 |
hl( $(samples.len), fgWhite, bright=true ), |
|
5 | 196 |
" sample(s) parsed from ", |
197 |
address.hl( fgYellow, bright=true ), |
|
198 |
" in ", hl($( round(cpu_time() - t0, 3) ), fgWhite, bright=true), " seconds." |
|
199 |
# " ", hl($(round((get_occupied_mem()/1024/1024),1)), fgWhite, bright=true), "MB memory used." |
|
200 |
) |
|
201 |
||
0 | 202 |
|
8 | 203 |
proc serverloop( conf: Config ): void = |
0 | 204 |
## Open a database connection, bind to the listening socket, |
205 |
## and start serving incoming netdata streams. |
|
206 |
let db = open( "", "", "", conf.dbopts ) |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
207 |
db.close |
8 | 208 |
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
|
209 |
|
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
210 |
# Ensure children are properly reaped. |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
211 |
# |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
212 |
var sa: Sigaction |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
213 |
sa.sa_handler = SIG_IGN |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
214 |
discard sigaction( SIGCHLD, sa ) |
5 | 215 |
|
8 | 216 |
# Setup listening socket. |
217 |
# |
|
218 |
var server = newSocket() |
|
0 | 219 |
server.set_sock_opt( OptReuseAddr, true ) |
5 | 220 |
server.bind_addr( Port(conf.listen_port), conf.listen_addr ) |
0 | 221 |
server.listen() |
222 |
||
5 | 223 |
if conf.verbose: |
224 |
echo( |
|
225 |
"Listening for incoming connections on ".hl( fgGreen, bright=true ), |
|
226 |
hl( (if conf.listen_addr == "0.0.0.0": "*" else: conf.listen_addr) , fgBlue, bright=true ), |
|
227 |
":", |
|
228 |
hl( $conf.listen_port, fgBlue, bright=true ), |
|
229 |
) |
|
230 |
echo "" |
|
231 |
||
8 | 232 |
# Wait for incoming connections, fork for each client. |
233 |
# |
|
0 | 234 |
while true: |
8 | 235 |
var |
236 |
client = new Socket |
|
237 |
address = "" |
|
6
1f366fc61592
Each incoming connection requires its own client socket.
Mahlon E. Smith <mahlon@laika.com>
parents:
5
diff
changeset
|
238 |
|
9
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
239 |
# Block, waiting for new connections. |
aa9d537f7067
Properly reap child processes.
Mahlon E. Smith <mahlon@laika.com>
parents:
8
diff
changeset
|
240 |
server.acceptAddr( client, address ) |
8 | 241 |
|
242 |
if fork() == 0: |
|
243 |
server.close |
|
244 |
client.process( address ) |
|
245 |
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
|
246 |
|
6
1f366fc61592
Each incoming connection requires its own client socket.
Mahlon E. Smith <mahlon@laika.com>
parents:
5
diff
changeset
|
247 |
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
|
248 |
when defined( testing ): dumpNumberOfInstances() |
0 | 249 |
|
250 |
||
8 | 251 |
proc parse_cmdline: Config = |
0 | 252 |
## Populate the config object with the user's preferences. |
5 | 253 |
|
8 | 254 |
# Config object defaults. |
255 |
# |
|
256 |
result = Config( |
|
257 |
dbopts: "host=localhost port=5432 dbname=netdata user=netdata application_name=netdata-tsrelay", |
|
258 |
listen_port: 14866, |
|
259 |
listen_addr: "0.0.0.0", |
|
260 |
verbose: true, |
|
261 |
debug: false |
|
262 |
) |
|
263 |
||
5 | 264 |
# always set debug mode if development build. |
8 | 265 |
result.debug = defined( testing ) |
5 | 266 |
|
0 | 267 |
for kind, key, val in getopt(): |
268 |
case kind |
|
269 |
||
270 |
of cmdArgument: |
|
271 |
discard |
|
272 |
||
273 |
of cmdLongOption, cmdShortOption: |
|
274 |
case key |
|
5 | 275 |
of "debug", "d": |
8 | 276 |
result.debug = true |
5 | 277 |
|
0 | 278 |
of "help", "h": |
279 |
echo USAGE |
|
280 |
quit( 0 ) |
|
5 | 281 |
|
282 |
of "quiet", "q": |
|
8 | 283 |
result.verbose = false |
0 | 284 |
|
285 |
of "version", "v": |
|
5 | 286 |
echo hl( "netdata_tsrelay " & VERSION, fgWhite, bright=true ) |
0 | 287 |
quit( 0 ) |
288 |
||
8 | 289 |
of "dbopts": result.dbopts = val |
290 |
of "listen-addr", "a": result.listen_addr = val |
|
291 |
of "listen-port", "p": result.listen_port = val.parse_int |
|
0 | 292 |
|
293 |
else: discard |
|
294 |
||
295 |
of cmdEnd: assert( false ) # shouldn't reach here ever |
|
296 |
||
297 |
||
298 |
when isMainModule: |
|
5 | 299 |
system.addQuitProc( resetAttributes ) |
8 | 300 |
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
|
301 |
if conf.debug: echo hl( $conf, fgYellow ) |
8 | 302 |
serverloop( conf ) |
0 | 303 |