summaryrefslogtreecommitdiff
path: root/heat/engine/resources/openstack/glance/image.py
blob: aee7601422c6ef22e726a9360bc8f62c1ffae21a (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
#
#    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 heat.common import exception
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support


class GlanceWebImage(resource.Resource):
    """A resource managing images in Glance using web-download import.

    This provides image support for recent Glance installation.
    """

    support_status = support.SupportStatus(version='12.0.0')

    PROPERTIES = (
        NAME, IMAGE_ID, MIN_DISK, MIN_RAM, PROTECTED,
        DISK_FORMAT, CONTAINER_FORMAT, LOCATION, TAGS,
        ARCHITECTURE, KERNEL_ID, OS_DISTRO, OS_VERSION, OWNER,
        VISIBILITY, RAMDISK_ID, ACTIVE, MEMBERS
    ) = (
        'name', 'id', 'min_disk', 'min_ram', 'protected',
        'disk_format', 'container_format', 'location', 'tags',
        'architecture', 'kernel_id', 'os_distro', 'os_version',
        'owner', 'visibility', 'ramdisk_id', 'active', 'members'
    )

    glance_id_pattern = ('^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}'
                         '-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$')

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name for the image. The name of an image is not '
              'unique to a Image Service node.')
        ),
        IMAGE_ID: properties.Schema(
            properties.Schema.STRING,
            _('The image ID. Glance will generate a UUID if not specified.')
        ),
        MIN_DISK: properties.Schema(
            properties.Schema.INTEGER,
            _('Amount of disk space (in GB) required to boot image. '
              'Default value is 0 if not specified '
              'and means no limit on the disk size.'),
            constraints=[
                constraints.Range(min=0),
            ],
            default=0
        ),
        MIN_RAM: properties.Schema(
            properties.Schema.INTEGER,
            _('Amount of ram (in MB) required to boot image. Default value '
              'is 0 if not specified and means no limit on the ram size.'),
            constraints=[
                constraints.Range(min=0),
            ],
            default=0
        ),
        PROTECTED: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Whether the image can be deleted. If the value is True, '
              'the image is protected and cannot be deleted.'),
            update_allowed=True,
            default=False
        ),
        DISK_FORMAT: properties.Schema(
            properties.Schema.STRING,
            _('Disk format of image.'),
            required=True,
            constraints=[
                constraints.AllowedValues(
                    ['ami', 'ari', 'aki', 'vhd', 'vhdx', 'vmdk', 'raw',
                     'qcow2', 'vdi', 'iso', 'ploop'])
            ]
        ),
        CONTAINER_FORMAT: properties.Schema(
            properties.Schema.STRING,
            _('Container format of image.'),
            required=True,
            constraints=[
                constraints.AllowedValues([
                    'ami', 'ari', 'aki', 'bare', 'ovf', 'ova', 'docker'])
            ]
        ),
        LOCATION: properties.Schema(
            properties.Schema.STRING,
            _('URL where the data for this image already resides. For '
              'example, if the image data is stored in swift, you could '
              'specify "swift://example.com/container/obj".'),
            required=True,
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            _('List of image tags.'),
            update_allowed=True,
        ),
        ARCHITECTURE: properties.Schema(
            properties.Schema.STRING,
            _('Operating system architecture.'),
            update_allowed=True,
        ),
        KERNEL_ID: properties.Schema(
            properties.Schema.STRING,
            _('ID of image stored in Glance that should be used as '
              'the kernel when booting an AMI-style image.'),
            update_allowed=True,
            constraints=[
                constraints.AllowedPattern(glance_id_pattern)
            ]
        ),
        OS_DISTRO: properties.Schema(
            properties.Schema.STRING,
            _('The common name of the operating system distribution '
              'in lowercase.'),
            update_allowed=True,
        ),
        OS_VERSION: properties.Schema(
            properties.Schema.STRING,
            _('Operating system version as specified by the distributor.'),
            update_allowed=True,
        ),
        OWNER: properties.Schema(
            properties.Schema.STRING,
            _('Owner of the image.'),
            update_allowed=True,
        ),
        VISIBILITY: properties.Schema(
            properties.Schema.STRING,
            _('Scope of image accessibility.'),
            update_allowed=True,
            default='private',
            constraints=[
                constraints.AllowedValues(
                    ['public', 'private', 'community', 'shared'])
            ]
        ),
        RAMDISK_ID: properties.Schema(
            properties.Schema.STRING,
            _('ID of image stored in Glance that should be used as '
              'the ramdisk when booting an AMI-style image.'),
            update_allowed=True,
            constraints=[
                constraints.AllowedPattern(glance_id_pattern)
            ]
        ),
        ACTIVE: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Activate or deactivate the image. Requires Admin Access.'),
            default=True,
            update_allowed=True,
            support_status=support.SupportStatus(version='16.0.0')
        ),
        MEMBERS: properties.Schema(
            properties.Schema.LIST,
            _('List of additional members that are permitted '
              'to read the image. This may be a Keystone Project '
              'IDs or User IDs, depending on the Glance configuration '
              'in use.'),
            schema=properties.Schema(
                properties.Schema.STRING,
                _('A member ID. This may be a Keystone Project ID '
                  'or User ID, depending on the Glance configuration '
                  'in use.')
            ),
            update_allowed=True,
            support_status=support.SupportStatus(version='16.0.0')
        )
    }

    default_client_name = 'glance'

    entity = 'images'

    def handle_create(self):
        args = dict((k, v) for k, v in self.properties.items()
                    if v is not None)
        members = args.pop(self.MEMBERS, [])
        active = args.pop(self.ACTIVE)
        location = args.pop(self.LOCATION)
        images = self.client().images
        image = images.create(**args)
        image_id = image.id
        self.resource_id_set(image_id)
        images.image_import(image_id, method='web-download', uri=location)
        for member in members:
            self.client().image_members.create(image_id, member)
        return active

    def check_create_complete(self, active):
        image = self.client().images.get(self.resource_id)
        if image.status == 'killed':
            raise exception.ResourceInError(
                resource_status=image.status,
            )
        if not active:
            if image.status == 'active':
                self.client().images.deactivate(self.resource_id)
                return True
            elif image.status == 'deactivated':
                return True
            else:
                return False
        else:
            return image.status == 'active'

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            active = prop_diff.pop(self.ACTIVE, None)
            if active is False:
                self.client().images.deactivate(self.resource_id)

            if self.TAGS in prop_diff:
                existing_tags = self.properties.get(self.TAGS) or []
                diff_tags = prop_diff.pop(self.TAGS) or []

                new_tags = set(diff_tags) - set(existing_tags)
                for tag in new_tags:
                    self.client().image_tags.update(
                        self.resource_id,
                        tag)

                removed_tags = set(existing_tags) - set(diff_tags)
                for tag in removed_tags:
                    with self.client_plugin().ignore_not_found:
                        self.client().image_tags.delete(
                            self.resource_id,
                            tag)

            if self.MEMBERS in prop_diff:
                existing_members = self.properties.get(self.MEMBERS) or []
                diff_members = prop_diff.pop(self.MEMBERS) or []

                new_members = set(diff_members) - set(existing_members)
                for _member in new_members:
                    self.glance().image_members.create(
                        self.resource_id, _member)
                removed_members = set(existing_members) - set(diff_members)
                for _member in removed_members:
                    self.glance().image_members.delete(
                        self.resource_id, _member)

        self.client().images.update(self.resource_id, **prop_diff)
        return active

    def check_update_complete(self, active):
        if active:
            self.client().images.reactivate(self.resource_id)
        return True

    def validate(self):
        super(GlanceWebImage, self).validate()
        container_format = self.properties[self.CONTAINER_FORMAT]
        if (container_format in ['ami', 'ari', 'aki']
                and self.properties[self.DISK_FORMAT] != container_format):
            msg = _("Invalid mix of disk and container formats. When "
                    "setting a disk or container format to one of 'aki', "
                    "'ari', or 'ami', the container and disk formats must "
                    "match.")
            raise exception.StackValidationFailed(message=msg)

        if (self.properties[self.MEMBERS]
                and self.properties[self.VISIBILITY] != 'shared'):
            raise exception.ResourcePropertyValueDependency(
                prop1=self.MEMBERS,
                prop2=self.VISIBILITY,
                value='shared')

    def get_live_resource_data(self):
        image_data = super(GlanceWebImage, self).get_live_resource_data()
        if image_data.get('status') in ('deleted', 'killed'):
            raise exception.EntityNotFound(entity='Resource',
                                           name=self.name)
        return image_data

    def parse_live_resource_data(self, resource_properties, resource_data):
        image_reality = {}

        for key in self.PROPERTIES:
            if key == self.LOCATION:
                continue
            if key == self.IMAGE_ID:
                if (resource_properties.get(self.IMAGE_ID) is not None or
                        resource_data.get(self.IMAGE_ID) != self.resource_id):
                    image_reality.update({self.IMAGE_ID: resource_data.get(
                        self.IMAGE_ID)})
                else:
                    image_reality.update({self.IMAGE_ID: None})
            else:
                image_reality.update({key: resource_data.get(key)})

        return image_reality


class GlanceImage(resource.Resource):
    """A resource managing images in Glance.

    A resource provides managing images that are meant to be used with other
    services.
    """

    support_status = support.SupportStatus(
        status=support.DEPRECATED,
        version='8.0.0',
        message=_('Creating a Glance Image based on an existing URL location '
                  'requires the Glance v1 API, which is deprecated.'),
        previous_status=support.SupportStatus(version='2014.2')
    )

    PROPERTIES = (
        NAME, IMAGE_ID, IS_PUBLIC, MIN_DISK, MIN_RAM, PROTECTED,
        DISK_FORMAT, CONTAINER_FORMAT, LOCATION, TAGS, EXTRA_PROPERTIES,
        ARCHITECTURE, KERNEL_ID, OS_DISTRO, OWNER, RAMDISK_ID
    ) = (
        'name', 'id', 'is_public', 'min_disk', 'min_ram', 'protected',
        'disk_format', 'container_format', 'location', 'tags',
        'extra_properties', 'architecture', 'kernel_id', 'os_distro',
        'owner', 'ramdisk_id'
    )

    glance_id_pattern = ('^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}'
                         '-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$')

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name for the image. The name of an image is not '
              'unique to a Image Service node.')
        ),
        IMAGE_ID: properties.Schema(
            properties.Schema.STRING,
            _('The image ID. Glance will generate a UUID if not specified.')
        ),
        IS_PUBLIC: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Scope of image accessibility. Public or private. '
              'Default value is False means private. Note: The policy '
              'setting of glance allows only users with admin roles to create '
              'public image by default.'),
            default=False,
        ),
        MIN_DISK: properties.Schema(
            properties.Schema.INTEGER,
            _('Amount of disk space (in GB) required to boot image. '
              'Default value is 0 if not specified '
              'and means no limit on the disk size.'),
            constraints=[
                constraints.Range(min=0),
            ],
            default=0
        ),
        MIN_RAM: properties.Schema(
            properties.Schema.INTEGER,
            _('Amount of ram (in MB) required to boot image. Default value '
              'is 0 if not specified and means no limit on the ram size.'),
            constraints=[
                constraints.Range(min=0),
            ],
            default=0
        ),
        PROTECTED: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Whether the image can be deleted. If the value is True, '
              'the image is protected and cannot be deleted.'),
            default=False
        ),
        DISK_FORMAT: properties.Schema(
            properties.Schema.STRING,
            _('Disk format of image.'),
            required=True,
            constraints=[
                constraints.AllowedValues(['ami', 'ari', 'aki',
                                           'vhd', 'vmdk', 'raw',
                                           'qcow2', 'vdi', 'iso'])
            ]
        ),
        CONTAINER_FORMAT: properties.Schema(
            properties.Schema.STRING,
            _('Container format of image.'),
            required=True,
            constraints=[
                constraints.AllowedValues(['ami', 'ari', 'aki',
                                           'bare', 'ova', 'ovf'])
            ]
        ),
        LOCATION: properties.Schema(
            properties.Schema.STRING,
            _('URL where the data for this image already resides. For '
              'example, if the image data is stored in swift, you could '
              'specify "swift://example.com/container/obj".'),
            required=True,
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            _('List of image tags.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0')
        ),
        EXTRA_PROPERTIES: properties.Schema(
            properties.Schema.MAP,
            _('Arbitrary properties to associate with the image.'),
            update_allowed=True,
            default={},
            support_status=support.SupportStatus(version='7.0.0')
        ),
        ARCHITECTURE: properties.Schema(
            properties.Schema.STRING,
            _('Operating system architecture.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0')
        ),
        KERNEL_ID: properties.Schema(
            properties.Schema.STRING,
            _('ID of image stored in Glance that should be used as '
              'the kernel when booting an AMI-style image.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0'),
            constraints=[
                constraints.AllowedPattern(glance_id_pattern)
            ]
        ),
        OS_DISTRO: properties.Schema(
            properties.Schema.STRING,
            _('The common name of the operating system distribution '
              'in lowercase.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0')
        ),
        OWNER: properties.Schema(
            properties.Schema.STRING,
            _('Owner of the image.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0')
        ),
        RAMDISK_ID: properties.Schema(
            properties.Schema.STRING,
            _('ID of image stored in Glance that should be used as '
              'the ramdisk when booting an AMI-style image.'),
            update_allowed=True,
            support_status=support.SupportStatus(version='7.0.0'),
            constraints=[
                constraints.AllowedPattern(glance_id_pattern)
            ]
        )
    }

    default_client_name = 'glance'

    entity = 'images'

    def handle_create(self):
        args = dict((k, v) for k, v in self.properties.items()
                    if v is not None)

        tags = args.pop(self.TAGS, [])
        args['properties'] = args.pop(self.EXTRA_PROPERTIES, {})
        architecture = args.pop(self.ARCHITECTURE, None)
        kernel_id = args.pop(self.KERNEL_ID, None)
        os_distro = args.pop(self.OS_DISTRO, None)
        ramdisk_id = args.pop(self.RAMDISK_ID, None)

        image_id = self.client(version=self.client_plugin().V1).images.create(
            **args).id
        self.resource_id_set(image_id)

        images = self.client().images
        if architecture is not None:
            images.update(image_id, architecture=architecture)
        if kernel_id is not None:
            images.update(image_id, kernel_id=kernel_id)
        if os_distro is not None:
            images.update(image_id, os_distro=os_distro)
        if ramdisk_id is not None:
            images.update(image_id, ramdisk_id=ramdisk_id)

        for tag in tags:
            self.client().image_tags.update(
                image_id,
                tag)

        return image_id

    def check_create_complete(self, image_id):
        image = self.client().images.get(image_id)
        return image.status == 'active'

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff and self.TAGS in prop_diff:
            existing_tags = self.properties.get(self.TAGS) or []
            diff_tags = prop_diff.pop(self.TAGS) or []

            new_tags = set(diff_tags) - set(existing_tags)
            for tag in new_tags:
                self.client().image_tags.update(
                    self.resource_id,
                    tag)

            removed_tags = set(existing_tags) - set(diff_tags)
            for tag in removed_tags:
                with self.client_plugin().ignore_not_found:
                    self.client().image_tags.delete(
                        self.resource_id,
                        tag)

        images = self.client().images

        if self.EXTRA_PROPERTIES in prop_diff:
            old_properties = self.properties.get(self.EXTRA_PROPERTIES) or {}
            new_properties = prop_diff.pop(self.EXTRA_PROPERTIES)
            prop_diff.update(new_properties)
            remove_props = list(set(old_properties) - set(new_properties))

            # Though remove_props defaults to None within the glanceclient,
            # setting it to a list (possibly []) every time ensures only one
            # calling format to images.update
            images.update(self.resource_id, remove_props, **prop_diff)
        else:
            images.update(self.resource_id, **prop_diff)

    def validate(self):
        super(GlanceImage, self).validate()
        container_format = self.properties[self.CONTAINER_FORMAT]
        if (container_format in ['ami', 'ari', 'aki']
                and self.properties[self.DISK_FORMAT] != container_format):
            msg = _("Invalid mix of disk and container formats. When "
                    "setting a disk or container format to one of 'aki', "
                    "'ari', or 'ami', the container and disk formats must "
                    "match.")
            raise exception.StackValidationFailed(message=msg)

    def get_live_resource_data(self):
        image_data = super(GlanceImage, self).get_live_resource_data()
        if image_data.get('status') in ('deleted', 'killed'):
            raise exception.EntityNotFound(entity='Resource',
                                           name=self.name)
        return image_data

    def parse_live_resource_data(self, resource_properties, resource_data):
        image_reality = {}

        # NOTE(prazumovsky): At first, there's no way to get location from
        # glance; at second, location property is doubtful, because glance
        # client v2 doesn't use location, it uses locations. So, we should
        # get location property from resource properties.
        if self.client().version == 1.0:
            image_reality.update(
                {self.LOCATION: resource_properties[self.LOCATION]})

        for key in self.PROPERTIES:
            if key == self.LOCATION:
                continue
            if key == self.IMAGE_ID:
                if (resource_properties.get(self.IMAGE_ID) is not None or
                        resource_data.get(self.IMAGE_ID) != self.resource_id):
                    image_reality.update({self.IMAGE_ID: resource_data.get(
                        self.IMAGE_ID)})
                else:
                    image_reality.update({self.IMAGE_ID: None})
            else:
                image_reality.update({key: resource_data.get(key)})

        return image_reality


def resource_mapping():
    return {
        'OS::Glance::Image': GlanceImage,
        'OS::Glance::WebImage': GlanceWebImage
    }