File: storage_pool.py

package info (click to toggle)
python-pylxd 2.2.10-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 820 kB
  • sloc: python: 7,258; sh: 104; makefile: 21
file content (602 lines) | stat: -rw-r--r-- 23,827 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
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
# Copyright (c) 2016 Canonical Ltd
#
#    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.
from pylxd.models import _model as model
from pylxd import managers


class StoragePool(model.Model):
    """An LXD storage_pool.

    This corresponds to the LXD endpoint at
    /1.0/storage-pools

    api_extension: 'storage'
    """
    name = model.Attribute(readonly=True)
    driver = model.Attribute(readonly=True)
    used_by = model.Attribute(readonly=True)
    config = model.Attribute()
    managed = model.Attribute(readonly=True)
    description = model.Attribute()
    status = model.Attribute(readonly=True)
    locations = model.Attribute(readonly=True)

    resources = model.Manager()
    volumes = model.Manager()

    def __init__(self, *args, **kwargs):
        super(StoragePool, self).__init__(*args, **kwargs)

        self.resources = StorageResourcesManager(self)
        self.volumes = StorageVolumeManager(self)

    @classmethod
    def get(cls, client, name):
        """Get a storage_pool by name.

        Implements GET /1.0/storage-pools/<name>

        :param client: The pylxd client object
        :type client: :class:`pylxd.client.Client`
        :param name: the name of the storage pool to get
        :type name: str
        :returns: a storage pool if successful, raises NotFound if not found
        :rtype: :class:`pylxd.models.storage_pool.StoragePool`
        :raises: :class:`pylxd.exceptions.NotFound`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        """
        client.assert_has_api_extension('storage')
        response = client.api.storage_pools[name].get()

        storage_pool = cls(client, **response.json()['metadata'])
        return storage_pool

    @classmethod
    def all(cls, client):
        """Get all storage_pools.

        Implements GET /1.0/storage-pools

        Note that the returned list is 'sparse' in that only the name of the
        pool is populated.  If any of the attributes are used, then the `sync`
        function is called to populate the object fully.

        :param client: The pylxd client object
        :type client: :class:`pylxd.client.Client`
        :returns: a storage pool if successful, raises NotFound if not found
        :rtype: [:class:`pylxd.models.storage_pool.StoragePool`]
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        """
        client.assert_has_api_extension('storage')
        response = client.api.storage_pools.get()

        storage_pools = []
        for url in response.json()['metadata']:
            name = url.split('/')[-1]
            storage_pools.append(cls(client, name=name))
        return storage_pools

    @classmethod
    def create(cls, client, definition):
        """Create a storage_pool from config.

        Implements POST /1.0/storage-pools

        The `definition` parameter defines what the storage pool will be.  An
        example config for the zfs driver is:

            {
                "config": {
                    "size": "10GB"
                },
                "driver": "zfs",
                "name": "pool1"
            }

        Note that **all** fields in the `definition` parameter are strings.

        For further details on the storage pool types see:
        https://lxd.readthedocs.io/en/latest/storage/

        The function returns the a `StoragePool` instance, if it is
        successfully created, otherwise an Exception is raised.

        :param client: The pylxd client object
        :type client: :class:`pylxd.client.Client`
        :param definition: the fields to pass to the LXD API endpoint
        :type definition: dict
        :returns: a storage pool if successful, raises NotFound if not found
        :rtype: :class:`pylxd.models.storage_pool.StoragePool`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            couldn't be created.
        """
        client.assert_has_api_extension('storage')
        client.api.storage_pools.post(json=definition)

        storage_pool = cls.get(client, definition['name'])
        return storage_pool

    @classmethod
    def exists(cls, client, name):
        """Determine whether a storage pool exists.

        A convenience method to determine a pool exists.  However, it is better
        to try to fetch it and catch the :class:`pylxd.exceptions.NotFound`
        exception, as otherwise the calling code is like to fetch the pool
        twice.  Only use this if the calling code doesn't *need* the actual
        storage pool information.

        :param client: The pylxd client object
        :type client: :class:`pylxd.client.Client`
        :param name: the name of the storage pool to get
        :type name: str
        :returns: True if the storage pool exists, False if it doesn't.
        :rtype: bool
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        """
        try:
            cls.get(client, name)
            return True
        except cls.NotFound:
            return False

    @property
    def api(self):
        """Provides an object with the endpoint:

        /1.0/storage-pools/<self.name>

        Used internally to construct endpoints.

        :returns: an API node with the named endpoint
        :rtype: :class:`pylxd.client._APINode`
        """
        return self.client.api.storage_pools[self.name]

    def save(self, wait=False):
        """Save the model using PUT back to the LXD server.

        Implements PUT /1.0/storage-pools/<self.name> *automagically*

        The fields affected are: `description` and `config`.  Note that they
        are replaced in their *entirety*.  If finer grained control is
        required, please use the
        :meth:`~pylxd.models.storage_pool.StoragePool.patch` method directly.

        Updating a storage pool may fail if the config is not acceptable to
        LXD. An :class:`~pylxd.exceptions.LXDAPIException` will be generated in
        that case.

        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be deleted.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StoragePool, self).save(wait=wait)

    def delete(self):
        """Delete the storage pool.

        Implements DELETE /1.0/storage-pools/<self.name>

        Deleting a storage pool may fail if it is being used.  See the LXD
        documentation for further details.

        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be deleted.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StoragePool, self).delete()

    def put(self, put_object, wait=False):
        """Put the storage pool.

        Implements PUT /1.0/storage-pools/<self.name>

        Putting to a storage pool may fail if the new configuration is
        incompatible with the pool.  See the LXD documentation for further
        details.

        Note that the object is refreshed with a `sync` if the PUT is
        successful.  If this is *not* desired, then the raw API on the client
        should be used.

        :param put_object: A dictionary.  The most useful key will be the
            `config` key.
        :type put_object: dict
        :param wait: Whether to wait for async operations to complete.
        :type wait: bool
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be modified.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StoragePool, self).put(put_object, wait)

    def patch(self, patch_object, wait=False):
        """Patch the storage pool.

        Implements PATCH /1.0/storage-pools/<self.name>

        Patching the object allows for more fine grained changes to the config.
        The object is refreshed if the PATCH is successful.  If this is *not*
        required, then use the client api directly.

        :param patch_object: A dictionary.  The most useful key will be the
            `config` key.
        :type patch_object: dict
        :param wait: Whether to wait for async operations to complete.
        :type wait: bool
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be modified.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StoragePool, self).patch(patch_object, wait)


