-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvioshc.py
2107 lines (1812 loc) · 79.1 KB
/
vioshc.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
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Copyright 2017, International Business Machines Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
from datetime import datetime
import os
import sys
import getopt
import subprocess
import threading
import re
import pycurl
import xml.etree.cElementTree as ET
import socket
import cStringIO
import shutil
# TODO: Use Standard logger instead of log routine
###############################################################################
# Initialize variables
###############################################################################
# Constants
LOG_DIR = "/tmp"
C_RSH = "/usr/lpp/bos.sysmgt/nim/methods/c_rsh"
action = "" # (user provided -l present?)
list_arg = "" # (user provided -l)
# Target HMC
hmc_ip = "" # (user provided)
hmc_user_id = "" # (user provided -u or retrieved)
hmc_password = "" # (user provided -p or retrieved)
hmc_info = {}
managed_system_info = {}
# Dual VIOS pair
vios_info = {}
vios1_name = ""
vios2_name = ""
vios_num = 0 # number of VIOS UUID provided (-U option)
vios1_uuid = "" # (user provided -U)
vios2_uuid = "" # (user provided -U)
managed_system_uuid = "" # (user provided -m)
lpar_info = {}
# Flags & Counters used by program
rc = 0
verbose = 0 # (user provided -v)
num_hc_fail = 0
num_hc_pass = 0
total_hc = 0
###############################################################################
# Define functions
###############################################################################
# File manipulation functions #
def touch(path):
"""
Create file
Input: (str) file path
Output: none
"""
log("creating file: {}\n".format(path))
try:
open(path, 'a')
except IOError as e:
write('ERROR: Failed to create file {}: {}.'
.format(path, e.strerror), lvl=0)
sys.exit(3)
os.utime(path, None)
def log(txt, debug='no'):
"""
Write debug trace in the log file
Input: (str) text to write
Input: (str) level of the trace, writes if set to 'debug'
Output: none
"""
global log_file
global mode
if mode == 'debug' or mode == debug:
log_file.write(txt)
def write(txt, lvl=1):
"""
Write provided text on stdout and in log file depneding of the level
Input: (str) text to write
Input: (int) level, if 0 then prints out, used for: ERROR, WARNING, etc.
>0, verbose needs to be greater than lvl to see it
Output: none
"""
global verbose
log(txt + '\n')
if verbose >= lvl:
print(txt)
def remove(path):
"""
Remove file
Input: (str) file path
Output: none
"""
try:
if os.path.exists(path):
os.remove(path)
else:
log('file {} does not exists.\n'.format(path))
except OSError as e:
write('ERROR: Failed to remove file {}: {}.'.format(path, e.strerror), lvl=0)
def format_xml_file(filename):
"""
Remove extra headers from top of XML file
Input: (str) file name
Output: none
"""
try:
f = open(filename, 'r+')
except IOError as e:
write('ERROR: Failed to create file {}: {}.'.format(filename, e.strerror), lvl=0)
sys.exit(3)
lines = f.readlines()
f.seek(0)
start_writing = False
for i in lines:
if i[0] == '<':
start_writing = True
if start_writing:
f.write(i)
f.truncate()
f.close()
def exec_cmd(cmd):
"""
Execute the given command
Input: (str) return code of command
Output:(int) stdout of the command
Output:(str) stderr of the command
"""
global log_dir
rc = 0
output = ''
errout = ''
th_id = threading.current_thread().ident
stderr_file = os.path.join(log_dir, 'cmd_stderr_{}'.format(th_id))
try:
myfile = open(stderr_file, 'w')
output = subprocess.check_output(cmd, stderr=myfile)
myfile.close()
s = re.search(r'rc=([-\d]+)$', output)
if s:
rc = int(s.group(1))
output = re.sub(r'rc=[-\d]+\n$', '', output) # remove the rc of c_rsh with echo $?
except subprocess.CalledProcessError as exc:
myfile.close()
errout = re.sub(r'rc=[-\d]+\n$', '', exc.output) # remove the rc of c_rsh with echo $?
rc = exc.returncode
write('Command: {} failed: {}'.format(cmd, exc.args), lvl=0)
except OSError as exc:
myfile.close
errout = re.sub(r'rc=[-\d]+\n$', '', exc.args[1]) # remove the rc of c_rsh with echo $?
rc = exc.args[0]
write('Command: {} failed, exception: {}'.format(cmd, exc.args), lvl=0)
except IOError as exc:
# generic exception
myfile.close
rc = exc.args[0]
write('Command: {} failed, exception: {}'.format(cmd, exc.args), lvl=0)
except Exception as exc:
rc = 1
write('Command: {} failed, exception: {}'.format(cmd, exc.args), lvl=0)
# check for error message
if os.path.getsize(stderr_file) > 0:
myfile = open(stderr_file, 'r')
errout += ''.join(myfile)
myfile.close()
os.remove(stderr_file)
log('command {} returned:\n'.format(cmd))
log(' rc:{}\n'.format(rc))
log(' stdout:{}\n'.format(output))
log(' stderr:{}\n'.format(errout))
return (rc, output, errout)
###############################################################################
# Interfacing functions
###############################################################################
def retrieve_usr_pass(hmc_info):
"""
Retrieve the username and password
Input: (str) hmc internet address
Output:(str) username
Output:(str) password
"""
if hmc_info is None or 'type' not in hmc_info or 'passwd_file' not in hmc_info:
write('ERROR: Failed to retrieve user ID and password for {}'
.format(hmc_info['hostname']), lvl=0)
return ("", "")
decrypt_file = get_decrypt_file(hmc_info['passwd_file'],
hmc_info['type'],
hmc_info['hostname'])
if decrypt_file != '':
(user, passwd) = get_usr_passwd(decrypt_file)
return (user, passwd)
def get_nim_info(obj_name):
"""
Get detailed on the provided Network Installation Management (NIM) object
Input: (str) NIM object name to look for
Output:(str) hash with NIM info, the associated value can be a list
"""
info = {}
cmd = ['/usr/sbin/lsnim', '-l', obj_name]
(rc, output, errout) = exec_cmd(cmd)
if rc != 0:
write('ERROR: Failed to get {} NIM info: {} {}'.format(obj_name, output, errout), lvl=0)
return None
for line in output.split('\n'):
match = re.match('^\s*(\S+)\s*=\s*(\S+)\s*$', line)
if match:
if match.group(1) not in info:
info[match.group(1)] = match.group(2)
elif type(info[match.group(1)]) is list:
info[match.group(1)].append(match.group(2))
else:
info[match.group(1)] = [info[match.group(1)]]
info[match.group(1)].append(match.group(2))
return info
def get_nim_name(hostname):
"""
Get NIM client name associated with the given hostname
Input: (str) hostname of the NIM client to look for
Output:(str) NIM object name
"""
name = ""
cmd = ['lsnim', '-a', 'if1']
(rc, output, errout) = exec_cmd(cmd)
if rc != 0:
write('ERROR: Failed to get NIM name for {}: {} {}'
.format(hostname, output, errout), lvl=0)
return ""
for line in output.split('\n'):
match = re.match('^\s*(\S+)\s*:\s*$', line)
if match:
name = match.group(1)
continue
match = re.match('^\s*if1\s*=\s*\S+\s+(\S+).*$', line)
if match and match.group(1) != hostname:
name = ""
continue
else:
break
if name == "":
write('ERROR: Failed to get NIM name for {}: Not Found'
.format(hostname), lvl=0)
return name
def get_hostname(host):
"""
Get network information from either IP address or hostname
Input: (str) IP address or hostname
Output: a triple (hostname, aliaslist, ipaddrlist)
with
- hostname: primary host name responding to the given ip_address
- aliaslist: list of alternative host names for the same address (can be empty)
- ipaddrlist: list of IPv4 addresses for the same interface on the same host
"""
try:
match_key = re.match('^\d+.*$', host)
if match_key:
return socket.gethostbyaddr(host)
else:
return socket.gethostbyname_ex(host)
except OSError as e:
write("ERROR: Failed to get hostname for %s: %d %s." % (host, e.errno, e.strerror), lvl=0)
sys.exit(3)
def get_decrypt_file(passwd_file, type, hostname):
"""
Decrypt the encrypted password file
Input: (str) password file
Input: (str) managed type
Input: (str) managed hostname
Output:(str) decrypted file
"""
log("getting decrypt file: {} for {} {}\n".format(passwd_file, type, hostname))
cmd = ["/usr/bin/dkeyexch", "-f", passwd_file, "-I", type, "-H", hostname, "-S"]
(rc, output, errout) = exec_cmd(cmd)
if rc != 0:
write("ERROR: Failed to get the encrypted password file path for {}: {} {}"
.format(hostname, output, errout), lvl=0)
return ""
# dkeyexch output is like:
# OpenSSH_6.0p1, OpenSSL 1.0.2h 3 May 2016
# /var/ibm/sysmgt/dsm/tmp/dsm1608597933307771402.tmp
return output.rstrip().split('\n')[1]
def get_usr_passwd(decrypt_file):
"""
Read the decrypted file and returns the username and password
Input: (str) decrypted file
Output:(str) username
Output:(str) password
"""
try:
f = open(decrypt_file, 'r')
except IOError as e:
write("ERROR: Failed to open file {}: {}.".format(decrypt_file, e.strerror), lvl=0)
sys.exit(3)
arr = f.read().split(' ')
f.close()
return arr
# TODO: change the xml parsing in build_managed_system?
def build_managed_system(hmc_info, vios_info, managed_system_info, xml_file):
"""
Retrieve managed systems, VIOS UUIDs and machine SerialNumber information
from provided XML file.
Input: (dict) hmc_info hash
Input: (str) xml_file of managed systems to parse
Output:(dict) VIOSes information
Output:(dict) managed systems and their SerialNumbers and VIOSes
"""
curr_managed_sys = "" # string to hold current managed system being searched
vios_num = 0
log("Parse xml file: {}\n".format(xml_file))
try:
tree = ET.ElementTree(file=xml_file)
except IOError as e:
write("ERROR: Failed to parse '{}' file.".format(xml_file), lvl=0)
sys.exit(3)
except ET.ParseError as e:
write("ERROR: Failed to parse '{}' file.".format(xml_file), lvl=0)
sys.exit(3)
log("Get managed system serial numbers\n")
iter_ = tree.getiterator()
for elem in iter_:
# Retrieving the current Managed System
if re.sub(r'{[^>]*}', "", elem.tag) == "entry":
elem_child = elem.getchildren()
for child in elem_child:
if re.sub(r'{[^>]*}', "", child.tag) != "id":
continue
if child.text in managed_system_info:
continue
curr_managed_sys = child.text
log("get managed system UUID: {}\n".format(curr_managed_sys))
managed_system_info[curr_managed_sys] = {}
managed_system_info[curr_managed_sys]['serial'] = "Not Found"
managed_system_info[curr_managed_sys]['vios'] = []
if re.sub(r'{[^>]*}', "", elem.tag) == "MachineTypeModelAndSerialNumber":
# string to append to the managed system dict
serial_string = ""
elem_child = elem.getchildren()
for serial_child in elem_child:
if re.sub(r'{[^>]*}', "", serial_child.tag) == "MachineType":
serial_string += serial_child.text + "-"
if re.sub(r'{[^>]*}', "", serial_child.tag) == "Model":
serial_string += serial_child.text + "*"
if re.sub(r'{[^>]*}', "", serial_child.tag) == "SerialNumber":
serial_string += serial_child.text
# Adding the serial to the current Managed System
managed_system_info[curr_managed_sys]['serial'] = serial_string
if re.sub(r'{[^>]*}', "", elem.tag) == "AssociatedVirtualIOServers":
write("Retrieving the VIOS UUIDs", lvl=2)
elem_child = elem.getchildren()
# The VIOS UUIDs are in the "link" attribute
for child in elem_child:
if re.sub(r'{[^>]*}', "", child.tag) != "link":
continue
match = re.match('^.*VirtualIOServer\/(\S+)$', child.attrib['href'])
if match:
uuid = match.group(1)
vios_num += 1
write("Collect info on clients of VIOS%d: {}".format(vios_num, uuid), lvl=2)
filename = "{}/vios{}.xml".format(xml_dir, vios_num)
rc = get_vios_info(hmc_info, uuid, filename)
if rc != 0:
write("WARNING: Failed to collect vios {} info: {}"
.format(uuid, rc[1]), lvl=1)
continue
vios_name = build_vios_info(vios_info, filename, uuid)
if vios_name == "":
continue
vios_info[vios_name]['managed_system'] = curr_managed_sys
vios_info[vios_name]['filename'] = filename
for key in vios_info[vios_name].keys():
log("vios_info[{}][{}] = {}\n"
.format(vios_name, key, vios_info[vios_name][key]))
managed_system_info[curr_managed_sys]['vios'].append(vios_name)
for ms in managed_system_info.keys():
for key in managed_system_info[ms].keys():
log("managed_system_info[{}][{}]: {}\n".format(ms, key, managed_system_info[ms][key]))
return 0
def get_session_key(hmc_info, filename):
"""
Get a session key from the HMC with a Curl request
Input: (dict) hmc_info hash with HMC IP address, user ID, password
Inputs: (str) file name to write the HMC answer
Output: (str) session key
"""
s_key = ""
try:
f = open(filename, 'wb')
except IOError as e:
write("ERROR: Failed to create file {}: {}.".format(filename, e.strerror), lvl=0)
sys.exit(3)
url = "https://{}:12443/rest/api/web/Logon".format(hmc_info['hostname'])
fields = '<LogonRequest schemaVersion=\"V1_0\" '\
'xmlns=\"http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/\" '\
'xmlns:mc=\"http://www.ibm.com/xmlns/systems/power/firmware/web/mc/2012_10/\"> '\
'<UserID>{}</UserID>'\
.format(hmc_info['user_id'])
log("curl request on: {}\n".format(url))
log("curl request fields: {} <Password>xxx</Password></LogonRequest>\n".format(fields))
fields += ' <Password>{}</Password></LogonRequest>'\
.format(hmc_info['user_password'])
hdrs = ['Content-Type: application/vnd.ibm.powervm.web+xml; type=LogonRequest']
try:
c = pycurl.Curl()
c.setopt(c.HTTPHEADER, hdrs)
c.setopt(c.CUSTOMREQUEST, "PUT")
c.setopt(c.POST, 1)
c.setopt(c.POSTFIELDS, fields)
c.setopt(c.URL, url)
c.setopt(c.SSL_VERIFYPEER, False)
c.setopt(c.WRITEDATA, f)
c.perform()
except pycurl.error as e:
write("ERROR: Curl request failed: {}".format(e), lvl=0)
return ""
# Reopen the file in text mode
f.close()
try:
f = open(filename, 'r')
except IOError as e:
write("ERROR: Failed to create file {}: {}.".format(filename, e.strerror), lvl=0)
sys.exit(3)
# Isolate session key
for line in f:
if re.search('<X-API-Session', line):
s_key = re.sub(r'<[^>]*>', "", line)
return s_key.strip()
def print_uuid(managed_system_info, vios_info, arg):
"""
Print out managed system and VIOS UUIDs
Input:(dict) HMC info to get: IP address, session key
Input: (str) set arg flag to 'a' to print VIOS information
Output:(int) 0 for success, !0 otherwise
"""
write("\n%-37s %-22s" % ("Managed Systems UUIDs", "Serial"), lvl=0)
write("-" * 37 + " " + "-" * 22, 0)
for key in managed_system_info.keys():
write("%-37s %-22s" % (key, managed_system_info[key]['serial']), lvl=0)
if arg == 'a':
write("\n\t%-37s %-14s" % ("VIOS", "Partition ID"), lvl=0)
write("\t" + "-" * 37 + " " + "-" * 14, lvl=0)
for vios in managed_system_info[key]['vios']:
write("\t%-37s %-14s" % (vios_info[vios]['uuid'], vios_info[vios]['id']), lvl=0)
write("", lvl=0)
write("", lvl=0)
return 0
###############################################################################
# Parsing functions
###############################################################################
def grep(filename, tag):
"""
Parse through xml to find tag value
Inputs: (str) XML file name to parse
Inputs: (str) tag to look for
Output: (str) value
"""
format_xml_file(filename)
try:
tree = ET.ElementTree(file=filename)
except IOError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return ""
except ET.ParseError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return ""
iter_ = tree.getiterator()
for elem in iter_:
if re.sub(r'{[^>]*}', "", elem.tag) == tag:
return elem.text
return ""
def grep_array(filename, tag):
"""
Parse through xml file to create list of tag values
Inputs: (str) XML file name to parse
Inputs: (str) tag to look for
Output: (array) values corresponding to given tag
"""
format_xml_file(filename)
arr = []
try:
tree = ET.ElementTree(file=filename)
except IOError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return arr
except ET.ParseError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return arr
iter_ = tree.getiterator()
for elem in iter_:
if re.sub(r'{[^>]*}', "", elem.tag) == tag:
arr.append(elem.text)
return arr
def grep_check(filename, tag):
"""
Check for existence of tag in file
Inputs: (str) XML file name to parse
Inputs: (str) tag to look for
Output: (bool) True if the tag is present
Output: True if tag exists, False otherwise
"""
# format_xml_file(filename)
found = False
try:
tree = ET.ElementTree(file=filename)
except IOError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return found
except ET.ParseError as e:
log("WARNING: Failed to parse '{}' to find '{}' tag.\n".format(filename, tag))
return found
iter_ = tree.getiterator()
for elem in iter_:
if re.sub(r'{[^>]*}', "", elem.tag) == tag:
found = True
return found
def awk(filename, tag1, tag2):
"""
Parse through specific sections of xml file to create a list of tag values
Inputs: (str) XML file name to parse
Inputs: (str) outer tag
Inputs: (str) inner tag
Output:(array) values corresponding to given tags
"""
arr = []
try:
tree = ET.ElementTree(file=filename)
except IOError as e:
log("WARNING: Failed to parse '{}' to find '{}' and '{}' tags.\n"
.format(filename, tag1, tag2))
return arr
except ET.ParseError as e:
log("WARNING: Failed to parse '{}' to find '{}' and '{}' tags.\n"
.format(filename, tag1, tag2))
return arr
iter_ = tree.getiterator()
for elem in iter_:
if re.sub(r'{[^>]*}', "", elem.tag) == tag1:
elem_child = elem.getchildren()
for child in elem_child:
if re.sub(r'{[^>]*}', "", child.tag) == tag2:
arr.append(child.text)
return arr
def build_vios_info(vios_info, filename, vios_uuid):
"""
Parse VirtualIOServer XML file to build the vios_info hash
Input:(dict) VIOS info to fill
Input: (str) XML file name
Input: (str) VIOS uuid to look for
Output:(str) VIOS name use in dictionary if success,
prints error message and exits upon error
"""
ns = {'Atom': 'http://www.w3.org/2005/Atom',
'vios': 'http://www.ibm.com/xmlns/systems/power/firmware/uom/mc/2012_10/'}
try:
e_tree = ET.parse(filename)
except IOError as e:
write("ERROR: Failed to parse {} for {}: {}."
.format(filename, vios_uuid, e), lvl=0)
sys.exit(3)
except ET.ParseError as e:
write("ERROR: Failed to parse {} for {}: {}".format(filename, vios_uuid, e), lvl=0)
sys.exit(3)
e_root = e_tree.getroot()
# NOTE: Some VIOSes do not return PartitionName element
# so in that case we use the short hostname as hash
# key and replace partition name by this short hostname
# Get element: ResourceMonitoringIPAddress
e_RMIPAddress = e_root.find(
"Atom:content/vios:VirtualIOServer/vios:ResourceMonitoringIPAddress",
ns)
if e_RMIPAddress is None:
write("WARNING: ResourceMonitoringIPAddress element not found in file {} for {}"
.format(filename, vios_uuid), lvl=1)
return ""
# sys.exit(3)
# Get the hostname
(hostname, aliases, ip_list) = get_hostname(e_RMIPAddress.text)
vios_name = hostname.split(".")[0]
vios_info[vios_name] = {}
vios_info[vios_name]['uuid'] = vios_uuid
vios_info[vios_name]['hostname'] = hostname
vios_info[vios_name]['ip'] = e_RMIPAddress.text
# Get element: PartitionName
e_PartionName = e_root.find("Atom:content/vios:VirtualIOServer/vios:PartitionName", ns)
if e_PartionName is None:
write("ERROR: PartitionName element not found in file {}".format(filename), lvl=0)
del vios_info[vios_name]
return ""
# sys.exit(3)
else:
vios_info[vios_name]['partition_name'] = e_PartionName.text
# Get element: PartitionID
e_PartionID = e_root.find("Atom:content/vios:VirtualIOServer/vios:PartitionID", ns)
if e_PartionID is None:
write("ERROR: PartitionID element not found in file {}".format(filename), lvl=0)
del vios_info[vios_name]
return ""
# sys.exit(3)
else:
vios_info[vios_name]['id'] = e_PartionID.text
# Get element: PartitionState
e_PartitionState = e_root.find("Atom:content/vios:VirtualIOServer/vios:PartitionState", ns)
if e_PartitionState is None:
write("ERROR: PartitionState element not found in file {}".format(filename), lvl=0)
vios_info[vios_name]['partition_state'] = "none"
# sys.exit(3)
else:
vios_info[vios_name]['partition_state'] = e_PartitionState.text
# Get element: ResourceMonitoringControlState
e_RMCState = e_root.find(
"Atom:content/vios:VirtualIOServer/vios:ResourceMonitoringControlState",
ns)
if e_RMCState is None:
write("ERROR: ResourceMonitoringControlState element not found in file {}"
.format(filename), lvl=0)
vios_info[vios_name]['control_state'] = e_RMCState.text
# sys.exit(3)
else:
vios_info[vios_name]['control_state'] = "none"
return vios_name
def build_lpar_info(lpar_info, filename):
"""
Parse the XML file to build the lpar_info hash. Retrieves partition ID
Input:(dict) LPAR info to fill
Input: (str) XML file name
Output:(int) 0 if success,
prints error message and exits upon error
"""
ns = {'Atom': 'http://www.w3.org/2005/Atom',
'lpar': 'http://www.ibm.com/xmlns/systems/power/firmware/uom/mc/2012_10/'}
try:
e_tree = ET.parse(filename)
except IOError as e:
write("ERROR: Failed to parse {}: {}.".format(filename, e.strerror), lvl=0)
sys.exit(3)
except ET.ParseError as e:
write("ERROR: Failed to parse {}: {}".format(filename, e), lvl=0)
sys.exit(3)
e_root = e_tree.getroot()
# Get partitions UUID: element: id
e_Partitions = e_root.findall("Atom:entry", ns)
if e_Partitions is None:
write("ERROR: Cannot get entry element in file {}".format(filename), lvl=0)
sys.exit(3)
elif len(e_Partitions) == 0:
write("No partion found in file {}".format(filename), lvl=1)
return 0
for e_Partition in e_Partitions:
# Get element: PartitionID
e_PartitionID = e_Partition.find("Atom:content/lpar:LogicalPartition/lpar:PartitionID", ns)
if e_PartitionID is None:
write("ERROR: PartitionID element not found in file {}".format(filename), lvl=0)
sys.exit(3)
lpar_info[e_PartitionID.text] = {}
e_PartitionUUID = e_Partition.find("Atom:id", ns)
if e_PartitionUUID is None:
write("ERROR: id element of PartitionID:{} entry not found in file {}"
.format(e_PartitionID.text, filename), lvl=0)
sys.exit(3)
lpar_info[e_PartitionID.text]['uuid'] = e_PartitionUUID.text
# Get element: PartitionName
e_PartionName = e_Partition.find("Atom:content/lpar:LogicalPartition/lpar:PartitionName",
ns)
if e_PartionName is None:
write("ERROR: PartitionName element of PartitionID={} not found in file {}"
.format(e_PartitionID.text, filename), lvl=0)
sys.exit(3)
lpar_info[e_PartitionID.text]['name'] = e_PartionName.text
return 0
###############################################################################
# c_rsh functions
###############################################################################
def get_vios_sea_state(vios_name, sea_device):
"""
Parse an XML file to get the SEA device state
Input:(dict) LPAR info to fill
Input: (str) VIOS name
Input: (str) SEA device name
Output:(int) 0 if success
Output:(str) SEA device state,
prints error message and exits upon error
"""
global vios_info
global xml_dir
state = ""
# file to get all SEA info (debug)
filename = "{}/{}_{}.txt".format(xml_dir, vios_name, sea_device)
try:
f = open(filename, 'w+')
except IOError as e:
write("ERROR: Failed to create file {}: {}.".format(filename, e.strerror), lvl=0)
f = None
# ssh into vios1
cmd = [C_RSH, vios_info[vios_name]['hostname'],
"LC_ALL=C /bin/entstat -d {}; echo rc=$?".format(sea_device)]
log("SharedEthernetAdapter cmd='{}'\n".format(cmd))
(rc, output, errout) = exec_cmd(cmd)
if rc != 0:
write("ERROR: Failed to get the state of the {} SEA adapter on {}: {} {}"
.format(sea_device, vios_name, output, errout), lvl=0)
return (1, "")
found_stat = False
found_packet = False
for line in output.rstrip().split('\n'):
# file to get all SEA info (for debug)
if not (f is None):
f.write("{}\n".format(line))
if not found_stat:
# Statistics for adapters in the Shared Ethernet Adapter entX
match_key = re.match(r"^Statistics for adapters in the Shared Ethernet Adapter {}"
.format(sea_device), line)
if match_key:
found_stat = True
continue
if not found_packet:
# Type of Packets Received:
match_key = re.match(r"^Type of Packets Received(.*)$", line)
if match_key:
found_packet = True
continue
if found_packet:
# State: PRIMARY | BACKUP | STANDBY | ......
match_key = re.match(r"^\s+State:\s+(.*)$", line)
if match_key:
state = match_key.group(1)
found_stat = False
found_packet = False
continue
if state == "":
write("ERROR: Failed to get the state of the {} SEA adapter on {}: State field not found."
.format(sea_device, vios_name), lvl=0)
return (1, "")
log("VIOS {} sea adapter {} is in {} state".format(vios_name, sea_device, state))
return (0, state)
def get_vscsi_mapping(vios_name, vios_uuid):
"""
Build vios_scsi_mapping dictionnary
from an XML file: <vios_name>_vscsi_mapping.xml
vios_scsi_mapping[UDID] = device_mapping dictionnary
device_mapping["Backing_device_Name"] = Backing_device_Name
device_mapping["Backing_device_Type"] = device_type
device_mapping["Reserve_policy"] = ReservePolicy
device_mapping["RemoteLParIDs"] = [] contains the list of client partition IDs
print device mapping table
Input: (str) vios name
Input: (str) vios UUID
Output:(dict) vios_scsi_mapping dictionnary
"""
global filename_msg
global hmc_info
global xml_dir
touch(filename_msg)
write("\nRecovering vSCSI mapping for {}:".format(vios_name), 2)
filename = "{}/{}_vscsi_mapping.xml".format(xml_dir, vios_name)
# Get vSCSI info, write data to file
url = "https://{}:12443/rest/api/uom/VirtualIOServer/{}?group=ViosSCSIMapping"\
.format(hmc_info['hostname'], vios_uuid)
curl_request(hmc_info['session_key'], url, filename)
# Check for error response in file
if grep_check(filename, 'HttpErrorResponse'):
write("ERROR: Request to {} returned Error Response.".format(url), lvl=0)
write("ERROR: Unable to detect vSCSI Information", lvl=0)
# Parse for backup device info
try:
tree = ET.ElementTree(file=filename)
except IOError as e:
write("ERROR: Failed to parse {}: {}.".format(filename, e.strerror), lvl=0)
sys.exit(2)
except ET.ParseError as e:
write("ERROR: Failed to parse {}: {}".format(filename, e), lvl=0)
sys.exit(2)
iter_ = tree.getiterator()
device_target_mapping = {}
for elem in iter_:
if re.sub(r'{[^>]*}', "", elem.tag) == 'ServerAdapter':
backing_device_name = ""
remote_logical_partition_id = ""
elem_child = elem.getchildren()
for child in elem_child:
if re.sub(r'{[^>]*}', "", child.tag) == 'BackingDeviceName':
backing_device_name = re.sub(r'<[^>]*>', "", child.text)
if re.sub(r'{[^>]*}', "", child.tag) == 'RemoteLogicalPartitionID':
remote_logical_partition_id = re.sub(r'<[^>]*>', "", child.text)
if backing_device_name not in device_target_mapping:
device_target_mapping[backing_device_name] = []
device_target_mapping[backing_device_name].append(remote_logical_partition_id)
for dev in device_target_mapping:
device_target_mapping[dev].sort()
vios_scsi_mapping = {}
for elem in iter_:
backing_device_name = ""
backing_device_type = ""
UDID = ""
reserve_policy = ""
if re.sub(r'{[^>]*}', "", elem.tag) == 'Storage':
elem_child = elem.getchildren()
for child in elem_child:
str_tag = re.sub(r'{[^>]*}', "", child.tag)
if str_tag == 'PhysicalVolume':
backing_device_type = "PhysicalVolume"
if str_tag == 'LogicalUnit':
backing_device_type = "ssp"
if str_tag == 'VirtualDisk':
backing_device_type = "LogicalVolume"
if str_tag == "PhysicalVolume" or\
str_tag == "LogicalUnit" or str_tag == "VirtualDisk":
sub_children = child.getchildren()
for kid in sub_children:
if re.sub(r'{[^>]*}', "", kid.tag) == 'VolumeName':
backing_device_name = re.sub(r'<[^>]*>', "", kid.text)
if re.sub(r'{[^>]*}', "", kid.tag) == 'UnitName':
backing_device_name = re.sub(r'<[^>]*>', "", kid.text)
if re.sub(r'{[^>]*}', "", kid.tag) == 'DiskName':
backing_device_name = re.sub(r'<[^>]*>', "", kid.text)
if re.sub(r'{[^>]*}', "", kid.tag) == 'ReservePolicy':
reserve_policy = re.sub(r'<[^>]*>', "", kid.text)
if re.sub(r'{[^>]*}', "", kid.tag) == 'UniqueDeviceID':
UDID = re.sub(r'<[^>]*>', "", kid.text)
else:
continue
vios_scsi_mapping[UDID] = {}
vios_scsi_mapping[UDID]["BackingDeviceName"] = backing_device_name
vios_scsi_mapping[UDID]["BackingDeviceType"] = backing_device_type
vios_scsi_mapping[UDID]["ReservePolicy"] = reserve_policy
vios_scsi_mapping[UDID]["RemoteLParIDs"] = []
if backing_device_name in device_target_mapping:
vios_scsi_mapping[UDID]["RemoteLParIDs"] = \
device_target_mapping[backing_device_name]
if len(vios_scsi_mapping) == 0:
write("WARNING: no vSCSI disks configured on {}.".format(vios_name), lvl=1)
else:
write("\nvSCSI mapping on {}:".format(vios_name), lvl=1)
vscsi_header = "Device Name UDID "\
" Disk Type Reserve Policy Client LPar ID"
divider = "-----------------------------------------------------------------"\
"------------------------------------------------------------------------"
format_string = "%-15s %-72s %-16s %-18s %-15s"
write(vscsi_header, lvl=1)
write(divider, lvl=1)