Code Coverage

Cobertura Coverage Report > osmclient.sol005 >

sdncontroller.py

Trend

File Coverage summary

NameClassesLinesConditionals
sdncontroller.py
100%
1/1
18%
17/94
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
sdncontroller.py
18%
17/94
N/A

Source

osmclient/sol005/sdncontroller.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 1 """
18 OSM SDN controller API handling
19 """
20
21 1 from osmclient.common import utils
22 1 from osmclient.common import wait as WaitForStatus
23 1 from osmclient.common.exceptions import ClientException
24 1 from osmclient.common.exceptions import NotFound
25 1 import json
26 1 import logging
27 1 import yaml
28
29
30 1 class SdnController(object):
31 1     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 = "/sdns"
38 0         self._apiBase = "{}{}{}".format(
39             self._apiName, self._apiVersion, self._apiResource
40         )
41
42     # SDNC '--wait' option
43 1     def _wait(self, id, wait_time, deleteFlag=False):
44 0         self._logger.debug("")
45 0         self._client.get_token()
46         # Endpoint to get operation status
47 0         apiUrlStatus = "{}{}{}".format(self._apiName, self._apiVersion, "/sdns")
48         # Wait for status for SDN instance creation/update/deletion
49 0         if isinstance(wait_time, bool):
50 0             wait_time = WaitForStatus.TIMEOUT_SDNC_OPERATION
51 0         WaitForStatus.wait_for_status(
52             "SDNC",
53             str(id),
54             wait_time,
55             apiUrlStatus,
56             self._http.get2_cmd,
57             deleteFlag=deleteFlag,
58         )
59
60 1     def _get_id_for_wait(self, name):
61         """Returns id of name, or the id itself if given as argument"""
62 0         self._logger.debug("")
63 0         for sdnc in self.list():
64 0             if name == sdnc["_id"] or name == sdnc["name"]:
65 0                 return sdnc["_id"]
66 0         return ""
67
68 1     def create(self, name, sdn_controller, wait=False):
69 0         self._logger.debug("")
70 0         if "config" in sdn_controller and isinstance(sdn_controller["config"], str):
71 0             sdn_controller["config"] = yaml.safe_load(sdn_controller["config"])
72 0         self._client.get_token()
73 0         http_code, resp = self._http.post_cmd(
74             endpoint=self._apiBase, postfields_dict=sdn_controller
75         )
76         # print('HTTP CODE: {}'.format(http_code))
77         # print('RESP: {}'.format(resp))
78         # if http_code in (200, 201, 202, 204):
79 0         if resp:
80 0             resp = json.loads(resp)
81 0         if not resp or "id" not in resp:
82 0             raise ClientException("unexpected response from server - {}".format(resp))
83 0         if wait:
84             # Wait for status for SDNC instance creation
85 0             self._wait(resp.get("id"), wait)
86 0         print(resp["id"])
87         # else:
88         #    msg = ""
89         #    if resp:
90         #        try:
91         #            msg = json.loads(resp)
92         #        except ValueError:
93         #            msg = resp
94         #    raise ClientException("failed to create SDN controller {} - {}".format(name, msg))
95
96 1     def update(self, name, sdn_controller, wait=False):
97 0         self._logger.debug("")
98 0         if "config" in sdn_controller and isinstance(sdn_controller["config"], str):
99 0             sdn_controller["config"] = yaml.safe_load(sdn_controller["config"])
100 0         self._client.get_token()
101 0         sdnc = self.get(name)
102 0         sdnc_id_for_wait = self._get_id_for_wait(name)
103 0         http_code, resp = self._http.patch_cmd(
104             endpoint="{}/{}".format(self._apiBase, sdnc["_id"]),
105             postfields_dict=sdn_controller,
106         )
107         # print('HTTP CODE: {}'.format(http_code))
108         # print('RESP: {}'.format(resp))
109         # if http_code in (200, 201, 202, 204):
110 0         if wait:
111             # In this case, 'resp' always returns None, so 'resp['id']' cannot be used.
112             # Use the previously obtained id instead.
113 0             wait_id = sdnc_id_for_wait
114             # Wait for status for VI instance update
115 0             self._wait(wait_id, wait)
116         # else:
117         #     pass
118         # else:
119         #    msg = ""
120         #    if resp:
121         #        try:
122         #            msg = json.loads(resp)
123         #        except ValueError:
124         #            msg = resp
125         #    raise ClientException("failed to update SDN controller {} - {}".format(name, msg))
126
127 1     def delete(self, name, force=False, wait=False):
128 0         self._logger.debug("")
129 0         self._client.get_token()
130 0         sdn_controller = self.get(name)
131 0         sdnc_id_for_wait = self._get_id_for_wait(name)
132 0         querystring = ""
133 0         if force:
134 0             querystring = "?FORCE=True"
135 0         http_code, resp = self._http.delete_cmd(
136             "{}/{}{}".format(self._apiBase, sdn_controller["_id"], querystring)
137         )
138         # print('HTTP CODE: {}'.format(http_code))
139         # print('RESP: {}'.format(resp))
140 0         if http_code == 202:
141 0             if wait:
142                 # Wait for status for SDNC instance deletion
143 0                 self._wait(sdnc_id_for_wait, wait, deleteFlag=True)
144             else:
145 0                 print("Deletion in progress")
146 0         elif http_code == 204:
147 0             print("Deleted")
148 0         elif resp and "result" in resp:
149 0             print("Deleted")
150         else:
151 0             msg = resp or ""
152             # if resp:
153             #     try:
154             #         msg = json.loads(resp)
155             #     except ValueError:
156             #         msg = resp
157 0             raise ClientException(
158                 "failed to delete SDN controller {} - {}".format(name, msg)
159             )
160
161 1     def list(self, filter=None):
162         """Returns a list of SDN controllers"""
163 0         self._logger.debug("")
164 0         self._client.get_token()
165 0         filter_string = ""
166 0         if filter:
167 0             filter_string = "?{}".format(filter)
168 0         _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
169         # print('RESP: {}'.format(resp))
170 0         if resp:
171 0             return json.loads(resp)
172 0         return list()
173
174 1     def get(self, name):
175         """Returns an SDN controller based on name or id"""
176 0         self._logger.debug("")
177 0         self._client.get_token()
178 0         if utils.validate_uuid4(name):
179 0             for sdnc in self.list():
180 0                 if name == sdnc["_id"]:
181 0                     return sdnc
182         else:
183 0             for sdnc in self.list():
184 0                 if name == sdnc["name"]:
185 0                     return sdnc
186 0         raise NotFound("SDN controller {} not found".format(name))