Merge "HA testcase containerized Compass support"
[yardstick.git] / api / resources / v2 / images.py
1 import logging
2 import subprocess
3 import threading
4
5 from api import ApiResource
6 from yardstick.common.utils import result_handler
7 from yardstick.common.utils import source_env
8 from yardstick.common.utils import change_obj_to_dict
9 from yardstick.common.openstack_utils import get_nova_client
10 from yardstick.common import constants as consts
11
12 LOG = logging.getLogger(__name__)
13 LOG.setLevel(logging.DEBUG)
14
15
16 class V2Images(ApiResource):
17
18     def get(self):
19         try:
20             source_env(consts.OPENRC)
21         except:
22             return result_handler(consts.API_ERROR, 'source openrc error')
23
24         nova_client = get_nova_client()
25         try:
26             images_list = nova_client.images.list()
27         except:
28             return result_handler(consts.API_ERROR, 'get images error')
29         else:
30             images = [self.get_info(change_obj_to_dict(i)) for i in images_list]
31             status = 1 if all(i['status'] == 'ACTIVE' for i in images) else 0
32
33         return result_handler(consts.API_SUCCESS, {'status': status, 'images': images})
34
35     def post(self):
36         return self._dispatch_post()
37
38     def get_info(self, data):
39         result = {
40             'name': data.get('name', ''),
41             'size': data.get('OS-EXT-IMG-SIZE:size', ''),
42             'status': data.get('status', ''),
43             'time': data.get('updated', '')
44         }
45         return result
46
47     def load_image(self, args):
48         thread = threading.Thread(target=self._load_images)
49         thread.start()
50         return result_handler(consts.API_SUCCESS, {})
51
52     def _load_images(self):
53         LOG.info('source openrc')
54         source_env(consts.OPENRC)
55
56         LOG.info('clean images')
57         cmd = [consts.CLEAN_IMAGES_SCRIPT]
58         p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
59                              cwd=consts.REPOS_DIR)
60         _, err = p.communicate()
61         if p.returncode != 0:
62             LOG.error('clean image failed: %s', err)
63
64         LOG.info('load images')
65         cmd = [consts.LOAD_IMAGES_SCRIPT]
66         p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
67                              cwd=consts.REPOS_DIR)
68         _, err = p.communicate()
69         if p.returncode != 0:
70             LOG.error('load image failed: %s', err)
71
72         LOG.info('Done')