summaryrefslogtreecommitdiff
path: root/openstackclient/volume/v3/volume_group.py
blob: 242ffcd49fe620fc0ec6d80e3899709bf05a49bf (plain)
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
# 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 argparse

from cinderclient import api_versions
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils

from openstackclient.i18n import _


def _format_group(group):
    columns = (
        'id',
        'status',
        'name',
        'description',
        'group_type',
        'volume_types',
        'availability_zone',
        'created_at',
        'volumes',
        'group_snapshot_id',
        'source_group_id',
    )
    column_headers = (
        'ID',
        'Status',
        'Name',
        'Description',
        'Group Type',
        'Volume Types',
        'Availability Zone',
        'Created At',
        'Volumes',
        'Group Snapshot ID',
        'Source Group ID',
    )

    # TODO(stephenfin): Consider using a formatter for volume_types since it's
    # a list
    return (
        column_headers,
        utils.get_item_properties(
            group,
            columns,
        ),
    )


class CreateVolumeGroup(command.ShowOne):
    """Create a volume group.

    Generic volume groups enable you to create a group of volumes and manage
    them together.

    Generic volume groups are more flexible than consistency groups. Currently
    volume consistency groups only support consistent group snapshot. It
    cannot be extended easily to serve other purposes. A project may want to
    put volumes used in the same application together in a group so that it is
    easier to manage them together, and this group of volumes may or may not
    support consistent group snapshot. Generic volume group solve this problem.
    By decoupling the tight relationship between the group construct and the
    consistency concept, generic volume groups can be extended to support other
    features in the future.

    This command requires ``--os-volume-api-version`` 3.13 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        # This is a bit complicated. We accept two patterns: a legacy pattern
        #
        #   volume group create \
        #     <volume-group-type> <volume-type> [<volume-type>...]
        #
        # and the modern approach
        #
        #   volume group create \
        #     --volume-group-type <volume-group-type>
        #     --volume-type <volume-type>
        #    [--volume-type <volume-type> ...]
        #
        # Because argparse doesn't properly support nested exclusive groups, we
        # use two groups: one to ensure users don't pass <volume-group-type> as
        # both a positional and an option argument and another to ensure users
        # don't pass <volume-type> this way. It's a bit weird but it catches
        # everything we care about.
        source_parser = parser.add_mutually_exclusive_group()
        # we use a different name purely so we can issue a deprecation warning
        source_parser.add_argument(
            'volume_group_type_legacy',
            metavar='<volume_group_type>',
            nargs='?',
            help=argparse.SUPPRESS,
        )
        volume_types_parser = parser.add_mutually_exclusive_group()
        # We need to use a separate dest
        # https://github.com/python/cpython/issues/101990
        volume_types_parser.add_argument(
            'volume_types_legacy',
            metavar='<volume_type>',
            nargs='*',
            default=[],
            help=argparse.SUPPRESS,
        )
        source_parser.add_argument(
            '--volume-group-type',
            metavar='<volume_group_type>',
            help=_('Volume group type to use (name or ID)'),
        )
        volume_types_parser.add_argument(
            '--volume-type',
            metavar='<volume_type>',
            dest='volume_types',
            action='append',
            default=[],
            help=_(
                'Volume type(s) to use (name or ID) '
                '(required with --volume-group-type)'
            ),
        )
        source_parser.add_argument(
            '--source-group',
            metavar='<source-group>',
            help=_(
                'Existing volume group to use (name or ID) '
                '(supported by --os-volume-api-version 3.14 or later)'
            ),
        )
        source_parser.add_argument(
            '--group-snapshot',
            metavar='<group-snapshot>',
            help=_(
                'Existing group snapshot to use (name or ID) '
                '(supported by --os-volume-api-version 3.14 or later)'
            ),
        )
        parser.add_argument(
            '--name',
            metavar='<name>',
            help=_('Name of the volume group.'),
        )
        parser.add_argument(
            '--description',
            metavar='<description>',
            help=_('Description of a volume group.')
        )
        parser.add_argument(
            '--availability-zone',
            metavar='<availability-zone>',
            help=_(
                'Availability zone for volume group. '
                '(not available if creating group from source)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if parsed_args.volume_group_type_legacy:
            msg = _(
                "Passing volume group type and volume types as positional "
                "arguments is deprecated. Use the --volume-group-type and "
                "--volume-type option arguments instead."
            )
            self.log.warning(msg)

        volume_group_type = parsed_args.volume_group_type or \
            parsed_args.volume_group_type_legacy
        volume_types = parsed_args.volume_types[:]
        volume_types.extend(parsed_args.volume_types_legacy)

        if volume_group_type:
            if volume_client.api_version < api_versions.APIVersion('3.13'):
                msg = _(
                    "--os-volume-api-version 3.13 or greater is required to "
                    "support the 'volume group create' command"
                )
                raise exceptions.CommandError(msg)
            if not volume_types:
                msg = _(
                    "--volume-types is a required argument when creating a "
                    "group from group type."
                )
                raise exceptions.CommandError(msg)

            volume_group_type_id = utils.find_resource(
                volume_client.group_types,
                volume_group_type,
            ).id
            volume_types_ids = []
            for volume_type in volume_types:
                volume_types_ids.append(
                    utils.find_resource(
                        volume_client.volume_types,
                        volume_type,
                    ).id
                )

            group = volume_client.groups.create(
                volume_group_type_id,
                ','.join(volume_types_ids),
                parsed_args.name,
                parsed_args.description,
                availability_zone=parsed_args.availability_zone,
            )

            group = volume_client.groups.get(group.id)
            return _format_group(group)

        else:
            if volume_client.api_version < api_versions.APIVersion('3.14'):
                msg = _(
                    "--os-volume-api-version 3.14 or greater is required to "
                    "support the 'volume group create "
                    "[--source-group|--group-snapshot]' command"
                )
                raise exceptions.CommandError(msg)
            if (parsed_args.source_group is None and
                    parsed_args.group_snapshot is None):
                msg = _(
                    "Either --source-group <source_group> or "
                    "'--group-snapshot <group_snapshot>' needs to be "
                    "provided to run the 'volume group create "
                    "[--source-group|--group-snapshot]' command"
                )
                raise exceptions.CommandError(msg)
            if parsed_args.availability_zone:
                msg = _("'--availability-zone' option will not work "
                        "if creating group from source.")
                self.log.warning(msg)

            source_group = None
            if parsed_args.source_group:
                source_group = utils.find_resource(volume_client.groups,
                                                   parsed_args.source_group)
            group_snapshot = None
            if parsed_args.group_snapshot:
                group_snapshot = utils.find_resource(
                    volume_client.group_snapshots,
                    parsed_args.group_snapshot)
            group = volume_client.groups.create_from_src(
                group_snapshot.id if group_snapshot else None,
                source_group.id if source_group else None,
                parsed_args.name,
                parsed_args.description)
            group = volume_client.groups.get(group.id)
            return _format_group(group)


class DeleteVolumeGroup(command.Command):
    """Delete a volume group.

    This command requires ``--os-volume-api-version`` 3.13 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Name or ID of volume group to delete'),
        )
        parser.add_argument(
            '--force',
            action='store_true',
            default=False,
            help=_(
                'Delete the volume group even if it contains volumes. '
                'This will delete any remaining volumes in the group.',
            )
        )
        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if volume_client.api_version < api_versions.APIVersion('3.13'):
            msg = _(
                "--os-volume-api-version 3.13 or greater is required to "
                "support the 'volume group delete' command"
            )
            raise exceptions.CommandError(msg)

        group = utils.find_resource(
            volume_client.groups,
            parsed_args.group,
        )

        volume_client.groups.delete(
            group.id, delete_volumes=parsed_args.force)


