| 1 |
#!/usr/bin/env python3 |
| 2 |
# Licensed under GPLv3 |
| 3 |
# |
| 4 |
# Simple script to query the management interface of a running n2n edge node |
| 5 |
|
| 6 |
import argparse |
| 7 |
import socket |
| 8 |
import json |
| 9 |
import collections |
| 10 |
|
| 11 |
|
| 12 |
class JsonUDP(): |
| 13 |
"""encapsulate communication with the edge""" |
| 14 |
|
| 15 |
def __init__(self, port): |
| 16 |
self.address = "127.0.0.1" |
| 17 |
self.port = port |
| 18 |
self.tag = 0 |
| 19 |
self.key = None |
| 20 |
self.debug = False |
| 21 |
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 22 |
self.sock.settimeout(1) |
| 23 |
|
| 24 |
def _next_tag(self): |
| 25 |
tagstr = str(self.tag) |
| 26 |
self.tag = (self.tag + 1) % 1000 |
| 27 |
return tagstr |
| 28 |
|
| 29 |
def _cmdstr(self, msgtype, cmdline): |
| 30 |
"""Create the full command string to send""" |
| 31 |
tagstr = self._next_tag() |
| 32 |
|
| 33 |
options = [tagstr] |
| 34 |
if self.key is not None: |
| 35 |
options += ['1'] # Flags set for auth key field |
| 36 |
options += [self.key] |
| 37 |
optionsstr = ':'.join(options) |
| 38 |
|
| 39 |
return tagstr, ' '.join((msgtype, optionsstr, cmdline)) |
| 40 |
|
| 41 |
def _rx(self, tagstr): |
| 42 |
"""Wait for rx packets""" |
| 43 |
|
| 44 |
seen_begin = False |
| 45 |
while not seen_begin: |
| 46 |
# TODO: there are no timeouts with any of the recv calls |
| 47 |
data, _ = self.sock.recvfrom(1024) |
| 48 |
data = json.loads(data.decode('utf8')) |
| 49 |
|
| 50 |
# TODO: We assume the first packet we get will be tagged for us |
| 51 |
assert(data['_tag'] == tagstr) |
| 52 |
|
| 53 |
if data['_type'] == 'error': |
| 54 |
raise ValueError('Error: {}'.format(data['error'])) |
| 55 |
|
| 56 |
if data['_type'] == 'replacing': |
| 57 |
# a signal that we have evicted an earlier subscribe |
| 58 |
continue |
| 59 |
|
| 60 |
if data['_type'] == 'subscribe': |
| 61 |
return True |
| 62 |
|
| 63 |
if data['_type'] == 'begin': |
| 64 |
seen_begin = True |
| 65 |
|
| 66 |
# Ideally, we would confirm that this is our "begin", but that |
| 67 |
# would need the cmd passed into this method, and that would |
| 68 |
# probably require parsing the cmdline passed to us :-( |
| 69 |
# assert(data['cmd'] == cmd) |
| 70 |
|
| 71 |
continue |
| 72 |
|
| 73 |
raise ValueError('Unknown data type {} from ' |
| 74 |
'edge'.format(data['_type'])) |
| 75 |
|
| 76 |
result = list() |
| 77 |
error = None |
| 78 |
|
| 79 |
while True: |
| 80 |
data, _ = self.sock.recvfrom(1024) |
| 81 |
data = json.loads(data.decode('utf8')) |
| 82 |
|
| 83 |
if data['_tag'] != tagstr: |
| 84 |
# this packet is not for us, ignore it |
| 85 |
continue |
| 86 |
|
| 87 |
if data['_type'] == 'error': |
| 88 |
# we still expect an end packet, so save the error |
| 89 |
error = ValueError('Error: {}'.format(data['error'])) |
| 90 |
continue |
| 91 |
|
| 92 |
if data['_type'] == 'end': |
| 93 |
if error: |
| 94 |
raise error |
| 95 |
return result |
| 96 |
|
| 97 |
if data['_type'] != 'row': |
| 98 |
raise ValueError('Unknown data type {} from ' |
| 99 |
'edge'.format(data['_type'])) |
| 100 |
|
| 101 |
# remove our boring metadata |
| 102 |
del data['_tag'] |
| 103 |
del data['_type'] |
| 104 |
|
| 105 |
if self.debug: |
| 106 |
print(data) |
| 107 |
|
| 108 |
result.append(data) |
| 109 |
|
| 110 |
def _call(self, msgtype, cmdline): |
| 111 |
"""Perform a rpc call""" |
| 112 |
tagstr, msgstr = self._cmdstr(msgtype, cmdline) |
| 113 |
self.sock.sendto(msgstr.encode('utf8'), (self.address, self.port)) |
| 114 |
return self._rx(tagstr) |
| 115 |
|
| 116 |
def read(self, cmdline): |
| 117 |
return self._call('r', cmdline) |
| 118 |
|
| 119 |
def write(self, cmdline): |
| 120 |
return self._call('w', cmdline) |
| 121 |
|
| 122 |
def sub(self, cmdline): |
| 123 |
return self._call('s', cmdline) |
| 124 |
|
| 125 |
def readevent(self): |
| 126 |
self.sock.settimeout(3600) |
| 127 |
|
| 128 |
data, _ = self.sock.recvfrom(1024) |
| 129 |
data = json.loads(data.decode('utf8')) |
| 130 |
# assert(data['_tag'] == tagstr) |
| 131 |
assert(data['_type'] == 'event') |
| 132 |
|
| 133 |
del data['_tag'] |
| 134 |
del data['_type'] |
| 135 |
return data |
| 136 |
|
| 137 |
|
| 138 |
def str_table(rows, columns, orderby): |
| 139 |
"""Given an array of dicts, do a simple table print""" |
| 140 |
result = list() |
| 141 |
widths = collections.defaultdict(lambda: 0) |
| 142 |
|
| 143 |
if len(rows) == 0: |
| 144 |
# No data to show, be sure not to truncate the column headings |
| 145 |
for col in columns: |
| 146 |
widths[col] = len(col) |
| 147 |
else: |
| 148 |
for row in rows: |
| 149 |
for col in columns: |
| 150 |
if col in row: |
| 151 |
widths[col] = max(widths[col], len(str(row[col]))) |
| 152 |
|
| 153 |
for col in columns: |
| 154 |
if widths[col] == 0: |
| 155 |
widths[col] = 1 |
| 156 |
result += "{:{}.{}} ".format(col, widths[col], widths[col]) |
| 157 |
result += "\n" |
| 158 |
|
| 159 |
if orderby is not None: |
| 160 |
rows = sorted(rows, key=lambda row: row.get(orderby, 0)) |
| 161 |
|
| 162 |
for row in rows: |
| 163 |
for col in columns: |
| 164 |
if col in row: |
| 165 |
data = row[col] |
| 166 |
else: |
| 167 |
data = '' |
| 168 |
result += "{:{}} ".format(data, widths[col]) |
| 169 |
result += "\n" |
| 170 |
|
| 171 |
return ''.join(result) |
| 172 |
|
| 173 |
|
| 174 |
def subcmd_show_supernodes(rpc, args): |
| 175 |
rows = rpc.read('supernodes') |
| 176 |
columns = [ |
| 177 |
'version', |
| 178 |
'current', |
| 179 |
'macaddr', |
| 180 |
'sockaddr', |
| 181 |
'uptime', |
| 182 |
] |
| 183 |
|
| 184 |
return str_table(rows, columns, args.orderby) |
| 185 |
|
| 186 |
|
| 187 |
def subcmd_show_edges(rpc, args): |
| 188 |
rows = rpc.read('edges') |
| 189 |
columns = [ |
| 190 |
'mode', |
| 191 |
'ip4addr', |
| 192 |
'macaddr', |
| 193 |
'sockaddr', |
| 194 |
'desc', |
| 195 |
] |
| 196 |
|
| 197 |
return str_table(rows, columns, args.orderby) |
| 198 |
|
| 199 |
|
| 200 |
def subcmd_show_help(rpc, args): |
| 201 |
result = 'Commands with pretty-printed output:\n\n' |
| 202 |
for name, cmd in subcmds.items(): |
| 203 |
result += "{:12} {}\n".format(name, cmd['help']) |
| 204 |
|
| 205 |
result += "\n" |
| 206 |
result += "Possble remote commands:\n" |
| 207 |
result += "(those without a pretty-printer will pass-through)\n\n" |
| 208 |
rows = rpc.read('help') |
| 209 |
for row in rows: |
| 210 |
result += "{:12} {}\n".format(row['cmd'], row['help']) |
| 211 |
return result |
| 212 |
|
| 213 |
|
| 214 |
subcmds = { |
| 215 |
'help': { |
| 216 |
'func': subcmd_show_help, |
| 217 |
'help': 'Show available commands', |
| 218 |
}, |
| 219 |
'supernodes': { |
| 220 |
'func': subcmd_show_supernodes, |
| 221 |
'help': 'Show the list of supernodes', |
| 222 |
}, |
| 223 |
'edges': { |
| 224 |
'func': subcmd_show_edges, |
| 225 |
'help': 'Show the list of edges/peers', |
| 226 |
}, |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
def subcmd_default(rpc, args): |
| 231 |
"""Just pass command through to edge""" |
| 232 |
cmdline = ' '.join([args.cmd] + args.args) |
| 233 |
if args.write: |
| 234 |
rows = rpc.write(cmdline) |
| 235 |
elif args.read: |
| 236 |
rows = rpc.read(cmdline) |
| 237 |
elif args.sub: |
| 238 |
if not rpc.sub(cmdline): |
| 239 |
raise ValueError('Could not subscribe') |
| 240 |
while True: |
| 241 |
event = rpc.readevent() |
| 242 |
# FIXME: violates layering.. |
| 243 |
print(json.dumps(event, sort_keys=True, indent=4)) |
| 244 |
else: |
| 245 |
raise ValueError('Unknown request type') |
| 246 |
return json.dumps(rows, sort_keys=True, indent=4) |
| 247 |
|
| 248 |
|
| 249 |
def main(): |
| 250 |
ap = argparse.ArgumentParser( |
| 251 |
description='Query the running local n2n edge') |
| 252 |
ap.add_argument('-t', '--mgmtport', action='store', default=5644, |
| 253 |
help='Management Port (default=5644)', type=int) |
| 254 |
ap.add_argument('-k', '--key', action='store', |
| 255 |
help='Password for mgmt commands') |
| 256 |
ap.add_argument('-d', '--debug', action='store_true', |
| 257 |
help='Also show raw internal data') |
| 258 |
ap.add_argument('--raw', action='store_true', |
| 259 |
help='Force cmd to avoid any pretty printing') |
| 260 |
ap.add_argument('--orderby', action='store', |
| 261 |
help='Hint to a pretty printer on how to sort') |
| 262 |
|
| 263 |
group = ap.add_mutually_exclusive_group() |
| 264 |
group.add_argument('--read', action='store_true', |
| 265 |
help='Make a read request (default)') |
| 266 |
group.add_argument('--write', action='store_true', |
| 267 |
help='Make a write request (only to non pretty' |
| 268 |
'printed cmds)') |
| 269 |
group.add_argument('--sub', action='store_true', |
| 270 |
help='Make a subscribe request') |
| 271 |
|
| 272 |
ap.add_argument('cmd', action='store', |
| 273 |
help='Command to run (try "help" for list)') |
| 274 |
ap.add_argument('args', action='store', nargs="*", |
| 275 |
help='Optional args for the command') |
| 276 |
|
| 277 |
args = ap.parse_args() |
| 278 |
|
| 279 |
if not args.read and not args.write and not args.sub: |
| 280 |
args.read = True |
| 281 |
|
| 282 |
if args.raw or (args.cmd not in subcmds): |
| 283 |
func = subcmd_default |
| 284 |
else: |
| 285 |
func = subcmds[args.cmd]['func'] |
| 286 |
|
| 287 |
rpc = JsonUDP(args.mgmtport) |
| 288 |
rpc.debug = args.debug |
| 289 |
rpc.key = args.key |
| 290 |
|
| 291 |
try: |
| 292 |
result = func(rpc, args) |
| 293 |
except socket.timeout as e: |
| 294 |
print(e) |
| 295 |
exit(1) |
| 296 |
|
| 297 |
print(result) |
| 298 |
|
| 299 |
|
| 300 |
if __name__ == '__main__': |
| 301 |
main() |