| 1 |
# Copyright 2013 Red Hat, Inc. |
| 2 |
# All Rights Reserved. |
| 3 |
# |
| 4 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 |
# not use this file except in compliance with the License. You may obtain |
| 6 |
# a copy of the License at |
| 7 |
# |
| 8 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
# |
| 10 |
# Unless required by applicable law or agreed to in writing, software |
| 11 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 |
# License for the specific language governing permissions and limitations |
| 14 |
# under the License. |
| 15 |
|
| 16 |
import os |
| 17 |
import shutil |
| 18 |
import subprocess |
| 19 |
import time |
| 20 |
|
| 21 |
from functools import wraps |
| 22 |
|
| 23 |
from six.moves import urllib |
| 24 |
from tempest.lib import exceptions |
| 25 |
from tenacity import retry |
| 26 |
from tenacity import stop_after_attempt |
| 27 |
|
| 28 |
from config_tempest import constants as C |
| 29 |
from config_tempest.services.base import VersionedService |
| 30 |
|
| 31 |
|
| 32 |
stop = stop_after_attempt(len(C.DEFAULT_IMAGES)) |
| 33 |
|
| 34 |
|
| 35 |
class ImageService(VersionedService): |
| 36 |
|
| 37 |
def __init__(self, name, s_type, service_url, token, |
| 38 |
disable_ssl_validation, client=None, **kwargs): |
| 39 |
super(ImageService, self).__init__( |
| 40 |
name, s_type, service_url, token, disable_ssl_validation, |
| 41 |
client, **kwargs) |
| 42 |
self.retry_attempt = -1 |
| 43 |
|
| 44 |
def set_image_preferences(self, disk_format, non_admin, no_rng=False, |
| 45 |
convert=False): |
| 46 |
"""Sets image prefferences. |
| 47 |
|
| 48 |
:type disk_format: string |
| 49 |
:type non_admin: bool |
| 50 |
:type no_rng: bool |
| 51 |
:type convert: bool |
| 52 |
""" |
| 53 |
self.disk_format = disk_format |
| 54 |
self.non_admin = non_admin |
| 55 |
self.no_rng = no_rng |
| 56 |
self.convert = convert |
| 57 |
|
| 58 |
def set_default_tempest_options(self, conf): |
| 59 |
# set 'image-feature-enabled' only if multiple stores available |
| 60 |
if self._is_multistore_enabled(): |
| 61 |
conf.set('image-feature-enabled', 'import_image', 'True') |
| 62 |
# When cirros is the image, set validation.image_ssh_user to cirros. |
| 63 |
# The option is heavily used in CI and it's also usefull for refstack, |
| 64 |
# because we don't have to specify overrides. |
| 65 |
if 'cirros' in conf.get_defaulted('image', |
| 66 |
'image_path').rsplit('/')[-1]: |
| 67 |
conf.set('validation', 'image_ssh_user', 'cirros') |
| 68 |
# image.http_image is a tempest option which defines 'http accessible |
| 69 |
# image', it can be in a compressed format so it can't be mistaken |
| 70 |
# for an image which will be uploaded to the glance. |
| 71 |
# image.http_image and image.image_path can be 2 different images. |
| 72 |
# If image.http_image wasn't set as an override, it will be set to |
| 73 |
# image.image_path or to DEFAULT_IMAGE |
| 74 |
image_path = conf.get_defaulted('image', 'image_path') |
| 75 |
if self._find_image_by_name(image_path) is None: |
| 76 |
conf.set('image', 'http_image', image_path) |
| 77 |
else: |
| 78 |
# image.image_path is name of the image already present in glance, |
| 79 |
# this value can't be set to image.http_image, therefor set the |
| 80 |
# default value |
| 81 |
conf.set('image', 'http_image', C.DEFAULT_IMAGE) |
| 82 |
conf.set('image', 'http_qcow2_image', C.DEFAULT_QCOW2_IMAGE) |
| 83 |
|
| 84 |
def _is_multistore_enabled(self): |
| 85 |
try: |
| 86 |
self.client.info_stores()['stores'] |
| 87 |
except Exception: |
| 88 |
C.LOG.info('Can not retrieve stores, either multiple stores are ' |
| 89 |
'not configured or user are not allowed access ' |
| 90 |
'to the stores information') |
| 91 |
return False |
| 92 |
return True |
| 93 |
|
| 94 |
def get_supported_versions(self): |
| 95 |
return ['v1', 'v2'] |
| 96 |
|
| 97 |
@staticmethod |
| 98 |
def get_service_type(): |
| 99 |
return ['image'] |
| 100 |
|
| 101 |
@staticmethod |
| 102 |
def get_codename(): |
| 103 |
return 'glance' |
| 104 |
|
| 105 |
def set_versions(self): |
| 106 |
super(ImageService, self).set_versions(top_level=False) |
| 107 |
|
| 108 |
def create_tempest_images(self, conf, retry_alt=False): |
| 109 |
"""Uploads an image to the glance. |
| 110 |
|
| 111 |
The method creates images specified in conf, if they're not created |
| 112 |
already. Then it sets their IDs to the conf. |
| 113 |
|
| 114 |
:type conf: TempestConf object |
| 115 |
""" |
| 116 |
# the absolute path is necessary for supporting older tempest versions, |
| 117 |
# which had CONF.scenario.img_dir option, see this line of code: |
| 118 |
# https://github.com/openstack/tempest/blob/a0ee8b4ccfc512a09 |
| 119 |
# e1ddb135950b767110aae9b/tempest/scenario/manager.py#L534 |
| 120 |
# If the path is not an absolute one, the concatenation of strings ^^ |
| 121 |
# will result in an invalid path |
| 122 |
# Moreover the absolute path is needed so that users can move the |
| 123 |
# generated tempest.conf outside of python-tempestconf destination, |
| 124 |
# otherwise tempest would fail accessing the CONF.scenario.img_file |
| 125 |
img_dir = os.path.abspath(os.path.join(C.DEFAULT_IMAGE_DIR)) |
| 126 |
image_path = conf.get_defaulted('image', 'image_path') |
| 127 |
img_path = os.path.join(img_dir, |
| 128 |
os.path.basename(image_path)) |
| 129 |
name = image_path[image_path.rfind('/') + 1:] |
| 130 |
if self.convert and name[-4:] == ".img": |
| 131 |
name = name[:-4] + ".raw" |
| 132 |
# create img_dir if it doesn't exist already |
| 133 |
os.makedirs(img_dir, exist_ok=True) |
| 134 |
alt_name = name + "_alt" |
| 135 |
image_id = None |
| 136 |
if conf.has_option('compute', 'image_ref'): |
| 137 |
image_id = conf.get('compute', 'image_ref') |
| 138 |
image_id = self.find_or_upload_image(image_id, name, |
| 139 |
image_source=image_path, |
| 140 |
image_dest=img_path, |
| 141 |
retry_alt=retry_alt) |
| 142 |
alt_image_id = None |
| 143 |
if conf.has_option('compute', 'image_ref_alt'): |
| 144 |
alt_image_id = conf.get('compute', 'image_ref_alt') |
| 145 |
alt_image_id = self.find_or_upload_image(alt_image_id, alt_name, |
| 146 |
image_source=image_path, |
| 147 |
image_dest=img_path, |
| 148 |
retry_alt=retry_alt) |
| 149 |
# get name of the image_id |
| 150 |
conf.set('scenario', 'img_file', img_path) |
| 151 |
conf.set('compute', 'image_ref', image_id) |
| 152 |
conf.set('compute', 'image_ref_alt', alt_image_id) |
| 153 |
|
| 154 |
def find_or_upload_image(self, image_id, image_name, image_source='', |
| 155 |
image_dest='', retry_alt=False): |
| 156 |
"""If the image is not found, uploads it. |
| 157 |
|
| 158 |
:type image_id: string |
| 159 |
:type image_name: string |
| 160 |
:type image_source: string |
| 161 |
:type image_dest: string |
| 162 |
""" |
| 163 |
image = self._find_image(image_id, image_name) |
| 164 |
|
| 165 |
if image: |
| 166 |
C.LOG.info("(no change) Found image '%s'", image['name']) |
| 167 |
path = os.path.abspath(image_dest) |
| 168 |
if not os.path.isfile(path): |
| 169 |
self._download_image(image['id'], path) |
| 170 |
else: |
| 171 |
C.LOG.info("Creating image '%s'", image_name) |
| 172 |
if image_source.startswith("http:") or \ |
| 173 |
image_source.startswith("https:"): |
| 174 |
try: |
| 175 |
self._download_file(image_source, image_dest) |
| 176 |
# We only download alternative image if the default image |
| 177 |
# fails |
| 178 |
except Exception: |
| 179 |
if retry_alt: |
| 180 |
self._download_with_retry(image_dest) |
| 181 |
else: |
| 182 |
try: |
| 183 |
shutil.copyfile(image_source, image_dest) |
| 184 |
except Exception: |
| 185 |
# let's try if this is the case when a user uses already |
| 186 |
# existing image in glance which is not uploaded as *_alt |
| 187 |
if image_name[-4:] == "_alt": |
| 188 |
image = self._find_image(None, image_name[:-4]) |
| 189 |
if image: |
| 190 |
path = os.path.abspath(image_dest) |
| 191 |
if not os.path.isfile(path): |
| 192 |
self._download_image(image['id'], path) |
| 193 |
else: |
| 194 |
if retry_alt: |
| 195 |
self._download_with_retry(image_dest) |
| 196 |
else: |
| 197 |
raise IOError |
| 198 |
image = self._upload_image(image_name, image_dest) |
| 199 |
return image['id'] |
| 200 |
|
| 201 |
@retry(stop=stop) |
| 202 |
def _download_with_retry(self, destination): |
| 203 |
self.retry_attempt += 1 |
| 204 |
self._download_file(C.DEFAULT_IMAGES[self.retry_attempt], destination) |
| 205 |
|
| 206 |
def _find_image(self, image_id, image_name): |
| 207 |
"""Find image by ID or name (the image client doesn't have this). |
| 208 |
|
| 209 |
:type image_id: string |
| 210 |
:type image_name: string |
| 211 |
""" |
| 212 |
if image_id: |
| 213 |
try: |
| 214 |
return self.client.show_image(image_id) |
| 215 |
except exceptions.NotFound: |
| 216 |
pass |
| 217 |
return self._find_image_by_name(image_name) |
| 218 |
|
| 219 |
def _find_image_by_name(self, image_name): |
| 220 |
"""Find image by name. |
| 221 |
|
| 222 |
:type image_name: string |
| 223 |
:return: Information in a dict about the found image |
| 224 |
:rtype: dict or None if image was not found |
| 225 |
""" |
| 226 |
for x in self.client.list_images()['images']: |
| 227 |
if x['name'] == image_name: |
| 228 |
return x |
| 229 |
return None |
| 230 |
|
| 231 |
def _upload_image(self, name, path): |
| 232 |
"""Upload image file from `path` into Glance with `name`. |
| 233 |
|
| 234 |
:type name: string |
| 235 |
:type path: string |
| 236 |
""" |
| 237 |
if self.convert: |
| 238 |
path = self.convert_image_to_raw(path) |
| 239 |
|
| 240 |
C.LOG.info("Uploading image '%s' from '%s'", |
| 241 |
name, os.path.abspath(path)) |
| 242 |
if self.non_admin: |
| 243 |
visibility = 'community' |
| 244 |
else: |
| 245 |
visibility = 'public' |
| 246 |
|
| 247 |
with open(path, 'rb') as data: |
| 248 |
args = {'name': name, 'disk_format': self.disk_format, |
| 249 |
'container_format': 'bare', 'visibility': visibility, |
| 250 |
'hw_rng_model': 'virtio'} |
| 251 |
if self.no_rng: |
| 252 |
args.pop('hw_rng_model') |
| 253 |
image = self.client.create_image(**args) |
| 254 |
self.client.store_image_file(image['id'], data) |
| 255 |
return image |
| 256 |
|
| 257 |
def _download_image(self, id, path): |
| 258 |
"""Download image from glance. |
| 259 |
|
| 260 |
:type id: string |
| 261 |
:type path: string |
| 262 |
""" |
| 263 |
C.LOG.info("Downloading image %s to %s", id, path) |
| 264 |
body = self.client.show_image_file(id) |
| 265 |
C.LOG.debug(type(body.data)) |
| 266 |
with open(path, 'wb') as out: |
| 267 |
out.write(body.data) |
| 268 |
|
| 269 |
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): |
| 270 |
"""Retry calling the decorated function using exponential backoff |
| 271 |
|
| 272 |
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ |
| 273 |
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry |
| 274 |
|
| 275 |
Licensed under the BSD 3-Clause "New" or "Revised" License |
| 276 |
(https://github.com/saltycrane/retry-decorator/blob/master/LICENSE) |
| 277 |
|
| 278 |
:param ExceptionToCheck: the exception to check |
| 279 |
:type ExceptionToCheck: Exception or tuple |
| 280 |
:param tries: number of times before giving up |
| 281 |
:type type: int |
| 282 |
:param delay: initial delay between retries in seconds |
| 283 |
:type type: int |
| 284 |
:param backoff: backoff multiplier e.g. value of 2 will double the |
| 285 |
delay each retry |
| 286 |
:type backoff: int |
| 287 |
:param logger: logger to use. If None, print |
| 288 |
:type logger: logging. Logger instance |
| 289 |
""" |
| 290 |
def deco_retry(f): |
| 291 |
@wraps(f) |
| 292 |
def f_retry(*args, **kwargs): |
| 293 |
mtries, mdelay = tries, delay |
| 294 |
while mtries > 1: |
| 295 |
try: |
| 296 |
return f(*args, **kwargs) |
| 297 |
except ExceptionToCheck as e: |
| 298 |
msg = "%s, Retrying in %d seconds." % (str(e), mdelay) |
| 299 |
if logger: |
| 300 |
logger.warning(msg) |
| 301 |
else: |
| 302 |
print(msg) |
| 303 |
time.sleep(mdelay) |
| 304 |
mtries -= 1 |
| 305 |
mdelay *= backoff |
| 306 |
return f(*args, **kwargs) |
| 307 |
return f_retry |
| 308 |
return deco_retry |
| 309 |
|
| 310 |
@retry(urllib.error.URLError, logger=C.LOG) |
| 311 |
def retry_urlopen(self, url): |
| 312 |
"""Opens url using urlopen. If it fails, it will try again. |
| 313 |
|
| 314 |
:type url: string |
| 315 |
""" |
| 316 |
return urllib.request.urlopen(url) |
| 317 |
|
| 318 |
def _download_file(self, url, destination): |
| 319 |
"""Downloads a file specified by `url` to `destination`. |
| 320 |
|
| 321 |
:type url: string |
| 322 |
:type destination: string |
| 323 |
""" |
| 324 |
if os.path.exists(destination): |
| 325 |
C.LOG.info("Image '%s' already fetched to '%s'.", url, destination) |
| 326 |
return |
| 327 |
C.LOG.info("Downloading '%s' and saving as '%s'", url, destination) |
| 328 |
f = self.retry_urlopen(url) |
| 329 |
data = f.read() |
| 330 |
with open(destination, "wb") as dest: |
| 331 |
dest.write(data) |
| 332 |
|
| 333 |
def convert_image_to_raw(self, path): |
| 334 |
"""Converts given image to raw format. |
| 335 |
|
| 336 |
:type path: string |
| 337 |
:return: path of the converted image |
| 338 |
:rtype: string |
| 339 |
""" |
| 340 |
head, tail = os.path.split(path) |
| 341 |
name = tail.rsplit('.', 1)[0] + '.raw' |
| 342 |
raw_path = os.path.join(head, name) |
| 343 |
# check if converted already |
| 344 |
if os.path.exists(raw_path): |
| 345 |
C.LOG.info("Image already converted in '%s'.", raw_path) |
| 346 |
else: |
| 347 |
C.LOG.info("Converting image '%s' to '%s'", |
| 348 |
os.path.abspath(path), os.path.abspath(raw_path)) |
| 349 |
rc = subprocess.call(['qemu-img', 'convert', path, raw_path]) |
| 350 |
if rc != 0: |
| 351 |
raise Exception("Converting of the image has finished with " |
| 352 |
"non-zero return code. The return code was " |
| 353 |
"'%d'", rc) |
| 354 |
self.disk_format = 'raw' |
| 355 |
return raw_path |