class SetVolumeGroup(command.ShowOne):
    """Update a volume group.

    This command requires ``--os-volume-api-version`` 3.13 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Name or ID of volume group.'),
        )
        parser.add_argument(
            '--name',
            metavar='<name>',
            help=_('New name for group.'),
        )
        parser.add_argument(
            '--description',
            metavar='<description>',
            help=_('New description for group.'),
        )
        parser.add_argument(
            '--enable-replication',
            action='store_true',
            dest='enable_replication',
            default=None,
            help=_(
                'Enable replication for group. '
                '(supported by --os-volume-api-version 3.38 or above)'
            ),
        )
        parser.add_argument(
            '--disable-replication',
            action='store_false',
            dest='enable_replication',
            help=_(
                'Disable replication for group. '
                '(supported by --os-volume-api-version 3.38 or above)'
            ),
        )
        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if volume_client.api_version < api_versions.APIVersion('3.13'):
            msg = _(
                "--os-volume-api-version 3.13 or greater is required to "
                "support the 'volume group set' command"
            )
            raise exceptions.CommandError(msg)

        group = utils.find_resource(
            volume_client.groups,
            parsed_args.group,
        )

        if parsed_args.enable_replication is not None:
            if volume_client.api_version < api_versions.APIVersion('3.38'):
                msg = _(
                    "--os-volume-api-version 3.38 or greater is required to "
                    "support the '--enable-replication' or "
                    "'--disable-replication' options"
                )
                raise exceptions.CommandError(msg)

            if parsed_args.enable_replication:
                volume_client.groups.enable_replication(group.id)
            else:
                volume_client.groups.disable_replication(group.id)

        kwargs = {}

        if parsed_args.name is not None:
            kwargs['name'] = parsed_args.name

        if parsed_args.description is not None:
            kwargs['description'] = parsed_args.description

        if kwargs:
            group = volume_client.groups.update(group.id, **kwargs)

        return _format_group(group)


class ListVolumeGroup(command.Lister):
    """Lists all volume groups.

    This command requires ``--os-volume-api-version`` 3.13 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            '--all-projects',
            dest='all_projects',
            action='store_true',
            default=utils.env('ALL_PROJECTS', default=False),
            help=_('Shows details for all projects (admin only).'),
        )
        # TODO(stephenfin): Add once we have an equivalent command for
        # 'cinder list-filters'
        # parser.add_argument(
        #     '--filter',
        #     metavar='<key=value>',
        #     action=parseractions.KeyValueAction,
        #     dest='filters',
        #     help=_(
        #         "Filter key and value pairs. Use 'foo' to "
        #         "check enabled filters from server. Use 'key~=value' for "
        #         "inexact filtering if the key supports "
        #         "(supported by --os-volume-api-version 3.33 or above)"
        #     ),
        # )
        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if volume_client.api_version < api_versions.APIVersion('3.13'):
            msg = _(
                "--os-volume-api-version 3.13 or greater is required to "
                "support the 'volume group list' command"
            )
            raise exceptions.CommandError(msg)

        search_opts = {
            'all_tenants': parsed_args.all_projects,
        }

        groups = volume_client.groups.list(
            search_opts=search_opts)

        column_headers = (
            'ID',
            'Status',
            'Name',
        )
        columns = (
            'id',
            'status',
            'name',
        )

        return (
            column_headers,
            (
                utils.get_item_properties(a, columns)
                for a in groups
            ),
        )