class StorageResourcesManager(managers.BaseManager):
    manager_for = 'pylxd.models.StorageResources'


class StorageResources(model.Model):
    """An LXD Storage Resources model.

    This corresponds to the LXD endpoing at
    /1.0/storage-pools/<pool>/resources

    At present, this is read-only model.

    api_extension: 'resources'
    """
    space = model.Attribute(readonly=True)
    inodes = model.Attribute(readonly=True)

    @classmethod
    def get(cls, storage_pool):
        """Get a storage_pool resource for a named pool

        Implements GET /1.0/storage-pools/<pool>/resources

        Needs the 'resources' api extension in the LXD server.

        :param storage_pool: a storage pool object on which to fetch resources
        :type storage_pool: :class:`pylxd.models.storage_pool.StoragePool`
        :returns: A storage resources object
        :rtype: :class:`pylxd.models.storage_pool.StorageResources`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'resources' api extension is missing.
        """
        storage_pool.client.assert_has_api_extension('resources')
        response = storage_pool.api.resources.get()
        resources = cls(storage_pool.client, **response.json()['metadata'])
        return resources


class StorageVolumeManager(managers.BaseManager):
    manager_for = 'pylxd.models.StorageVolume'


class StorageVolume(model.Model):
    """An LXD Storage volume.

    This corresponds to the LXD endpoing at
    /1.0/storage-pools/<pool>/volumes

    api_extension: 'storage'
    """
    name = model.Attribute(readonly=True)
    type = model.Attribute(readonly=True)
    description = model.Attribute(readonly=True)
    config = model.Attribute()
    used_by = model.Attribute(readonly=True)
    location = model.Attribute(readonly=True)

    storage_pool = model.Parent()

    @property
    def api(self):
        """Provides an object with the endpoint:

        /1.0/storage-pools/<storage_pool.name>/volumes/<self.type>/<self.name>

        Used internally to construct endpoints.

        :returns: an API node with the named endpoint
        :rtype: :class:`pylxd.client._APINode`
        """
        return self.storage_pool.api.volumes[self.type][self.name]

    @classmethod
    def all(cls, storage_pool):
        """Get all the volumnes for this storage pool.

        Implements GET /1.0/storage-pools/<name>/volumes

        Volumes returned from this method will only have the name
        set, as that is the only property returned from LXD. If more
        information is needed, `StorageVolume.sync` is the method call
        that should be used.

        Note that the storage volume types are 'container', 'image' and
        'custom', and these maps to the names 'containers', 'images' and
        everything else is mapped to 'custom'.

        :param storage_pool: a storage pool object on which to fetch resources
        :type storage_pool: :class:`pylxd.models.storage_pool.StoragePool`
        :returns: a list storage volume if successful
        :rtype: [:class:`pylxd.models.storage_pool.StorageVolume`]
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        """
        storage_pool.client.assert_has_api_extension('storage')
        response = storage_pool.api.volumes.get()

        volumes = []
        for volume in response.json()['metadata']:
            (_type, name) = volume.split('/')[-2:]
            # for each type, convert to the string that will work with GET
            if _type == 'containers':
                _type = 'container'
            elif _type == 'images':
                _type = 'image'
            else:
                _type = 'custom'
            volumes.append(
                cls(storage_pool.client,
                    name=name,
                    type=_type,
                    storage_pool=storage_pool))
        return volumes

    @classmethod
    def get(cls, storage_pool, _type, name):
        """Get a StorageVolume by type and name.

        Implements GET /1.0/storage-pools/<pool>/volumes/<type>/<name>

        The `_type` param can only (currently) be one of 'container', 'image'
        or 'custom'.  This was determined by read the LXD source.

        :param storage_pool: a storage pool object on which to fetch resources
        :type storage_pool: :class:`pylxd.models.storage_pool.StoragePool`
        :param _type: the type; one of 'container', 'image', 'custom'
        :type _type: str
        :param name: the name of the storage volume to get
        :type name: str
        :returns: a storage pool if successful, raises NotFound if not found
        :rtype: :class:`pylxd.models.storage_pool.StorageVolume`
        :raises: :class:`pylxd.exceptions.NotFound`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        """
        storage_pool.client.assert_has_api_extension('storage')
        response = storage_pool.api.volumes[_type][name].get()

        volume = cls(
            storage_pool.client, storage_pool=storage_pool,
            **response.json()['metadata'])
        return volume

    @classmethod
    # def create(cls, storage_pool, definition, wait=True, *args):
    def create(cls, storage_pool, *args, **kwargs):
        """Create a 'custom' Storage Volume in the associated storage pool.

        Implements POST /1.0/storage-pools/<pool>/volumes/custom

        See https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-19 for
        more details on what the `definition` parameter dictionary should
        contain for various volume creation.

        At the moment the only type of volume that can be created is 'custom',
        and this is currently hardwired into the function.

        The function signature 'hides' that the first parameter to the function
        is the definition.  The function should be called as:

        >>> a_storage_pool.volumes.create(definition_dict, wait=<bool>)

        where `definition_dict` is mandatory, and `wait` defaults to True,
        which makes the default a synchronous function call.

        Note that **all** fields in the `definition` parameter are strings.

        If the caller doesn't wan't to wait for an async operation, then it
        MUST be passed as a keyword argument, and not as a positional
        substitute.

        The function returns the a
        :class:`~pylxd.models.storage_pool.StoragePool` instance, if it is
        successfully created, otherwise an Exception is raised.

        :param storage_pool: a storage pool object on which to fetch resources
        :type storage_pool: :class:`pylxd.models.storage_pool.StoragePool`
        :param definition: the fields to pass to the LXD API endpoint
        :type definition: dict
        :param wait: wait until an async action has completed (default True)
        :type wait: bool
        :returns: a storage pool volume if successful, raises NotFound if not
            found
        :rtype: :class:`pylxd.models.storage_pool.StorageVolume`
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            volume couldn't be created.
        """
        # This is really awkward, but the implementation details mean,
        # depending on how this function is called, we can't know whether the
        # 2nd positional argument will be definition or a client object. This
        # is an difficulty with how BaseManager is implemented, and to get the
        # convenience of being able to call this 'naturally' off of a
        # storage_pool.  So we have to jump through some hurdles to get the
        # right positional parameters.
        storage_pool.client.assert_has_api_extension('storage')
        wait = kwargs.get('wait', True)
        definition = args[-1]
        assert isinstance(definition, dict)
        assert 'name' in definition
        response = storage_pool.api.volumes.custom.post(json=definition)

        if response.json()['type'] == 'async' and wait:
            storage_pool.client.operations.wait_for_operation(
                response.json()['operation'])

        volume = cls.get(storage_pool,
                         'custom',
                         definition['name'])
        return volume

    def rename(self, _input, wait=False):
        """Rename a storage volume

        This requires api_extension: 'storage_api_volume_rename'.

        Implements: POST /1.0/storage-pools/<pool>/volumes/<type>/<name>

        This operation is either sync or async (when moving to a different
        pool).

        This command also allows the migration across instances, and therefore
        it returns the metadata section (as a dictionary) from the call.  The
        caller should assume that the object is stale and refetch it after any
        migrations are done.  However, the 'name' attribute of the object is
        updated for consistency.

        Unlike :meth:`~pylxd.models.storage_pool.StorageVolume.create`, this
        method does not override any items in the input definition, although it
        does check that the 'name' and 'pool' parameters are set.

        Please see: https://github.com/lxc/lxd/blob/master/doc/rest-api.md
        #10storage-poolspoolvolumestypename
        for more details.

        :param _input: The `input` specification for the rename.
        :type _input: dict
        :param wait: Wait for an async operation, if it is async.
        :type wait: bool
        :returns:  The dictionary from the metadata section of the response if
            successful.
        :rtype: dict[str, str]
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage_api_volume_rename' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            volume couldn't be renamed.
        """
        assert isinstance(_input, dict)
        assert 'name' in _input
        assert 'pool' in _input
        response = self.api.post(json=_input)

        response_json = response.json()
        if wait:
            self.client.operations.wait_for_operation(
                response_json['operation'])
        self.name = _input['name']
        return response_json['metadata']

    def put(self, put_object, wait=False):
        """Put the storage volume.

        Implements: PUT /1.0/storage-pools/<pool>/volumes/<type>/<name>

        Note that this is functionality equivalent to
        :meth:`~pyxld.models.storage_pool.StorageVolume.save` but by using a
        new object (`put_object`) rather than modifying the object and then
        calling :meth:`~pyxld.models.storage_pool.StorageVolume.save`.

        Putting to a storage volume may fail if the new configuration is
        incompatible with the pool.  See the LXD documentation for further
        details.

        Note that the object is refreshed with a `sync` if the PUT is
        successful.  If this is *not* desired, then the raw API on the client
        should be used.

        :param put_object: A dictionary.  The most useful key will be the
            `config` key.
        :type put_object: dict
        :param wait: Whether to wait for async operations to complete.
        :type wait: bool
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be modified.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StorageVolume, self).put(put_object, wait)

    def patch(self, patch_object, wait=False):
        """Patch the storage volume.

        Implements: PATCH /1.0/storage-pools/<pool>/volumes/<type>/<name>

        Patching the object allows for more fine grained changes to the config.
        The object is refreshed if the PATCH is successful.  If this is *not*
        required, then use the client api directly.

        :param patch_object: A dictionary.  The most useful key will be the
            `config` key.
        :type patch_object: dict
        :param wait: Whether to wait for async operations to complete.
        :type wait: bool
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage
            volume can't be modified.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StorageVolume, self).patch(patch_object, wait)

    def save(self, wait=False):
        """Save the model using PUT back to the LXD server.

        Implements: PUT /1.0/storage-pools/<pool>/volumes/<type>/<name>
        *automagically*.

        The field affected is `config`.  Note that it is replaced *entirety*.
        If finer grained control is required, please use the
        :meth:`~pylxd.models.storage_pool.StorageVolume.patch` method directly.

        Updating a storage volume may fail if the config is not acceptable to
        LXD. An :class:`~pylxd.exceptions.LXDAPIException` will be generated in
        that case.

        :param wait: Whether to wait for async operations to complete.
        :type wait: bool
        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage
            volume can't be deleted.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StorageVolume, self).save(wait=wait)

    def delete(self):
        """Delete the storage pool.

        Implements: DELETE /1.0/storage-pools/<pool>/volumes/<type>/<name>

        Deleting a storage volume may fail if it is being used.  See the LXD
        documentation for further details.

        :raises: :class:`pylxd.exceptions.LXDAPIExtensionNotAvailable` if the
            'storage' api extension is missing.
        :raises: :class:`pylxd.exceptions.LXDAPIException` if the storage pool
            can't be deleted.
        """
        # Note this method exists so that it is documented via sphinx.
        super(StorageVolume, self).delete()