1 # Copyright 2018 Telefonica
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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
18 OSM SDN controller API handling
21 from osmclient
.common
import utils
22 from osmclient
.common
import wait
as WaitForStatus
23 from osmclient
.common
.exceptions
import ClientException
24 from osmclient
.common
.exceptions
import NotFound
30 class SdnController(object):
31 def __init__(self
, http
=None, client
=None):
34 self
._logger
= logging
.getLogger('osmclient')
35 self
._apiName
= '/admin'
36 self
._apiVersion
= '/v1'
37 self
._apiResource
= '/sdns'
38 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
39 self
._apiVersion
, self
._apiResource
)
41 # SDNC '--wait' option
42 def _wait(self
, id, deleteFlag
=False):
43 self
._logger
.debug("")
44 self
._client
.get_token()
45 # Endpoint to get operation status
46 apiUrlStatus
= '{}{}{}'.format(self
._apiName
, self
._apiVersion
, '/sdns')
47 # Wait for status for SDN instance creation/update/deletion
48 WaitForStatus
.wait_for_status(
51 WaitForStatus
.TIMEOUT_SDNC_OPERATION
,
54 deleteFlag
=deleteFlag
)
56 def _get_id_for_wait(self
, name
):
57 """Returns id of name, or the id itself if given as argument
59 self
._logger
.debug("")
60 for sdnc
in self
.list():
61 if name
== sdnc
['_id']:
63 for sdnc
in self
.list():
64 if name
== sdnc
['name']:
68 def create(self
, name
, sdn_controller
, wait
=False):
69 self
._logger
.debug("")
70 if 'config' in sdn_controller
and isinstance(sdn_controller
["config"], str):
71 sdn_controller
["config"] = yaml
.safe_load(sdn_controller
["config"])
72 self
._client
.get_token()
73 http_code
, resp
= self
._http
.post_cmd(endpoint
=self
._apiBase
,
74 postfields_dict
=sdn_controller
)
75 #print('HTTP CODE: {}'.format(http_code))
76 #print('RESP: {}'.format(resp))
77 #if http_code in (200, 201, 202, 204):
79 resp
= json
.loads(resp
)
80 if not resp
or 'id' not in resp
:
81 raise ClientException('unexpected response from server - {}'.format(
84 # Wait for status for SDNC instance creation
85 self
._wait
(resp
.get('id'))
91 # msg = json.loads(resp)
94 # raise ClientException("failed to create SDN controller {} - {}".format(name, msg))
96 def update(self
, name
, sdn_controller
, wait
=False):
97 self
._logger
.debug("")
98 if 'config' in sdn_controller
and isinstance(sdn_controller
["config"], str):
99 sdn_controller
["config"] = yaml
.safe_load(sdn_controller
["config"])
100 self
._client
.get_token()
101 sdnc
= self
.get(name
)
102 sdnc_id_for_wait
= self
._get
_id
_for
_wait
(name
)
103 http_code
, resp
= self
._http
.patch_cmd(endpoint
='{}/{}'.format(self
._apiBase
,sdnc
['_id']),
104 postfields_dict
=sdn_controller
)
105 # print('HTTP CODE: {}'.format(http_code))
106 # print('RESP: {}'.format(resp))
107 #if http_code in (200, 201, 202, 204):
109 # In this case, 'resp' always returns None, so 'resp['id']' cannot be used.
110 # Use the previously obtained id instead.
111 wait_id
= sdnc_id_for_wait
112 # Wait for status for VI instance update
120 # msg = json.loads(resp)
123 # raise ClientException("failed to update SDN controller {} - {}".format(name, msg))
125 def delete(self
, name
, force
=False, wait
=False):
126 self
._logger
.debug("")
127 self
._client
.get_token()
128 sdn_controller
= self
.get(name
)
129 sdnc_id_for_wait
= self
._get
_id
_for
_wait
(name
)
132 querystring
= '?FORCE=True'
133 http_code
, resp
= self
._http
.delete_cmd('{}/{}{}'.format(self
._apiBase
,
134 sdn_controller
['_id'], querystring
))
135 # print('HTTP CODE: {}'.format(http_code))
136 # print('RESP: {}'.format(resp))
139 # Wait for status for SDNC instance deletion
140 self
._wait
(sdnc_id_for_wait
, deleteFlag
=True)
142 print('Deletion in progress')
143 elif http_code
== 204:
145 elif resp
and 'result' in resp
:
151 # msg = json.loads(resp)
154 raise ClientException("failed to delete SDN controller {} - {}".format(name
, msg
))
156 def list(self
, filter=None):
157 """Returns a list of SDN controllers
159 self
._logger
.debug("")
160 self
._client
.get_token()
163 filter_string
= '?{}'.format(filter)
164 _
, resp
= self
._http
.get2_cmd('{}{}'.format(self
._apiBase
,filter_string
))
165 #print('RESP: {}'.format(resp))
167 return json
.loads(resp
)
171 """Returns an SDN controller based on name or id
173 self
._logger
.debug("")
174 self
._client
.get_token()
175 if utils
.validate_uuid4(name
):
176 for sdnc
in self
.list():
177 if name
== sdnc
['_id']:
180 for sdnc
in self
.list():
181 if name
== sdnc
['name']:
183 raise NotFound("SDN controller {} not found".format(name
))