-
Notifications
You must be signed in to change notification settings - Fork 0
/
d81s.py
executable file
·2448 lines (2102 loc) · 114 KB
/
d81s.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/python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Deck 8 One Step - Main Explorer
# ------------------------------------------------------------------------------
import threading
import configparser
import re
import mysql.connector
from mysql.connector import errorcode
import paramiko
import base64
import http.client
import xml.etree.ElementTree as ET
import subprocess
import time
# ------------------------------------------------------------------------------
# Default variables (Overrided by INI-file)
# ------------------------------------------------------------------------------
db_connections_limit = 32
# ------------------------------------------------------------------------------
# Execute a command via SSH and read results
# ------------------------------------------------------------------------------
def ssh_exec(host, user, password, port, command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=password, port=port)
stdin, stdout, stderr = client.exec_command(command)
data = stdout.read()
# TO-DO: Check error = stderr.read() for errors
client.close()
try:
data = data.decode('utf-8')
except UnicodeDecodeError:
data = data.decode('cp1251')
return data
# ------------------------------------------------------------------------------
# Connect with the MySql Database
# ------------------------------------------------------------------------------
def connect_db(host, database, user, password):
try:
cnx = mysql.connector.connect(host=host, database=database,
user=user, password=password)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(time.ctime(time.time()) + ":",
"Fatal: Wrong DB user/password specified in the INI-file")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(time.ctime(time.time()) + ":",
"Fatal: Database does not exists")
else:
print(err)
return cnx
# ------------------------------------------------------------------------------
# Gets the field 'what' from the 'table' where the 'key' like 'value'
# SELECT %1 FROM %2 WHERE %3 LIKE "$%" LIMIT 1;
# ------------------------------------------------------------------------------
def get_valbykey(cursor, session_id, what, table, key, value):
select = ("SELECT " + what +
" FROM " + table +
" WHERE session_id=" + str(session_id) +
" AND " + str(key) +
" LIKE %s LIMIT 1")
cursor.execute(select, (value,))
try:
return tuple(cursor)[0][0]
except IndexError:
return 'NULL'
# ------------------------------------------------------------------------------
# Insert the new row to the 'sources' table
# ------------------------------------------------------------------------------
def insert_source(cursor, session_id, explorer, host, login, password, proto,
port, url):
add_source = ("INSERT INTO sources "
"(session_id, explorer, host, login, password, proto, "
"port, url) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)")
data_source = (session_id, explorer, host, login, password,
proto, port, url)
cursor.execute(add_source, data_source)
return cursor.lastrowid
# ------------------------------------------------------------------------------
# Connect with Hitachi Command Suite (HDVM) to send XML Request and get Response
# ------------------------------------------------------------------------------
def hdvm_getstoragearray(host, login, password, request, serial, arraytype):
b64lp = base64.b64encode((login + ':' + password).encode('ascii'))
headers = {'Content-Type': 'text/xml',
'User-Agent': 'Deck Eight:One Step:0',
'Authorization': 'Basic ' + b64lp.decode('utf-8')}
body_up = """\
<?xml version="1.0" encoding="UTF-8"?>
<HiCommandServerMessage>
<APIInfo version="7.1" />
<Request>
<StorageManager>
"""
body_down = """\
</StorageManager>
</Request>
</HiCommandServerMessage>"""
if request == 'GetAllArrays':
body_middle = """\
<Get target="StorageArray" option="all">
<StorageArray />
</Get>
"""
elif request == 'GetArray_LUNs':
body_middle = """\
<Get target="StorageArray">
<StorageArray objectID="ARRAY.""" + arraytype + """.""" + serial + """">
<LogicalUnit>
<Filter>
<Condition type="ALL" />
</Filter>
<Path>
<HostInfo />
<WorldWideName />
</Path>
</LogicalUnit>
</StorageArray>
</Get>
"""
elif request == 'GetArray_Ports':
body_middle = """\
<Get target="StorageArray">
<StorageArray objectID="ARRAY.""" + arraytype + """.""" + serial + """">
<Port>
<HostStorageDomain />
</Port>
</StorageArray>
</Get>
"""
elif request == 'GetArray_RGs':
body_middle = """\
<Get target="StorageArray">
<StorageArray objectID="ARRAY.""" + arraytype + """.""" + serial + """">
<ArrayGroup />
</StorageArray>
</Get>
"""
elif request == 'GetArray_Pools':
body_middle = """\
<Get target="StorageArray">
<StorageArray objectID="ARRAY.""" + arraytype + """.""" + serial + """">
<JournalPool />
</StorageArray>
</Get>
"""
elif request == 'GetArray_LDEVs':
body_middle = """\
<Get target="StorageArray">
<StorageArray objectID="ARRAY.""" + arraytype + """.""" + serial + """">
<LDEV>
<ObjectLabel />
</LDEV>
</StorageArray>
</Get>
"""
body = body_up + body_middle + body_down
httpc = http.client.HTTPConnection(host, 2001, timeout = 120)
httpc.request('POST', '/service/ServerAdmin', body, headers)
resp = httpc.getresponse()
data = resp.read()
data = data.decode('utf-8')
httpc.close()
return data
# ------------------------------------------------------------------------------
# Split the string 'ln' by colon and return the second part
# ------------------------------------------------------------------------------
def split_colon(ln):
return ln.split(':')[1].strip()
# ------------------------------------------------------------------------------
# Normalize WWNs format: 50014380029FD42A > 50:01:43:80:02:9f:d4:2a
# ------------------------------------------------------------------------------
def wwn_up2brocade(raw_wwn):
return ':'.join([raw_wwn[x:x+2] for x in range(0, len(raw_wwn), 2)]).lower()
# ------------------------------------------------------------------------------
# Read configuration parameters from the INI-file
# Gets the 'ini-filename' as the parameter, returns the 'config' object
# ------------------------------------------------------------------------------
def read_ini(inifile):
global sources_bfcs
global sources_hdvm
global sources_3par
global sources_ibts
global sources_heva
config = configparser.ConfigParser()
if inifile not in config.read(inifile):
print(time.ctime(time.time()) + ":", "Fatal: Unable to find INI-file")
exit(1)
# Read the [SOURCES] section
if 'SOURCES' in config.sections():
# Parse and save BFCS Sources configuration
sources_bfcs = []
try:
for ln in config['SOURCES']['BFCS'].splitlines():
fields = re.split("[ \t]+", ln)
sources_bfcs.append(dict(host=fields[0],
login=fields[1],
password=fields[2]))
except(IndexError, KeyError):
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [SOURCES][BFCS] value of the INI-file")
exit(1)
# Parse and save HDVM Sources configuration
sources_hdvm = []
try:
for ln in config['SOURCES']['HDVM'].splitlines():
fields = re.split("[ \t]+", ln)
sources_hdvm.append(dict(host=fields[0],
login=fields[1],
password=fields[2]))
except(IndexError, KeyError):
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [SOURCES][HDVM] value of the INI-file")
exit(1)
# Parse and save 3PAR Sources configuration
sources_3par = []
try:
for ln in config['SOURCES']['3PAR'].splitlines():
fields = re.split("[ \t]+", ln)
sources_3par.append(dict(host=fields[0],
login=fields[1],
password=fields[2]))
except(IndexError, KeyError):
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [SOURCES][3PAR] value of the INI-file")
exit(1)
# Parse and save IBTS (IBM TS Tape Libraries) Sources configuration
sources_ibts = []
try:
for ln in config['SOURCES']['IBTS'].splitlines():
fields = re.split("[ \t]+", ln)
sources_ibts.append(dict(host=fields[0], model=fields[1]))
except(IndexError, KeyError):
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [SOURCES][IBTS] value of the INI-file")
exit(1)
# Parse and save HEVA Sources configuration
sources_heva = []
try:
for ln in config['SOURCES']['HEVA'].splitlines():
fields = re.split("[ \t]+", ln)
sources_heva.append(dict(host=fields[0],
login=fields[1],
password=fields[2]))
except(IndexError, KeyError):
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [SOURCES][HEVA] value of the INI-file")
exit(1)
if not config['TOOLS']['sssu']:
print(time.ctime(time.time()) + ":",
"Fatal: Unable to process [TOOLS][sssu] value of the INI-file")
exit(1)
else:
print(time.ctime(time.time()) + ":",
"Fatal: [SOURCES] section is NOT present in the INI-file")
exit(1)
# Fetch variables of the [DATABASE] section or die
if 'DATABASE' in config.sections():
if not config['DATABASE']['host']:
print(time.ctime(time.time()) + ":",
"Fatal: Missing [DATABASE][host] variable of the INI-file")
exit(1)
if not config['DATABASE']['database']:
print(time.ctime(time.time()) + ":",
"Fatal: Missing [DATABASE][database] variable of the INI-file")
exit(1)
if not config['DATABASE']['user']:
print(time.ctime(time.time()) + ":",
"Fatal: Missing [DATABASE][user] variable of the INI-file")
exit(1)
if not config['DATABASE']['password']:
print(time.ctime(time.time()) + ":",
"Fatal: Missing [DATABASE][password] variable of the INI-file")
exit(1)
else:
print(time.ctime(time.time()) + ":",
"Fatal: [DATABASE] section is NOT present in the INI-file")
exit(1)
return config
# ------------------------------------------------------------------------------
# Start the new discovery session
# Returns the Session ID
# ------------------------------------------------------------------------------
def start_session():
# Connect with the database
cnx = connect_db(config['DATABASE']['host'], config['DATABASE']['database'],
config['DATABASE']['user'], config['DATABASE']['password'])
cursor = cnx.cursor()
add_session = ("INSERT INTO sessions (time_start, state) VALUES (now(), 1)")
cursor.execute(add_session, "")
session_id = cursor.lastrowid
cnx.commit()
cursor.close()
cnx.close()
return session_id
# ------------------------------------------------------------------------------
# End the discovery session
# ------------------------------------------------------------------------------
def end_session():
# Connect with the database
cnx = connect_db(config['DATABASE']['host'], config['DATABASE']['database'],
config['DATABASE']['user'], config['DATABASE']['password'])
cursor = cnx.cursor()
session = ("UPDATE sessions SET time_end=now(), state=%s WHERE session_id=%s")
data_session = (0, session_id)
cursor.execute(session, data_session)
cnx.commit()
cursor.close()
cnx.close()
return session_id
# ------------------------------------------------------------------------------
# Scan BFCS-sources for the Fabrics and fill in the appropriate tables
# 1: Fabric. Create the fabric entry in the database ('bfcf'-table) then
# populate the 'bfcf-members'-table with all fabric members;
# 2: Zoning. Get from the source BFCS-switch and store in the database zoning
# information for the fabric;
# 3: Name Service. Scan the fabric name service for the active device WWNs
# and store them within database.
# ------------------------------------------------------------------------------
def explore_bfcs(scr_bfcs):
# Open connection with the database
cnx = connect_db(config['DATABASE']['host'], config['DATABASE']['database'],
config['DATABASE']['user'], config['DATABASE']['password'])
cursor = cnx.cursor()
print(time.ctime(time.time()) + ":",
"Debug: BFCS:", scr_bfcs['host']+":", "Start scan")
# Add the source for the current BFCF/BFCS discovery
source_id_bfcs = insert_source(cursor, session_id, 'BFCS', scr_bfcs['host'],
scr_bfcs['login'], scr_bfcs['password'],
'SSH', '22', 'NA')
cnx.commit()
# - 1: Fabric --------------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: BFCS:", scr_bfcs['host']+":", "Fabric")
# Get the 'fabricshow' output from the switch
fshow_raw = ssh_exec(host=scr_bfcs['host'],
user=scr_bfcs['login'],
password=scr_bfcs['password'],
port=22,
command='fabricshow')
# Split fabricshow output into lines and parse fields
fabricshow = []
principal_wwn = 'NULL'
fabric_name = ''
for ln in fshow_raw.splitlines():
if 'fffc' in ln: # Found the fabric switch
is_principal = 0
fields = re.split("[ \t]+", ln.lstrip()) # Parse the fields
switch_name = fields[5].strip('"')
if '>' in switch_name: # Principal switch detection
is_principal = 1
switch_name = switch_name.lstrip('>"')
# Save the Principal switch info
principal_name = switch_name # Principal switchname
principal_wwn = fields[2] # Principal WWN
principal_domain = fields[0].rstrip(':')# Principal Domain ID
principal_ip = fields[3] # Principal IP address
fabricshow.append(dict(did_dec = fields[0].rstrip(':'), # Remove ':' from the DID field
did_hex = fields[1], # Switch address in hex
wwn = fields[2], # Switch WWN
ip = fields[3], # Switch IP
name = switch_name, # Switch name
principal = is_principal)) # Principal switch marker
if 'Fabric Name:' in ln: # Save the name of the Fabric ...
fabric_name = re.split(": ", ln)[1]
fabricname_on = 1
if fabric_name == '': # ... or let it be the name
fabric_name = principal_name # of principal switch
# Search for the Fabric entry in the BFCF table of the database
bfcf_id = get_valbykey(cursor, session_id, 'bfcf_id', 'bfcf',
'principal_wwn', principal_wwn)
if bfcf_id != 'NULL':
# This fabric is already exists in the database
print(time.ctime(time.time()) + ":",
"Info: Skip the Fabric: " +
principal_wwn + ": it is already exists in the database")
return 0
# continue
if principal_wwn == 'NULL':
# We did not detected Fabric
print(time.ctime(time.time()) + ":",
"Info: Skip Fabric exploration of the Source",
scr_bfcs['host'], ": unable to detect Principal switch")
return 0
# continue
# Add the new Fabric to the 'bfcf' table
add_bfcf = ("INSERT INTO bfcf "
"(session_id, source_id, principal_wwn, principal_domain, "
"principal_ip, principal_name, fabric_name) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s)")
data_bfcf = (session_id, source_id_bfcs, principal_wwn, principal_domain,
principal_ip, principal_name, fabric_name)
cursor.execute(add_bfcf, data_bfcf)
cnx.commit()
# Save the new Fabric ID
bfcf_id = cursor.lastrowid
# Fill in Brocade Fabric Member switches - 'bfcf_members' table
for fab_bfcs in fabricshow:
add_bfcf_members = ("INSERT INTO bfcf_members "
"(bfcf_id, domain, switchid, wwn, ip, name, "
"principal) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s)")
data_bfcf_members = (bfcf_id, fab_bfcs['did_dec'], fab_bfcs['did_hex'],
fab_bfcs['wwn'], fab_bfcs['ip'], fab_bfcs['name'],
fab_bfcs['principal'])
cursor.execute(add_bfcf_members, data_bfcf_members)
cnx.commit()
# - 2: Zoning --------------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: BFCS:", scr_bfcs['host']+":", "Zoning")
# Get the BFCF zoning information from the switch
zshow_raw = ssh_exec(host = scr_bfcs['host'],
user = scr_bfcs['login'],
password = scr_bfcs['password'],
port = 22,
command = 'cfgactvshow')
# command = 'zoneshow')
# Parse and format raw 'zoneshow' data
cfg_state = 0
record_type = ''
in_record = 0
zoneshow = []
rcnt = 0
zshow_list = re.split("[;\t\n\r]+", zshow_raw)
for field in zshow_list:
if field == ' ':
continue
field = field.strip()
if field == 'Defined configuration:':
cfg_state = 0
continue
if field == 'Effective configuration:':
cfg_state = 1
continue
if field == 'zone:':
in_record = 1
record_type = 'z' # zone
continue
if field == 'alias:':
in_record = 1
record_type = 'a' # alias
continue
if field == 'cfg:':
in_record = 1
record_type = 'c' # configuration
continue
if in_record == 0 and cfg_state == 1: # Only Effective configuration
# so we will omit 'record_type'
# because it's always 'zone'
zoneshow.append(dict(cfg_state = cfg_state,
# zoneshow.append(dict(cfg_state = cfg_state,
# record_type = record_type,
record_name = name,
record_member = field,
record_count = rcnt))
else:
name = field
in_record = 0
rcnt = rcnt + 1
# Fill in the 'bfcf_zoning' table with formatted 'zoneshow' data
for rc in zoneshow:
add_bfcf_members = ("INSERT INTO bfcf_zoning "
# "(bfcf_id, record_count, record_type, "
"(bfcf_id, record_count, "
# " record_name, record_member, cfg_state) "
" record_name, record_member) "
"VALUES "
# "(%s, %s, %s, %s, %s, %s)")
"(%s, %s, %s, %s)")
# data_bfcf_members = (bfcf_id, rc['record_count'], rc['record_type'],
data_bfcf_members = (bfcf_id, rc['record_count'],
rc['record_name'], rc['record_member'])
# rc['cfg_state'])
cursor.execute(add_bfcf_members, data_bfcf_members)
cnx.commit()
# - 3: Name Service --------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: BFCS:", scr_bfcs['host']+":", "Name Service")
# Get the nameserver information from the switch
nsshow_raw = ssh_exec(host = scr_bfcs['host'],
user = scr_bfcs['login'],
password = scr_bfcs['password'],
port = 22,
command = 'nsshow -t && nscamshow -t')
# Parse and format raw 'nsshow' data to get ports
port_type = address = cos = port_name = node_name = did = aid = alpa = ''
fabric_port_name = device_type = port_symb = node_symb = ''
for ln in nsshow_raw.splitlines():
# Find all blocks of Nx_ports in the fabric
nx_ports = re.compile('^ +N |^ +NL |^ +U ')
if nx_ports.match(ln):
# Yes, this is a first line of the Nx_port segment
if port_type != '':
# We found the Next Nx_port segment, that means we are finished
# to parse the Previous one and must push it to the database
add_bfcf_ns = ("INSERT INTO bfcf_ns "
"(bfcf_id, port_type, address, cos, "
"port_name, node_name, did, aid, alpa, "
"fabric_port_name, device_type, "
"port_index, port_symb, node_symb) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s)")
add_bfcf_data = (bfcf_id, port_type, address, cos, port_name,
node_name, did, aid, alpa,
fabric_port_name, device_type, port_index,
port_symb, node_symb)
cursor.execute(add_bfcf_ns, add_bfcf_data)
# Clean the buffer values for the next iteration
port_type = address = cos = port_name = node_name = ''
did = pid = loop = fabric_port_name = device_type = ''
port_symb = node_symb = ''
# Parse the remains of the first string
fields = re.split("[; \t]+", ln.strip())
port_type = fields[0] # Port type
address = fields[1] # FC-address
cos = fields[2] # COS
port_name = fields[3] # PWWN
node_name = fields[4] # NWWN
did = int(address[:2], 16) # Domain ID in decimal
aid = int(address[2:-2], 16) # Area ID in decimal
alpa = int(address[-2:], 16) # AL_PA in decimal
else:
# No, we are already inside of the Nx_port segment, so
# process all remained strings as the fields of Nx_port segment
fields = re.split(":[ \t]+", ln.strip())
if fields[0] == 'Fabric Port Name':
fabric_port_name = fields[1]
if fields[0] == 'Device type':
device_type = fields[1]
if fields[0] == 'Port Index':
port_index = fields[1]
if fields[0] == 'PortSymb':
port_symb = fields[1]
if fields[0] == 'NodeSymb':
node_symb = fields[1]
cnx.commit()
cursor.close()
cnx.close()
print(time.ctime(time.time()) + ":",
"Debug: BFCS:", scr_bfcs['host']+":", "End scan")
return 0
# ------------------------------------------------------------------------------
# Scan HDVM-sources and fill in the appropriate tables
# 1: HDVM Arrays. Get all Storage arrays from every HDVM-source;
# 2: HDVM LUNs. Get LUNs (+ LDEVs, WWNs) from every Storage array of the all
# HDVM-sources;
# 3: HDVM Ports. Get all storage ports (names, WWNs);
# 4: HDVM RG. Get arrays raid-groups (collected but not analized);
# 5: HDVM LDEVS. Must to get LDEVs to fill in missing raid-level info of the
# THP Pools on the R600 arrays on the old HDVM-servers;
# 6: HDVM THP Pools. DP Pools.
# ------------------------------------------------------------------------------
def explore_hdvm(scr_hdvm):
# Open connection with the database
cnx = connect_db(config['DATABASE']['host'], config['DATABASE']['database'],
config['DATABASE']['user'],
config['DATABASE']['password'])
cursor = cnx.cursor()
# Populate the 'sources' table from the INI-file with the HDVM-systems
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", "Start scan")
source_id_hdvm = insert_source(cursor, session_id, 'HDVM', scr_hdvm['host'],
scr_hdvm['login'], scr_hdvm['password'],
'NA', 0, 'NA')
cnx.commit()
# - 1: HDVM Arrays ---------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", "Arrays")
# Get all storage arrays info from the HDVM source
hdvm_array_data = hdvm_getstoragearray(scr_hdvm['host'], scr_hdvm['login'],
scr_hdvm['password'],
'GetAllArrays', 0, 0)
# Parse an XML-output...
xml_hdvm_array = ET.fromstring(hdvm_array_data)
for hdvm_array in xml_hdvm_array.iter('StorageArray'):
name = hdvm_array.get('name')
serialNumber = hdvm_array.get('serialNumber')
arrayType = hdvm_array.get('arrayType')
displayArrayType = hdvm_array.get('displayArrayType')
capacityInKB = hdvm_array.get('capacityInKB')
allocatedCapacityInKB = hdvm_array.get('allocatedCapacityInKB')
freeCapacityInKB = hdvm_array.get('freeCapacityInKB')
totalFreeSpaceInKB = hdvm_array.get('totalFreeSpaceInKB')
numberOfControllers = hdvm_array.get('numberOfControllers')
cacheInMB = hdvm_array.get('cacheInMB')
hardwareRevision = hdvm_array.get('hardwareRevision')
controllerVersion = hdvm_array.get('controllerVersion')
# Search for this array in the hdvm_arrays
array_id = get_valbykey(cursor, session_id, 'array_id', 'hdvm_arrays',
'serial', serialNumber)
if array_id != 'NULL':
# This HDVM-array is already exists in the database (skip it)
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host'] + ":", name + ":",
"Skip the duplicated entry")
continue;
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name)
# ... and save arrays info to the database 'arrays' table
add_hdvm_array = ("INSERT INTO hdvm_arrays "
"(session_id, source_id, name, serial, array_type, "
"display_array_type, capacity, allocated_capacity, "
"free_capacity, total_free_space, "
"number_of_controllers, cache, hardware_revision, "
"controller_version) "
"VALUES (" +
str(session_id) + ", " + str(source_id_hdvm) +
", \'" + str(name) + "\', \'" + str(serialNumber) +
"\', \'" + str(arrayType) + "\', \'" +
str(displayArrayType) + "\', " + str(capacityInKB) +
", " + str(allocatedCapacityInKB) + ", " +
str(freeCapacityInKB) + ", " +
str(totalFreeSpaceInKB) + ", " +
str(numberOfControllers) + ", " + str(cacheInMB) +
", \'" + str(hardwareRevision) + "\', \'" +
str(controllerVersion) + "\')")
cursor.execute(add_hdvm_array, ())
cnx.commit()
# Save 'array_id' to use in the dependent tables
array_id_hdvm = cursor.lastrowid
# - 2: HDVM LUNs -------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name+":", "LUNs")
# From the HDVM source get all ...
hdvm_lun_data = hdvm_getstoragearray(scr_hdvm['host'],
scr_hdvm['login'],
scr_hdvm['password'],
'GetArray_LUNs',
serialNumber,
arrayType)
xml_hdvm_lun = ET.fromstring(hdvm_lun_data)
# ... LDEVs info by LUN ...
for hdvm_lun in xml_hdvm_lun.iter('LogicalUnit'):
devNum = hdvm_lun.get('devNum') # LDEV ordinal number
if arrayType in ['R500', 'R600', 'R700', 'HM700']: # -- Hitach/HP HI-ENDs --
culdev_hex = str("{:06x}".format(int(hdvm_lun.get('devNum')))).upper()
devNumDisplay = re.sub(r'(?<=.)(?=(..)+\b)', ':', culdev_hex) # devNum is CLPR:CU:LDEV
emulation = hdvm_lun.get('emulation') # Emulation
devCount = hdvm_lun.get('devCount') # Offset in LUSE
else: # -- Hitachi Midrange --
devNumDisplay = devNum # LDEV
emulation = '' # Not available
devCount = '' # N/A
raidType = hdvm_lun.get('raidType') # Raid-level
capacityInKB = hdvm_lun.get('capacityInKB') # capacityInKB
consumedCapacityInKB = hdvm_lun.get('consumedCapacityInKB') # consumedCapacityInKB
commandDevice = hdvm_lun.get('commandDevice') # commandDevice 0 or 1
rg_number = hdvm_lun.get('arrayGroup') # Raid-group ordinal number
# for details see "4: RGs"
# section below
dpPoolID = hdvm_lun.get('dpPoolID') # DP Pool ID
dpType = hdvm_lun.get('dpType') # Pool type:
# 0 - normal
# -1 - absent
# ... LUNs ...
for hdvm_lun_path in hdvm_lun.findall("Path"):
portID = hdvm_lun_path.get('portID') # Storage array Port ID
domainID = hdvm_lun_path.get('domainID') # Hostgroup ID
lun = hdvm_lun_path.get('lun') # LUN. Real lun number
# ... Host WWNs ...
for hdvm_lun_path_wwn in hdvm_lun_path.findall("WorldWideName"):
wwn = hdvm_lun_path_wwn.get('wwn').lower().replace(".", ":") # Host WWN
nickname = hdvm_lun_path_wwn.get('nickname') # Host nickname
# ... and save them to the database
add_hdvm_lun = ("INSERT INTO hdvm_lun "
"(array_id, dev_num, dev_num_display, "
"capacity, emulation, device_count, "
"rg_number, raid_type, consumed_capacity, "
"command_device, dp_pool_id, dp_type, "
"port_id, domain_id, lun, wwn, nickname) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s)")
data_hdvm_lun = (array_id_hdvm, devNum, devNumDisplay,
capacityInKB, emulation, devCount,
rg_number, raidType, consumedCapacityInKB,
commandDevice, dpPoolID, dpType,
portID, domainID, lun, wwn, nickname)
cursor.execute(add_hdvm_lun, data_hdvm_lun)
cnx.commit()
# - 3: HDVM Ports ------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name+":", "Ports")
hdvm_port_data = hdvm_getstoragearray(scr_hdvm['host'],
scr_hdvm['login'],
scr_hdvm['password'],
'GetArray_Ports',
serialNumber,
arrayType)
xml_hdvm_port = ET.fromstring(hdvm_port_data)
for hdvm_port in xml_hdvm_port.iter('Port'):
portID = hdvm_port.get('portID')
portType = hdvm_port.get('portType')
portRole = hdvm_port.get('portRole')
topology = hdvm_port.get('topology')
port_displayName = hdvm_port.get('displayName')
lunSecurity = hdvm_port.get('lunSecurityEnabled')
controllerID = hdvm_port.get('controllerID')
pwwn = hdvm_port.get('worldWidePortName').lower().replace(".", ":")
channelSpeed = hdvm_port.get('channelSpeed')
portOption = hdvm_port.get('portOption')
for hdvm_port_hg in hdvm_port.findall("HostStorageDomain"):
domainID = hdvm_port_hg.get('domainID')
hostMode = hdvm_port_hg.get('hostMode')
hostMode2 = hdvm_port_hg.get('hostMode2')
# Hi-Ends uses hostModeOption but not hostMode2 so:
try:
hostModeOption = dvm_port_hg.get('hostModeOption')
except NameError:
hostModeOption = ''
hostMode2 = str(hostMode2) + str(hostModeOption)
hg_displayName = hdvm_port_hg.get('displayName')
domainType = hdvm_port_hg.get('domainType')
nickname = hdvm_port_hg.get('nickname')
add_hdvm_port = ("INSERT INTO hdvm_port "
"(array_id, port_id, port_type, port_role, "
"topology, port_display_name, lun_security, "
"controller_id, pwwn, channel_speed, "
"port_option, domain_id, host_mode, "
"host_mode2, hg_display_name, domain_type, "
"nickname) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s, %s, %s, %s, %s)")
data_hdvm_port = (array_id_hdvm, portID, portType, portRole,
topology, port_displayName, lunSecurity,
controllerID, pwwn, channelSpeed,
portOption, domainID, hostMode, hostMode2,
hg_displayName, domainType, nickname)
cursor.execute(add_hdvm_port, data_hdvm_port)
# - 4: HDVM RGs --------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name+":", "Raid Groups")
hdvm_rg_data = hdvm_getstoragearray(scr_hdvm['host'],
scr_hdvm['login'],
scr_hdvm['password'],
'GetArray_RGs',
serialNumber,
arrayType)
xml_hdvm_rg = ET.fromstring(hdvm_rg_data)
for hdvm_rg in xml_hdvm_rg.iter('ArrayGroup'):
displayName = hdvm_rg.get('displayName')
chassis = hdvm_rg.get('chassis')
controllerID = hdvm_rg.get('controllerID')
number = hdvm_rg.get('number') # Ordinal number
rt = hdvm_rg.get('raidType')
if rt != '-': raidType = rt
diskSizeInKB = hdvm_rg.get('diskSizeInKB')
diskType = hdvm_rg.get('diskType')
totalCapacity = hdvm_rg.get('totalCapacity')
allocatedCapacity = hdvm_rg.get('allocatedCapacity')
freeCapacity = hdvm_rg.get('freeCapacity')
totalFreeSpace = hdvm_rg.get('totalFreeSpace')
emulation = hdvm_rg.get('emulation')
rg_type = hdvm_rg.get('type') # -1: Pools not supported
# 0: RG on any
# 1: Ext on R600/R700/HM700
# 3: ThP on R600/R700/HM700
# 4: ThP on HUS150/AMS2500
volumeType = hdvm_rg.get('volumeType') # 4: Ext volume with rg_type: 4
encrypted = hdvm_rg.get('encrypted')
protectionLevel = hdvm_rg.get('protectionLevel')
dpPoolID = hdvm_rg.get('dpPoolID')
formFactor = hdvm_rg.get('formFactor')
add_hdvm_rg = ("INSERT INTO hdvm_rg "
"(array_id, number, display_name, disk_size, "
"disk_type, total_capacity, allocated_capacity, "
"free_capacity, total_free_space, dp_pool_id, "
"emulation, chassis, controller_id, "
"raid_type, rg_type, volume_type, encrypted, "
"protection_level, form_factor) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s, %s, %s, %s, %s, %s)")
data_hdvm_rg = (array_id_hdvm, number, displayName, diskSizeInKB,
diskType, totalCapacity, allocatedCapacity,
freeCapacity, totalFreeSpace, dpPoolID, emulation,
chassis, controllerID, raidType, rg_type,
volumeType, encrypted, protectionLevel, formFactor)
cursor.execute(add_hdvm_rg, data_hdvm_rg)
# - 5: HDVM LDEVs ------------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name+":", "LDEVs")
hdvm_ldev_data = hdvm_getstoragearray(scr_hdvm['host'],
scr_hdvm['login'],
scr_hdvm['password'],
'GetArray_LDEVs',
serialNumber,
arrayType)
xml_hdvm_ldev = ET.fromstring(hdvm_ldev_data)
for hdvm_ldev in xml_hdvm_ldev.iter('LDEV'):
status = hdvm_ldev.get('status')
quorumDisk = hdvm_ldev.get('quorumDisk')
encrypted = hdvm_ldev.get('encrypted')
threshold = hdvm_ldev.get('threshold')
dpPoolID = hdvm_ldev.get('dpPoolID')
consumedSizeInKB = hdvm_ldev.get('consumedSizeInKB')
dpType = hdvm_ldev.get('dpType')
chassis = hdvm_ldev.get('chassis')
arrayGroup = hdvm_ldev.get('arrayGroup')
devNum = hdvm_ldev.get('devNum') # LDEV ordinal number
if arrayType in ['R500', 'R600', 'R700', 'HM700']: # -- Hitach/HP HI-ENDs --
culdev_hex = str("{:06x}".format(int(hdvm_ldev.get('devNum')))).upper()
devNumDisplay = re.sub(r'(?<=.)(?=(..)+\b)', ':', culdev_hex) # devNum is CLPR:CU:LDEV
emulation = hdvm_ldev.get('emulation')
else:
devNumDisplay = devNum # LDEV display
emulation = '' # Not available
raidType = hdvm_ldev.get('raidType')
volumeKind = hdvm_ldev.get('volumeKind')
sizeInKB = hdvm_ldev.get('sizeInKB')
add_hdvm_ldev = ("INSERT INTO hdvm_ldev "
"(array_id, ldev_status, quorum_disk, "
"encrypted, threshold, dp_pool_id, "
"consumed_size, dp_type, chassis, "
"array_group_number, dev_num, dev_num_display, "
"raid_type, volume_kind, emulation, size) "
"VALUES "
"(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s, %s, %s, %s)")
data_hdvm_ldev = (array_id_hdvm, status, quorumDisk, encrypted,
threshold, dpPoolID, consumedSizeInKB, dpType,
chassis, arrayGroup, devNum, devNumDisplay,
raidType, volumeKind, emulation, sizeInKB)
cursor.execute(add_hdvm_ldev, data_hdvm_ldev)
# - 6: HDVM THP Pools --------------------------------------------------
print(time.ctime(time.time()) + ":",
"Debug: HDVM:", scr_hdvm['host']+":", name+":", "THP Pools")
hdvm_pool_data = hdvm_getstoragearray(scr_hdvm['host'],
scr_hdvm['login'],
scr_hdvm['password'],
'GetArray_Pools',
serialNumber,
arrayType)
xml_hdvm_pool = ET.fromstring(hdvm_pool_data)
for hdvm_pool in xml_hdvm_pool.iter('JournalPool'):