File: resource_locks.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 (412 lines) | stat: -rw-r--r-- 14,033 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
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
#    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 openstackclient.identity import common as identity_common
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils as osc_utils
from oslo_utils import uuidutils

from manilaclient.common._i18n import _
from manilaclient.common.apiclient import utils as apiutils
from manilaclient.common import constants


LOG = logging.getLogger(__name__)


LOCK_DETAIL_ATTRIBUTES = [
    'ID',
    'Resource Id',
    'Resource Type',
    'Resource Action',
    'Lock Context',
    'User Id',
    'Project Id',
    'Created At',
    'Updated At',
    'Lock Reason',
]

LOCK_SUMMARY_ATTRIBUTES = [
    'ID',
    'Resource Id',
    'Resource Type',
    'Resource Action',
]

RESOURCE_TYPE_MANAGERS = {
    'share': 'shares',
    'access_rule': 'share_access_rules'
}


class CreateResourceLock(command.ShowOne):
    """Create a new resource lock."""
    _description = _("Lock a resource action from occurring on a resource")

    def get_parser(self, prog_name):
        parser = super(CreateResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            'resource',
            metavar='<resource_name_or_id>',
            help='Name or ID of resource to lock.')
        parser.add_argument(
            'resource_type',
            metavar='<resource_type>',
            help='Type of the resource (e.g.: share, access).')
        parser.add_argument(
            '--resource-action',
            '--resource_action',
            metavar='<resource_action>',
            default='delete',
            help='Action to lock on the resource (default="delete")')
        parser.add_argument(
            '--lock-reason',
            '--lock_reason',
            '--reason',
            metavar='<lock_reason>',
            help='Reason for the resource lock.')
        return parser

    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        resource_type = parsed_args.resource_type
        if resource_type not in RESOURCE_TYPE_MANAGERS:
            raise exceptions.CommandError(_("Unsupported resource type"))
        res_manager = RESOURCE_TYPE_MANAGERS[resource_type]

        resource = osc_utils.find_resource(getattr(share_client, res_manager),
                                           parsed_args.resource)
        resource_lock = share_client.resource_locks.create(
            resource.id,
            resource_type,
            parsed_args.resource_action,
            parsed_args.lock_reason
        )

        resource_lock._info.pop('links', None)

        return self.dict2columns(resource_lock._info)


class DeleteResourceLock(command.Command):
    """Remove one or more resource locks."""
    _description = _("Remove one or more resource locks")

    def get_parser(self, prog_name):
        parser = super(DeleteResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            'lock',
            metavar='<lock>',
            nargs='+',
            help='ID(s) of the lock(s).')
        return parser

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

        for lock in parsed_args.lock:
            try:
                lock = apiutils.find_resource(
                    share_client.resource_locks,
                    lock
                )
                lock.delete()
            except Exception as e:
                failure_count += 1
                LOG.error(_(
                    "Failed to delete %(lock)s: %(e)s"),
                    {'lock': lock, 'e': e})

        if failure_count > 0:
            raise exceptions.CommandError(_(
                "Unable to delete some or all of the specified locks."))


