File: share_network_subnets.py

package info (click to toggle)
python-manilaclient 5.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,768 kB
  • sloc: python: 49,541; makefile: 99; sh: 2
file content (352 lines) | stat: -rw-r--r-- 13,540 bytes parent folder | download
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
#    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 logging
from operator import xor

from osc_lib.cli import format_columns
from osc_lib.cli import parseractions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils as oscutils

from manilaclient import api_versions
from manilaclient.common._i18n import _
from manilaclient.common import cliutils


LOG = logging.getLogger(__name__)


class CreateShareNetworkSubnet(command.ShowOne):
    """Create a share network subnet."""
    _description = _("Create a share network subnet")

    def get_parser(self, prog_name):
        parser = super(CreateShareNetworkSubnet, self).get_parser(prog_name)
        parser.add_argument(
            "share_network",
            metavar="<share-network>",
            help=_("Share network name or ID.")
        )
        parser.add_argument(
            "--neutron-net-id",
            metavar="<neutron-net-id>",
            default=None,
            help=_("Neutron network ID. Used to set up network for share "
                   "servers (optional). Should be defined together with "
                   "'--neutron-subnet-id'.")
        )
        parser.add_argument(
            "--neutron-subnet-id",
            metavar="<neutron-subnet-id>",
            default=None,
            help=_("Neutron subnet ID. Used to set up network for share "
                   "servers (optional). Should be defined together with "
                   "'--neutron-net-id' to which this subnet belongs to. ")
        )
        parser.add_argument(
            "--availability-zone",
            metavar="<availability-zone>",
            default=None,
            help=_("Optional availability zone that the subnet is available "
                   "within (Default=None). If None, the subnet will be "
                   "considered as being available across all availability "
                   "zones.")
        )
        parser.add_argument(
            '--check-only',
            default=False,
            action='store_true',
            help=_("Run a dry-run of a share network subnet create. "
                   "Available only for microversion >= 2.70.")
        )
        parser.add_argument(
            '--restart-check',
            default=False,
            action='store_true',
            help=_("Restart a dry-run of a share network subnet create. "
                   "Helpful when check results are stale. "
                   "Available only for microversion >= 2.70.")
        )
        parser.add_argument(
            "--property",
            metavar="<key=value>",
            default={},
            action=parseractions.KeyValueAction,
            help=_("Set a property to this share network subnet "
                   "(repeat option to set multiple properties). "
                   "Available only for microversion >= 2.78."),
        )
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        # check and restart check during create is only available from 2.70.
        if (parsed_args.check_only and
                share_client.api_version < api_versions.APIVersion("2.70")):
            raise exceptions.CommandError(
                "Check only can be specified only with manila API "
                "version >= 2.70.")
        if (parsed_args.restart_check and
                share_client.api_version < api_versions.APIVersion("2.70")):
            raise exceptions.CommandError(
                "Restart check can be specified only with manila API "
                "version >= 2.70.")

        if (parsed_args.property and
                share_client.api_version < api_versions.APIVersion("2.78")):
            raise exceptions.CommandError(
                "Property can be specified only with manila API "
                "version >= 2.78.")

        if xor(bool(parsed_args.neutron_net_id),
               bool(parsed_args.neutron_subnet_id)):
            raise exceptions.CommandError(
                "Both neutron_net_id and neutron_subnet_id should be "
                "specified. Alternatively, neither of them should be "
                "specified.")

        share_network_id = oscutils.find_resource(
            share_client.share_networks,
            parsed_args.share_network).id

        if parsed_args.check_only or parsed_args.restart_check:

            if parsed_args.property:
                raise exceptions.CommandError(
                    "Property cannot be specified with check operation.")

            subnet_create_check = (
                share_client.share_networks.share_network_subnet_create_check(
                    neutron_net_id=parsed_args.neutron_net_id,
                    neutron_subnet_id=parsed_args.neutron_subnet_id,
                    availability_zone=parsed_args.availability_zone,
                    reset_operation=parsed_args.restart_check,
                    share_network_id=share_network_id)
            )
            subnet_data = subnet_create_check[1]
            if subnet_data:
                if parsed_args.formatter == 'table':
                    for k, v in subnet_data.items():
                        if isinstance(v, dict):
                            capabilities_list = [v]
                            dict_values = cliutils.convert_dict_list_to_string(
                                capabilities_list
                            )
                            subnet_data[k] = dict_values
        else:
            share_network_subnet = share_client.share_network_subnets.create(
                neutron_net_id=parsed_args.neutron_net_id,
                neutron_subnet_id=parsed_args.neutron_subnet_id,
                availability_zone=parsed_args.availability_zone,
                share_network_id=share_network_id,
                metadata=parsed_args.property
            )
            subnet_data = share_network_subnet._info

        return self.dict2columns(subnet_data)


class DeleteShareNetworkSubnet(command.Command):
    """Delete a share network subnet."""
    _description = _("Delete a share network subnet")

    def get_parser(self, prog_name):
        parser = super(DeleteShareNetworkSubnet, self).get_parser(prog_name)
        parser.add_argument(
            "share_network",
            metavar="<share-network>",
            help=_("Share network name or ID.")
        )
        parser.add_argument(
            "share_network_subnet",
            metavar="<share-network-subnet>",
            nargs="+",
            help=_("ID(s) of share network subnet(s) to be deleted.")
        )
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        result = 0

        share_network_id = oscutils.find_resource(
            share_client.share_networks,
            parsed_args.share_network).id

        for subnet in parsed_args.share_network_subnet:
            try:
                share_client.share_network_subnets.delete(
                    share_network_id,
                    subnet)

            except Exception as e:
                result += 1
                LOG.error(f"Failed to delete share network subnet with "
                          f"ID {subnet}: {e}")
        if result > 0:
            total = len(parsed_args.share_network_subnet)
            raise exceptions.CommandError(
                f"{result} of {total} share network subnets failed to be "
                f"deleted.")


class ShowShareNetworkSubnet(command.ShowOne):
    """Show share network subnet."""
    _description = _("Show share network subnet")

    def get_parser(self, prog_name):
        parser = super(ShowShareNetworkSubnet, self).get_parser(prog_name)
        parser.add_argument(
            "share_network",
            metavar="<share-network>",
            help=_("Share network name or ID.")
        )
        parser.add_argument(
            "share_network_subnet",
            metavar="<share-network-subnet>",
            help=_("ID of share network subnet to show.")
        )
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share_network_id = oscutils.find_resource(
            share_client.share_networks,
            parsed_args.share_network).id

        share_network_subnet = share_client.share_network_subnets.get(
            share_network_id,
            parsed_args.share_network_subnet)
        data = share_network_subnet._info

        # Special mapping for columns to make the output easier to read:
        # 'metadata' --> 'properties'
        data.update(
            {
                'properties':
                    format_columns.DictColumn(data.pop('metadata', {})),
            },
        )

        return self.dict2columns(data)


class SetShareNetworkSubnet(command.Command):
    """Set share network subnet properties."""
    _description = _("Set share network subnet properties")

    def get_parser(self, prog_name):
        parser = super(SetShareNetworkSubnet, self).get_parser(prog_name)
        parser.add_argument(
            "share_network",
            metavar="<share-network>",
            help=_("Share network name or ID.")
        )
        parser.add_argument(
            "share_network_subnet",
            metavar="<share-network-subnet>",
            help=_("ID of share network subnet to set a property.")
        )
        parser.add_argument(
            "--property",
            metavar="<key=value>",
            default={},
            action=parseractions.KeyValueAction,
            help=_("Set a property to this share network subnet "
                   "(repeat option to set multiple properties). "
                   "Available only for microversion >= 2.78."),
        )
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        if (parsed_args.property and
                share_client.api_version < api_versions.APIVersion("2.78")):
            raise exceptions.CommandError(
                "Property can be specified only with manila API "
                "version >= 2.78.")

        share_network_id = oscutils.find_resource(
            share_client.share_networks,
            parsed_args.share_network).id

        if parsed_args.property:
            try:
                share_client.share_network_subnets.set_metadata(
                    share_network_id, parsed_args.property,
                    subresource=parsed_args.share_network_subnet)
            except Exception as e:
                raise exceptions.CommandError(_(
                    "Failed to set subnet property '%(properties)s': %(e)s") %
                    {'properties': parsed_args.property, 'e': e})


class UnsetShareNetworkSubnet(command.Command):
    """Unset a share network subnet property."""
    _description = _("Unset a share network subnet property")

    def get_parser(self, prog_name):
        parser = super(UnsetShareNetworkSubnet, self).get_parser(prog_name)
        parser.add_argument(
            "share_network",
            metavar="<share-network>",
            help=_("Share network name or ID.")
        )
        parser.add_argument(
            "share_network_subnet",
            metavar="<share-network-subnet>",
            help=_("ID of share network subnet to set a property.")
        )
        parser.add_argument(
            '--property',
            metavar='<key>',
            action='append',
            help=_("Remove a property from share network subnet "
                   "(repeat option to remove multiple properties). "
                   "Available only for microversion >= 2.78."),
        )
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        if (parsed_args.property and
                share_client.api_version < api_versions.APIVersion("2.78")):
            raise exceptions.CommandError(
                "Property can be specified only with manila API "
                "version >= 2.78.")

        share_network_id = oscutils.find_resource(
            share_client.share_networks,
            parsed_args.share_network).id

        if parsed_args.property:
            result = 0
            for key in parsed_args.property:
                try:
                    share_client.share_network_subnets.delete_metadata(
                        share_network_id, [key],
                        subresource=parsed_args.share_network_subnet)
                except Exception as e:
                    result += 1
                    LOG.error("Failed to unset subnet property "
                              "'%(key)s': %(e)s", {'key': key, 'e': e})
            if result > 0:
                total = len(parsed_args.property)
                raise exceptions.CommandError(
                    f"{result} of {total} subnet properties failed to be "
                    f"unset.")