cbe89462912d85c73cbb3c9b8328f75bff504095
[yardstick.git] / api / resources / v2 / openrcs.py
1 import uuid
2 import logging
3 import re
4 import os
5
6 import yaml
7 from oslo_serialization import jsonutils
8
9 from api import ApiResource
10 from api.database.v2.handlers import V2OpenrcHandler
11 from api.database.v2.handlers import V2EnvironmentHandler
12 from yardstick.common import constants as consts
13 from yardstick.common.utils import result_handler
14 from yardstick.common.utils import makedirs
15 from yardstick.common.utils import source_env
16
17 LOG = logging.getLogger(__name__)
18 LOG.setLevel(logging.DEBUG)
19
20
21 class V2Openrc(ApiResource):
22
23     def post(self):
24         return self._dispatch_post()
25
26     def upload_openrc(self, args):
27         try:
28             upload_file = args['file']
29         except KeyError:
30             return result_handler(consts.API_ERROR, 'file must be provided')
31
32         try:
33             environment_id = args['environment_id']
34         except KeyError:
35             return result_handler(consts.API_ERROR, 'environment_id must be provided')
36
37         LOG.info('writing openrc: %s', consts.OPENRC)
38         makedirs(consts.CONF_DIR)
39         upload_file.save(consts.OPENRC)
40         source_env(consts.OPENRC)
41
42         LOG.info('parsing openrc')
43         try:
44             openrc_data = self._get_openrc_dict()
45         except Exception:
46             LOG.exception('parse openrc failed')
47             return result_handler(consts.API_ERROR, 'parse openrc failed')
48
49         openrc_id = str(uuid.uuid4())
50         self._write_into_database(environment_id, openrc_id, openrc_data)
51
52         LOG.info('writing ansible cloud conf')
53         try:
54             self._generate_ansible_conf_file(openrc_data)
55         except Exception:
56             LOG.exception('write cloud conf failed')
57             return result_handler(consts.API_ERROR, 'genarate ansible conf failed')
58         LOG.info('finish writing ansible cloud conf')
59
60         return result_handler(consts.API_SUCCESS, {'openrc': openrc_data, 'uuid': openrc_id})
61
62     def update_openrc(self, args):
63         try:
64             openrc_vars = args['openrc']
65         except KeyError:
66             return result_handler(consts.API_ERROR, 'openrc must be provided')
67
68         try:
69             environment_id = args['environment_id']
70         except KeyError:
71             return result_handler(consts.API_ERROR, 'environment_id must be provided')
72
73         LOG.info('writing openrc: %s', consts.OPENRC)
74         makedirs(consts.CONF_DIR)
75
76         lines = ['export {}={}\n'.format(k, v) for k, v in openrc_vars.items()]
77         LOG.debug('writing: %s', ''.join(lines))
78         with open(consts.OPENRC, 'w') as f:
79             f.writelines(lines)
80         LOG.info('writing openrc: Done')
81
82         LOG.info('source openrc: %s', consts.OPENRC)
83         try:
84             source_env(consts.OPENRC)
85         except Exception:
86             LOG.exception('source openrc failed')
87             return result_handler(consts.API_ERROR, 'source openrc failed')
88         LOG.info('source openrc: Done')
89
90         openrc_id = str(uuid.uuid4())
91         self._write_into_database(environment_id, openrc_id, openrc_vars)
92
93         LOG.info('writing ansible cloud conf')
94         try:
95             self._generate_ansible_conf_file(openrc_vars)
96         except Exception:
97             LOG.exception('write cloud conf failed')
98             return result_handler(consts.API_ERROR, 'genarate ansible conf failed')
99         LOG.info('finish writing ansible cloud conf')
100
101         return result_handler(consts.API_SUCCESS, {'openrc': openrc_vars, 'uuid': openrc_id})
102
103     def _write_into_database(self, environment_id, openrc_id, openrc_data):
104         LOG.info('writing openrc to database')
105         openrc_handler = V2OpenrcHandler()
106         openrc_init_data = {
107             'uuid': openrc_id,
108             'environment_id': environment_id,
109             'content': jsonutils.dumps(openrc_data)
110         }
111         openrc_handler.insert(openrc_init_data)
112
113         LOG.info('binding openrc to environment: %s', environment_id)
114         environment_handler = V2EnvironmentHandler()
115         environment_handler.update_attr(environment_id, {'openrc_id': openrc_id})
116
117     def _get_openrc_dict(self):
118         with open(consts.OPENRC) as f:
119             content = f.readlines()
120
121         result = {}
122         for line in content:
123             m = re.search(r'(\ .*)=(.*)', line)
124             if m:
125                 try:
126                     value = os.environ[m.group(1).strip()]
127                 except KeyError:
128                     pass
129                 else:
130                     result.update({m.group(1).strip(): value})
131
132         return result
133
134     def _generate_ansible_conf_file(self, openrc_data):
135         ansible_conf = {
136             'clouds': {
137                 'opnfv': {
138                     'auth': {
139                     }
140                 }
141             }
142         }
143         black_list = ['OS_IDENTITY_API_VERSION', 'OS_IMAGE_API_VERSION']
144
145         for k, v in openrc_data.items():
146             if k.startswith('OS') and k not in black_list:
147                 key = k[3:].lower()
148                 ansible_conf['clouds']['opnfv']['auth'][key] = v
149
150         try:
151             value = openrc_data['OS_IDENTITY_API_VERSION']
152         except KeyError:
153             pass
154         else:
155             ansible_conf['clouds']['opnfv']['identity_api_version'] = value
156
157         makedirs(consts.OPENSTACK_CONF_DIR)
158         with open(consts.CLOUDS_CONF, 'w') as f:
159             yaml.dump(ansible_conf, f, default_flow_style=False)