1# All Rights Reserved.
2#
3#    Licensed under the Apache License, Version 2.0 (the "License"); you may
4#    not use this file except in compliance with the License. You may obtain
5#    a copy of the License at
6#
7#         http://www.apache.org/licenses/LICENSE-2.0
8#
9#    Unless required by applicable law or agreed to in writing, software
10#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12#    License for the specific language governing permissions and limitations
13#    under the License.
14
15
16import copy
17
18from os_brick.initiator import initiator_connector
19
20
21class BaseISCSIConnector(initiator_connector.InitiatorConnector):
22    def _iterate_all_targets(self, connection_properties):
23        for portal, iqn, lun in self._get_all_targets(connection_properties):
24            props = copy.deepcopy(connection_properties)
25            props['target_portal'] = portal
26            props['target_iqn'] = iqn
27            props['target_lun'] = lun
28            for key in ('target_portals', 'target_iqns', 'target_luns'):
29                props.pop(key, None)
30            yield props
31
32    @staticmethod
33    def _get_luns(con_props, iqns=None):
34        luns = con_props.get('target_luns')
35        num_luns = len(con_props['target_iqns']) if iqns is None else len(iqns)
36        return luns or [con_props['target_lun']] * num_luns
37
38    def _get_all_targets(self, connection_properties):
39        if all(key in connection_properties for key in ('target_portals',
40                                                        'target_iqns')):
41            return list(zip(connection_properties['target_portals'],
42                            connection_properties['target_iqns'],
43                            self._get_luns(connection_properties)))
44
45        return [(connection_properties['target_portal'],
46                 connection_properties['target_iqn'],
47                 connection_properties.get('target_lun', 0))]
48