-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathemc_vmax_utils.py
More file actions
1742 lines (1454 loc) · 66.9 KB
/
emc_vmax_utils.py
File metadata and controls
1742 lines (1454 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
# Copyright (c) 2012 - 2014 EMC Corporation.
# All Rights Reserved.
#
# 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.
import datetime
import random
import re
from xml.dom.minidom import parseString
import six
from cinder import context
from cinder import exception
from cinder.i18n import _, _LE, _LI
from cinder.openstack.common import log as logging
from cinder.openstack.common import loopingcall
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
try:
import pywbem
pywbemAvailable = True
except ImportError:
pywbemAvailable = False
STORAGEGROUPTYPE = 4
POSTGROUPTYPE = 3
EMC_ROOT = 'root/emc'
CONCATENATED = 'concatenated'
CINDER_EMC_CONFIG_FILE_PREFIX = '/etc/cinder/cinder_emc_config_'
CINDER_EMC_CONFIG_FILE_POSTFIX = '.xml'
ISCSI = 'iscsi'
FC = 'fc'
JOB_RETRIES = 60
INTERVAL_10_SEC = 10
CIM_ERR_NOT_FOUND = 6
class EMCVMAXUtils(object):
"""Utility class for SMI-S based EMC volume drivers.
This Utility class is for EMC volume drivers based on SMI-S.
It supports VMAX arrays.
"""
def __init__(self, prtcl):
if not pywbemAvailable:
LOG.info(_LI(
'Module PyWBEM not installed. '
'Install PyWBEM using the python-pywbem package.'))
self.protocol = prtcl
def find_storage_configuration_service(self, conn, storageSystemName):
"""Given the storage system name, get the storage configuration service
:param conn: connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundconfigService
"""
foundConfigService = None
configservices = conn.EnumerateInstanceNames(
'EMC_StorageConfigurationService')
for configservice in configservices:
if storageSystemName == configservice['SystemName']:
foundConfigService = configservice
LOG.debug("Found Storage Configuration Service: "
"%(configservice)s",
{'configservice': configservice})
break
if foundConfigService is None:
exceptionMessage = (_("Storage Configuration Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundConfigService
def find_controller_configuration_service(self, conn, storageSystemName):
"""Get the controller config by using the storage service name.
Given the storage system name, get the controller configuration
service.
:param conn: connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundconfigService
"""
foundConfigService = None
configservices = conn.EnumerateInstanceNames(
'EMC_ControllerConfigurationService')
for configservice in configservices:
if storageSystemName == configservice['SystemName']:
foundConfigService = configservice
LOG.debug("Found Controller Configuration Service: "
"%(configservice)s",
{'configservice': configservice})
break
if foundConfigService is None:
exceptionMessage = (_("Controller Configuration Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundConfigService
def find_element_composition_service(self, conn, storageSystemName):
"""Given the storage system name, get the element composition service.
:param conn: the connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundElementCompositionService
"""
foundElementCompositionService = None
elementCompositionServices = conn.EnumerateInstanceNames(
'Symm_ElementCompositionService')
for elementCompositionService in elementCompositionServices:
if storageSystemName == elementCompositionService['SystemName']:
foundElementCompositionService = elementCompositionService
LOG.debug("Found Element Composition Service:"
"%(elementCompositionService)s"
% {'elementCompositionService':
elementCompositionService})
break
if foundElementCompositionService is None:
exceptionMessage = (_("Element Composition Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundElementCompositionService
def find_storage_relocation_service(self, conn, storageSystemName):
"""Given the storage system name, get the storage relocation service.
:param conn: the connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundStorageRelocationService
"""
foundStorageRelocationService = None
storageRelocationServices = conn.EnumerateInstanceNames(
'Symm_StorageRelocationService')
for storageRelocationService in storageRelocationServices:
if storageSystemName == storageRelocationService['SystemName']:
foundStorageRelocationService = storageRelocationService
LOG.debug(
"Found Element Composition Service: "
"%(storageRelocationService)s",
{'storageRelocationService': storageRelocationService})
break
if foundStorageRelocationService is None:
exceptionMessage = (_("Storage Relocation Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundStorageRelocationService
def find_storage_hardwareid_service(self, conn, storageSystemName):
"""Given the storage system name, get the storage hardware service.
:param conn: the connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundStorageRelocationService
"""
foundHardwareService = None
storageHardwareservices = conn.EnumerateInstanceNames(
'EMC_StorageHardwareIDManagementService')
for storageHardwareservice in storageHardwareservices:
if storageSystemName == storageHardwareservice['SystemName']:
foundHardwareService = storageHardwareservice
LOG.debug("Found Storage Hardware ID Management Service:"
"%(storageHardwareservice)s",
{'storageHardwareservice': storageHardwareservice})
break
if foundHardwareService is None:
exceptionMessage = (_("Storage HardwareId mgmt Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundHardwareService
def find_replication_service(self, conn, storageSystemName):
"""Given the storage system name, get the replication service.
:param conn: the connection to the ecom server
:param storageSystemName: the storage system name
:returns: foundRepService
"""
foundRepService = None
repservices = conn.EnumerateInstanceNames(
'EMC_ReplicationService')
for repservice in repservices:
if storageSystemName == repservice['SystemName']:
foundRepService = repservice
LOG.debug("Found Replication Service:"
"%(repservice)s",
{'repservice': repservice})
break
if foundRepService is None:
exceptionMessage = (_("Replication Service not found "
"on %(storageSystemName)s")
% {'storageSystemName': storageSystemName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundRepService
def get_tier_policy_service(self, conn, storageSystemInstanceName):
"""Gets the tier policy service for a given storage system instance.
Given the storage system instance name, get the existing tier
policy service.
:param conn: the connection information to the ecom server
:param storageSystemInstanceName: the storageSystem instance Name
:returns: foundTierPolicyService - the tier policy
service instance name
"""
foundTierPolicyService = None
groups = conn.AssociatorNames(
storageSystemInstanceName,
ResultClass='Symm_TierPolicyService',
AssocClass='CIM_HostedService')
if len(groups) > 0:
foundTierPolicyService = groups[0]
if foundTierPolicyService is None:
exceptionMessage = (_(
"Tier Policy Service not found "
"for %(storageSystemName)s")
% {'storageSystemName': storageSystemInstanceName})
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(data=exceptionMessage)
return foundTierPolicyService
def wait_for_job_complete(self, conn, job):
"""Given the job wait for it to complete.
:param conn: connection to the ecom server
:param job: the job dict
:returns: rc - the return code
:returns: errorDesc - the error description string
"""
jobInstanceName = job['Job']
self._wait_for_job_complete(conn, job)
jobinstance = conn.GetInstance(jobInstanceName,
LocalOnly=False)
rc = jobinstance['ErrorCode']
errorDesc = jobinstance['ErrorDescription']
LOG.debug('Return code is: %(rc)lu'
'Error Description is: %(errorDesc)s',
{'rc': rc,
'errorDesc': errorDesc})
return rc, errorDesc
def _wait_for_job_complete(self, conn, job):
"""Given the job wait for it to complete.
:param conn: connection to the ecom server
:param job: the job dict
"""
def _wait_for_job_complete():
"""Called at an interval until the job is finished"""
retries = kwargs['retries']
wait_for_job_called = kwargs['wait_for_job_called']
if self._is_job_finished(conn, job):
raise loopingcall.LoopingCallDone()
if retries > JOB_RETRIES:
LOG.error(_LE("_wait_for_job_complete "
"failed after %(retries)d "
"tries."),
{'retries': retries})
raise loopingcall.LoopingCallDone()
try:
kwargs['retries'] = retries + 1
if not wait_for_job_called:
if self._is_job_finished(conn, job):
kwargs['wait_for_job_called'] = True
except Exception as e:
LOG.error(_LE("Exception: %s") % six.text_type(e))
exceptionMessage = (_("Issue encountered waiting for job."))
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(exceptionMessage)
kwargs = {'retries': 0,
'wait_for_job_called': False}
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_job_complete)
timer.start(interval=INTERVAL_10_SEC).wait()
def _is_job_finished(self, conn, job):
"""Check if the job is finished.
:param conn: connection to the ecom server
:param job: the job dict
:returns: True if finished; False if not finished;
"""
jobInstanceName = job['Job']
jobinstance = conn.GetInstance(jobInstanceName,
LocalOnly=False)
jobstate = jobinstance['JobState']
# From ValueMap of JobState in CIM_ConcreteJob
# 2L=New, 3L=Starting, 4L=Running, 32767L=Queue Pending
# ValueMap("2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13..32767,
# 32768..65535"),
# Values("New, Starting, Running, Suspended, Shutting Down,
# Completed, Terminated, Killed, Exception, Service,
# Query Pending, DMTF Reserved, Vendor Reserved")]
# NOTE(deva): string matching based on
# http://ipmitool.cvs.sourceforge.net/
# viewvc/ipmitool/ipmitool/lib/ipmi_chassis.c
if jobstate in [2L, 3L, 4L, 32767L]:
return False
else:
return True
def wait_for_sync(self, conn, syncName):
"""Given the sync name wait for it to fully synchronize.
:param conn: connection to the ecom server
:param syncName: the syncName
"""
def _wait_for_sync():
"""Called at an interval until the synchronization is finished."""
retries = kwargs['retries']
wait_for_sync_called = kwargs['wait_for_sync_called']
if self._is_sync_complete(conn, syncName):
raise loopingcall.LoopingCallDone()
if retries > JOB_RETRIES:
LOG.error(_LE("_wait_for_sync failed after %(retries)d "
"tries."),
{'retries': retries})
raise loopingcall.LoopingCallDone()
try:
kwargs['retries'] = retries + 1
if not wait_for_sync_called:
if self._is_sync_complete(conn, syncName):
kwargs['wait_for_sync_called'] = True
except Exception as e:
LOG.error(_LE("Exception: %s") % six.text_type(e))
exceptionMessage = (_("Issue encountered waiting for "
"synchronization."))
LOG.error(exceptionMessage)
raise exception.VolumeBackendAPIException(exceptionMessage)
kwargs = {'retries': 0,
'wait_for_sync_called': False}
timer = loopingcall.FixedIntervalLoopingCall(_wait_for_sync)
timer.start(interval=INTERVAL_10_SEC).wait()
def _is_sync_complete(self, conn, syncName):
"""Check if the job is finished.
:param conn: connection to the ecom server
:param syncName: the sync name
:returns: True if fully synchronized; False if not;
"""
syncInstance = conn.GetInstance(syncName,
LocalOnly=False)
percentSynced = syncInstance['PercentSynced']
LOG.debug("percent synced is %(percentSynced)lu.",
{'percentSynced': percentSynced})
if percentSynced < 100:
return False
else:
return True
def get_num(self, numStr, datatype):
"""Get the ecom int from the number.
:param numStr: the number in string format
:param datatype: the type to convert it to
:returns: result
"""
try:
result = {
'8': pywbem.Uint8(numStr),
'16': pywbem.Uint16(numStr),
'32': pywbem.Uint32(numStr),
'64': pywbem.Uint64(numStr)
}
result = result.get(datatype, numStr)
except NameError:
result = numStr
return result
def find_storage_system(self, conn, configService):
"""Finds the storage system for a particular config service.
Given the storage configuration service get the CIM_StorageSystem
from it.
:param conn: the connection to the ecom server
:param storageConfigService: the storage configuration service
:returns: rc - the return code of the job
:returns: jobDict - the job dict
"""
foundStorageSystemInstanceName = None
groups = conn.AssociatorNames(
configService,
AssocClass='CIM_HostedService')
if len(groups) > 0:
foundStorageSystemInstanceName = groups[0]
else:
LOG.error(_LE("Cannot get storage system"))
raise
return foundStorageSystemInstanceName
def get_storage_group_from_volume(self, conn, volumeInstanceName):
"""Returns the storage group for a particular volume.
Given the volume instance name get the associated storage group if it
is belong to one
:param conn: connection to the ecom server
:param volumeInstanceName: the volume instance name
:returns: foundStorageGroupInstanceName - the storage group
instance name
"""
foundStorageGroupInstanceName = None
storageGroupInstanceNames = conn.AssociatorNames(
volumeInstanceName,
ResultClass='CIM_DeviceMaskingGroup')
if len(storageGroupInstanceNames) > 0:
foundStorageGroupInstanceName = storageGroupInstanceNames[0]
return foundStorageGroupInstanceName
def wrap_get_storage_group_from_volume(self, conn, volumeInstanceName):
"""Unit test aid"""
return self.get_storage_group_from_volume(conn, volumeInstanceName)
def find_storage_masking_group(self, conn, controllerConfigService,
storageGroupName):
"""Given the storage group name get the storage group.
:param conn: connection to the ecom server
:param controllerConfigService: the controllerConfigService
:param storageGroupName: the name of the storage group you are getting
:param foundStorageGroup: storage group instance name
"""
foundStorageMaskingGroupInstanceName = None
storageMaskingGroupInstances = (
conn.Associators(controllerConfigService,
ResultClass='CIM_DeviceMaskingGroup'))
for storageMaskingGroupInstance in \
storageMaskingGroupInstances:
if storageGroupName == storageMaskingGroupInstance['ElementName']:
# Check that it has not been deleted recently.
instance = self.get_existing_instance(
conn, storageMaskingGroupInstance.path)
if instance is None:
# Storage group not found.
foundStorageMaskingGroupInstanceName = None
else:
foundStorageMaskingGroupInstanceName = (
storageMaskingGroupInstance.path)
break
return foundStorageMaskingGroupInstanceName
def find_storage_system_name_from_service(self, configService):
"""Given any service get the storage system name from it.
:param configService: the configuration service
:returns: configService['SystemName'] - storage system name (String)
"""
return configService['SystemName']
def find_volume_instance(self, conn, volumeDict, volumeName):
"""Given the volumeDict get the instance from it.
:param conn: connection to the ecom server
:param volumeDict: the volume Dict
:param volumeName: the user friendly name of the volume
:returns: foundVolumeInstance - the volume instance
"""
volumeInstanceName = self.get_instance_name(volumeDict['classname'],
volumeDict['keybindings'])
foundVolumeInstance = conn.GetInstance(volumeInstanceName)
if foundVolumeInstance is None:
LOG.debug("Volume %(volumeName)s not found on the array.",
{'volumeName': volumeName})
else:
LOG.debug("Volume name: %(volumeName)s Volume instance: "
"%(vol_instance)s.",
{'volumeName': volumeName,
'vol_instance': foundVolumeInstance.path})
return foundVolumeInstance
def get_host_short_name(self, hostName):
"""Returns the short name for a given qualified host name.
Checks the host name to see if it is the fully qualified host name
and returns part before the dot. If there is no dot in the hostName
the full hostName is returned.
:param hostName: the fully qualified host name ()
:param shortHostName: the short hostName
"""
shortHostName = None
hostArray = hostName.split('.')
if len(hostArray) > 2:
shortHostName = hostArray[0]
else:
shortHostName = hostName
return shortHostName
def get_instance_name(self, classname, bindings):
"""Get the instance from the classname and bindings.
NOTE: This exists in common too...will be moving it to other file
where both common and masking can access it
:param classname: class name for the volume instance
:param bindings: volume created from job
:returns: foundVolumeInstance - the volume instance
"""
instanceName = None
try:
instanceName = pywbem.CIMInstanceName(
classname,
namespace=EMC_ROOT,
keybindings=bindings)
except NameError:
instanceName = None
return instanceName
def get_ecom_server(self, filename):
"""Given the file name get the ecomPort and ecomIP from it.
:param filename: the path and file name of the emc configuration file
:returns: ecomIp - the ecom IP address
:returns: ecomPort - the ecom port
"""
ecomIp = self._parse_from_file(filename, 'EcomServerIp')
ecomPort = self._parse_from_file(filename, 'EcomServerPort')
if ecomIp is not None and ecomPort is not None:
LOG.debug("Ecom IP: %(ecomIp)s Port: %(ecomPort)s",
{'ecomIp': ecomIp, 'ecomPort': ecomPort})
return ecomIp, ecomPort
else:
LOG.debug("Ecom server not found.")
return None
def get_ecom_cred(self, filename):
"""Given the filename get the ecomUser and ecomPasswd.
:param filename: the path and filename of the emc configuration file
:returns: ecomUser - the ecom user
:returns: ecomPasswd - the ecom password
"""
ecomUser = self._parse_from_file(filename, 'EcomUserName')
ecomPasswd = self._parse_from_file(filename, 'EcomPassword')
if ecomUser is not None and ecomPasswd is not None:
return ecomUser, ecomPasswd
else:
LOG.debug("Ecom user not found.")
return None
def get_ecom_cred_SSL(self, filename):
"""Given the filename get the ecomUser and ecomPasswd.
:param filename: the path and filename of the emc configuration file
:returns: ecomUser - the ecom user
:returns: ecomPasswd - the ecom password
"""
ecomUseSSL = self._parse_from_file(filename, 'EcomUseSSL')
ecomCACert = self._parse_from_file(filename, 'EcomCACert')
ecomNoVerification = self._parse_from_file(
filename, 'EcomNoVerification')
if ecomUseSSL is not None and ecomUseSSL == 'True':
ecomUseSSL = True
if ecomNoVerification is not None and ecomNoVerification == 'True':
ecomNoVerification = True
return ecomUseSSL, ecomCACert, ecomNoVerification
else:
ecomUseSSL = False
ecomNoVerification = False
return ecomUseSSL, ecomCACert, ecomNoVerification
def parse_file_to_get_port_group_name(self, fileName):
"""Parses a file and chooses a port group randomly.
Given a file, parse it to get all the possible
portGroupElements and choose one randomly.
:param fileName: the path and name of the file
:returns: portGroupName - the name of the port group chosen
"""
portGroupName = None
myFile = open(fileName, 'r')
data = myFile.read()
myFile.close()
dom = parseString(data)
portGroupElements = dom.getElementsByTagName('PortGroup')
if portGroupElements is not None and len(portGroupElements) > 0:
portGroupNames = []
for portGroupElement in portGroupElements:
if portGroupElement.hasChildNodes():
portGroupName = portGroupElement.childNodes[0].nodeValue
portGroupName = portGroupName.replace('\n', '')
portGroupName = portGroupName.replace('\r', '')
portGroupName = portGroupName.replace('\t', '')
portGroupName = portGroupName.strip()
if portGroupName:
portGroupNames.append(portGroupName)
LOG.debug("portGroupNames: %(portGroupNames)s",
{'portGroupNames': portGroupNames})
numPortGroups = len(portGroupNames)
if numPortGroups > 0:
selectedPortGroupName = (
portGroupNames[random.randint(0, numPortGroups - 1)])
LOG.debug("Returning Selected Port Group: "
"'%(selectedPortGroupName)s'",
{'selectedPortGroupName': selectedPortGroupName})
return selectedPortGroupName
exception_message = (_("No Port Group elements found in config file."))
LOG.error(exception_message)
raise exception.VolumeBackendAPIException(data=exception_message)
def _parse_from_file(self, fileName, stringToParse):
"""parse the string from XML.
Remove newlines, tabs and trailing spaces
:param fileName: the path and name of the file
:returns: retString - the returned string
"""
retString = None
myFile = open(fileName, 'r')
data = myFile.read()
myFile.close()
dom = parseString(data)
tag = dom.getElementsByTagName(stringToParse)
if tag is not None and len(tag) > 0:
strXml = tag[0].toxml()
strXml = strXml.replace('<%s>' % stringToParse, '')
strXml = strXml.replace('\n', '')
strXml = strXml.replace('\r', '')
strXml = strXml.replace('\t', '')
retString = strXml.replace('</%s>' % stringToParse, '')
retString = retString.strip()
return retString
def parse_fast_policy_name_from_file(self, fileName):
"""Parse the fast policy name from config file.
If it is not there, then NON FAST is assumed.
:param fileName: the path and name of the file
:returns: fastPolicyName - the fast policy name
"""
fastPolicyName = self._parse_from_file(fileName, 'FastPolicy')
if fastPolicyName:
LOG.debug("File %(fileName)s: Fast Policy is %(fastPolicyName)s",
{'fileName': fileName,
'fastPolicyName': fastPolicyName})
return fastPolicyName
else:
LOG.info(_LI("Fast Policy not found."))
return None
def parse_array_name_from_file(self, fileName):
"""Parse the array name from config file.
If it is not there then there should only be one array configured to
the ecom. If there is more than one then erroneous results can occur.
:param fileName: the path and name of the file
:returns: arrayName - the array name
"""
arrayName = self._parse_from_file(fileName, 'Array')
if arrayName:
return arrayName
else:
LOG.debug("Array not found from config file.")
return None
def parse_pool_name_from_file(self, fileName):
"""Parse the pool name from config file.
If it is not there then we will attempt to get it from extra specs.
:param fileName: the path and name of the file
:returns: poolName - the pool name
"""
poolName = self._parse_from_file(fileName, 'Pool')
if poolName:
return poolName
else:
LOG.debug("Pool not found from config file.")
return None
def parse_slo_from_file(self, fileName):
"""Parse the slo from config file.
Please note that the string 'NONE' is returned if it not found.
:param fileName: the path and name of the file
:returns: slo - the slo or 'NONE'
"""
slo = self._parse_from_file(fileName, 'SLO')
if slo:
return slo
else:
LOG.debug("SLO not in config file. "
"Defaulting to NONE")
return 'NONE'
def parse_workload_from_file(self, fileName):
"""Parse the workload from config file.
Please note that the string 'NONE' is returned if it not found.
:param fileName: the path and name of the file
:returns: workload - the workload or 'NONE'
"""
workload = self._parse_from_file(fileName, 'Workload')
if workload:
return workload
else:
LOG.debug("Workload not in config file. "
"Defaulting to NONE")
return 'NONE'
def parse_pool_instance_id(self, poolInstanceId):
"""Given the instance Id parse the pool name and system name from it.
Example of pool InstanceId: Symmetrix+0001233455555+U+Pool 0
:param poolInstanceId: the path and name of the file
:returns: poolName - the pool name
:returns: systemName - the system name
"""
poolName = None
systemName = None
endp = poolInstanceId.rfind('+')
if endp > -1:
poolName = poolInstanceId[endp + 1:]
idarray = poolInstanceId.split('+')
if len(idarray) > 2:
systemName = idarray[0] + '+' + idarray[1]
LOG.debug("Pool name: %(poolName)s System name: %(systemName)s.",
{'poolName': poolName, 'systemName': systemName})
return poolName, systemName
def parse_pool_instance_id_v3(self, poolInstanceId):
"""Given the instance Id parse the pool name and system name from it.
Example of pool InstanceId: Symmetrix+0001233455555+U+Pool 0
:param poolInstanceId: the path and name of the file
:returns: poolName - the pool name
:returns: systemName - the system name
"""
poolName = None
systemName = None
endp = poolInstanceId.rfind('-+-')
if endp > -1:
poolName = poolInstanceId[endp + 3:]
idarray = poolInstanceId.split('-+-')
if len(idarray) > 2:
systemName = idarray[0] + '-+-' + idarray[1]
LOG.debug("Pool name: %(poolName)s System name: %(systemName)s.",
{'poolName': poolName, 'systemName': systemName})
return poolName, systemName
def convert_gb_to_bits(self, strGbSize):
"""Convert GB(string) to bits(string).
:param strGB: string -- The size in GB
:returns: strBitsSize string -- The size in bits
"""
strBitsSize = six.text_type(int(strGbSize) * 1024 * 1024 * 1024)
LOG.debug("Converted %(strGbSize)s GBs to %(strBitsSize)s Bits",
{'strGbSize': strGbSize, 'strBitsSize': strBitsSize})
return strBitsSize
def check_if_volume_is_composite(self, conn, volumeInstance):
"""Check if the volume is composite.
:param conn: the connection information to the ecom server
:param volumeInstance: the volume Instance
:returns: 'True', 'False' or 'Undetermined'
"""
propertiesList = volumeInstance.properties.items()
for properties in propertiesList:
if properties[0] == 'IsComposite':
cimProperties = properties[1]
if 'True' in six.text_type(cimProperties.value):
return 'True'
elif 'False' in six.text_type(cimProperties.value):
return 'False'
else:
return 'Undetermined'
return 'Undetermined'
def get_assoc_pool_from_volume(self, conn, volumeInstanceName):
"""Give the volume instance get the associated pool instance
:param conn: connection to the ecom server
:param volumeInstanceName: the volume instance name
:returns: foundPoolInstanceName
"""
foundPoolInstanceName = None
foundPoolInstanceNames = (
conn.AssociatorNames(volumeInstanceName,
ResultClass='EMC_VirtualProvisioningPool'))
if len(foundPoolInstanceNames) > 0:
foundPoolInstanceName = foundPoolInstanceNames[0]
return foundPoolInstanceName
def check_if_volume_is_extendable(self, conn, volumeInstance):
"""Checks if a volume is extendable or not.
Check underlying CIM_StorageExtent to see if the volume is
concatenated or not.
If isConcatenated is true then it is a concatenated and
extendable.
If isConcatenated is False and isVolumeComposite is True then
it is striped and not extendable.
If isConcatenated is False and isVolumeComposite is False then
it has one member only but is still extendable.
:param conn: the connection information to the ecom server
:param volumeInstance: the volume instance
:returns: 'True', 'False' or 'Undetermined'
"""
isConcatenated = None
isVolumeComposite = self.check_if_volume_is_composite(
conn, volumeInstance)
storageExtentInstances = conn.Associators(
volumeInstance.path,
ResultClass='CIM_StorageExtent')
if len(storageExtentInstances) > 0:
storageExtentInstance = storageExtentInstances[0]
propertiesList = storageExtentInstance.properties.items()
for properties in propertiesList:
if properties[0] == 'IsConcatenated':
cimProperties = properties[1]
isConcatenated = six.text_type(cimProperties.value)
if isConcatenated is not None:
break
if 'True' in isConcatenated:
return 'True'
elif 'False' in isConcatenated and 'True' in isVolumeComposite:
return 'False'
elif 'False' in isConcatenated and 'False' in isVolumeComposite:
return 'True'
else:
return 'Undetermined'
def get_composite_type(self, compositeTypeStr):
"""Get the int value of composite type.
The default is '2' concatenated.
:param compositeTypeStr: 'concatenated' or 'striped'. Cannot be None
:returns: compositeType = 2 or 3
"""
compositeType = 2
stripedStr = 'striped'
try:
if compositeTypeStr.lower() == stripedStr.lower():
compositeType = 3
except KeyError:
# Default to concatenated if not defined
pass
return compositeType
def is_volume_bound_to_pool(self, conn, volumeInstance):
'''Check if volume is bound to a pool.
:param conn: the connection information to the ecom server
:param storageServiceInstanceName: the storageSystem instance Name
:returns: foundIsSupportsTieringPolicies - true/false
'''
propertiesList = volumeInstance.properties.items()
for properties in propertiesList:
if properties[0] == 'EMCIsBound':
cimProperties = properties[1]
if 'True' in six.text_type(cimProperties.value):
return 'True'
elif 'False' in six.text_type(cimProperties.value):
return 'False'
else:
return 'Undetermined'
return 'Undetermined'
def get_space_consumed(self, conn, volumeInstance):
'''Check the space consumed of a volume.
:param conn: the connection information to the ecom server
:param volumeInstance: the volume Instance
:returns: spaceConsumed
'''
foundSpaceConsumed = None
unitnames = conn.References(
volumeInstance, ResultClass='CIM_AllocatedFromStoragePool',
Role='Dependent')
for unitname in unitnames:
propertiesList = unitname.properties.items()
for properties in propertiesList:
if properties[0] == 'SpaceConsumed':
cimProperties = properties[1]
foundSpaceConsumed = cimProperties.value
break
if foundSpaceConsumed is not None:
break
return foundSpaceConsumed
def get_volume_size(self, conn, volumeInstance):
'''Get the volume size.
ConsumableBlocks * BlockSize
:param conn: the connection information to the ecom server
:param volumeInstance: the volume Instance
:returns: volumeSizeOut
'''
volumeSizeOut = 'Undetermined'
numBlocks = 0
blockSize = 0
propertiesList = volumeInstance.properties.items()
for properties in propertiesList:
if properties[0] == 'ConsumableBlocks':
cimProperties = properties[1]
numBlocks = int(cimProperties.value)
if properties[0] == 'BlockSize':
cimProperties = properties[1]
blockSize = int(cimProperties.value)
if blockSize > 0 and numBlocks > 0: