summaryrefslogtreecommitdiff
path: root/libs/glance.py
blob: 3adf64b29f43a3c5e97d93b8a62ddcf8462a6290 (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
from __future__ import print_function
import datetime
import glanceclient
import json
import os
import time
import traceback


class Glance(object):
    def __init__(self, keystone, endpoint_type="publicURL"):
        self.keystone = keystone
        self.glance = glanceclient.Client(keystone.os_image_api_version,
                                          endpoint=keystone.get_glance_url(endpoint_type=endpoint_type),
                                          session=keystone.session)

    def find(self, image_name):
        for image in self.glance.images.list():
            if image.name == image_name:
                return image
        return None

    def delete(self, image_name):
        image = self.find(image_name)
        if image:
            self.glance.images.delete(image.id)

    def upload(self, image_name, image_type, file_path, visibility, tag):
        self.delete(image_name)
        image = self.glance.images.create(name=image_name)
        if image.status != "queued":
            raise Exception("Image did not enter queued state upon create.")
        image = self.glance.images.update(image.id, disk_format=image_type)
        image = self.glance.images.update(image.id, container_format="bare")
        image = self.glance.images.update(image.id, visibility=visibility)
        image = self.glance.images.update(image.id, tags=[str(tag)])
        with open(file_path, "rb") as stream:
            self.glance.images.upload(image.id, stream)
        return image.id

    def download(self, image_name, file_path):
        image = self.find(image_name)
        if image:
            data = self.glance.images.data(image.id)
            os.remove(file_path)
            with open(file_path, "w") as stream:
                for chunk in data:
                    stream.write(chunk)