/
huawei_iscsi.py
1440 lines (1255 loc) · 55.5 KB
/
huawei_iscsi.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) 2012 Huawei Technologies Co., Ltd.
# Copyright (c) 2012 OpenStack LLC.
# 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.
"""
Volume driver for HUAWEI T series and Dorado storage systems.
"""
import re
import socket
import time
from oslo.config import cfg
from xml.etree import ElementTree as ET
from cinder import exception
from cinder.openstack.common import excutils
from cinder.openstack.common import log as logging
from cinder import utils
from cinder.volume import driver
LOG = logging.getLogger(__name__)
huawei_opt = [
cfg.StrOpt('cinder_huawei_conf_file',
default='/etc/cinder/cinder_huawei_conf.xml',
help='config data for cinder huawei plugin')]
HOST_GROUP_NAME = 'HostGroup_OpenStack'
HOST_NAME_PREFIX = 'Host_'
HOST_PORT_PREFIX = 'HostPort_'
VOL_AND_SNAP_NAME_FREFIX = 'OpenStack_'
READBUFFERSIZE = 8192
class SSHConnection(utils.SSHPool):
"""An SSH connetion class .
For some reasons, we can not use method ssh_execute defined in utils to
send CLI commands. Here we define a new class inherited to SSHPool. Use
method create() to build a new SSH client and use invoke_shell() to start
an interactive shell session on the storage system.
"""
def __init__(self, ip, port, login, password, conn_timeout,
privatekey=None, *args, **kwargs):
self.ssh = None
super(SSHConnection, self).__init__(ip, port, conn_timeout, login,
password, privatekey=None,
*args, **kwargs)
def connect(self):
"""Create an SSH client and open an interactive SSH channel."""
self.ssh = self.create()
self.channel = self.ssh.invoke_shell()
self.channel.resize_pty(600, 800)
def close(self):
"""Close SSH connection."""
self.channel.close()
self.ssh.close()
def read(self, timeout=None):
"""Read data from SSH channel."""
result = ''
user_flg = self.login + ':/>$'
self.channel.settimeout(timeout)
while True:
try:
result = result + self.channel.recv(READBUFFERSIZE)
except socket.timeout:
break
else:
# If we get the complete result string, then no need to wait
# until time out.
if re.search(user_flg, result) or re.search('(y/n)', result):
break
return result
def send_cmd(self, strcmd, timeout, waitstr=None):
"""Send SSH commands and return results."""
info = ''
self.channel.send(strcmd + '\n')
result = self.read(timeout)
info = '\r\n'.join(result.split('\r\n')[1:-1])
return info
class HuaweiISCSIDriver(driver.ISCSIDriver):
"""Huawei T series and Dorado iSCSI volume driver."""
def __init__(self, *args, **kwargs):
super(HuaweiISCSIDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(huawei_opt)
self.device_type = {}
self.login_info = {}
self.hostgroup_id = None
# Flag to tell whether the other controller is available
# if the current controller can not be connected to.
self.controller_alterable = True
def do_setup(self, context):
"""Check config file."""
LOG.debug(_('do_setup.'))
self._check_conf_file()
# Create hostgroup.
self.login_info = self._get_login_info()
hostgroup_name = HOST_GROUP_NAME
self.hostgroup_id = self._find_hostgroup(hostgroup_name)
if not self.hostgroup_id:
self._create_hostgroup(hostgroup_name)
self.hostgroup_id = self._find_hostgroup(hostgroup_name)
def check_for_setup_error(self):
"""Try to connect with device and get device type."""
LOG.debug(_('check_for_setup_error.'))
self.login_info = self._get_login_info()
self.device_type = self._get_device_type()
if not self.device_type['type']:
err_msg = (_('check_for_setup_error: Can not get device type.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
LOG.debug(_('check_for_setup_error: Device type is:%(type)s, '
'version is:%(version)s.')
% {'type': self.device_type['type'],
'version': self.device_type['version']})
# Now only version V1 is supported.
if self.device_type['version'] != 'V100R':
err_msg = (_('check_for_setup_error: Product version not right. '
'Please make sure the product version is V1.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
def create_volume(self, volume):
"""Create a new volume."""
volume_name = self._name_translate(volume['name'])
LOG.debug(_('create_volume:volume name: %s.') % volume_name)
self.login_info = self._get_login_info()
if int(volume['size']) == 0:
volume_sise = '100M'
else:
volume_sise = '%sG' % volume['size']
self._create_volume(volume_name, volume_sise)
def delete_volume(self, volume):
"""Delete a volume."""
volume_name = self._name_translate(volume['name'])
LOG.debug(_('delete_volume: volume name: %s.') % volume_name)
self.login_info = self._get_login_info()
volume_id = self._find_lun(volume_name)
if volume_id:
self._delete_volume(volume_name, volume_id)
else:
err_msg = (_('delete_volume:No need to delete volume.'
'Volume %(name)s does not exist.')
% {'name': volume['name']})
LOG.error(err_msg)
def create_export(self, context, volume):
"""Driver entry point to get the export info for a new volume."""
volume_name = self._name_translate(volume['name'])
LOG.debug(_('create_export: volume name:%s') % volume['name'])
lun_id = self._find_lun(volume_name)
if not lun_id:
err_msg = (_('create_export:Volume %(name)s does not exist.')
% {'name': volume_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
return {'provider_location': lun_id}
def ensure_export(self, context, volume):
"""Driver entry point to get the export info for a existing volume."""
pass
def remove_export(self, context, volume_id):
"""Driver entry point to remove an export for a volume."""
pass
def initialize_connection(self, volume, connector):
"""Map a volume to a host and return target iSCSI information."""
initiator_name = connector['initiator']
volume_name = self._name_translate(volume['name'])
LOG.debug(_('initialize_connection: volume name: %(volume)s. '
'initiator name: %(ini)s.')
% {'volume': volume_name,
'ini': initiator_name})
host_name = HOST_NAME_PREFIX + str(hash(initiator_name))
host_id = self._find_host_in_hostgroup(host_name, self.hostgroup_id)
if not host_id:
self._add_host(host_name, self.hostgroup_id)
host_id = self._find_host_in_hostgroup(host_name,
self.hostgroup_id)
# Create an initiator.
added = self._check_initiator(initiator_name)
if not added:
self._add_initiator(initiator_name)
# Add the initiator to host.
port_name = HOST_PORT_PREFIX + str(hash(initiator_name))
port_info = initiator_name
portadded = False
hostport_info = self._get_hostport_info(host_id)
if hostport_info:
for hostport in hostport_info:
if hostport['info'] == initiator_name:
portadded = True
break
if not portadded:
self._add_hostport(port_name, host_id, port_info)
LOG.debug(_('initialize_connection:host name: %(host)s,'
'initiator name: %(ini)s, '
'hostport name: %(port)s')
% {'host': host_name,
'ini': initiator_name,
'port': port_name})
# Get target iSCSI iqn.
iscsi_conf = self._get_iscsi_info()
target_ip = None
for ini in iscsi_conf['Initiator']:
if ini['Name'] == initiator_name:
target_ip = ini['TargetIP']
break
if not target_ip:
target_ip = iscsi_conf['DefaultTargetIP']
target_iqn = self._get_tgt_iqn(target_ip)
if not target_iqn:
err_msg = (_('initialize_connection:'
'Failed to find target iSCSI iqn.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
# Map a LUN to a host if not mapped.
lun_id = self._find_lun(volume_name)
if not lun_id:
err_msg = (_('initialize_connection:Failed to find the '
'given volume. '
'volume name:%(volume)s.')
% {'volume': volume_name})
raise exception.VolumeBackendAPIException(data=err_msg)
hostlun_id = None
map_info = self._get_map_info(host_id)
# Make sure the hostLUN ID starts from 1.
new_hostlun_id = 1
new_hostlunid_found = False
if map_info:
for map in map_info:
if map['devlunid'] == lun_id:
hostlun_id = map['hostlunid']
break
elif not new_hostlunid_found:
if new_hostlun_id < int(map['hostlunid']):
new_hostlunid_found = True
else:
new_hostlun_id = int(map['hostlunid']) + 1
# The LUN is not mapped to the host.
if not hostlun_id:
self._map_lun(lun_id, host_id, new_hostlun_id)
hostlun_id = self._get_hostlunid(host_id, lun_id)
# Return iSCSI properties.
properties = {}
properties['target_discovered'] = False
properties['target_portal'] = ('%s:%s' % (target_ip, '3260'))
properties['target_iqn'] = target_iqn
properties['target_lun'] = int(hostlun_id)
properties['volume_id'] = volume['id']
auth = volume['provider_auth']
if auth:
(auth_method, auth_username, auth_secret) = auth.split()
properties['auth_method'] = auth_method
properties['auth_username'] = auth_username
properties['auth_password'] = auth_secret
return {'driver_volume_type': 'iscsi', 'data': properties}
def terminate_connection(self, volume, connector, **kwargs):
"""Delete map between a volume and a host."""
initiator_name = connector['initiator']
volume_name = self._name_translate(volume['name'])
LOG.debug(_('terminate_connection:volume name: %(volume)s, '
'initiator name: %(ini)s.')
% {'volume': volume_name,
'ini': initiator_name})
self.login_info = self._get_login_info()
host_name = HOST_NAME_PREFIX + str(hash(initiator_name))
host_id = self._find_host_in_hostgroup(host_name, self.hostgroup_id)
if not host_id:
err_msg = (_('terminate_connection:Host does not exist. '
'Host name:%(host)s.')
% {'host': host_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
# Delete host map.
lun_id = self._find_lun(volume_name)
if not lun_id:
err_msg = (_('terminate_connection:volume does not exist.'
'volume name:%(volume)s')
% {'volume': volume_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
map_id = None
mapnum = 0
map_info = self._get_map_info(host_id)
if map_info:
mapnum = len(map_info)
for map in map_info:
if map['devlunid'] == lun_id:
map_id = map['mapid']
break
if map_id:
self._delete_map(map_id)
mapnum = mapnum - 1
else:
LOG.error(_('terminate_connection:No map between host '
'and volume. Host name:%(hostname)s,'
'volume name:%(volumename)s.')
% {'hostname': host_name,
'volumename': volume_name})
# Delete host initiator when no LUN mapped to it.
portnum = 0
hostportinfo = self._get_hostport_info(host_id)
if hostportinfo:
portnum = len(hostportinfo)
for hostport in hostportinfo:
if hostport['info'] == initiator_name and mapnum == 0:
self._delete_hostport(hostport['id'])
self._delete_initiator(initiator_name)
portnum = portnum - 1
break
else:
LOG.error(_('terminate_connection:No initiator is added '
'to the host. Host name:%(hostname)s')
% {'hostname': host_name})
# Delete host when no initiator added to it.
if portnum == 0:
self._delete_host(host_id)
def create_snapshot(self, snapshot):
"""Create a snapshot."""
snapshot_name = self._name_translate(snapshot['name'])
volume_name = self._name_translate(snapshot['volume_name'])
LOG.debug(_('create_snapshot:snapshot name:%(snapshot)s, '
'volume name:%(volume)s.')
% {'snapshot': snapshot_name,
'volume': volume_name})
self.login_info = self._get_login_info()
if self.device_type['type'] == 'Dorado2100 G2':
err_msg = (_('create_snapshot:Device does not support snapshot.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
if self._is_resource_pool_enough() is False:
err_msg = (_('create_snapshot:'
'Resource pool needs 1GB valid size at least.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
lun_id = self._find_lun(volume_name)
if not lun_id:
err_msg = (_('create_snapshot:Volume does not exist.'
'Volume name:%(name)s')
% {'name': volume_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
self._create_snapshot(snapshot_name, lun_id)
snapshot_id = self._find_snapshot(snapshot_name)
if not snapshot_id:
err_msg = (_('create_snapshot:Snapshot does not exist.'
'Snapshot name:%(name)s')
% {'name': snapshot_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
self._active_snapshot(snapshot_id)
def delete_snapshot(self, snapshot):
"""Delete a snapshot."""
snapshot_name = self._name_translate(snapshot['name'])
volume_name = self._name_translate(snapshot['volume_name'])
LOG.debug(_('delete_snapshot:snapshot name:%(snapshot)s, '
'volume name:%(volume)s.')
% {'snapshot': snapshot_name,
'volume': volume_name})
self.login_info = self._get_login_info()
if self.device_type['type'] == 'Dorado2100 G2':
err_msg = (_('delete_snapshot:Device does not support snapshot.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
snapshot_id = self._find_snapshot(snapshot_name)
if snapshot_id:
self._disable_snapshot(snapshot_id)
self._delete_snapshot(snapshot_id)
else:
err_msg = (_('delete_snapshot:Snapshot does not exist. '
'snapshot name:%(snap)s')
% {'snap': snapshot_name})
LOG.debug(err_msg)
def create_volume_from_snapshot(self, volume, snapshot):
"""Create a volume from a snapshot.
We use LUNcopy to create a new LUN from snapshot.
"""
snapshot_name = self._name_translate(snapshot['name'])
volume_name = self._name_translate(volume['name'])
LOG.debug(_('create_volume_from_snapshot:snapshot '
'name:%(snapshot)s, '
'volume name:%(volume)s.')
% {'snapshot': snapshot_name,
'volume': volume_name})
self.login_info = self._get_login_info()
if self.device_type['type'].find('Dorado') > -1:
err_msg = (_('create_volume_from_snapshot:Device does '
'not support create volume from snapshot. '
'Volume name:%(volume)s, '
'snapshot name:%(snapshot)s.')
% {'volume': volume_name,
'snapshot': snapshot_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
snapshot_id = self._find_snapshot(snapshot_name)
if not snapshot_id:
err_msg = (_('create_volume_from_snapshot:Snapshot does not exist.'
'Snapshot name:%(name)s')
% {'name': snapshot_name})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
# Create a target LUN.
if int(volume['size']) == 0:
volume_size = '%sG' % snapshot['volume_size']
else:
volume_size = '%sG' % volume['size']
self._create_volume(volume_name, volume_size)
volume_id = self._find_lun(volume_name)
luncopy_name = volume_name
try:
self._create_luncopy(luncopy_name, snapshot_id, volume_id)
luncopy_id = self._find_luncopy(luncopy_name)
self._start_luncopy(luncopy_id)
self._wait_for_luncopy(luncopy_name)
# If LUNcopy failed,we should delete the target volume.
except Exception:
with excutils.save_and_reraise_exception():
self._delete_luncopy(luncopy_id)
self._delete_volume(volume_name, volume_id)
self._delete_luncopy(luncopy_id)
def get_volume_stats(self, refresh=False):
"""Get volume status.
If 'refresh' is True, run update the stats first.
"""
if refresh:
self._update_volume_status()
return self._stats
def _check_conf_file(self):
"""Check the config file, make sure the key elements are set."""
root = self._read_xml()
try:
IP1 = root.findtext('Storage/ControllerIP0')
IP2 = root.findtext('Storage/ControllerIP1')
username = root.findtext('Storage/UserName')
pwd = root.findtext('Storage/UserPassword')
pool = root.findall('LUN/StoragePool')
isconfwrong = False
if ((not IP1 and not IP2) or
(not username) or
(not pwd) or
(not pool)):
isconfwrong = True
elif not pool[0].attrib['Name']:
isconfwrong = True
if isconfwrong is True:
err_msg = (_('Config file is wrong. '
'Controler IP, UserName, UserPassword and '
'StoragePool must be set.'))
LOG.error(err_msg)
raise exception.InvalidInput(reason=err_msg)
except Exception as err:
LOG.error(_('_check_conf_file: %s') % str(err))
raise exception.VolumeBackendAPIException(data=err)
def _read_xml(self):
"""Open xml file."""
filename = self.configuration.cinder_huawei_conf_file
try:
tree = ET.parse(filename)
root = tree.getroot()
except Exception as err:
LOG.error(_('_read_xml:%s') % err)
raise exception.VolumeBackendAPIException(data=err)
return root
def _get_login_info(self):
"""Get login IP, username and password from config file."""
logininfo = {}
root = self._read_xml()
try:
logininfo['ControllerIP0'] = root.findtext('Storage/ControllerIP0')
logininfo['ControllerIP1'] = root.findtext('Storage/ControllerIP1')
logininfo['UserName'] = root.findtext('Storage/UserName')
logininfo['UserPassword'] = root.findtext('Storage/UserPassword')
except Exception as err:
LOG.debug(_('_get_login_info error. %s') % err)
raise exception.VolumeBackendAPIException(data=err)
return logininfo
def _get_lun_set_info(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',
'StoragePool': 'RAID_001'}
root = self._read_xml()
try:
luntype = root.findtext('LUN/LUNType')
if luntype in ['Thick', 'Thin']:
lunsetinfo['LUNType'] = luntype
elif luntype is not '' or luntype is not None:
err_msg = (_('Config file is wrong. LUNType must be "Thin"'
' or "Thick". LUNType:%(type)s')
% {'type': luntype})
raise exception.VolumeBackendAPIException(data=err_msg)
# Here we do not judge whether the parameters are right.
# CLI will return error responses if the parameters not right.
stripunitsize = root.findtext('LUN/StripUnitSize')
if stripunitsize is not '' and stripunitsize is not None:
lunsetinfo['StripUnitSize'] = stripunitsize
writetype = root.findtext('LUN/WriteType')
if writetype is not '' and writetype is not None:
lunsetinfo['WriteType'] = writetype
mirrorswitch = root.findtext('LUN/MirrorSwitch')
if mirrorswitch is not '' and mirrorswitch is not None:
lunsetinfo['MirrorSwitch'] = mirrorswitch
if self.device_type['type'] == 'Tseries':
pooltype = luntype
prefetch = root.find('LUN/Prefetch')
if ((prefetch is not None) and
(prefetch.attrib['Type'] != '')):
lunsetinfo['PrefetchType'] = prefetch.attrib['Type']
if lunsetinfo['PrefetchType'] == '1':
lunsetinfo['PrefetchValue'] = prefetch.attrib['Value']
elif lunsetinfo['PrefetchType'] == '2':
lunsetinfo['PrefetchTimes'] = prefetch.attrib['Value']
else:
LOG.debug(_('_get_lun_set_info:Use default prefetch type. '
'Prefetch type:Intelligent.'))
# No need to set Prefetch type for Dorado.
elif self.device_type['type'] == 'Dorado5100':
pooltype = 'Thick'
elif self.device_type['type'] == 'Dorado2100 G2':
return lunsetinfo
poolsinfo = self._find_pool_info(pooltype)
if not poolsinfo:
err_msg = (_('_get_lun_set_info:No available pools! '
'Please check whether storage pool is created.'))
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
pools = root.findall('LUN/StoragePool')
lunsetinfo['StoragePool'] = \
self._get_maximum_pool(pools, poolsinfo, luntype)
except Exception as err:
LOG.error(_('_get_lun_set_info:%s') % err)
raise exception.VolumeBackendAPIException(data=err)
return lunsetinfo
def _find_pool_info(self, pooltype):
"""Return pools information created in storage device."""
if pooltype == 'Thick':
cli_cmd = ('showrg')
else:
cli_cmd = ('showpool')
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) <= 6:
return None
pools_list = []
for i in range(6, len(en) - 2):
r = en[i].split()
pools_list.append(r)
return pools_list
def _get_maximum_pool(self, poolinconf, poolindev, luntype):
"""Get the maximum pool from config file.
According to the given pools' name in config file,
we select the pool of maximum free capacity.
"""
maxpoolid = None
maxpoolsize = 0
if luntype == 'Thin':
nameindex = 1
sizeindex = 4
else:
nameindex = 5
sizeindex = 3
for pool in poolinconf:
poolname = pool.attrib['Name']
for pooldetail in poolindev:
if pooldetail[nameindex] == poolname:
if int(float(pooldetail[sizeindex])) > maxpoolsize:
maxpoolid = pooldetail[0]
maxpoolsize = int(float(pooldetail[sizeindex]))
break
if maxpoolid:
return maxpoolid
else:
err_msg = (_('_get_maximum_pool:maxpoolid is None.'
'Please check config file and make sure '
'the "Name" in "StoragePool" is right.'))
raise exception.VolumeBackendAPIException(data=err_msg)
def _get_iscsi_info(self):
"""Get iSCSI info from config file."""
iscsiinfo = {}
root = self._read_xml()
try:
iscsiinfo['DefaultTargetIP'] = \
root.findtext('iSCSI/DefaultTargetIP')
initiator_list = []
for dic in root.findall('iSCSI/Initiator'):
initiator_list.append(dic.attrib)
iscsiinfo['Initiator'] = initiator_list
except Exception as err:
LOG.error(_('_get_iscsi_info:%s') % str(err))
return iscsiinfo
def _execute_cli(self, cmd):
"""Build SSH connection to execute CLI commands.
If the connection to first controller time out,
try to connect to the other controller.
"""
user = self.login_info['UserName']
pwd = self.login_info['UserPassword']
while True:
if self.controller_alterable:
ip = self.login_info['ControllerIP0']
else:
ip = self.login_info['ControllerIP1']
try:
ssh = SSHConnection(ip, 22, user, pwd, 30)
ssh.connect()
while True:
out = ssh.send_cmd(cmd, 30)
if out.find('(y/n)') > -1:
cmd = 'y'
else:
break
ssh.close()
except Exception as err:
if ((not self.controller_alterable) and
(str(err).find('timed out') > -1)):
self.controller_alterable = False
LOG.debug(_('_execute_cli:Connect to controller0 %(ctr0)s'
' time out.Try to Connect to controller1 '
'%(ctr1)s.')
% {'ctr0': self.login_info['ControllerIP0'],
'ctr1': self.login_info['ControllerIP1']})
continue
else:
LOG.error(_('_execute_cli:%s') % err)
raise exception.VolumeBackendAPIException(data=err)
index = out.find(user + ':/>')
if index > -1:
return out[index:]
else:
return out
def _name_translate(self, name):
"""Form new names because of the 32-character limit on names."""
newname = VOL_AND_SNAP_NAME_FREFIX + str(hash(name))
LOG.debug(_('_name_translate:Name in cinder: %(old)s, '
'new name in storage system: %(new)s')
% {'old': name,
'new': newname})
return newname
def _find_lun(self, name):
"""Get the ID of a LUN with the given LUN name."""
cli_cmd = ('showlun')
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) <= 6:
return None
if 'Dorado2100 G2' == self.device_type['type']:
d = 2
elif 'Dorado5100' == self.device_type['type']:
d = 1
else:
d = 0
for i in range(6, len(en) - 2):
r = en[i].split()
if r[6 - d] == name:
return r[0]
return None
def _create_hostgroup(self, hostgroupname):
"""Create a host group."""
cli_cmd = ('createhostgroup -n %(name)s'
% {'name': hostgroupname})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_create_hostgroup:Failed to Create hostgroup. '
'Hostgroup name: %(name)s. '
'out:%(out)s.')
% {'name': hostgroupname,
'out': out})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
def _find_hostgroup(self, groupname):
"""Get the given hostgroup ID."""
cli_cmd = ('showhostgroup')
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) <= 6:
return None
for i in range(6, len(en) - 2):
r = en[i].split()
if r[1] == groupname:
return r[0]
return None
def _add_host(self, hostname, hostgroupid):
"""Add a new host."""
cli_cmd = ('addhost -group %(groupid)s -n %(hostname)s -t 0'
% {'groupid': hostgroupid,
'hostname': hostname})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_add_host:Failed to add host to hostgroup.'
'host name:%(host)s '
'hostgroup id:%(hostgroup)s '
'out:%(out)s')
% {'host': hostname,
'hostgroup': hostgroupid,
'out': out})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
def _check_initiator(self, ininame):
"""Check whether the initiator is already added."""
cli_cmd = ('showiscsiini -ini %(name)s'
% {'name': ininame})
out = self._execute_cli(cli_cmd)
if out.find('Initiator Information') > -1:
return True
else:
return False
def _add_initiator(self, ininame):
"""Add a new initiator to storage device."""
cli_cmd = ('addiscsiini -n %(name)s'
% {'name': ininame})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_add_initiator:Failed to add initiator.'
'initiator name:%(name)s '
'out:%(out)s')
% {'name': ininame,
'out': out})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
def _delete_initiator(self, ininame):
"""Delete an initiator."""
cli_cmd = ('deliscsiini -n %(name)s'
% {'name': ininame})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_delete_initiator:ERROE:Failed to delete initiator.'
'initiator name:%(name)s '
'out:%(out)s')
% {'name': ininame,
'out': out})
LOG.error(err_msg)
def _find_host_in_hostgroup(self, hostname, hostgroupid):
"""Get the given host ID."""
cli_cmd = ('showhost -group %(groupid)s'
% {'groupid': hostgroupid})
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) < 6:
return None
for i in range(6, len(en) - 2):
r = en[i].split()
if r[1] == hostname:
return r[0]
return None
def _get_hostport_info(self, hostid):
"""Get hostports details of the given host."""
cli_cmd = ('showhostport -host %(hostid)s'
% {'hostid': hostid})
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) < 6:
return None
hostportinfo = []
list_key = ['id', 'name', 'info', 'type', 'hostid',
'linkstatus', 'multioathtype']
for i in range(6, len(en) - 2):
list_val = en[i].split()
hostport_dic = dict(map(None, list_key, list_val))
hostportinfo.append(hostport_dic)
return hostportinfo
def _add_hostport(self, portname, hostid, portinfo, multipathtype=0):
"""Add a host port."""
cli_cmd = ('addhostport -host %(id)s -type 5 '
'-info %(info)s -n %(name)s -mtype %(mtype)s'
% {'id': hostid,
'info': portinfo,
'name': portname,
'mtype': multipathtype})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_add_hostport:Failed to add hostport. '
'port name:%(port)s'
'port information:%(info)s '
'host id:%(host)s'
'out:%(out)s')
% {'port': portname,
'info': portinfo,
'host': hostid,
'out': out})
LOG.error(err_msg)
raise exception.VolumeBackendAPIException(data=err_msg)
def _delete_hostport(self, portid):
"""Delete a host port."""
cli_cmd = ('delhostport -force -p %(portid)s'
% {'portid': portid})
out = self._execute_cli(cli_cmd)
if not re.search('command operates successfully', out):
err_msg = (_('_delete_hostport:Failed to delete host port. '
'port id:%(portid)s')
% {'portid': portid})
LOG.error(err_msg)
def _get_tgt_iqn(self, iscsiip):
"""Get target iSCSI iqn."""
LOG.debug(_('_get_tgt_iqn:iSCSI IP is %s.') % iscsiip)
cli_cmd = ('showiscsitgtname')
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) < 4:
return None
index = en[4].find('iqn')
iqn_prefix = en[4][index:]
iqn_prefix.strip()
iscsiip_info = self._get_iscsi_ip_info(iscsiip)
if iscsiip_info:
if iscsiip_info['ctrid'] == 'A':
ctr = '0'
elif iscsiip_info['ctrid'] == 'B':
ctr = '1'
interface = '0' + iscsiip_info['interfaceid']
port = iscsiip_info['portid'].replace('P', '0')
iqn_suffix = ctr + '02' + interface + port
for i in range(0, len(iqn_suffix)):
if iqn_suffix[i] != '0':
iqn_suffix = iqn_suffix[i:]
break
if self.device_type['type'] == 'Tseries':
iqn = iqn_prefix + ':' + iqn_suffix + ':' \
+ iscsiip_info['ipaddress']
elif self.device_type['type'] == "Dorado2100 G2":
iqn = iqn_prefix + ":" + iscsiip_info['ipaddress'] + "-" \
+ iqn_suffix
else:
iqn = iqn_prefix + ':' + iscsiip_info['ipaddress']
LOG.debug(_('_get_tgt_iqn:iSCSI target iqn is:%s') % iqn)
return iqn
else:
return None
def _get_iscsi_ip_info(self, iscsiip):
"""Get iSCSI IP infomation of storage device."""
cli_cmd = ('showiscsiip')
out = self._execute_cli(cli_cmd)
en = out.split('\r\n')
if len(en) < 6:
return None
iscsiIPinfo = {}
for i in range(6, len(en) - 2):
r = en[i].split()
if r[3] == iscsiip:
iscsiIPinfo['ctrid'] = r[0]
iscsiIPinfo['interfaceid'] = r[1]
iscsiIPinfo['portid'] = r[2]
iscsiIPinfo['ipaddress'] = r[3]
return iscsiIPinfo
return None
def _map_lun(self, lunid, hostid, new_hostlun_id):
"""Map a lun to a host.
Here we give the hostlun ID which starts from 1.
"""
cli_cmd = ('addhostmap -host %(hostid)s -devlun %(lunid)s'
'-hostlun %(hostlunid)s'
% {'hostid': hostid,
'lunid': lunid,