Code Coverage

Cobertura Coverage Report > osmclient.sol005 >

vim.py

Trend

Classes0%
 
Lines0%
 
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
vim.py
0%
0/1
0%
0/152
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
vim.py
0%
0/152
N/A

Source

osmclient/sol005/vim.py
1 # Copyright 2018 Telefonica
2 #
3 # All Rights Reserved.
4 #
5 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
6 #    not use this file except in compliance with the License. You may obtain
7 #    a copy of the License at
8 #
9 #         http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #    Unless required by applicable law or agreed to in writing, software
12 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 #    License for the specific language governing permissions and limitations
15 #    under the License.
16
17 0 """
18 OSM vim API handling
19 """
20
21 0 from osmclient.common import utils
22 0 from osmclient.common import wait as WaitForStatus
23 0 from osmclient.common.exceptions import ClientException
24 0 from osmclient.common.exceptions import NotFound
25 0 import yaml
26 0 import json
27 0 import logging
28
29
30 0 class Vim(object):
31 0     def __init__(self, http=None, client=None):
32 0         self._http = http
33 0         self._client = client
34 0         self._logger = logging.getLogger('osmclient')
35 0         self._apiName = '/admin'
36 0         self._apiVersion = '/v1'
37 0         self._apiResource = '/vim_accounts'
38 0         self._apiBase = '{}{}{}'.format(self._apiName,
39                                         self._apiVersion, self._apiResource)
40
41     # VIM '--wait' option
42 0     def _wait(self, id, wait_time, deleteFlag=False):
43 0         self._logger.debug("")
44 0         self._client.get_token()
45         # Endpoint to get operation status
46 0         apiUrlStatus = '{}{}{}'.format(self._apiName, self._apiVersion, '/vim_accounts')
47         # Wait for status for VIM instance creation/deletion
48 0         if isinstance(wait_time, bool):
49 0             wait_time = WaitForStatus.TIMEOUT_VIM_OPERATION
50 0         WaitForStatus.wait_for_status(
51             'VIM',
52             str(id),
53             wait_time,
54             apiUrlStatus,
55             self._http.get2_cmd,
56             deleteFlag=deleteFlag)
57
58 0     def _get_id_for_wait(self, name):
59         """ Returns id of name, or the id itself if given as argument
60         """
61 0         self._logger.debug("")
62 0         self._client.get_token()
63 0         for vim in self.list():
64 0             if name == vim['uuid']:
65 0                 return vim['uuid']
66 0         for vim in self.list():
67 0             if name == vim['name']:
68 0                 return vim['uuid']
69 0         return ''
70
71 0     def create(self, name, vim_access, sdn_controller=None, sdn_port_mapping=None, wait=False):
72 0         self._logger.debug("")
73 0         self._client.get_token()
74 0         if 'vim-type' not in vim_access:
75             #'openstack' not in vim_access['vim-type']):
76 0             raise Exception("vim type not provided")
77
78 0         vim_account = {}
79 0         vim_account['name'] = name
80 0         vim_account = self.update_vim_account_dict(vim_account, vim_access)
81
82 0         vim_config = {}
83 0         if 'config' in vim_access and vim_access['config'] is not None:
84 0             vim_config = yaml.safe_load(vim_access['config'])
85 0         if sdn_controller:
86 0             sdnc = self._client.sdnc.get(sdn_controller)
87 0             vim_config['sdn-controller'] = sdnc['_id']
88 0         if sdn_port_mapping:
89 0             with open(sdn_port_mapping, 'r') as f:
90 0                 vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
91 0         if vim_config:
92 0             vim_account['config'] = vim_config
93             #vim_account['config'] = json.dumps(vim_config)
94
95 0         http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
96                                        postfields_dict=vim_account)
97         #print('HTTP CODE: {}'.format(http_code))
98         #print('RESP: {}'.format(resp))
99         #if http_code in (200, 201, 202, 204):
100 0         if resp:
101 0             resp = json.loads(resp)
102 0         if not resp or 'id' not in resp:
103 0             raise ClientException('unexpected response from server - {}'.format(
104                                   resp))
105 0         if wait:
106             # Wait for status for VIM instance creation
107 0             self._wait(resp.get('id'), wait)
108 0         print(resp['id'])
109         #else:
110         #    msg = ""
111         #    if resp:
112         #        try:
113         #            msg = json.loads(resp)
114         #        except ValueError:
115         #            msg = resp
116         #    raise ClientException("failed to create vim {} - {}".format(name, msg))
117
118 0     def update(self, vim_name, vim_account, sdn_controller, sdn_port_mapping, wait=False):
119 0         self._logger.debug("")
120 0         self._client.get_token()
121 0         vim = self.get(vim_name)
122 0         vim_id_for_wait = self._get_id_for_wait(vim_name)
123 0         vim_config = {}
124 0         if 'config' in vim_account:
125 0             if vim_account.get('config')=="" and (sdn_controller or sdn_port_mapping):
126 0                 raise ClientException("clearing config is incompatible with updating SDN info")
127 0             if vim_account.get('config')=="":
128 0                 vim_config = None
129             else:
130 0                 vim_config = yaml.safe_load(vim_account['config'])
131 0         if sdn_controller == "":
132 0             vim_config['sdn-controller'] = None
133 0             vim_config['sdn-port-mapping'] = None
134         else:
135 0             if sdn_controller:
136 0                 sdnc = self._client.sdnc.get(sdn_controller)
137 0                 vim_config['sdn-controller'] = sdnc['_id']
138 0             if sdn_port_mapping:
139 0                 with open(sdn_port_mapping, 'r') as f:
140 0                     vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
141 0         vim_account['config'] = vim_config
142         #vim_account['config'] = json.dumps(vim_config)
143 0         http_code, resp = self._http.patch_cmd(endpoint='{}/{}'.format(self._apiBase,vim['_id']),
144                                        postfields_dict=vim_account)
145         # print('HTTP CODE: {}'.format(http_code))
146         # print('RESP: {}'.format(resp))
147         #if http_code in (200, 201, 202, 204):
148 0         if wait:
149             # In this case, 'resp' always returns None, so 'resp['id']' cannot be used.
150             # Use the previously obtained id instead.
151 0             wait_id = vim_id_for_wait
152             # Wait for status for VI instance update
153 0             self._wait(wait_id, wait)
154         # else:
155         #     pass
156         #else:
157         #    msg = ""
158         #    if resp:
159         #        try:
160         #            msg = json.loads(resp)
161         #        except ValueError:
162         #            msg = resp
163         #    raise ClientException("failed to update vim {} - {}".format(vim_name, msg))
164
165 0     def update_vim_account_dict(self, vim_account, vim_access):
166 0         self._logger.debug("")
167 0         vim_account['vim_type'] = vim_access['vim-type']
168 0         vim_account['description'] = vim_access['description']
169 0         vim_account['vim_url'] = vim_access['vim-url']
170 0         vim_account['vim_user'] = vim_access['vim-username']
171 0         vim_account['vim_password'] = vim_access['vim-password']
172 0         vim_account['vim_tenant_name'] = vim_access['vim-tenant-name']
173 0         return vim_account
174
175 0     def get_id(self, name):
176         """Returns a VIM id from a VIM name
177         """
178 0         self._logger.debug("")
179 0         for vim in self.list():
180 0             if name == vim['name']:
181 0                 return vim['uuid']
182 0         raise NotFound("vim {} not found".format(name))
183
184 0     def delete(self, vim_name, force=False, wait=False):
185 0         self._logger.debug("")
186 0         self._client.get_token()
187 0         vim_id = vim_name
188 0         if not utils.validate_uuid4(vim_name):
189 0             vim_id = self.get_id(vim_name)
190 0         querystring = ''
191 0         if force:
192 0             querystring = '?FORCE=True'
193 0         http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
194                                          vim_id, querystring))
195         #print('HTTP CODE: {}'.format(http_code))
196         #print('RESP: {}'.format(resp))
197 0         if http_code == 202:
198 0             if wait:
199                 # When deleting an account, 'resp' may be None.
200                 # In such a case, the 'id' from 'resp' cannot be used, so use 'vim_id' instead
201 0                 wait_id = vim_id
202 0                 if resp:
203 0                     resp = json.loads(resp)
204 0                     wait_id = resp.get('id')
205                 # Wait for status for VIM account deletion
206 0                 self._wait(wait_id, wait, deleteFlag=True)
207             else:
208 0                 print('Deletion in progress')
209 0         elif http_code == 204:
210 0             print('Deleted')
211         else:
212 0             msg = resp or ""
213             # if resp:
214             #     try:
215             #         msg = json.loads(resp)
216             #     except ValueError:
217             #         msg = resp
218 0             raise ClientException("failed to delete vim {} - {}".format(vim_name, msg))
219
220 0     def list(self, filter=None):
221         """Returns a list of VIM accounts
222         """
223 0         self._logger.debug("")
224 0         self._client.get_token()
225 0         filter_string = ''
226 0         if filter:
227 0             filter_string = '?{}'.format(filter)
228 0         _, resp = self._http.get2_cmd('{}{}'.format(self._apiBase,filter_string))
229 0         if not resp:
230 0             return list()
231 0         vim_accounts = json.loads(resp)
232 0         for datacenter in vim_accounts:
233 0             datacenter["uuid"] = datacenter.get('_id')  # backward compatibility?
234 0         return vim_accounts
235
236 0     def get(self, name):
237         """Returns a VIM account based on name or id
238         """
239 0         self._logger.debug("")
240 0         self._client.get_token()
241 0         vim_id = name
242 0         if not utils.validate_uuid4(name):
243 0             vim_id = self.get_id(name)
244 0         try:
245 0             _, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase,vim_id))
246 0             if resp:
247 0                 resp = json.loads(resp)
248 0             if not resp or '_id' not in resp:
249 0                 raise ClientException('failed to get vim info: {}'.format(resp))
250 0             return resp
251 0         except NotFound:
252 0             raise NotFound("vim '{}' not found".format(name))
253