293362a3e7ad5d0df2f592ffb3b03f752b5ef5d9
[osm/osmclient.git] / 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 """
18 OSM vim API handling
19 """
20
21 from osmclient.common import utils
22 from osmclient.common.exceptions import ClientException
23 from osmclient.common.exceptions import NotFound
24 import yaml
25 import json
26
27
28 class Vim(object):
29 def __init__(self, http=None, client=None):
30 self._http = http
31 self._client = client
32 self._apiName = '/admin'
33 self._apiVersion = '/v1'
34 self._apiResource = '/vim_accounts'
35 self._apiBase = '{}{}{}'.format(self._apiName,
36 self._apiVersion, self._apiResource)
37 def create(self, name, vim_access, sdn_controller=None, sdn_port_mapping=None):
38 if 'vim-type' not in vim_access:
39 #'openstack' not in vim_access['vim-type']):
40 raise Exception("vim type not provided")
41
42 vim_account = {}
43 vim_account['name'] = name
44 vim_account = self.update_vim_account_dict(vim_account, vim_access)
45
46 vim_config = {}
47 if 'config' in vim_access and vim_access['config'] is not None:
48 vim_config = yaml.safe_load(vim_access['config'])
49 if sdn_controller:
50 sdnc = self._client.sdnc.get(sdn_controller)
51 vim_config['sdn-controller'] = sdnc['_id']
52 if sdn_port_mapping:
53 with open(sdn_port_mapping, 'r') as f:
54 vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
55 if vim_config:
56 vim_account['config'] = vim_config
57 #vim_account['config'] = json.dumps(vim_config)
58
59 http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
60 postfields_dict=vim_account)
61 #print 'HTTP CODE: {}'.format(http_code)
62 #print 'RESP: {}'.format(resp)
63 if http_code in (200, 201, 202, 204):
64 if resp:
65 resp = json.loads(resp)
66 if not resp or 'id' not in resp:
67 raise ClientException('unexpected response from server - {}'.format(
68 resp))
69 print(resp['id'])
70 else:
71 msg = ""
72 if resp:
73 try:
74 msg = json.loads(resp)
75 except ValueError:
76 msg = resp
77 raise ClientException("failed to create vim {} - {}".format(name, msg))
78
79 def update(self, vim_name, vim_account, sdn_controller, sdn_port_mapping):
80 vim = self.get(vim_name)
81
82 vim_config = {}
83 if 'config' in vim_account:
84 if vim_account.get('config')=="" and (sdn_controller or sdn_port_mapping):
85 raise ClientException("clearing config is incompatible with updating SDN info")
86 if vim_account.get('config')=="":
87 vim_config = None
88 else:
89 vim_config = yaml.safe_load(vim_account['config'])
90 if sdn_controller:
91 sdnc = self._client.sdnc.get(sdn_controller)
92 vim_config['sdn-controller'] = sdnc['_id']
93 if sdn_port_mapping:
94 with open(sdn_port_mapping, 'r') as f:
95 vim_config['sdn-port-mapping'] = yaml.safe_load(f.read())
96 vim_account['config'] = vim_config
97 #vim_account['config'] = json.dumps(vim_config)
98 http_code, resp = self._http.put_cmd(endpoint='{}/{}'.format(self._apiBase,vim['_id']),
99 postfields_dict=vim_account)
100 #print 'HTTP CODE: {}'.format(http_code)
101 #print 'RESP: {}'.format(resp)
102 if http_code in (200, 201, 202, 204):
103 if resp:
104 resp = json.loads(resp)
105 if not resp or 'id' not in resp:
106 raise ClientException('unexpected response from server - {}'.format(
107 resp))
108 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 update vim {} - {}".format(vim_name, msg))
117
118 def update_vim_account_dict(self, vim_account, vim_access):
119 vim_account['vim_type'] = vim_access['vim-type']
120 vim_account['description'] = vim_access['description']
121 vim_account['vim_url'] = vim_access['vim-url']
122 vim_account['vim_user'] = vim_access['vim-username']
123 vim_account['vim_password'] = vim_access['vim-password']
124 vim_account['vim_tenant_name'] = vim_access['vim-tenant-name']
125 return vim_account
126
127 def get_id(self, name):
128 """Returns a VIM id from a VIM name
129 """
130 for vim in self.list():
131 if name == vim['name']:
132 return vim['uuid']
133 raise NotFound("vim {} not found".format(name))
134
135 def delete(self, vim_name, force=False):
136 vim_id = vim_name
137 if not utils.validate_uuid4(vim_name):
138 vim_id = self.get_id(vim_name)
139 querystring = ''
140 if force:
141 querystring = '?FORCE=True'
142 http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
143 vim_id, querystring))
144 #print 'HTTP CODE: {}'.format(http_code)
145 #print 'RESP: {}'.format(resp)
146 if http_code == 202:
147 print('Deletion in progress')
148 elif http_code == 204:
149 print('Deleted')
150 else:
151 msg = ""
152 if resp:
153 try:
154 msg = json.loads(resp)
155 except ValueError:
156 msg = resp
157 raise ClientException("failed to delete vim {} - {}".format(vim_name, msg))
158
159 def list(self, filter=None):
160 """Returns a list of VIM accounts
161 """
162 filter_string = ''
163 if filter:
164 filter_string = '?{}'.format(filter)
165 resp = self._http.get_cmd('{}{}'.format(self._apiBase,filter_string))
166 if not resp:
167 return list()
168 vim_accounts = []
169 for datacenter in resp:
170 vim_accounts.append({"name": datacenter['name'], "uuid": datacenter['_id']
171 if '_id' in datacenter else None})
172 return vim_accounts
173
174 def get(self, name):
175 """Returns a VIM account based on name or id
176 """
177 vim_id = name
178 if not utils.validate_uuid4(name):
179 vim_id = self.get_id(name)
180 resp = self._http.get_cmd('{}/{}'.format(self._apiBase,vim_id))
181 if not resp or '_id' not in resp:
182 raise ClientException('failed to get vim info: '.format(
183 resp))
184 else:
185 return resp
186 raise NotFound("vim {} not found".format(name))
187