]> git.proxmox.com Git - ceph.git/blame - ceph/src/pybind/mgr/dashboard/controllers/rbd.py
import ceph quincy 17.2.6
[ceph.git] / ceph / src / pybind / mgr / dashboard / controllers / rbd.py
CommitLineData
11fdf7f2
TL
1# -*- coding: utf-8 -*-
2# pylint: disable=unused-argument
3# pylint: disable=too-many-statements,too-many-branches
11fdf7f2 4
1911f103 5import logging
11fdf7f2 6import math
11fdf7f2 7from datetime import datetime
f67539c2 8from functools import partial
11fdf7f2 9
2a845540 10import cherrypy
11fdf7f2
TL
11import rbd
12
11fdf7f2 13from .. import mgr
9f95a23c 14from ..exceptions import DashboardException
11fdf7f2
TL
15from ..security import Scope
16from ..services.ceph_service import CephService
f67539c2 17from ..services.exception import handle_rados_error, handle_rbd_error, serialize_dashboard_exception
2a845540
TL
18from ..services.rbd import MIRROR_IMAGE_MODE, RbdConfiguration, \
19 RbdMirroringService, RbdService, RbdSnapshotService, format_bitmask, \
20 format_features, get_image_spec, parse_image_spec, rbd_call, \
f67539c2 21 rbd_image_call
11fdf7f2 22from ..tools import ViewCache, str_to_bool
2a845540
TL
23from . import APIDoc, APIRouter, BaseController, CreatePermission, \
24 DeletePermission, Endpoint, EndpointDoc, ReadPermission, RESTController, \
25 Task, UIRouter, UpdatePermission, allow_empty_body
26from ._version import APIVersion
11fdf7f2 27
1911f103
TL
28logger = logging.getLogger(__name__)
29
f67539c2 30RBD_SCHEMA = ([{
f67539c2
TL
31 "value": ([str], ''),
32 "pool_name": (str, 'pool name')
33}])
34
35RBD_TRASH_SCHEMA = [{
36 "status": (int, ''),
37 "value": ([str], ''),
38 "pool_name": (str, 'pool name')
39}]
40
11fdf7f2
TL
41
42# pylint: disable=not-callable
9f95a23c 43def RbdTask(name, metadata, wait_for): # noqa: N802
11fdf7f2
TL
44 def composed_decorator(func):
45 func = handle_rados_error('pool')(func)
46 func = handle_rbd_error()(func)
47 return Task("rbd/{}".format(name), metadata, wait_for,
48 partial(serialize_dashboard_exception, include_http_status=True))(func)
49 return composed_decorator
50
51
11fdf7f2
TL
52def _sort_features(features, enable=True):
53 """
54 Sorts image features according to feature dependencies:
55
56 object-map depends on exclusive-lock
57 journaling depends on exclusive-lock
58 fast-diff depends on object-map
59 """
9f95a23c 60 ORDER = ['exclusive-lock', 'journaling', 'object-map', 'fast-diff'] # noqa: N806
11fdf7f2
TL
61
62 def key_func(feat):
63 try:
64 return ORDER.index(feat)
65 except ValueError:
66 return id(feat)
67
68 features.sort(key=key_func, reverse=not enable)
69
70
a4b75251
TL
71@APIRouter('/block/image', Scope.RBD_IMAGE)
72@APIDoc("RBD Management API", "Rbd")
11fdf7f2
TL
73class Rbd(RESTController):
74
11fdf7f2
TL
75 # set of image features that can be enable on existing images
76 ALLOW_ENABLE_FEATURES = {"exclusive-lock", "object-map", "fast-diff", "journaling"}
77
78 # set of image features that can be disabled on existing images
79 ALLOW_DISABLE_FEATURES = {"exclusive-lock", "object-map", "fast-diff", "deep-flatten",
80 "journaling"}
81
2a845540
TL
82 DEFAULT_LIMIT = 5
83
84 def _rbd_list(self, pool_name=None, offset=0, limit=DEFAULT_LIMIT, search='', sort=''):
11fdf7f2
TL
85 if pool_name:
86 pools = [pool_name]
87 else:
88 pools = [p['pool_name'] for p in CephService.get_pool_list('rbd')]
89
2a845540
TL
90 images, num_total_images = RbdService.rbd_pool_list(
91 pools, offset=offset, limit=limit, search=search, sort=sort)
92 cherrypy.response.headers['X-Total-Count'] = num_total_images
93 pool_result = {}
94 for i, image in enumerate(images):
95 pool = image['pool_name']
96 if pool not in pool_result:
97 pool_result[pool] = {'value': [], 'pool_name': image['pool_name']}
98 pool_result[pool]['value'].append(image)
99
100 images[i]['configuration'] = RbdConfiguration(
101 pool, image['namespace'], image['name']).list()
102 return list(pool_result.values())
11fdf7f2
TL
103
104 @handle_rbd_error()
105 @handle_rados_error('pool')
f67539c2
TL
106 @EndpointDoc("Display Rbd Images",
107 parameters={
108 'pool_name': (str, 'Pool Name'),
2a845540
TL
109 'limit': (int, 'limit'),
110 'offset': (int, 'offset'),
f67539c2
TL
111 },
112 responses={200: RBD_SCHEMA})
2a845540
TL
113 @RESTController.MethodMap(version=APIVersion(2, 0)) # type: ignore
114 def list(self, pool_name=None, offset: int = 0, limit: int = DEFAULT_LIMIT,
115 search: str = '', sort: str = ''):
39ae355f
TL
116 return self._rbd_list(pool_name, offset=int(offset), limit=int(limit),
117 search=search, sort=sort)
11fdf7f2
TL
118
119 @handle_rbd_error()
120 @handle_rados_error('pool')
9f95a23c
TL
121 def get(self, image_spec):
122 return RbdService.get_image(image_spec)
11fdf7f2
TL
123
124 @RbdTask('create',
9f95a23c 125 {'pool_name': '{pool_name}', 'namespace': '{namespace}', 'image_name': '{name}'}, 2.0)
2a845540
TL
126 def create(self, name, pool_name, size, namespace=None, schedule_interval='',
127 obj_size=None, features=None, stripe_unit=None, stripe_count=None,
128 data_pool=None, configuration=None, mirror_mode=None):
11fdf7f2
TL
129
130 size = int(size)
131
132 def _create(ioctx):
133 rbd_inst = rbd.RBD()
134
135 # Set order
136 l_order = None
137 if obj_size and obj_size > 0:
138 l_order = int(round(math.log(float(obj_size), 2)))
139
140 # Set features
141 feature_bitmask = format_features(features)
142
143 rbd_inst.create(ioctx, name, size, order=l_order, old_format=False,
144 features=feature_bitmask, stripe_unit=stripe_unit,
145 stripe_count=stripe_count, data_pool=data_pool)
9f95a23c
TL
146 RbdConfiguration(pool_ioctx=ioctx, namespace=namespace,
147 image_name=name).set_configuration(configuration)
148
149 rbd_call(pool_name, namespace, _create)
2a845540
TL
150 if mirror_mode:
151 RbdMirroringService.enable_image(name, pool_name, namespace,
152 MIRROR_IMAGE_MODE[mirror_mode])
153
154 if schedule_interval:
155 image_spec = get_image_spec(pool_name, namespace, name)
156 RbdMirroringService.snapshot_schedule_add(image_spec, schedule_interval)
9f95a23c
TL
157
158 @RbdTask('delete', ['{image_spec}'], 2.0)
159 def delete(self, image_spec):
160 pool_name, namespace, image_name = parse_image_spec(image_spec)
11fdf7f2 161
9f95a23c
TL
162 image = RbdService.get_image(image_spec)
163 snapshots = image['snapshots']
164 for snap in snapshots:
165 RbdSnapshotService.remove_snapshot(image_spec, snap['name'], snap['is_protected'])
11fdf7f2 166
11fdf7f2 167 rbd_inst = rbd.RBD()
9f95a23c
TL
168 return rbd_call(pool_name, namespace, rbd_inst.remove, image_name)
169
170 @RbdTask('edit', ['{image_spec}', '{name}'], 4.0)
2a845540
TL
171 def set(self, image_spec, name=None, size=None, features=None,
172 configuration=None, enable_mirror=None, primary=None,
173 resync=False, mirror_mode=None, schedule_interval='',
174 remove_scheduling=False):
175
9f95a23c 176 pool_name, namespace, image_name = parse_image_spec(image_spec)
11fdf7f2 177
11fdf7f2
TL
178 def _edit(ioctx, image):
179 rbd_inst = rbd.RBD()
180 # check rename image
181 if name and name != image_name:
182 rbd_inst.rename(ioctx, image_name, name)
183
184 # check resize
185 if size and size != image.size():
186 image.resize(size)
187
39ae355f
TL
188 mirror_image_info = image.mirror_image_get_info()
189 if enable_mirror and mirror_image_info['state'] == rbd.RBD_MIRROR_IMAGE_DISABLED:
190 RbdMirroringService.enable_image(
191 image_name, pool_name, namespace,
192 MIRROR_IMAGE_MODE[mirror_mode])
193 elif (enable_mirror is False
194 and mirror_image_info['state'] == rbd.RBD_MIRROR_IMAGE_ENABLED):
195 RbdMirroringService.disable_image(
196 image_name, pool_name, namespace)
197
11fdf7f2
TL
198 # check enable/disable features
199 if features is not None:
200 curr_features = format_bitmask(image.features())
201 # check disabled features
202 _sort_features(curr_features, enable=False)
203 for feature in curr_features:
204 if feature not in features and feature in self.ALLOW_DISABLE_FEATURES:
81eedcae
TL
205 if feature not in format_bitmask(image.features()):
206 continue
11fdf7f2
TL
207 f_bitmask = format_features([feature])
208 image.update_features(f_bitmask, False)
209 # check enabled features
210 _sort_features(features)
211 for feature in features:
212 if feature not in curr_features and feature in self.ALLOW_ENABLE_FEATURES:
81eedcae
TL
213 if feature in format_bitmask(image.features()):
214 continue
11fdf7f2
TL
215 f_bitmask = format_features([feature])
216 image.update_features(f_bitmask, True)
217
218 RbdConfiguration(pool_ioctx=ioctx, image_name=image_name).set_configuration(
219 configuration)
220
2a845540
TL
221 if primary and not mirror_image_info['primary']:
222 RbdMirroringService.promote_image(
223 image_name, pool_name, namespace)
224 elif primary is False and mirror_image_info['primary']:
225 RbdMirroringService.demote_image(
226 image_name, pool_name, namespace)
227
228 if resync:
229 RbdMirroringService.resync_image(image_name, pool_name, namespace)
230
231 if schedule_interval:
232 RbdMirroringService.snapshot_schedule_add(image_spec, schedule_interval)
233
234 if remove_scheduling:
235 RbdMirroringService.snapshot_schedule_remove(image_spec)
236
9f95a23c 237 return rbd_image_call(pool_name, namespace, image_name, _edit)
11fdf7f2
TL
238
239 @RbdTask('copy',
9f95a23c 240 {'src_image_spec': '{image_spec}',
11fdf7f2 241 'dest_pool_name': '{dest_pool_name}',
9f95a23c 242 'dest_namespace': '{dest_namespace}',
11fdf7f2
TL
243 'dest_image_name': '{dest_image_name}'}, 2.0)
244 @RESTController.Resource('POST')
f91f0fd5 245 @allow_empty_body
9f95a23c
TL
246 def copy(self, image_spec, dest_pool_name, dest_namespace, dest_image_name,
247 snapshot_name=None, obj_size=None, features=None,
248 stripe_unit=None, stripe_count=None, data_pool=None, configuration=None):
249 pool_name, namespace, image_name = parse_image_spec(image_spec)
11fdf7f2
TL
250
251 def _src_copy(s_ioctx, s_img):
252 def _copy(d_ioctx):
253 # Set order
254 l_order = None
255 if obj_size and obj_size > 0:
256 l_order = int(round(math.log(float(obj_size), 2)))
257
258 # Set features
259 feature_bitmask = format_features(features)
260
261 if snapshot_name:
262 s_img.set_snap(snapshot_name)
263
264 s_img.copy(d_ioctx, dest_image_name, feature_bitmask, l_order,
265 stripe_unit, stripe_count, data_pool)
266 RbdConfiguration(pool_ioctx=d_ioctx, image_name=dest_image_name).set_configuration(
267 configuration)
268
9f95a23c 269 return rbd_call(dest_pool_name, dest_namespace, _copy)
11fdf7f2 270
9f95a23c 271 return rbd_image_call(pool_name, namespace, image_name, _src_copy)
11fdf7f2 272
9f95a23c 273 @RbdTask('flatten', ['{image_spec}'], 2.0)
11fdf7f2
TL
274 @RESTController.Resource('POST')
275 @UpdatePermission
f91f0fd5 276 @allow_empty_body
9f95a23c 277 def flatten(self, image_spec):
11fdf7f2
TL
278
279 def _flatten(ioctx, image):
280 image.flatten()
281
9f95a23c
TL
282 pool_name, namespace, image_name = parse_image_spec(image_spec)
283 return rbd_image_call(pool_name, namespace, image_name, _flatten)
11fdf7f2
TL
284
285 @RESTController.Collection('GET')
286 def default_features(self):
287 rbd_default_features = mgr.get('config')['rbd_default_features']
288 return format_bitmask(int(rbd_default_features))
289
f67539c2
TL
290 @RESTController.Collection('GET')
291 def clone_format_version(self):
292 """Return the RBD clone format version.
293 """
294 rbd_default_clone_format = mgr.get('config')['rbd_default_clone_format']
295 if rbd_default_clone_format != 'auto':
296 return int(rbd_default_clone_format)
297 osd_map = mgr.get_osdmap().dump()
298 min_compat_client = osd_map.get('min_compat_client', '')
299 require_min_compat_client = osd_map.get('require_min_compat_client', '')
300 if max(min_compat_client, require_min_compat_client) < 'mimic':
301 return 1
302
303 return 2
304
9f95a23c 305 @RbdTask('trash/move', ['{image_spec}'], 2.0)
11fdf7f2 306 @RESTController.Resource('POST')
f91f0fd5 307 @allow_empty_body
9f95a23c 308 def move_trash(self, image_spec, delay=0):
11fdf7f2
TL
309 """Move an image to the trash.
310 Images, even ones actively in-use by clones,
311 can be moved to the trash and deleted at a later time.
312 """
9f95a23c 313 pool_name, namespace, image_name = parse_image_spec(image_spec)
11fdf7f2 314 rbd_inst = rbd.RBD()
9f95a23c 315 return rbd_call(pool_name, namespace, rbd_inst.trash_move, image_name, delay)
11fdf7f2
TL
316
317
2a845540
TL
318@UIRouter('/block/rbd')
319class RbdStatus(BaseController):
320 @EndpointDoc("Display RBD Image feature status")
321 @Endpoint()
322 @ReadPermission
323 def status(self):
324 status = {'available': True, 'message': None}
325 if not CephService.get_pool_list('rbd'):
326 status['available'] = False
327 status['message'] = 'No RBD pools in the cluster. Please create a pool '\
328 'with the "rbd" application label.' # type: ignore
329 return status
330
331
a4b75251
TL
332@APIRouter('/block/image/{image_spec}/snap', Scope.RBD_IMAGE)
333@APIDoc("RBD Snapshot Management API", "RbdSnapshot")
11fdf7f2
TL
334class RbdSnapshot(RESTController):
335
336 RESOURCE_ID = "snapshot_name"
337
338 @RbdTask('snap/create',
9f95a23c
TL
339 ['{image_spec}', '{snapshot_name}'], 2.0)
340 def create(self, image_spec, snapshot_name):
341 pool_name, namespace, image_name = parse_image_spec(image_spec)
342
11fdf7f2 343 def _create_snapshot(ioctx, img, snapshot_name):
2a845540
TL
344 mirror_info = img.mirror_image_get_info()
345 mirror_mode = img.mirror_image_get_mode()
346 if (mirror_info['state'] == rbd.RBD_MIRROR_IMAGE_ENABLED
347 and mirror_mode == rbd.RBD_MIRROR_IMAGE_MODE_SNAPSHOT):
348 img.mirror_image_create_snapshot()
349 else:
350 img.create_snap(snapshot_name)
11fdf7f2 351
9f95a23c
TL
352 return rbd_image_call(pool_name, namespace, image_name, _create_snapshot,
353 snapshot_name)
11fdf7f2
TL
354
355 @RbdTask('snap/delete',
9f95a23c
TL
356 ['{image_spec}', '{snapshot_name}'], 2.0)
357 def delete(self, image_spec, snapshot_name):
358 return RbdSnapshotService.remove_snapshot(image_spec, snapshot_name)
11fdf7f2
TL
359
360 @RbdTask('snap/edit',
9f95a23c
TL
361 ['{image_spec}', '{snapshot_name}'], 4.0)
362 def set(self, image_spec, snapshot_name, new_snap_name=None,
11fdf7f2
TL
363 is_protected=None):
364 def _edit(ioctx, img, snapshot_name):
365 if new_snap_name and new_snap_name != snapshot_name:
366 img.rename_snap(snapshot_name, new_snap_name)
367 snapshot_name = new_snap_name
368 if is_protected is not None and \
369 is_protected != img.is_protected_snap(snapshot_name):
370 if is_protected:
371 img.protect_snap(snapshot_name)
372 else:
373 img.unprotect_snap(snapshot_name)
374
9f95a23c
TL
375 pool_name, namespace, image_name = parse_image_spec(image_spec)
376 return rbd_image_call(pool_name, namespace, image_name, _edit, snapshot_name)
11fdf7f2
TL
377
378 @RbdTask('snap/rollback',
9f95a23c 379 ['{image_spec}', '{snapshot_name}'], 5.0)
11fdf7f2
TL
380 @RESTController.Resource('POST')
381 @UpdatePermission
f91f0fd5 382 @allow_empty_body
9f95a23c 383 def rollback(self, image_spec, snapshot_name):
11fdf7f2
TL
384 def _rollback(ioctx, img, snapshot_name):
385 img.rollback_to_snap(snapshot_name)
9f95a23c
TL
386
387 pool_name, namespace, image_name = parse_image_spec(image_spec)
388 return rbd_image_call(pool_name, namespace, image_name, _rollback, snapshot_name)
11fdf7f2
TL
389
390 @RbdTask('clone',
9f95a23c 391 {'parent_image_spec': '{image_spec}',
11fdf7f2 392 'child_pool_name': '{child_pool_name}',
9f95a23c 393 'child_namespace': '{child_namespace}',
11fdf7f2
TL
394 'child_image_name': '{child_image_name}'}, 2.0)
395 @RESTController.Resource('POST')
f91f0fd5 396 @allow_empty_body
9f95a23c
TL
397 def clone(self, image_spec, snapshot_name, child_pool_name,
398 child_image_name, child_namespace=None, obj_size=None, features=None,
399 stripe_unit=None, stripe_count=None, data_pool=None, configuration=None):
11fdf7f2
TL
400 """
401 Clones a snapshot to an image
402 """
403
9f95a23c
TL
404 pool_name, namespace, image_name = parse_image_spec(image_spec)
405
11fdf7f2
TL
406 def _parent_clone(p_ioctx):
407 def _clone(ioctx):
408 # Set order
409 l_order = None
410 if obj_size and obj_size > 0:
411 l_order = int(round(math.log(float(obj_size), 2)))
412
413 # Set features
414 feature_bitmask = format_features(features)
415
416 rbd_inst = rbd.RBD()
417 rbd_inst.clone(p_ioctx, image_name, snapshot_name, ioctx,
418 child_image_name, feature_bitmask, l_order,
419 stripe_unit, stripe_count, data_pool)
420
421 RbdConfiguration(pool_ioctx=ioctx, image_name=child_image_name).set_configuration(
422 configuration)
423
9f95a23c 424 return rbd_call(child_pool_name, child_namespace, _clone)
11fdf7f2 425
9f95a23c 426 rbd_call(pool_name, namespace, _parent_clone)
11fdf7f2
TL
427
428
a4b75251
TL
429@APIRouter('/block/image/trash', Scope.RBD_IMAGE)
430@APIDoc("RBD Trash Management API", "RbdTrash")
11fdf7f2 431class RbdTrash(RESTController):
9f95a23c 432 RESOURCE_ID = "image_id_spec"
f67539c2
TL
433
434 def __init__(self):
435 super().__init__()
436 self.rbd_inst = rbd.RBD()
11fdf7f2
TL
437
438 @ViewCache()
439 def _trash_pool_list(self, pool_name):
440 with mgr.rados.open_ioctx(pool_name) as ioctx:
11fdf7f2 441 result = []
9f95a23c
TL
442 namespaces = self.rbd_inst.namespace_list(ioctx)
443 # images without namespace
444 namespaces.append('')
445 for namespace in namespaces:
446 ioctx.set_namespace(namespace)
447 images = self.rbd_inst.trash_list(ioctx)
448 for trash in images:
449 trash['pool_name'] = pool_name
450 trash['namespace'] = namespace
451 trash['deletion_time'] = "{}Z".format(trash['deletion_time'].isoformat())
452 trash['deferment_end_time'] = "{}Z".format(
453 trash['deferment_end_time'].isoformat())
454 result.append(trash)
11fdf7f2
TL
455 return result
456
457 def _trash_list(self, pool_name=None):
458 if pool_name:
459 pools = [pool_name]
460 else:
461 pools = [p['pool_name'] for p in CephService.get_pool_list('rbd')]
462
463 result = []
464 for pool in pools:
465 # pylint: disable=unbalanced-tuple-unpacking
466 status, value = self._trash_pool_list(pool)
467 result.append({'status': status, 'value': value, 'pool_name': pool})
468 return result
469
470 @handle_rbd_error()
471 @handle_rados_error('pool')
f67539c2
TL
472 @EndpointDoc("Get RBD Trash Details by pool name",
473 parameters={
474 'pool_name': (str, 'Name of the pool'),
475 },
476 responses={200: RBD_TRASH_SCHEMA})
11fdf7f2
TL
477 def list(self, pool_name=None):
478 """List all entries from trash."""
479 return self._trash_list(pool_name)
480
481 @handle_rbd_error()
482 @handle_rados_error('pool')
483 @RbdTask('trash/purge', ['{pool_name}'], 2.0)
484 @RESTController.Collection('POST', query_params=['pool_name'])
485 @DeletePermission
f91f0fd5 486 @allow_empty_body
11fdf7f2
TL
487 def purge(self, pool_name=None):
488 """Remove all expired images from trash."""
1911f103 489 now = "{}Z".format(datetime.utcnow().isoformat())
11fdf7f2
TL
490 pools = self._trash_list(pool_name)
491
492 for pool in pools:
493 for image in pool['value']:
494 if image['deferment_end_time'] < now:
1911f103
TL
495 logger.info('Removing trash image %s (pool=%s, namespace=%s, name=%s)',
496 image['id'], pool['pool_name'], image['namespace'], image['name'])
9f95a23c
TL
497 rbd_call(pool['pool_name'], image['namespace'],
498 self.rbd_inst.trash_remove, image['id'], 0)
11fdf7f2 499
9f95a23c 500 @RbdTask('trash/restore', ['{image_id_spec}', '{new_image_name}'], 2.0)
11fdf7f2
TL
501 @RESTController.Resource('POST')
502 @CreatePermission
f91f0fd5 503 @allow_empty_body
9f95a23c 504 def restore(self, image_id_spec, new_image_name):
11fdf7f2 505 """Restore an image from trash."""
9f95a23c
TL
506 pool_name, namespace, image_id = parse_image_spec(image_id_spec)
507 return rbd_call(pool_name, namespace, self.rbd_inst.trash_restore, image_id,
508 new_image_name)
11fdf7f2 509
9f95a23c
TL
510 @RbdTask('trash/remove', ['{image_id_spec}'], 2.0)
511 def delete(self, image_id_spec, force=False):
11fdf7f2
TL
512 """Delete an image from trash.
513 If image deferment time has not expired you can not removed it unless use force.
514 But an actively in-use by clones or has snapshots can not be removed.
515 """
9f95a23c
TL
516 pool_name, namespace, image_id = parse_image_spec(image_id_spec)
517 return rbd_call(pool_name, namespace, self.rbd_inst.trash_remove, image_id,
518 int(str_to_bool(force)))
519
520
a4b75251
TL
521@APIRouter('/block/pool/{pool_name}/namespace', Scope.RBD_IMAGE)
522@APIDoc("RBD Namespace Management API", "RbdNamespace")
9f95a23c 523class RbdNamespace(RESTController):
f67539c2
TL
524
525 def __init__(self):
526 super().__init__()
527 self.rbd_inst = rbd.RBD()
9f95a23c
TL
528
529 def create(self, pool_name, namespace):
530 with mgr.rados.open_ioctx(pool_name) as ioctx:
531 namespaces = self.rbd_inst.namespace_list(ioctx)
532 if namespace in namespaces:
533 raise DashboardException(
534 msg='Namespace already exists',
535 code='namespace_already_exists',
536 component='rbd')
537 return self.rbd_inst.namespace_create(ioctx, namespace)
538
539 def delete(self, pool_name, namespace):
540 with mgr.rados.open_ioctx(pool_name) as ioctx:
541 # pylint: disable=unbalanced-tuple-unpacking
2a845540 542 images, _ = RbdService.rbd_pool_list([pool_name], namespace=namespace)
9f95a23c
TL
543 if images:
544 raise DashboardException(
545 msg='Namespace contains images which must be deleted first',
546 code='namespace_contains_images',
547 component='rbd')
548 return self.rbd_inst.namespace_remove(ioctx, namespace)
549
550 def list(self, pool_name):
551 with mgr.rados.open_ioctx(pool_name) as ioctx:
552 result = []
553 namespaces = self.rbd_inst.namespace_list(ioctx)
554 for namespace in namespaces:
555 # pylint: disable=unbalanced-tuple-unpacking
2a845540 556 images, _ = RbdService.rbd_pool_list([pool_name], namespace=namespace)
9f95a23c
TL
557 result.append({
558 'namespace': namespace,
559 'num_images': len(images) if images else 0
560 })
561 return result