/
rest_common.py
1288 lines (1074 loc) · 49.3 KB
/
rest_common.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
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2013 Huawei Technologies Co., Ltd.
# Copyright (c) 2013 OpenStack Foundation
# 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.
"""Common class for Huawei HVS storage drivers."""
import base64
import cookielib
import json
import time
import urllib2
import uuid
from xml.etree import ElementTree as ET
from cinder import context
from cinder import exception
from cinder.openstack.common import excutils
from cinder.openstack.common import log as logging
from cinder import units
from cinder import utils
from cinder.volume.drivers.huawei import huawei_utils
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
QOS_KEY = ["Qos-high", "Qos-normal", "Qos-low"]
TIER_KEY = ["Tier-high", "Tier-normal", "Tier-low"]
class HVSCommon():
"""Common class for Huawei OceanStor HVS storage system."""
def __init__(self, configuration):
self.configuration = configuration
self.cookie = cookielib.CookieJar()
self.url = None
self.xml_conf = self.configuration.cinder_huawei_conf_file
def call(self, url=False, data=None, method=None):
"""Send requests to HVS server.
Send HTTPS call, get response in JSON.
Convert response into Python Object and return it.
"""
LOG.debug(_('HVS Request URL: %(url)s') % {'url': url})
LOG.debug(_('HVS Request Data: %(data)s') % {'data': data})
headers = {"Connection": "keep-alive",
"Content-Type": "application/json"}
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
urllib2.install_opener(opener)
try:
urllib2.socket.setdefaulttimeout(720)
req = urllib2.Request(url, data, headers)
if method:
req.get_method = lambda: method
res = urllib2.urlopen(req).read().decode("utf-8")
LOG.debug(_('HVS Response Data: %(res)s') % {'res': res})
except Exception as err:
err_msg = _('Bad reponse from server: %s') % err
LOG.error(err_msg)
raise err
try:
res_json = json.loads(res)
except Exception as err:
LOG.error(_('JSON transfer error'))
raise err
return res_json
def login(self):
"""Log in HVS array.
If login failed, the driver will sleep 30's to avoid frequent
connection to the server.
"""
login_info = self._get_login_info()
url = login_info['HVSURL'] + "xx/sessions"
data = json.dumps({"username": login_info['UserName'],
"password": login_info['UserPassword'],
"scope": "0"})
result = self.call(url, data)
if (result['error']['code'] != 0) or ("data" not in result):
time.sleep(30)
msg = _("Login error, reason is %s") % result
LOG.error(msg)
raise exception.CinderException(msg)
deviceid = result['data']['deviceid']
self.url = login_info['HVSURL'] + deviceid
return deviceid
def _init_tier_parameters(self, parameters, lunparam):
"""Init the LUN parameters through the volume type "performance"."""
if "tier" in parameters:
smart_tier = parameters['tier']
if smart_tier == 'Tier_high':
lunparam['INITIALDISTRIBUTEPOLICY'] = "1"
elif smart_tier == 'Tier_normal':
lunparam['INITIALDISTRIBUTEPOLICY'] = "2"
elif smart_tier == 'Tier_low':
lunparam['INITIALDISTRIBUTEPOLICY'] = "3"
else:
lunparam['INITIALDISTRIBUTEPOLICY'] = "2"
def _init_lun_parameters(self, name, parameters):
"""Init basic LUN parameters """
lunparam = {"TYPE": "11",
"NAME": name,
"PARENTTYPE": "216",
"PARENTID": parameters['pool_id'],
"DESCRIPTION": "",
"ALLOCTYPE": parameters['LUNType'],
"CAPACITY": parameters['volume_size'],
"WRITEPOLICY": parameters['WriteType'],
"MIRRORPOLICY": parameters['MirrorSwitch'],
"PREFETCHPOLICY": parameters['PrefetchType'],
"PREFETCHVALUE": parameters['PrefetchValue'],
"DATATRANSFERPOLICY": "1",
"INITIALDISTRIBUTEPOLICY": "0"}
return lunparam
def _init_qos_parameters(self, parameters, lun_param):
"""Init the LUN parameters through the volume type "Qos-xxx"."""
policy_id = None
policy_info = None
if "qos" in parameters:
policy_info = self._find_qos_policy_info(parameters['qos'])
if policy_info:
policy_id = policy_info['ID']
lun_param['IOClASSID'] = policy_info['ID']
qos_level = parameters['qos_level']
if qos_level == 'Qos-high':
lun_param['IOPRIORITY'] = "3"
elif qos_level == 'Qos-normal':
lun_param['IOPRIORITY'] = "2"
elif qos_level == 'Qos-low':
lun_param['IOPRIORITY'] = "1"
else:
lun_param['IOPRIORITY'] = "2"
return (policy_info, policy_id)
def _assert_rest_result(self, result, err_str):
error_code = result['error']['code']
if error_code != 0:
msg = _('%(err)s\nresult: %(res)s') % {'err': err_str,
'res': result}
LOG.error(msg)
raise exception.CinderException(msg)
def _assert_data_in_result(self, result, msg):
if "data" not in result:
err_msg = _('%s "data" was not in result.') % msg
LOG.error(err_msg)
raise exception.CinderException(err_msg)
def _create_volume(self, lun_param):
url = self.url + "/lun"
data = json.dumps(lun_param)
result = self.call(url, data)
msg = 'Create volume error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data']['ID']
def create_volume(self, volume):
volume_name = self._encode_name(volume['id'])
config_params = self._parse_volume_type(volume)
# Prepare lun parameters, including qos parameter and tier parameter.
lun_param = self._init_lun_parameters(volume_name, config_params)
self._init_tier_parameters(config_params, lun_param)
policy_info, policy_id = self._init_qos_parameters(config_params,
lun_param)
# Create LUN in array
lunid = self._create_volume(lun_param)
# Enable qos, need to add lun into qos policy
if "qos" in config_params:
lun_list = policy_info['LUNLIST']
lun_list.append(lunid)
if policy_id:
self._update_qos_policy_lunlist(lun_list, policy_id)
else:
LOG.warn(_("Can't find the Qos policy in array"))
# Create lun group and add LUN into to lun group
lungroup_id = self._create_lungroup(volume_name)
self._associate_lun_to_lungroup(lungroup_id, lunid)
return lunid
def _get_volume_size(self, poolinfo, volume):
"""Calculate the volume size.
We should devide the given volume size by 512 for the HVS system
caculates volume size with sectors, which is 512 bytes.
"""
volume_size = units.GiB / 512 # 1G
if int(volume['size']) != 0:
volume_size = int(volume['size']) * units.GiB / 512
return volume_size
def delete_volume(self, volume):
"""Delete a volume.
Three steps: first, remove associate from lun group.
Second, remove associate from qos policy. Third, remove the lun.
"""
name = self._encode_name(volume['id'])
lun_id = self._get_volume_by_name(name)
lungroup_id = self._find_lungroup(name)
if lun_id and lungroup_id:
self._delete_lun_from_qos_policy(volume, lun_id)
self._delete_associated_lun_from_lungroup(lungroup_id, lun_id)
self._delete_lungroup(lungroup_id)
self._delete_lun(lun_id)
else:
LOG.warn(_("Can't find lun or lun goup in array"))
def _delete_lun_from_qos_policy(self, volume, lun_id):
"""Remove lun from qos policy."""
parameters = self._parse_volume_type(volume)
if "qos" in parameters:
qos = parameters['qos']
policy_info = self._find_qos_policy_info(qos)
if policy_info:
lun_list = policy_info['LUNLIST']
for item in lun_list:
if lun_id == item:
lun_list.remove(item)
self._update_qos_policy_lunlist(lun_list, policy_info['ID'])
def _delete_lun(self, lun_id):
url = self.url + "/lun/" + lun_id
data = json.dumps({"TYPE": "11",
"ID": lun_id})
result = self.call(url, data, "DELETE")
self._assert_rest_result(result, 'delete lun error')
def _encode_name(self, name):
uuid_str = name.replace("-", "")
vol_uuid = uuid.UUID('urn:uuid:%s' % uuid_str)
vol_encoded = base64.urlsafe_b64encode(vol_uuid.bytes)
newuuid = vol_encoded.replace("=", "")
return newuuid
def _find_pool_info(self):
root = huawei_utils.parse_xml_file(self.xml_conf)
pool_name = root.findtext('LUN/StoragePool')
if not pool_name:
err_msg = _("Invalid resource pool: %s") % pool_name
LOG.error(err_msg)
raise exception.InvalidInput(err_msg)
url = self.url + "/storagepool"
result = self.call(url, None)
self._assert_rest_result(result, 'Query resource pool error')
poolinfo = {}
if "data" in result:
for item in result['data']:
if pool_name.strip() == item['NAME']:
poolinfo['ID'] = item['ID']
poolinfo['CAPACITY'] = item['USERFREECAPACITY']
poolinfo['TOTALCAPACITY'] = item['USERTOTALCAPACITY']
break
if not poolinfo:
msg = (_('Get pool info error, pool name is:%s') % pool_name)
LOG.error(msg)
raise exception.CinderException(msg)
return poolinfo
def _get_volume_by_name(self, name):
url = self.url + "/lun"
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Get volume by name error!')
volume_id = None
if "data" in result:
for item in result['data']:
if name == item['NAME']:
volume_id = item['ID']
break
return volume_id
def _active_snapshot(self, snapshot_id):
activeurl = self.url + "/snapshot/activate"
data = json.dumps({"SNAPSHOTLIST": [snapshot_id]})
result = self.call(activeurl, data)
self._assert_rest_result(result, 'Active snapshot error.')
def _create_snapshot(self, snapshot):
snapshot_name = self._encode_name(snapshot['id'])
volume_name = self._encode_name(snapshot['volume_id'])
LOG.debug(_('create_snapshot:snapshot name:%(snapshot)s, '
'volume name:%(volume)s.')
% {'snapshot': snapshot_name,
'volume': volume_name})
lun_id = self._get_volume_by_name(volume_name)
url = self.url + "/snapshot"
data = json.dumps({"TYPE": "27",
"NAME": snapshot_name,
"PARENTTYPE": "11",
"PARENTID": lun_id})
result = self.call(url, data)
msg = 'Create snapshot error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data']['ID']
def create_snapshot(self, snapshot):
snapshot_id = self._create_snapshot(snapshot)
self._active_snapshot(snapshot_id)
def _stop_snapshot(self, snapshot):
snapshot_name = self._encode_name(snapshot['id'])
volume_name = self._encode_name(snapshot['volume_id'])
LOG.debug(_('_stop_snapshot:snapshot name:%(snapshot)s, '
'volume name:%(volume)s.')
% {'snapshot': snapshot_name,
'volume': volume_name})
snapshotid = self._get_snapshotid_by_name(snapshot_name)
stopdata = json.dumps({"ID": snapshotid})
url = self.url + "/snapshot/stop"
result = self.call(url, stopdata, "PUT")
self._assert_rest_result(result, 'Stop snapshot error.')
return snapshotid
def _delete_snapshot(self, snapshotid):
url = self.url + "/snapshot/%s" % snapshotid
data = json.dumps({"TYPE": "27", "ID": snapshotid})
result = self.call(url, data, "DELETE")
self._assert_rest_result(result, 'Delete snapshot error.')
def delete_snapshot(self, snapshot):
snapshotid = self._stop_snapshot(snapshot)
self._delete_snapshot(snapshotid)
def _get_snapshotid_by_name(self, name):
url = self.url + "/snapshot"
data = json.dumps({"TYPE": "27"})
result = self.call(url, data, "GET")
self._assert_rest_result(result, 'Get snapshot id error.')
snapshot_id = None
if "data" in result:
for item in result['data']:
if name == item['NAME']:
snapshot_id = item['ID']
break
return snapshot_id
def _copy_volume(self, volume, copy_name, src_lun, tgt_lun):
luncopy_id = self._create_luncopy(copy_name,
src_lun, tgt_lun)
try:
self._start_luncopy(luncopy_id)
self._wait_for_luncopy(luncopy_id)
except Exception:
with excutils.save_and_reraise_exception():
self._delete_luncopy(luncopy_id)
self.delete_volume(volume)
self._delete_luncopy(luncopy_id)
def create_volume_from_snapshot(self, volume, snapshot):
"""Create a volume from a snapshot.
We use LUNcopy to copy a new volume from snapshot.
The time needed increases as volume size does.
"""
snapshot_name = self._encode_name(snapshot['id'])
src_lun_id = self._get_snapshotid_by_name(snapshot_name)
tgt_lun_id = self.create_volume(volume)
luncopy_name = self._encode_name(volume['id'])
self._copy_volume(volume, luncopy_name, src_lun_id, tgt_lun_id)
def create_cloned_volume(self, volume, src_vref):
"""Clone a new volume from an existing volume."""
volume_name = self._encode_name(src_vref['id'])
src_lun_id = self._get_volume_by_name(volume_name)
tgt_lun_id = self.create_volume(volume)
luncopy_name = self._encode_name(volume['id'])
self._copy_volume(volume, luncopy_name, src_lun_id, tgt_lun_id)
def _create_luncopy(self, luncopyname, srclunid, tgtlunid):
"""Create a luncopy."""
url = self.url + "/luncopy"
data = json.dumps({"TYPE": "219",
"NAME": luncopyname,
"DESCRIPTION": luncopyname,
"COPYSPEED": "2",
"LUNCOPYTYPE": "1",
"SOURCELUN": ("INVALID;%s;INVALID;INVALID;INVALID"
% srclunid),
"TARGETLUN": ("INVALID;%s;INVALID;INVALID;INVALID"
% tgtlunid)})
result = self.call(url, data)
msg = 'Create lun copy error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data']['ID']
def _add_host_into_hostgroup(self, host_name, host_ip):
"""Associate host to hostgroup.
If host group doesn't exist, create one.
"""
hostgroup_id = self._find_hostgroup(host_name)
if hostgroup_id is None:
hostgroup_id = self._create_hostgroup(host_name)
hostid = self._find_host(host_name)
if hostid is None:
os_type = huawei_utils.get_conf_host_os_type(host_ip,
self.xml_conf)
hostid = self._add_host(host_name, os_type)
self._associate_host_to_hostgroup(hostgroup_id, hostid)
return hostid, hostgroup_id
def _mapping_hostgroup_and_lungroup(self, volume_name,
hostgroup_id, host_id):
"""Add hostgroup and lungroup to view."""
lungroup_id = self._find_lungroup(volume_name)
lun_id = self._get_volume_by_name(volume_name)
view_id = self._find_mapping_view(volume_name)
LOG.debug(_('_mapping_hostgroup_and_lungroup: lun_group: %(lun_group)s'
'view_id: %(view_id)s')
% {'lun_group': str(lungroup_id),
'view_id': str(view_id)})
try:
if view_id is None:
view_id = self._add_mapping_view(volume_name, host_id)
self._associate_hostgroup_to_view(view_id, hostgroup_id)
self._associate_lungroup_to_view(view_id, lungroup_id)
else:
if not self._hostgroup_associated(view_id, hostgroup_id):
self._associate_hostgroup_to_view(view_id, hostgroup_id)
if not self._lungroup_associated(view_id, lungroup_id):
self._associate_lungroup_to_view(view_id, lungroup_id)
except Exception:
with excutils.save_and_reraise_exception():
self._delete_hostgoup_mapping_view(view_id, hostgroup_id)
self._delete_lungroup_mapping_view(view_id, lungroup_id)
self._delete_mapping_view(view_id)
return lun_id
def _ensure_initiator_added(self, initiator_name, hostid):
added = self._initiator_is_added_to_array(initiator_name)
if not added:
self._add_initiator_to_array(initiator_name)
else:
if self._is_initiator_associated_to_host(initiator_name) is False:
self._associate_initiator_to_host(initiator_name, hostid)
def initialize_connection_iscsi(self, volume, connector):
"""Map a volume to a host and return target iSCSI information."""
initiator_name = connector['initiator']
volume_name = self._encode_name(volume['id'])
LOG.debug(_('initiator name:%(initiator_name)s, '
'volume name:%(volume)s.')
% {'initiator_name': initiator_name,
'volume': volume_name})
(iscsi_iqn, target_ip) = self._get_iscsi_params(connector)
#create host_goup if not exist
hostid, hostgroup_id = self._add_host_into_hostgroup(connector['host'],
connector['ip'])
self._ensure_initiator_added(initiator_name, hostid)
# Mapping lungooup and hostgoup to view
lun_id = self._mapping_hostgroup_and_lungroup(volume_name,
hostgroup_id, hostid)
hostlunid = self._find_host_lun_id(hostid, lun_id)
LOG.debug(_("host lun id is %s") % hostlunid)
# Return iSCSI properties.
properties = {}
properties['target_discovered'] = False
properties['target_portal'] = ('%s:%s' % (target_ip, '3260'))
properties['target_iqn'] = iscsi_iqn
properties['target_lun'] = int(hostlunid)
properties['volume_id'] = volume['id']
return {'driver_volume_type': 'iscsi', 'data': properties}
def initialize_connection_fc(self, volume, connector):
wwns = connector['wwpns']
volume_name = self._encode_name(volume['id'])
LOG.debug(_('initiator name:%(initiator_name)s, '
'volume name:%(volume)s.')
% {'initiator_name': wwns,
'volume': volume_name})
# Create host group if not exist
hostid, hostgroup_id = self._add_host_into_hostgroup(connector['host'],
connector['ip'])
free_wwns = self._get_connected_free_wwns()
LOG.debug(_("the free wwns %s") % free_wwns)
for wwn in wwns:
if wwn in free_wwns:
self._add_fc_port_to_host(hostid, wwn)
lun_id = self._mapping_hostgroup_and_lungroup(volume_name,
hostgroup_id, hostid)
host_lun_id = self._find_host_lun_id(hostid, lun_id)
tgt_port_wwns = []
for wwn in wwns:
tgtwwpns = self._get_fc_target_wwpns(wwn)
if tgtwwpns:
tgt_port_wwns.append(tgtwwpns)
# Return FC properties.
properties = {}
properties['target_discovered'] = False
properties['target_wwn'] = tgt_port_wwns
properties['target_lun'] = int(host_lun_id)
properties['volume_id'] = volume['id']
LOG.debug(_("the fc server properties is:%s") % properties)
return {'driver_volume_type': 'fibre_channel',
'data': properties}
def _get_iscsi_tgt_port(self):
url = self.url + "/iscsidevicename"
result = self.call(url, None)
msg = 'Get iSCSI target port error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data'][0]['CMO_ISCSI_DEVICE_NAME']
def _find_hostgroup(self, groupname):
"""Get the given hostgroup id."""
url = self.url + "/hostgroup"
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Get host group information error.')
host_group_id = None
if "data" in result:
for item in result['data']:
if groupname == item['NAME']:
host_group_id = item['ID']
break
return host_group_id
def _find_lungroup(self, lungroupname):
"""Get the given hostgroup id."""
url = self.url + "/lungroup"
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Get lun group information error.')
lun_group_id = None
if 'data' in result:
for item in result['data']:
if lungroupname == item['NAME']:
lun_group_id = item['ID']
break
return lun_group_id
def _create_hostgroup(self, hostgroupname):
url = self.url + "/hostgroup"
data = json.dumps({"TYPE": "14", "NAME": hostgroupname})
result = self.call(url, data)
msg = 'Create host group error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data']['ID']
def _create_lungroup(self, lungroupname):
url = self.url + "/lungroup"
data = json.dumps({"DESCRIPTION": lungroupname,
"NAME": lungroupname})
result = self.call(url, data)
msg = 'Create lun group error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
return result['data']['ID']
def _delete_lungroup(self, lungroupid):
url = self.url + "/LUNGroup/" + lungroupid
result = self.call(url, None, "DELETE")
self._assert_rest_result(result, 'Delete lun group error.')
def _lungroup_associated(self, viewid, lungroupid):
url_subfix = ("/mappingview/associate?TYPE=245&"
"ASSOCIATEOBJTYPE=256&ASSOCIATEOBJID=%s" % lungroupid)
url = self.url + url_subfix
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Check lun group associated error.')
if "data" in result:
for item in result['data']:
if viewid == item['ID']:
return True
return False
def _hostgroup_associated(self, viewid, hostgroupid):
url_subfix = ("/mappingview/associate?TYPE=245&"
"ASSOCIATEOBJTYPE=14&ASSOCIATEOBJID=%s" % hostgroupid)
url = self.url + url_subfix
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Check host group associated error.')
if "data" in result:
for item in result['data']:
if viewid == item['ID']:
return True
return False
def _find_host_lun_id(self, hostid, lunid):
time.sleep(2)
url = self.url + ("/lun/associate?TYPE=11&ASSOCIATEOBJTYPE=21"
"&ASSOCIATEOBJID=%s" % (hostid))
result = self.call(url, None, "GET")
self._assert_rest_result(result, 'Find host lun id error.')
host_lun_id = 1
if "data" in result:
for item in result['data']:
if lunid == item['ID']:
associate_data = result['data'][0]['ASSOCIATEMETADATA']
try:
hostassoinfo = json.loads(associate_data)
host_lun_id = hostassoinfo['HostLUNID']
break
except Exception as err:
msg = _("JSON transfer data error. %s") % err
LOG.error(msg)
raise err
return host_lun_id
def _find_host(self, hostname):
"""Get the given host ID."""
url = self.url + "/host"
data = json.dumps({"TYPE": "21"})
result = self.call(url, data, "GET")
self._assert_rest_result(result, 'Find host in host group error.')
host_id = None
if "data" in result:
for item in result['data']:
if hostname == item['NAME']:
host_id = item['ID']
break
return host_id
def _add_host(self, hostname, type):
"""Add a new host."""
url = self.url + "/host"
data = json.dumps({"TYPE": "21",
"NAME": hostname,
"OPERATIONSYSTEM": type})
result = self.call(url, data)
self._assert_rest_result(result, 'Add new host error.')
if "data" in result:
return result['data']['ID']
else:
return None
def _associate_host_to_hostgroup(self, hostgroupid, hostid):
url = self.url + "/host/associate"
data = json.dumps({"ID": hostgroupid,
"ASSOCIATEOBJTYPE": "21",
"ASSOCIATEOBJID": hostid})
result = self.call(url, data)
self._assert_rest_result(result, 'Associate host to host group error.')
def _associate_lun_to_lungroup(self, lungroupid, lunid):
"""Associate lun to lun group."""
url = self.url + "/lungroup/associate"
data = json.dumps({"ID": lungroupid,
"ASSOCIATEOBJTYPE": "11",
"ASSOCIATEOBJID": lunid})
result = self.call(url, data)
self._assert_rest_result(result, 'Associate lun to lun group error.')
def _delete_associated_lun_from_lungroup(self, lungroupid, lunid):
"""Remove lun from lun group."""
url = self.url + ("/lungroup/associate?ID=%s"
"&ASSOCIATEOBJTYPE=11&ASSOCIATEOBJID=%s"
% (lungroupid, lunid))
result = self.call(url, None, 'DELETE')
self._assert_rest_result(result,
'Delete associated lun from lun group error')
def _initiator_is_added_to_array(self, ininame):
"""Check whether the initiator is already added in array."""
url = self.url + "/iscsi_initiator"
data = json.dumps({"TYPE": "222", "ID": ininame})
result = self.call(url, data, "GET")
self._assert_rest_result(result,
'Check initiator added to array error.')
if "data" in result:
for item in result['data']:
if item["ID"] == ininame:
return True
return False
def _is_initiator_associated_to_host(self, ininame):
"""Check whether the initiator is associated to the host."""
url = self.url + "/iscsi_initiator"
data = json.dumps({"TYPE": "222", "ID": ininame})
result = self.call(url, data, "GET")
self._assert_rest_result(result,
'Check initiator associated to host error.')
if "data" in result:
for item in result['data']:
if item['ID'] == ininame and item['ISFREE'] == "true":
return False
return True
def _add_initiator_to_array(self, ininame):
"""Add a new initiator to storage device."""
url = self.url + "/iscsi_initiator/"
data = json.dumps({"TYPE": "222",
"ID": ininame,
"USECHAP": "False"})
result = self.call(url, data)
self._assert_rest_result(result, 'Add initiator to array error.')
def _associate_initiator_to_host(self, ininame, hostid):
"""Associate initiator with the host."""
url = self.url + "/iscsi_initiator/" + ininame
data = json.dumps({"TYPE": "222",
"ID": ininame,
"USECHAP": "False",
"PARENTTYPE": "21",
"PARENTID": hostid})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Associate initiator to host error.')
def _find_mapping_view(self, name):
"""Find mapping view."""
url = self.url + "/mappingview"
data = json.dumps({"TYPE": "245"})
result = self.call(url, data, "GET")
msg = 'Find map view error.'
self._assert_rest_result(result, msg)
self._assert_data_in_result(result, msg)
viewid = None
for item in result['data']:
if name == item['NAME']:
viewid = item['ID']
break
return viewid
def _add_mapping_view(self, name, host_id):
url = self.url + "/mappingview"
data = json.dumps({"NAME": name, "TYPE": "245"})
result = self.call(url, data)
self._assert_rest_result(result, 'Add map view error.')
return result['data']['ID']
def _associate_hostgroup_to_view(self, viewID, hostGroupID):
url = self.url + "/MAPPINGVIEW/CREATE_ASSOCIATE"
data = json.dumps({"ASSOCIATEOBJTYPE": "14",
"ASSOCIATEOBJID": hostGroupID,
"TYPE": "245",
"ID": viewID})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Associate host to view error.')
def _associate_lungroup_to_view(self, viewID, lunGroupID):
url = self.url + "/MAPPINGVIEW/CREATE_ASSOCIATE"
data = json.dumps({"ASSOCIATEOBJTYPE": "256",
"ASSOCIATEOBJID": lunGroupID,
"TYPE": "245",
"ID": viewID})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Associate lun group to view error.')
def _delete_lungroup_mapping_view(self, view_id, lungroup_id):
"""remove lun group associate from the mapping view."""
url = self.url + "/mappingview/REMOVE_ASSOCIATE"
data = json.dumps({"ASSOCIATEOBJTYPE": "256",
"ASSOCIATEOBJID": lungroup_id,
"TYPE": "245",
"ID": view_id})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Delete lun group from view error.')
def _delete_hostgoup_mapping_view(self, view_id, hostgroup_id):
"""remove host group associate from the mapping view."""
url = self.url + "/mappingview/REMOVE_ASSOCIATE"
data = json.dumps({"ASSOCIATEOBJTYPE": "14",
"ASSOCIATEOBJID": hostgroup_id,
"TYPE": "245",
"ID": view_id})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Delete host group from view error.')
def _delete_mapping_view(self, view_id):
"""remove mapping view from the storage."""
url = self.url + "/mappingview/" + view_id
result = self.call(url, None, "DELETE")
self._assert_rest_result(result, 'Delete map view error.')
def terminate_connection(self, volume, connector, **kwargs):
"""Delete map between a volume and a host."""
initiator_name = connector['initiator']
volume_name = self._encode_name(volume['id'])
host_name = connector['host']
LOG.debug(_('terminate_connection:volume name: %(volume)s, '
'initiator name: %(ini)s.')
% {'volume': volume_name,
'ini': initiator_name})
view_id = self._find_mapping_view(volume_name)
hostgroup_id = self._find_hostgroup(host_name)
lungroup_id = self._find_lungroup(volume_name)
if view_id is not None:
self._delete_hostgoup_mapping_view(view_id, hostgroup_id)
self._delete_lungroup_mapping_view(view_id, lungroup_id)
self._delete_mapping_view(view_id)
def login_out(self):
"""logout the session."""
url = self.url + "/sessions"
result = self.call(url, None, "DELETE")
self._assert_rest_result(result, 'Log out of session error.')
def _start_luncopy(self, luncopyid):
"""Starte a LUNcopy."""
url = self.url + "/LUNCOPY/start"
data = json.dumps({"TYPE": "219", "ID": luncopyid})
result = self.call(url, data, "PUT")
self._assert_rest_result(result, 'Start lun copy error.')
def _get_capacity(self):
"""Get free capacity and total capacity of the pools."""
poolinfo = self._find_pool_info()
pool_capacity = {'total_capacity': 0.0,
'CAPACITY': 0.0}
if poolinfo:
total = int(poolinfo['TOTALCAPACITY']) / 1024.0 / 1024.0 / 2
free = int(poolinfo['CAPACITY']) / 1024.0 / 1024.0 / 2
pool_capacity['total_capacity'] = total
pool_capacity['free_capacity'] = free
return pool_capacity
def _get_lun_conf_params(self):
"""Get parameters from config file for creating lun."""
# Default lun set information
lunsetinfo = {'LUNType': 'Thick',
'StripUnitSize': '64',
'WriteType': '1',
'MirrorSwitch': '1',
'PrefetchType': '3',
'PrefetchValue': '0',
'PrefetchTimes': '0'}
root = huawei_utils.parse_xml_file(self.xml_conf)
luntype = root.findtext('LUN/LUNType')
if luntype:
if luntype.strip() in ['Thick', 'Thin']:
lunsetinfo['LUNType'] = luntype.strip()
if luntype.strip() == 'Thick':
lunsetinfo['LUNType'] = 0
if luntype.strip() == 'Thin':
lunsetinfo['LUNType'] = 1
elif luntype is not '' and luntype is not None:
err_msg = (_('Config file is wrong. LUNType must be "Thin"'
' or "Thick". LUNType:%(fetchtype)s')
% {'fetchtype': luntype})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
stripunitsize = root.findtext('LUN/StripUnitSize')
if stripunitsize is not None:
lunsetinfo['StripUnitSize'] = stripunitsize.strip()
writetype = root.findtext('LUN/WriteType')
if writetype is not None:
lunsetinfo['WriteType'] = writetype.strip()
mirrorswitch = root.findtext('LUN/MirrorSwitch')
if mirrorswitch is not None:
lunsetinfo['MirrorSwitch'] = mirrorswitch.strip()
prefetch = root.find('LUN/Prefetch')
fetchtype = prefetch.attrib['Type']
if prefetch is not None and prefetch.attrib['Type']:
if fetchtype in ['0', '1', '2', '3']:
lunsetinfo['PrefetchType'] = fetchtype.strip()
typevalue = prefetch.attrib['Value'].strip()
if lunsetinfo['PrefetchType'] == '1':
lunsetinfo['PrefetchValue'] = typevalue
elif lunsetinfo['PrefetchType'] == '2':
lunsetinfo['PrefetchValue'] = typevalue
else:
err_msg = (_('PrefetchType config is wrong. PrefetchType'
' must in 1,2,3,4. fetchtype is:%(fetchtype)s')
% {'fetchtype': fetchtype})
LOG.error(err_msg)
raise exception.CinderException(err_msg)
else:
LOG.debug(_('Use default prefetch fetchtype. '
'Prefetch fetchtype:Intelligent.'))
return lunsetinfo
def _wait_for_luncopy(self, luncopyid):
"""Wait for LUNcopy to complete."""
while True:
luncopy_info = self._get_luncopy_info(luncopyid)
if luncopy_info['status'] == '40':
break
elif luncopy_info['state'] != '1':
err_msg = (_('_wait_for_luncopy:LUNcopy status is not normal.'
'LUNcopy name: %(luncopyname)s')
% {'luncopyname': luncopyid})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
time.sleep(10)
def _get_luncopy_info(self, luncopyid):
"""Get LUNcopy information."""
url = self.url + "/LUNCOPY?range=[0-100000]"
data = json.dumps({"TYPE": "219", })
result = self.call(url, data, "GET")
self._assert_rest_result(result, 'Get lun copy information error.')
luncopyinfo = {}
if "data" in result:
for item in result['data']: