Support of WIM accounts in osmclient
[osm/osmclient.git] / osmclient / sol005 / wim.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 wim 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 Wim(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 = '/wim_accounts'
35 self._apiBase = '{}{}{}'.format(self._apiName,
36 self._apiVersion, self._apiResource)
37 def create(self, name, wim_input, wim_port_mapping=None):
38 if 'wim_type' not in wim_input:
39 raise Exception("wim type not provided")
40
41 wim_account = wim_input
42 wim_account["name"] = name
43
44 wim_config = {}
45 if 'config' in wim_input and wim_input['config'] is not None:
46 wim_config = yaml.safe_load(wim_input['config'])
47 if wim_port_mapping:
48 with open(wim_port_mapping, 'r') as f:
49 wim_config['wim_port_mapping'] = yaml.safe_load(f.read())
50 if wim_config:
51 wim_account['config'] = wim_config
52 #wim_account['config'] = json.dumps(wim_config)
53
54 http_code, resp = self._http.post_cmd(endpoint=self._apiBase,
55 postfields_dict=wim_account)
56 #print 'HTTP CODE: {}'.format(http_code)
57 #print 'RESP: {}'.format(resp)
58 if http_code in (200, 201, 202, 204):
59 if resp:
60 resp = json.loads(resp)
61 if not resp or 'id' not in resp:
62 raise ClientException('unexpected response from server - {}'.format(
63 resp))
64 print(resp['id'])
65 else:
66 msg = ""
67 if resp:
68 try:
69 msg = json.loads(resp)
70 except ValueError:
71 msg = resp
72 raise ClientException("failed to create wim {} - {}".format(name, msg))
73
74 def update(self, wim_name, wim_account, wim_port_mapping=None):
75 wim = self.get(wim_name)
76
77 wim_config = {}
78 if 'config' in wim_account:
79 if wim_account.get('config')=="" and (wim_port_mapping):
80 raise ClientException("clearing config is incompatible with updating SDN info")
81 if wim_account.get('config')=="":
82 wim_config = None
83 else:
84 wim_config = yaml.safe_load(wim_account['config'])
85 if wim_port_mapping:
86 with open(wim_port_mapping, 'r') as f:
87 wim_config['wim_port_mapping'] = yaml.safe_load(f.read())
88 wim_account['config'] = wim_config
89 #wim_account['config'] = json.dumps(wim_config)
90 http_code, resp = self._http.put_cmd(endpoint='{}/{}'.format(self._apiBase,wim['_id']),
91 postfields_dict=wim_account)
92 #print 'HTTP CODE: {}'.format(http_code)
93 #print 'RESP: {}'.format(resp)
94 if http_code in (200, 201, 202, 204):
95 pass
96 else:
97 msg = ""
98 if resp:
99 try:
100 msg = json.loads(resp)
101 except ValueError:
102 msg = resp
103 raise ClientException("failed to update wim {} - {}".format(wim_name, msg))
104
105 def update_wim_account_dict(self, wim_account, wim_input):
106 print (wim_input)
107 wim_account['wim_type'] = wim_input['wim_type']
108 wim_account['description'] = wim_input['description']
109 wim_account['wim_url'] = wim_input['url']
110 wim_account['user'] = wim_input.get('wim-username')
111 wim_account['password'] = wim_input.get('wim-password')
112 return wim_account
113
114 def get_id(self, name):
115 """Returns a VIM id from a VIM name
116 """
117 for wim in self.list():
118 if name == wim['name']:
119 return wim['uuid']
120 raise NotFound("wim {} not found".format(name))
121
122 def delete(self, wim_name, force=False):
123 wim_id = wim_name
124 if not utils.validate_uuid4(wim_name):
125 wim_id = self.get_id(wim_name)
126 querystring = ''
127 if force:
128 querystring = '?FORCE=True'
129 http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
130 wim_id, querystring))
131 #print 'HTTP CODE: {}'.format(http_code)
132 #print 'RESP: {}'.format(resp)
133 if http_code == 202:
134 print('Deletion in progress')
135 elif http_code == 204:
136 print('Deleted')
137 else:
138 msg = ""
139 if resp:
140 try:
141 msg = json.loads(resp)
142 except ValueError:
143 msg = resp
144 raise ClientException("failed to delete wim {} - {}".format(wim_name, msg))
145
146 def list(self, filter=None):
147 """Returns a list of VIM accounts
148 """
149 filter_string = ''
150 if filter:
151 filter_string = '?{}'.format(filter)
152 resp = self._http.get_cmd('{}{}'.format(self._apiBase,filter_string))
153 if not resp:
154 return list()
155 wim_accounts = []
156 for datacenter in resp:
157 wim_accounts.append({"name": datacenter['name'], "uuid": datacenter['_id']
158 if '_id' in datacenter else None})
159 return wim_accounts
160
161 def get(self, name):
162 """Returns a VIM account based on name or id
163 """
164 wim_id = name
165 if not utils.validate_uuid4(name):
166 wim_id = self.get_id(name)
167 resp = self._http.get_cmd('{}/{}'.format(self._apiBase,wim_id))
168 if not resp or '_id' not in resp:
169 raise ClientException('failed to get wim info: '.format(
170 resp))
171 else:
172 return resp
173 raise NotFound("wim {} not found".format(name))
174