File: checkpoints.py

package info (click to toggle)
python-karborclient 2.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 776 kB
  • sloc: python: 8,201; makefile: 21; sh: 10
file content (283 lines) | stat: -rw-r--r-- 10,283 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
#    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.

"""Data protection V1 checkpoint action implementations"""

from osc_lib.command import command
from osc_lib import utils as osc_utils
from oslo_log import log as logging
from oslo_serialization import jsonutils

from karborclient.common.apiclient import exceptions
from karborclient.i18n import _
from karborclient import utils


def format_checkpoint(checkpoint_info):
    if 'protection_plan' in checkpoint_info:
        plan = checkpoint_info['protection_plan']
        checkpoint_info['protection_plan'] = "Name: %s\nId: %s" % (
            plan['name'], plan['id'])
    if 'resource_graph' in checkpoint_info:
        checkpoint_info['resource_graph'] = jsonutils.dumps(jsonutils.loads(
            checkpoint_info['resource_graph']), indent=2, sort_keys=True)
    checkpoint_info.pop("links", None)


class ListCheckpoints(command.Lister):
    _description = _("List checkpoints.")

    log = logging.getLogger(__name__ + ".ListCheckpoints")

    def get_parser(self, prog_name):
        parser = super(ListCheckpoints, self).get_parser(prog_name)
        parser.add_argument(
            'provider_id',
            metavar='<provider_id>',
            help=_('ID of provider.'),
        )
        parser.add_argument(
            '--all-projects',
            action='store_true',
            default=False,
            help=_('Include all projects (admin only)'),
        )
        parser.add_argument(
            '--plan_id',
            metavar='<plan_id>',
            default=None,
            help=_('Filters results by a plan ID. Default=None.'),
        )
        parser.add_argument(
            '--start_date',
            type=str,
            metavar='<start_date>',
            default=None,
            help=_('Filters results by a start date("Y-m-d"). Default=None.'),
        )
        parser.add_argument(
            '--end_date',
            type=str,
            metavar='<end_date>',
            default=None,
            help=_('Filters results by a end date("Y-m-d"). Default=None.'),
        )
        parser.add_argument(
            '--project_id',
            metavar='<project_id>',
            default=None,
            help=_('Filters results by a project ID. Default=None.'),
        )
        parser.add_argument(
            '--marker',
            metavar='<checkpoint>',
            help=_('The last checkpoint ID of the previous page.'),
        )
        parser.add_argument(
            '--limit',
            type=int,
            metavar='<num-checkpoints>',
            help=_('Maximum number of checkpoints to display.'),
        )
        parser.add_argument(
            '--sort',
            metavar="<key>[:<direction>]",
            default=None,
            help=_("Sort output by selected keys and directions(asc or desc), "
                   "multiple keys and directions can be "
                   "specified separated by comma"),
        )
        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        data_protection_client = self.app.client_manager.data_protection
        all_projects = bool(parsed_args.project_id) or parsed_args.all_projects
        search_opts = {
            'plan_id': parsed_args.plan_id,
            'start_date': parsed_args.start_date,
            'end_date': parsed_args.end_date,
            'project_id': parsed_args.project_id,
            'all_tenants': all_projects
        }

        data = data_protection_client.checkpoints.list(
            provider_id=parsed_args.provider_id, search_opts=search_opts,
            marker=parsed_args.marker, limit=parsed_args.limit,
            sort=parsed_args.sort)

        column_headers = ['Id', 'Project id', 'Status', 'Protection plan',
                          'Metadata', 'Created at']

        def plan_formatter(plan):
            return "Name: %s\nId: %s" % (plan['name'],
                                         plan['id'])
        formatters = {"Protection plan": plan_formatter}
        return (column_headers,
                (osc_utils.get_item_properties(
                    s, column_headers, formatters=formatters
                ) for s in data))


