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