-
Notifications
You must be signed in to change notification settings - Fork 0
/
t128-configure-router.py
executable file
·253 lines (212 loc) · 8.46 KB
/
t128-configure-router.py
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
import argparse
import os
import requests
import sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class UnauthorizedException(Exception):
pass
class RestGraphqlApi(object):
"""Representation of REST connection."""
token = None
authorized = False
def __init__(self, host='localhost', verify=False, user='admin', password=None):
self.host = host
self.verify = verify
self.user = user
self.password = password
def get(self, location, authorization_required=True):
"""Get data per REST API."""
url = 'https://{}/api/v1/{}'.format(self.host, location.strip('/'))
headers = {
'Content-Type': 'application/json',
}
if authorization_required:
if not self.authorized:
self.login()
if self.token:
headers['Authorization'] = 'Bearer {}'.format(self.token)
request = requests.get(
url, headers=headers,
verify=self.verify)
return request
def post(self, location, json, authorization_required=True):
"""Send data per REST API via post."""
url = 'https://{}/api/v1/{}'.format(self.host, location.strip('/'))
headers = {
'Content-Type': 'application/json',
}
# Login if not yet done
if authorization_required:
if not self.authorized:
self.login()
if self.token:
headers['Authorization'] = 'Bearer {}'.format(self.token)
request = requests.post(
url, headers=headers, json=json,
verify=self.verify)
return request
def patch(self, location, json, authorization_required=True):
"""Send data per REST API via patch."""
url = 'https://{}/api/v1/{}'.format(self.host, location.strip('/'))
headers = {
'Content-Type': 'application/json',
}
# Login if not yet done
if authorization_required:
if not self.authorized:
self.login()
if self.token:
headers['Authorization'] = 'Bearer {}'.format(self.token)
request = requests.patch(
url, headers=headers, json=json,
verify=self.verify)
return request
def login(self):
json = {
'username': self.user,
}
if self.password:
json['password'] = self.password
else:
key_file = 'pdc_ssh_key'
if not os.path.isfile(key_file):
key_file = '/home/admin/.ssh/pdc_ssh_key'
key_content = ''
with open(key_file) as fd:
key_content = fd.read()
json['local'] = key_content
request = self.post('/login', json, authorization_required=False)
if request.status_code == 200:
self.token = request.json()['token']
self.authorized = True
else:
message = request.json()['message']
raise UnauthorizedException(message)
def get_routers(self):
return self.get('/router').json()
def get_nodes(self, router_name):
return self.get('/config/running/authority/router/{}/node'.format(
router_name)).json()
def has_uncommitted_changes(self):
"""Return whether conductor's candidate config differs from running."""
request = self.get('/config/version?datastore=candidate')
if request.status_code != 200:
fatal('Cannot connect to REST API.')
return request.json()['isDirty']
def log(*messages):
"""Write messages to log file."""
print(*messages)
def fatal(*messages):
"""Show error message and quit."""
log('FATAL:', *messages)
sys.exit(1)
def info(*messages):
"""Show error message and quit."""
log('INFO:', *messages)
def warning(*messages):
"""Show error message and quit."""
log('WARNING:', *messages)
def parse_arguments():
"""Get commandline arguments."""
parser = argparse.ArgumentParser(
description='Configure selected options of 128T routers')
parser.add_argument('--router', '-r', help='Router name', required=True)
parser.add_argument('--commit', help='Commit config',
action='store_true')
parser.add_argument('--yes', help='Commit unconfirmed', action='store_true')
parser.add_argument('--asset-id', '-a', help='Change asset id')
parser.add_argument('--enable-asset-resilency', action='store_true')
parser.add_argument('--enable-maintenance-mode', action='store_true')
parser.add_argument('--disable-maintenance-mode', action='store_true')
# for remote conductor (e.g. testing purposes)
parser.add_argument('--conductor', '-c', required=True,
help='conductor host')
parser.add_argument('--username', '-u', default='admin',
help='conductor username (default: admin)')
parser.add_argument('--password', '-p', default='128Tadmin',
help='conductor password')
return parser.parse_args()
def get_config(api, locations, router_name, node_name):
config = {}
for dict_key, tup in locations.items():
location = tup[0].format(router=router_name, node=node_name)
key = tup[1]
config[dict_key] = api.get('/config/running' + location).json()[key]
return config
def update_config(api, locations, router_name, node_name, changes):
for dict_key, new_value in changes.items():
tup = locations[dict_key]
location = tup[0].format(router=router_name, node=node_name)
key = tup[1]
api.patch('/config/candidate' + location, {key: new_value})
def show_changes(router_name, current_config, new_config, commit):
if current_config == new_config:
info('Nothing has changed.')
return {}
if commit:
mode = 'committed'
else:
mode = 'applied to candidate config'
print('The following changes for router {} will be {}:'.format(
router_name, mode))
changes = {}
for key, value in current_config.items():
new_value = new_config[key]
if new_value != value:
changes[key] = new_value
print('{}: {} => {}'.format(key, value, new_value))
return changes
def main():
args = parse_arguments()
params = {}
if args.conductor:
params['host'] = args.conductor
if args.username and args.password:
params['user'] = args.username
params['password'] = args.password
api = RestGraphqlApi(**params)
if api.has_uncommitted_changes():
fatal('Conductor has uncommitted changes.',
'Quit here to avoid commit conflicts.')
router_name = args.router
routers = [r['name'] for r in api.get_routers()]
if router_name not in routers:
fatal('Specified router in unknown on conductor:', router_name)
nodes = api.get_nodes(router_name)
num_nodes = len(nodes)
if num_nodes != 1:
fatal('This script supports only routers with one node.',
num_nodes,'found.')
node_name = nodes[0]['name']
locations = {
'maintenance-mode': ('/authority/router/{router}', 'maintenance-mode'),
'asset-connection-resiliency': ('/authority/router/{router}/system/asset-connection-resiliency', 'enabled'),
'asset-id': ('/authority/router/{router}/node/{node}', 'asset-id'),
}
current_config = get_config(api, locations, router_name, node_name)
new_config = current_config.copy()
if args.asset_id:
new_config['asset-id'] = args.asset_id
if args.enable_asset_resilency:
new_config['asset-connection-resiliency'] = 'true'
if args.enable_maintenance_mode:
new_config['maintenance-mode'] = True
if args.disable_maintenance_mode:
new_config['maintenance-mode'] = False
changes = show_changes(router_name, current_config, new_config, args.commit)
if not changes:
return
if not args.yes:
answer = input('Please confirm (y/n): ')
if answer.lower() not in ('y', 'yes'):
return
update_config(api, locations, router_name, node_name, changes)
if args.commit:
api.post('/config/commit', {})
info('Changes from candidate to running config have been committed.')
else:
warning('No --commit argument given. Candidate config has been updated, but NOT committed!')
if __name__ == '__main__':
main()