class ShowCheckpoint(command.ShowOne):
    _description = "Shows checkpoint details"

    def get_parser(self, prog_name):
        parser = super(ShowCheckpoint, self).get_parser(prog_name)
        parser.add_argument(
            'provider_id',
            metavar="<provider_id>",
            help=_('Id of provider.')
        )
        parser.add_argument(
            'checkpoint_id',
            metavar="<checkpoint_id>",
            help=_('Id of checkpoint.')
        )
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.data_protection
        checkpoint = client.checkpoints.get(parsed_args.provider_id,
                                            parsed_args.checkpoint_id)
        format_checkpoint(checkpoint._info)
        return zip(*sorted(checkpoint._info.items()))


class CreateCheckpoint(command.ShowOne):
    _description = "Creates a checkpoint"

    def get_parser(self, prog_name):
        parser = super(CreateCheckpoint, self).get_parser(prog_name)
        parser.add_argument(
            'provider_id',
            metavar='<provider_id>',
            help=_('ID of provider.')
        )
        parser.add_argument(
            'plan_id',
            metavar='<plan_id>',
            help=_('ID of plan.')
        )
        parser.add_argument(
            '--extra_info',
            type=str,
            nargs='*',
            metavar='<key=value>',
            default=None,
            help=_('The extra info of a checkpoint.')
        )
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.data_protection
        checkpoint_extra_info = None
        if parsed_args.extra_info is not None:
            checkpoint_extra_info = utils.extract_extra_info(parsed_args)
        checkpoint = client.checkpoints.create(parsed_args.provider_id,
                                               parsed_args.plan_id,
                                               checkpoint_extra_info)
        format_checkpoint(checkpoint._info)
        return zip(*sorted(checkpoint._info.items()))


class DeleteCheckpoint(command.Command):
    _description = "Delete checkpoint"

    log = logging.getLogger(__name__ + ".DeleteCheckpoint")

    def get_parser(self, prog_name):
        parser = super(DeleteCheckpoint, self).get_parser(prog_name)
        parser.add_argument(
            'provider_id',
            metavar='<provider_id>',
            help=_('Id of provider.')
        )
        parser.add_argument(
            'checkpoint',
            metavar='<checkpoint>',
            nargs="+",
            help=_('Id of checkpoint.')
        )
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.data_protection
        failure_count = 0
        for checkpoint_id in parsed_args.checkpoint:
            try:
                client.checkpoints.delete(parsed_args.provider_id,
                                          checkpoint_id)
            except exceptions.NotFound:
                failure_count += 1
                self.log.error(
                    "Failed to delete '{0}'; checkpoint not found".
                    format(checkpoint_id))
        if failure_count == len(parsed_args.checkpoint):
            raise exceptions.CommandError(
                "Unable to find and delete any of the "
                "specified checkpoint.")


class ResetCheckpointState(command.Command):
    _description = "Reset checkpoint state"

    log = logging.getLogger(__name__ + ".ResetCheckpointState")

    def get_parser(self, prog_name):
        parser = super(ResetCheckpointState, self).get_parser(prog_name)
        parser.add_argument(
            'provider_id',
            metavar='<provider_id>',
            help=_('Id of provider.')
        )
        parser.add_argument(
            'checkpoint',
            metavar='<checkpoint>',
            nargs="+",
            help=_('Id of checkpoint.')
        )
        parser.add_argument(
            '--available',
            action='store_const', dest='state',
            default='error', const='available',
            help=_('Request the checkpoint be reset to "available" state '
                   'instead of "error" state(the default).'),
        )
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.data_protection
        failure_count = 0
        for checkpoint_id in parsed_args.checkpoint:
            try:
                client.checkpoints.reset_state(
                    parsed_args.provider_id, checkpoint_id, parsed_args.state)
            except exceptions.NotFound:
                failure_count += 1
                self.log.error(
                    "Failed to reset state of '{0}'; checkpoint "
                    "not found".format(checkpoint_id))
            except exceptions.Forbidden:
                failure_count += 1
                self.log.error(
                    "Failed to reset state of '{0}'; not "
                    "allowed".format(checkpoint_id))
            except exceptions.BadRequest:
                failure_count += 1
                self.log.error(
                    "Failed to reset state of '{0}'; invalid input or "
                    "current checkpoint state".format(checkpoint_id))
        if failure_count == len(parsed_args.checkpoint):
            raise exceptions.CommandError(
                "Unable to find or reset any of the specified "
                "checkpoint's state.")