class ListResourceLock(command.Lister):
    """Lists all resource locks."""
    _description = _("Lists all resource locks")

    def get_parser(self, prog_name):
        parser = super(ListResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            '--all-projects',
            action='store_true',
            help=_("Filter resource locks for all projects. (Admin only).")
        )
        parser.add_argument(
            '--project',
            default=None,
            help=_("Filter resource locks for specific project by name or ID, "
                   "combine with --all-projects (Admin only).")
        )
        parser.add_argument(
            '--user',
            default=None,
            help=_("Filter resource locks for specific user by name or ID, "
                   "combine with --all-projects to search across projects "
                   "(Admin only).")
        )
        parser.add_argument(
            '--id',
            metavar='<id>',
            default=None,
            help='Filter resource locks by ID. Default=None.')
        parser.add_argument(
            '--resource',
            '--resource-id',
            '--resource_id',
            default=None,
            metavar='<resource-id>',
            dest='resource',
            help=_("Filter resource locks for a resource by ID, specify "
                   "--resource-type to look up by name.")
        )
        parser.add_argument(
            '--resource-type',
            '--resource_type',
            default=None,
            metavar='<resource_type>',
            help=_("Filter resource locks by type of resource.")
        )
        parser.add_argument(
            '--resource-action',
            '--resource_action',
            default=None,
            metavar='<resource_action>',
            help=_("Filter resource locks by resource action.")
        )

        parser.add_argument(
            '--lock-context',
            '--lock_context',
            '--context',
            default=None,
            choices=['user', 'admin', 'service'],
            metavar='<lock_context>',
            help=_("Filter resource locks by context.")
        )
        parser.add_argument(
            '--since',
            default=None,
            metavar='<created_since>',
            help=_("Filter resource locks created since given date. "
                   "The date format must be conforming to ISO8601. ")
        )
        parser.add_argument(
            '--before',
            default=None,
            metavar='<created_before>',
            help=_("Filter resource locks created before given date. "
                   "The date format must be conforming to ISO8601. ")
        )
        parser.add_argument(
            '--limit',
            metavar='<limit>',
            type=int,
            default=None,
            help=_("Number of resource locks to list. (Default=None)"))
        parser.add_argument(
            '--offset',
            metavar="<offset>",
            default=None,
            help='Starting position of resource lock records '
                 'in a paginated list.')
        parser.add_argument(
            '--sort-key', '--sort_key',
            metavar='<sort_key>',
            type=str,
            default=None,
            choices=constants.RESOURCE_LOCK_SORT_KEY_VALUES,
            help='Key to be sorted, available keys are %(keys)s. '
                 'Default=None.'
                 % {'keys': constants.RESOURCE_LOCK_SORT_KEY_VALUES})
        parser.add_argument(
            '--sort-dir', '--sort_dir',
            metavar='<sort_dir>',
            type=str,
            default=None,
            choices=constants.SORT_DIR_VALUES,
            help='Sort direction, available values are %(values)s. '
                 'OPTIONAL: Default=None.' % {
                     'values': constants.SORT_DIR_VALUES})
        parser.add_argument(
            '--detailed',
            dest='detailed',
            metavar='<0|1>',
            nargs='?',
            type=int,
            const=1,
            default=0,
            help="Show detailed information about filtered resource locks.")
        return parser

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

        columns = (
            LOCK_SUMMARY_ATTRIBUTES
            if not parsed_args.detailed
            else LOCK_DETAIL_ATTRIBUTES
        )

        project_id = None
        user_id = None

        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain).id
        if parsed_args.user:
            user_id = identity_common.find_user(identity_client,
                                                parsed_args.user,
                                                parsed_args.user_domain).id
        # set all_projects when using project option
        all_projects = bool(parsed_args.project) or parsed_args.all_projects

        resource_id = parsed_args.resource
        resource_type = parsed_args.resource_type
        if resource_type is not None:
            if resource_type not in RESOURCE_TYPE_MANAGERS:
                raise exceptions.CommandError(_("Unsupported resource type"))
            if resource_id is not None:
                res_manager = RESOURCE_TYPE_MANAGERS[resource_type]
                resource_id = osc_utils.find_resource(
                    getattr(share_client, res_manager),
                    parsed_args.resource
                ).id
        elif resource_id and not uuidutils.is_uuid_like(resource_id):
            raise exceptions.CommandError(
                _("Provide resource ID or specify --resource-type."))

        search_opts = {
            'all_projects': all_projects,
            'project_id': project_id,
            'user_id': user_id,
            'id': parsed_args.id,
            'resource_id': resource_id,
            'resource_type': parsed_args.resource_type,
            'resource_action': parsed_args.resource_action,
            'lock_context': parsed_args.lock_context,
            'created_before': parsed_args.before,
            'created_since': parsed_args.since,
            'limit': parsed_args.limit,
            'offset': parsed_args.offset,
        }

        resource_locks = share_client.resource_locks.list(
            search_opts=search_opts,
            sort_key=parsed_args.sort_key,
            sort_dir=parsed_args.sort_dir
        )

        return (columns, (osc_utils.get_item_properties
                (m, columns) for m in resource_locks))


class ShowResourceLock(command.ShowOne):
    """Show details about a resource lock."""
    _description = _("Show details about a resource lock")

    def get_parser(self, prog_name):
        parser = super(ShowResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            'lock',
            metavar='<lock>',
            help=_('ID of resource lock to show.'))
        return parser

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

        resource_lock = apiutils.find_resource(
            share_client.resource_locks,
            parsed_args.lock)

        return (
            LOCK_DETAIL_ATTRIBUTES,
            osc_utils.get_dict_properties(resource_lock._info,
                                          LOCK_DETAIL_ATTRIBUTES)
        )


class SetResourceLock(command.Command):
    """Set resource lock properties."""
    _description = _("Update resource lock properties")

    def get_parser(self, prog_name):
        parser = super(SetResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            'lock',
            metavar='<lock>',
            help='ID of lock to update.')
        parser.add_argument(
            '--resource-action',
            '--resource_action',
            metavar='<resource_action>',
            help='Resource action to set in the resource lock')
        parser.add_argument(
            '--lock-reason',
            '--lock_reason',
            '--reason',
            dest='lock_reason',
            help="Reason for the resource lock")
        return parser

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

        update_kwargs = {}
        if parsed_args.resource_action is not None:
            update_kwargs['resource_action'] = parsed_args.resource_action
        if parsed_args.lock_reason is not None:
            update_kwargs['lock_reason'] = parsed_args.lock_reason
        if update_kwargs:
            share_client.resource_locks.update(
                parsed_args.lock,
                **update_kwargs
            )


class UnsetResourceLock(command.Command):
    """Unsets a property on a resource lock."""
    _description = _("Remove resource lock properties")

    def get_parser(self, prog_name):
        parser = super(UnsetResourceLock, self).get_parser(prog_name)
        parser.add_argument(
            'lock',
            metavar='<lock>',
            help='ID of resource lock to update.')
        parser.add_argument(
            '--lock-reason',
            '--lock_reason',
            '--reason',
            dest='lock_reason',
            action='store_true',
            default=False,
            help="Unset the lock reason. (Default=False)")
        return parser

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

        if parsed_args.lock_reason:
            share_client.resource_locks.update(
                parsed_args.lock,
                lock_reason=None
            )