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)