This repository has been archived by the owner on Feb 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathochami-cli
executable file
·794 lines (704 loc) · 31.7 KB
/
ochami-cli
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
#!/usr/bin/env python3
import requests
import yaml
import argparse
import json
import os
import sys
import webbrowser
import urllib
import uuid
import base64
import time
import random
from http.server import HTTPServer, BaseHTTPRequestHandler
from ClusterShell.NodeSet import NodeSet
access_token = ""
cacert=True
verbose=False
############# UTIL ############
def checkTokenExpired(access_token):
import jwt
from datetime import datetime, timedelta
try:
decoded = jwt.decode(jwt=access_token, algorithms=["RS256"], options={"verify_signature": False, "verify_aud": False})
except jwt.ExpiredSignatureError:
print("Token is expired. Generate a new ACCESS_TOKEN")
return False
else:
exp = decoded['exp']
now = int(str(datetime.now().timestamp()).split(".")[0])
diff = exp - now
if diff <= 600:
print("Token will expire in " + str(timedelta(seconds=diff)) + ' minutes')
return True
def readConfig(cfile):
with open(cfile, mode='r') as f:
cdict = yaml.safe_load(f)
return cdict
def makeRequest(url, r_type, headers, jdata=None, cert=cacert):
if r_type == "get":
r = requests.get(url, json = jdata, headers=headers, verify=cert)
elif r_type == "post":
r = requests.post(url, json = jdata, headers=headers, verify=cert)
elif r_type == "put":
r = requests.put(url, json = jdata, headers=headers, verify=cert)
elif r_type == "patch":
r = requests.patch(url, json = jdata, headers=headers, verify=cert)
elif r_type == "delete":
r = requests.delete(url, json = jdata, headers=headers, verify=cert)
else:
print("unrecognized request type: ", r_type)
# Make this more informative when things break...
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
pass
finally:
if verbose or not r.ok:
print(f'HTTP {r.status_code} ({r.reason})')
ret = {}
if r.content:
if verbose or not r.ok:
print(f'Response: {r.content.decode("utf-8")}')
try:
ret = r.json()
except:
pass
return ret
def nodeComponentPayload(smd):
sdata = {
"Components": [
{
"ID": smd['xname'],
"State": "Ready",
"Enabled": True,
"Role": "Compute",
"Arch": "X86",
"NID": smd['nid']
}
],
"Force": False
}
return sdata
def ethernetInterfacePayload(smd, ntype):
sdata = {
"Description": "Interface for " + smd['name'],
"MACAddress": smd['mac'],
"IPAddresses": [
{
"IPAddress": smd['ipaddr'],
"Network": ntype
}
],
"ComponentID": smd['xname']
}
return sdata
def redfishEndpointPayload(smd):
sdata = {
"ID": smd['xname'].replace('n0',''),
"Name": smd['name'],
"Hostname": smd['name'],
"Domain": "",
"FQDN": smd['name'],
"Enabled": True,
"User": "root",
"Password": "",
"MacRequired": True,
"IPAddress": smd['bmc_ipaddr'],
"RediscoverOnUpdate": False,
"Systems": [
{
"Data": {
"@odata.id": "/redfish/v1/Systems/Self",
"Id": "Self",
"Description": "System Self",
"Name": "System",
"Status": {
"State": "Enabled"
},
"SystemType": "Physical",
"UUID": str(uuid.uuid4())
},
"EthernetInterfaces": [
{
"@odata.id": "/redfish/v1/Systems/Self/EthernetInterfaces/"+smd['name'],
"Id": smd['name'],
"InterfaceEnabled": True,
"MACAddress": smd['mac'],
"Description": ""
}
]
}
]
}
return sdata
def groupsPayload(label, members):
gdata = {
"label": label,
"description": label + " nodes",
"members": {
"ids": members
}
}
return gdata
def bssPayload(bss):
bdata = {
'macs': bss['macs'],
'initrd': bss['initrd'],
'kernel': bss['kernel'],
'params': bss['params']
}
return bdata
############# UTIL ############
############# SMD #############
def dumpSMD(smd_url, headers, cert):
data = []
smd = getSMDComponents(smd_url, headers, cert, None, None)
nid_list = []
for s in smd['Components']:
if 'NID' in s:
nid_list.append(s['NID'])
nid_max = max(nid_list)
nid_size = len(str(nid_max))
for s in smd['Components']:
if 'Role' in s:
sdict = {}
sdict['xname'] = s['ID']
sdict['nid'] = s['NID']
sdict['name'] = cluster_prefix+str(s['NID']).zfill(nid_size)
ei = getSMDInterfaces(smd_url, headers, cert, s['ID'])
sdict['mac'] = ei[0]['MACAddress']
sdict['ipaddr'] = ei[0]['IPAddresses'][0]['IPAddress']
bmc_xname = s['ID'].split('n')[0]
ri = getRedfishInterfaces(smd_url, headers, cert, bmc_xname)
sdict['bmc_ipaddr'] = ri['RedfishEndpoints'][0]['IPAddress']
data.append(sdict)
yaml_formatted_str = yaml.dump(data, default_flow_style=False)
print(yaml_formatted_str)
def printSMD(smd_url, headers, cert, smd_data, frmt):
nodes = {}
if frmt == 'json':
json_formatted_str = json.dumps(smd_data, indent=2)
print(json_formatted_str)
elif frmt == 'yaml':
yaml_formatted_str = yaml.dump(smd_data, default_flow_style=False)
print(yaml_formatted_str)
else:
if 'Components' in smd_data:
for c in smd_data['Components']:
if 'Role' in c:
if c['Role'] not in nodes:
nodes[c['Role']] = NodeSet()
nodes[c['Role']].update(c['ID'])
else:
if 'BMC' not in nodes:
nodes['BMC'] = NodeSet()
nodes['BMC'].update(c['ID'])
for n,v in nodes.items():
print(n+': ', v)
elif type(smd_data) is list:
for c in smd_data:
print(c['ComponentID'], c['MACAddress'], c['IPAddresses'][0]['IPAddress'])
elif type(smd_data) is dict:
print(json.dumps(smd_data, indent=2))
def addNode(smd_url, headers, cert, xname, nid):
nc = nodeComponentPayload({'xname': xname, 'nid': nid})
makeRequest(smd_url+'/State/Components', 'post', headers=headers, cert=cert, jdata=nc)
def deleteNode(smd_url, headers, cert, xname):
makeRequest(url=smd_url+'/State/Components/'+xname, r_type='delete', headers=headers, cert=cert)
def addInterface(smd_url, headers, cert, name, xname, mac, ipaddr, ntype):
ei = ethernetInterfacePayload({'name': name,'xname': xname,'mac': mac, 'ipaddr': ipaddr}, ntype)
makeRequest(url=smd_url+'/Inventory/EthernetInterfaces', r_type='post', jdata=ei, headers=headers, cert=cert)
def deleteEthernetInterface(smd_url, headers, cert, xname):
smd_data = getSMDInterfaces(smd_url, headers, cert, xname)
if smd_data:
makeRequest(url=smd_url+'/Inventory/EthernetInterfaces/'+smd_data['ID'], r_type='delete', headers=headers, cert=cert)
def addRedfishEndpoint(smd_url, headers, cert, name, xname, mac, bmc_ipaddr):
re = redfishEndpointPayload({'name': name, 'xname': xname, 'mac': mac, 'bmc_ipaddr': bmc_ipaddr})
makeRequest(url=smd_url+'/Inventory/RedfishEndpoints', r_type='post', headers=headers, cert=cert, jdata=re)
def addSMDGroup(smd_url, headers, cert, gname):
g = groupsPayload(gname, [])
makeRequest(url=smd_url+'/groups', r_type='post', headers=headers, cert=cert, jdata=g)
def addSMDGroupMember(smd_url, headers, cert, gname, member):
g = { "id": member }
makeRequest(url=smd_url+'/groups/'+gname+'/members', r_type='post', headers=headers, cert=cert, jdata=g)
def getSMDComponents(smd_url, headers, cert, xname, nid):
if not xname and not nid:
data = makeRequest(url=smd_url+'/State/Components', r_type='get', headers=headers, cert=cert)
elif xname:
data = makeRequest(url=smd_url+'/State/Components/'+xname, r_type='get', headers=headers, cert=cert)
elif nid:
data = makeRequest(url=smd_url+'/State/Components?nid='+nid, r_type='get', headers=headers, cert=cert)
return data
def getSMDInterfaces(smd_url, headers, cert, xname):
if not xname:
data = makeRequest(url=smd_url+'/Inventory/EthernetInterfaces', r_type='get', headers=headers, cert=cert)
return data
else:
data = makeRequest(url=smd_url+'/Inventory/EthernetInterfaces?ComponentID='+xname, r_type='get', headers=headers, cert=cert)
return data
return {}
def getRedfishInterfaces(smd_url, headers, cert, xname):
if not xname:
data = makeRequest(url=smd_url+'/Inventory/RedfishEndpoints', r_type='get', headers=headers, cert=cert)
return data
else:
data = makeRequest(url=smd_url+'/Inventory/RedfishEndpoints?ID='+xname, r_type='get', headers=headers, cert=cert)
return data
return {}
def getNidMacMap(smd_url, headers, cert):
data = makeRequest(url=smd_url+'/Inventory/EthernetInterfaces', r_type='get', headers=headers, cert=cert)
macs_xnames = {}
for s in data:
macs_xnames[s['MACAddress']] = s['ComponentID']
macs_nids = {}
data = makeRequest(url=smd_url+'/State/Components/', r_type='get', headers=headers, cert=cert)
for s in data['Components']:
for k,v in macs_xnames.items():
if s['ID'] == v:
macs_nids[k] = s['NID']
return macs_nids
def getMacFromXname(smd_url, headers, cert, xname):
data = makeRequest(url=smd_url+'/Inventory/EthernetInterfaces', r_type='get', headers=headers, cert=cert)
mac_list = []
if not xname:
for s in data:
if 'MACAddress' in s:
mac_list.append(s['MACAddress'])
else:
for s in data:
if s['ComponentID'] == xname:
if 'MACAddress' in s:
mac_list.append(s['MACAddress'])
return mac_list
def getNidFromXname(smd_url, headers, cert, xname):
data = makeRequest(url=smd_url+'/State/Components/'+xname, r_type='get', headers=headers, cert=cert)
if 'NID' in data:
return data['NID']
return None
def getXnameFromNid(smd_url, headers, cert, nid):
data = makeRequest(url=smd_url+'/State/Components?nid='+nid, r_type='get', headers=headers, cert=cert)
for d in data['Components']:
if 'ID' in d:
return d['ID']
return None
############# SMD #############
############# BSS #############
def printBSS(smd_url, bss_data, headers, cert, frmt):
for b in bss_data:
if 'cloud-init' in b:
del b['cloud-init']
data = getNidMacMap(smd_url, headers, cert)
if frmt == 'json':
json_formatted_str = json.dumps(bss_data, indent=2)
print(json_formatted_str)
elif frmt == 'yaml':
yaml_formatted_str = yaml.dump(bss_data, default_flow_style=False)
print(yaml_formatted_str)
else:
for b in bss_data:
pdata = {}
pdata['nids'] = NodeSet()
pdata['kernel'] = b['kernel']
pdata['initrd'] = b['initrd']
pdata['params'] = b['params']
max_nid = max(data.values())
nid_length = len(str(max_nid))
for m in b['macs']:
nid = cluster_prefix+str(data[m]).zfill(nid_length)
pdata['nids'].update(nid)
print("nodes:", pdata['nids'])
print("kernel: ", pdata['kernel'])
print("initrd: ", pdata['initrd'])
print("params: ", pdata['params'])
print()
def getBSS(bss_url, headers, cert):
data = makeRequest(url=bss_url+'/bootparameters', r_type='get', headers=headers, cert=cert)
return data
def getBSSfiltered(bss_url, fil, headers, cert):
data = makeRequest(url=bss_url+'/bootparameters'+fil, r_type='get', headers=headers, cert=cert)
return data
def addBootParams(bss_url, headers, cert, bss_data):
makeRequest(url=bss_url+'/bootparameters', r_type='post', jdata=bss_data, headers=headers, cert=cert)
def updateBootParams(bss_url, headers, cert, bss_data):
makeRequest(url=bss_url+'/bootparameters', r_type='put', jdata=bss_data, headers=headers, cert=cert)
def patchBootParamsConfig(bss_url, headers, cert, bss_data):
makeRequest(url=bss_url+'/bootparameters', r_type='patch', jdata=bss_data, headers=headers, cert=cert)
def patchBootParamsArgs(smd_url, bss_url, headers, cert, xname, nid, image, kernel, initrd, params):
if nid:
xname = getXnameFromNid(smd_url, headers, cert, nid)
macs = getMacFromXname(smd_url, headers, cert, xname)
bss_query = '?mac=' + ','.join(macs)
bdata = getBSSfiltered(bss_url, bss_query, headers, cert)
for b in bdata:
if image:
param_list = b['params'].split(' ')
for p in param_list:
if p.startswith('root=nfs') or p.startswith('root=live'):
param_list.remove(p)
img_param = image
param_list.append(img_param)
new_params = ' '.join(param_list)
else:
new_params = b['params']
if kernel:
new_kernel = kernel
else:
new_kernel = b['kernel']
if initrd:
new_initrd = initrd
else:
new_initrd = b['initrd']
if params:
new_params = params
elif not image:
new_params = b['params']
new_bss = bssPayload({'macs': b['macs'], 'kernel': new_kernel, 'initrd': new_initrd, 'params': new_params})
patchBootParamsConfig(bss_url, headers, cert, new_bss)
def deleteBootParams(bss_url, headers, cert, bss_data):
makeRequest(url=bss_url+'/bootparameters', r_type='delete', jdata=bss_data, headers=headers, cert=cert)
def setBootParams(smd_url, bss_url, headers, cert, xname, nid, image, kernel, initrd, params):
if nid:
xname = getXnameFromNid(smd_url, headers, cert, nid)
macs = getMacFromXname(smd_url, headers, cert, xname)
bss_query = '?mac=' + ','.join(macs)
bdata = getBSSfiltered(bss_url, bss_query, headers, cert)
for b in bdata:
if image:
param_list = b['params'].split(' ')
for p in param_list:
if p.startswith('root=nfs') or p.startswith('root=live'):
param_list.remove(p)
img_param = image
param_list.append(img_param)
new_params = ' '.join(param_list)
else:
new_params = b['params']
if kernel:
new_kernel = kernel
else:
new_kernel = b['kernel']
if initrd:
new_initrd = initrd
else:
new_initrd = b['initrd']
if params:
new_params = params
elif not image:
new_params = b['params']
new_bss = bssPayload({'macs': b['macs'], 'kernel': new_kernel, 'initrd': new_initrd, 'params': new_params})
updateBootParams(bss_url, headers, cert, new_bss)
############# BSS #############
############# Cloud Init ######
def addCloudInitData(cloud_init_url, headers, cert, ci_dict):
r = makeRequest(url=cloud_init_url, r_type='post', jdata=ci_dict, headers=headers, cert=cert)
print(r)
def delCloudInitData(cloud_init_url, headers, cert, ci_dict):
r = makeRequest(url=cloud_init_url+'/'+ci_dict['name'], r_type='delete', headers=headers, cert=cert)
print(r)
def delCloudInitDataByName(cloud_init_url, headers, cert, name):
r = makeRequest(url=cloud_init_url+'/'+name, r_type='delete', headers=headers, cert=cert)
print(r)
def getCloudInitData(cloud_init_url, headers, cert, name):
r = makeRequest(url=cloud_init_url+'/'+name, r_type='get', headers=headers, cert=cert)
return r
def printCloudInitdata(ci_data, name):
ci_data['name'] = name
yaml_formatted_str = yaml.dump(ci_data, default_flow_style=False, width=4096)
print(yaml_formatted_str)
############# Cloud Init ######
############# AUTH ############
class AccessTokenHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.receive_token()
def receive_token(self):
# length = int(self.headers.get('content-length'))
# field_data = self.rfile.read(length)
# fields = urllib.parse.parse_qs(str(field_data,"UTF-8"))
if self.headers.get("access_token"):
global access_token
access_token = self.headers.get('access_token')
with open(".ochami-token", "w+") as f:
f.write(access_token)
print(f"token received: {access_token}")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def login(url: str, host: str, port: int) -> str:
global access_token
# open browser and wait for access code if target is set
if host:
url += f"?target={urllib.parse.quote_plus(f'http://{host}:{port}')}"
is_open = webbrowser.open(url)
if is_open:
print(f"waiting to receive an access token...")
if host:
try:
httpd = HTTPServer((host, port), AccessTokenHandler)
while not access_token:
httpd.serve_forever()
except KeyboardInterrupt:
print("shutting down without receiving token")
httpd.shutdown()
def is_access_token_valid(token: str) -> bool:
# NOTE: doing validation manually even though PyJwt can do this as well
# no token is automatically invalid
if not token:
print("no token found")
return False
# base64 decode the token into its 3 segments
segments = token.split(".", 3)
decoded_segments = []
for segment in segments:
padded = segment + "="*divmod(len(segment),4)[1]
decoded_segments.append(base64.urlsafe_b64decode(padded))
# check payload for expiration date (token is valid if it doesn't exist)
if len(decoded_segments) >= 2:
payload = json.loads(decoded_segments[1])
expires_at = payload["exp"]
if expires_at:
current_time = time.time()
return current_time < expires_at
else:
print("could not validate token")
return False
############# AUTH ############
def setArgs():
parser = argparse.ArgumentParser()
parser.add_argument("--access-token", dest="access_token", default="", type=str)
parser.add_argument("--access-token-file", dest="access_token_file", default=".access-token", type=str)
parser.add_argument("--ca-cert", dest="ca_cert", type=str, default="", help="set path for CA certificate")
parser.add_argument('--smd-url', type=str)
parser.add_argument('--bss-url', type=str)
parser.add_argument('--cloud-init-url', type=str)
parser.add_argument('--cloud-init-secure-url', type=str)
parser.add_argument('--verbose', '-v', action='store_true')
subparser = parser.add_subparsers(dest='command')
smd = subparser.add_parser('smd')
smd.add_argument('--payload', type=str, help="Path to YAML-formatted payload file to send to SMD")
smd.add_argument('--add-node', dest='add_node', action="store_true", default=False)
smd.add_argument('--delete-node', dest='delete_node', action="store_true", default=False)
smd.add_argument('--add-interface', dest='add_interface', action="store_true", default=False)
smd.add_argument('--delete-interface', dest='delete_interface', action="store_true", default=False)
smd.add_argument('--add-rf-endpoint', dest='add_rf_endpoint', action="store_true", default=False)
smd.add_argument('--get-components', dest='get_components', action="store_true", default=False)
smd.add_argument('--get-interfaces', dest='get_interfaces', action="store_true", default=False)
smd.add_argument('--fake-discovery', dest='fake_discovery', action="store_true", default=False)
smd.add_argument('--name',type=str)
smd.add_argument('--xname',type=str)
smd.add_argument('--mac',type=str)
smd.add_argument('--ipaddr',type=str)
smd.add_argument('--bmc-ipaddr',dest="bmc_ipaddr",type=str)
smd.add_argument('--nid',type=str)
smd.add_argument('--format', type=str, help="Output format; can be 'json' or 'yaml', anything else (default) uses a condensed yaml format")
smd.add_argument('--dump', action="store_true", default=False)
bss = subparser.add_parser('bss')
bss.add_argument('--payload', type=str, help="Path to YAML-formatted payload file to send to BSS")
bss.add_argument('--add-bootparams', dest='add_bootparams', action="store_true", default=False, help="Create boot parameters (must not already exist)")
bss.add_argument('--update-bootparams', dest='update_bootparams', action="store_true", default=False, help="Set or update boot parameters for one or more hosts")
bss.add_argument('--patch-bootparams', dest='patch_bootparams', action="store_true", default=False, help="Update an existing entry with new boot parameters while retaining existing settings")
bss.add_argument('--delete-bootparams', dest='delete_bootparams', action="store_true", default=False, help="Delete existing boot parameters")
bss.add_argument('--get-bootparams', dest='get_bootparams', action="store_true", default=False, help="Retrieve boot parameters")
bss.add_argument('--xname', type=str)
bss.add_argument('--nid', type=str)
bss.add_argument('--image', type=str)
bss.add_argument('--kernel', type=str)
bss.add_argument('--initrd', type=str)
bss.add_argument('--params', type=str)
bss.add_argument('--format', type=str, help="Output format; can be 'json' or 'yaml', anything else (default) uses a condensed yaml format")
login = subparser.add_parser('login')
login.add_argument("--url", type=str, default="http://127.0.0.1:3333/login", help="set the login URL")
login.add_argument("--target-host", dest='host', type=str, default="127.0.0.1", help="set the target host receive access token")
login.add_argument("--target-port", dest='port', type=int, default=5000, help="set the target port receive access token")
cloud_init = subparser.add_parser('cloud-init')
cloud_init.add_argument('--payload', type=str, help="Path to YAML-formatted payload file to send to cloud-init")
cloud_init.add_argument('--add-ci-data', dest='add_ci_data', action="store_true", default=False, help="Add cloud-init data")
cloud_init.add_argument('--del-ci-data', dest='del_ci_data', action="store_true", default=False, help="Delete cloud-init data")
cloud_init.add_argument('--update-ci-data', dest='update_ci_data', action="store_true", default=False, help="Update cloud-init data")
cloud_init.add_argument('--get-ci-data', dest='get_ci_data', action="store_true", default=False, help="Get cloud-init data")
cloud_init.add_argument('--secure-ci', dest='secure_ci', action="store_true", default=False, help="Use secure endpoint")
cloud_init.add_argument('--name', type=str)
args = parser.parse_args()
return args
def main():
global access_token
global cacert
global verbose
args = setArgs()
headers = {}
global cluster_prefix
if os.getenv('CLUSTER_PREFIX'):
cluster_prefix=os.getenv('CLUSTER_PREFIX')
else:
cluster_prefix='nid'
verbose = args.verbose
# do access token stuff
if os.getenv("ACCESS_TOKEN"):
access_token = os.getenv('ACCESS_TOKEN')
headers = {"Authorization": f"Bearer {os.getenv('ACCESS_TOKEN')}"}
if args.access_token:
access_token = args.access_token
if access_token:
headers = {"Authorization": f"Bearer {args.access_token}"}
elif args.access_token_file:
if os.path.exists(args.access_token_file):
with open(args.access_token_file, "r") as f:
access_token = f.read()
if access_token:
headers = {"Authorization": f"Bearer {access_token}"}
# Check Token
if args.command != "login":
if not access_token:
print("ERROR: Neither --access-token, --access-token-file, nor ACCESS_TOKEN were set.")
sys.exit(1)
if not checkTokenExpired(access_token):
sys.exit(1)
# set CA cert var
if os.getenv("CACERT"):
cacert = os.getenv('CACERT')
if args.ca_cert:
cacert = args.ca_cert
if args.smd_url:
smd_url = args.smd_url
elif os.getenv("SMD_URL"):
smd_url = os.getenv('SMD_URL')
if args.bss_url:
bss_url = args.bss_url
elif os.getenv("BSS_URL"):
bss_url = os.getenv('BSS_URL')
if args.cloud_init_url:
cloud_init_url = args.cloud_init_url
elif os.getenv("CLOUD_INIT_URL"):
cloud_init_url = os.getenv('CLOUD_INIT_URL')
if args.cloud_init_secure_url:
cloud_init_secure_url = args.cloud_init_secure_url
elif os.getenv("CLOUD_INIT_SECURE_URL"):
cloud_init_secure_url = os.getenv('CLOUD_INIT_SECURE_URL')
if args.command == "smd":
if args.payload:
payload = args.payload
cdict = readConfig(payload)
existing_groups = []
for c in cdict['nodes']:
if args.fake_discovery:
print(c)
try:
addRedfishEndpoint(smd_url, headers, cacert, c['name'], c['xname'], c['mac'], c['bmc_ipaddr'])
except Exception as e:
print(e)
try:
addNode(smd_url, headers, cacert, c['xname'], c['nid'])
except Exception as e:
print(e)
try:
if 'ipaddr' in c:
addInterface(smd_url, headers, cacert, c['name'], c['xname'], c['mac'], c['ipaddr'], ntype="NMN")
if 'hsn_ipaddr' in c:
if 'hsn_mac' not in c:
# Generate Random MAC for HSN network. Getting this info is time consuming and not critical
hsn_mac = "02:00:00:%02x:%02x:%02x" % (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
else:
hsn_mac = c['hsn_mac']
addInterface(smd_url, headers, cacert, c['name'], c['xname'], hsn_mac, c['hsn_ipaddr'], ntype="HSN")
if 'external_ipaddr' and 'external_mac' in c:
addInterface(smd_url, headers, cacert, c['name'], c['xname'], c['external_mac'], c['external_ipaddr'], ntype="External")
except Exception as e:
print(e)
try:
if c['group'] not in existing_groups:
addSMDGroup(smd_url, headers, cacert, c['group'])
existing_groups.append(c['group'])
addSMDGroupMember(smd_url, headers, cacert, c['group'], c['xname'])
except Exception as e:
print(e)
elif args.add_node:
addNode(smd_url, headers, cacert, args.xname, args.nid)
elif args.delete_node:
deleteNode(smd_url, headers, cacert, args.xname)
elif args.add_interface:
addInterface(smd_url, headers, cacert, args.name, args.xname, args.mac, args.ipaddr)
elif args.delete_interface:
deleteEthernetInterface(smd_url, headers, cacert, args.xname)
elif args.add_rf_endpoint:
addRedfishEndpoint(smd_url, headers, cacert, args.name, args.xname, args.mac, args.bmc_ipaddr)
elif args.get_components:
sc = getSMDComponents(smd_url, headers, cacert, args.xname, args.nid)
printSMD(smd_url, headers, cacert, sc, args.format)
elif args.get_interfaces:
si = getSMDInterfaces(smd_url, headers, cacert, args.xname)
printSMD(smd_url, headers, cacert, si, args.format)
elif args.dump:
dumpSMD(smd_url, headers, cacert)
elif args.command == "bss":
if args.payload:
payload = args.payload
bss_dict = readConfig(payload)
if args.add_bootparams:
if args.payload:
addBootParams(bss_url, headers, cacert, bss_dict)
else:
mac = getMacFromXname(smd_url, headers, cacert, args.xname)
addBootParams(bss_url, headers, cacert, {'macs': mac, 'kernel': args.kernel, 'initrd': args.initrd, 'params': args.params})
elif args.update_bootparams:
if args.payload:
updateBootParams(bss_url, headers, cacert, bss_dict)
else:
if args.image or args.kernel or args.initrd or args.params:
setBootParams(smd_url, bss_url, headers, cacert, args.xname, args.nid, args.image, args.kernel, args.initrd, args.params)
elif args.patch_bootparams:
if args.payload:
patchBootParamsConfig(bss_url, headers, cacert, bss_dict)
else:
if args.image or args.kernel or args.initrd or args.params:
patchBootParamsArgs(smd_url, bss_url, headers, cacert, args.xname, args.nid, args.image, args.kernel, args.initrd, args.params)
elif args.delete_bootparams:
deleteBootParams(bss_url, headers, cacert, bss_dict)
elif args.get_bootparams:
bss = getBSS(bss_url, headers, cacert)
if not bss:
print("null")
else:
printBSS(smd_url, bss, headers, cacert, args.format)
elif args.command == "login":
url = args.url
host = args.host
port = args.port
# todo: only try to log in if we have an invalid token
if not is_access_token_valid(access_token):
access_token = ""
login(url, host, port)
else:
print("found a valid token")
elif args.command == "cloud-init":
if args.secure_ci:
ci_url = cloud_init_secure_url
else:
ci_url = cloud_init_url
if args.name:
name = args.name
else:
name = None
if args.payload:
payload = args.payload
ci_dict = readConfig(payload)
if args.add_ci_data:
if not ci_dict:
sys.exit("Payload file is required when adding cloud-init data")
addCloudInitData(ci_url, headers, cacert, ci_dict)
elif args.del_ci_data:
delCloudInitDataByName(ci_url, headers, cacert, name)
elif args.update_ci_data:
if not ci_dict:
sys.exit("Payload is required when adding cloud-init data")
delCloudInitData(ci_url, headers, cacert, ci_dict)
addCloudInitData(ci_url, headers, cacert, ci_dict)
elif args.get_ci_data:
if name:
ci_data = getCloudInitData(ci_url, headers, cacert, name)
printCloudInitdata(ci_data, name)
else:
sys.exit("Name of cloud-init target is required when getting cloud-init data")
if __name__ == "__main__":
main()
# example usage: ./ochami-cli --smd-url https://foobar.openchami.cluster/hsm/v2 smd --payload payload.yml