class ShowVolumeGroup(command.ShowOne):
    """Show detailed information for a volume group.

    This command requires ``--os-volume-api-version`` 3.13 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Name or ID of volume group.'),
        )
        parser.add_argument(
            '--volumes',
            action='store_true',
            dest='show_volumes',
            default=None,
            help=_(
                'Show volumes included in the group. '
                '(supported by --os-volume-api-version 3.25 or above)'
            ),
        )
        parser.add_argument(
            '--no-volumes',
            action='store_false',
            dest='show_volumes',
            help=_(
                'Do not show volumes included in the group. '
                '(supported by --os-volume-api-version 3.25 or above)'
            ),
        )
        parser.add_argument(
            '--replication-targets',
            action='store_true',
            dest='show_replication_targets',
            default=None,
            help=_(
                'Show replication targets for the group. '
                '(supported by --os-volume-api-version 3.38 or above)'
            ),
        )
        parser.add_argument(
            '--no-replication-targets',
            action='store_false',
            dest='show_replication_targets',
            help=_(
                'Do not show replication targets for the group. '
                '(supported by --os-volume-api-version 3.38 or above)'
            ),
        )

        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if volume_client.api_version < api_versions.APIVersion('3.13'):
            msg = _(
                "--os-volume-api-version 3.13 or greater is required to "
                "support the 'volume group show' command"
            )
            raise exceptions.CommandError(msg)

        kwargs = {}

        if parsed_args.show_volumes is not None:
            if volume_client.api_version < api_versions.APIVersion('3.25'):
                msg = _(
                    "--os-volume-api-version 3.25 or greater is required to "
                    "support the '--(no-)volumes' option"
                )
                raise exceptions.CommandError(msg)

            kwargs['list_volume'] = parsed_args.show_volumes

        if parsed_args.show_replication_targets is not None:
            if volume_client.api_version < api_versions.APIVersion('3.38'):
                msg = _(
                    "--os-volume-api-version 3.38 or greater is required to "
                    "support the '--(no-)replication-targets' option"
                )
                raise exceptions.CommandError(msg)

        group = utils.find_resource(
            volume_client.groups,
            parsed_args.group,
        )

        group = volume_client.groups.show(group.id, **kwargs)

        if parsed_args.show_replication_targets:
            replication_targets = \
                volume_client.groups.list_replication_targets(group.id)

            group.replication_targets = replication_targets

        # TODO(stephenfin): Show replication targets
        return _format_group(group)


class FailoverVolumeGroup(command.Command):
    """Failover replication for a volume group.

    This command requires ``--os-volume-api-version`` 3.38 or greater.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument(
            'group',
            metavar='<group>',
            help=_('Name or ID of volume group to failover replication for.'),
        )
        parser.add_argument(
            '--allow-attached-volume',
            action='store_true',
            dest='allow_attached_volume',
            default=False,
            help=_(
                'Allow group with attached volumes to be failed over.',
            )
        )
        parser.add_argument(
            '--disallow-attached-volume',
            action='store_false',
            dest='allow_attached_volume',
            default=False,
            help=_(
                'Disallow group with attached volumes to be failed over.',
            )
        )
        parser.add_argument(
            '--secondary-backend-id',
            metavar='<backend_id>',
            help=_('Secondary backend ID.'),
        )
        return parser

    def take_action(self, parsed_args):
        volume_client = self.app.client_manager.volume

        if volume_client.api_version < api_versions.APIVersion('3.38'):
            msg = _(
                "--os-volume-api-version 3.38 or greater is required to "
                "support the 'volume group failover' command"
            )
            raise exceptions.CommandError(msg)

        group = utils.find_resource(
            volume_client.groups,
            parsed_args.group,
        )

        volume_client.groups.failover_replication(
            group.id,
            allow_attached_volume=parsed_args.allow_attached_volume,
            secondary_backend_id=parsed_args.secondary_backend_id,
        )