Fix bug 2373 - Remove old code from v1 client in ns_show
[osm/osmclient.git] / osmclient / sol005 / nst.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 NST (Network Slice Template) API handling
19 """
20
21 from osmclient.common.exceptions import NotFound
22 from osmclient.common.exceptions import ClientException
23 from osmclient.common import utils
24 import json
25 import magic
26 import logging
27 import os.path
28
29 # from os import stat
30 # from os.path import basename
31
32
33 class Nst(object):
34 def __init__(self, http=None, client=None):
35 self._http = http
36 self._client = client
37 self._logger = logging.getLogger("osmclient")
38 self._apiName = "/nst"
39 self._apiVersion = "/v1"
40 self._apiResource = "/netslice_templates"
41 self._apiBase = "{}{}{}".format(
42 self._apiName, self._apiVersion, self._apiResource
43 )
44
45 def list(self, filter=None):
46 self._logger.debug("")
47 self._client.get_token()
48 filter_string = ""
49 if filter:
50 filter_string = "?{}".format(filter)
51 _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
52 # print(yaml.safe_dump(resp))
53 if resp:
54 return json.loads(resp)
55 return list()
56
57 def get(self, name):
58 self._logger.debug("")
59 self._client.get_token()
60 if utils.validate_uuid4(name):
61 for nst in self.list():
62 if name == nst["_id"]:
63 return nst
64 else:
65 for nst in self.list():
66 if "name" in nst and name == nst["name"]:
67 return nst
68 raise NotFound("nst {} not found".format(name))
69
70 def get_individual(self, name):
71 self._logger.debug("")
72 nst = self.get(name)
73 # It is redundant, since the previous one already gets the whole nstinfo
74 # The only difference is that a different primitive is exercised
75 try:
76 _, resp = self._http.get2_cmd("{}/{}".format(self._apiBase, nst["_id"]))
77 # print(yaml.safe_dump(resp))
78 if resp:
79 return json.loads(resp)
80 except NotFound:
81 raise NotFound("nst '{}' not found".format(name))
82 raise NotFound("nst '{}' not found".format(name))
83
84 def get_thing(self, name, thing, filename):
85 self._logger.debug("")
86 nst = self.get(name)
87 headers = self._client._headers
88 headers["Accept"] = "application/binary"
89 try:
90 http_code, resp = self._http.get2_cmd(
91 "{}/{}/{}".format(self._apiBase, nst["_id"], thing)
92 )
93 except NotFound:
94 raise NotFound("nst '{} 'not found".format(name))
95 # print('HTTP CODE: {}'.format(http_code))
96 # print('RESP: {}'.format(resp))
97 # if http_code in (200, 201, 202, 204):
98 if resp:
99 # store in a file
100 return json.loads(resp)
101 # else:
102 # msg = ""
103 # if resp:
104 # try:
105 # msg = json.loads(resp)
106 # except ValueError:
107 # msg = resp
108 # raise ClientException("failed to get {} from {} - {}".format(thing, name, msg))
109
110 def get_descriptor(self, name, filename):
111 self._logger.debug("")
112 self.get_thing(name, "nst", filename)
113
114 def get_package(self, name, filename):
115 self._logger.debug("")
116 self.get_thing(name, "nst_content", filename)
117
118 def get_artifact(self, name, artifact, filename):
119 self._logger.debug("")
120 self.get_thing(name, "artifacts/{}".format(artifact), filename)
121
122 def delete(self, name, force=False):
123 self._logger.debug("")
124 nst = self.get(name)
125 querystring = ""
126 if force:
127 querystring = "?FORCE=True"
128 http_code, resp = self._http.delete_cmd(
129 "{}/{}{}".format(self._apiBase, nst["_id"], querystring)
130 )
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 = resp or ""
139 # if resp:
140 # try:
141 # resp = json.loads(resp)
142 # except ValueError:
143 # msg = resp
144 raise ClientException("failed to delete nst {} - {}".format(name, msg))
145
146 def create(self, filename, overwrite=None, update_endpoint=None):
147 self._logger.debug("")
148 if os.path.isdir(filename):
149 charm_folder = filename.rstrip("/")
150 for files in os.listdir(charm_folder):
151 if "nst.yaml" in files:
152 results = self._client.package_tool.validate(
153 charm_folder, recursive=False
154 )
155 for result in results:
156 if result["valid"] != "OK":
157 raise ClientException(
158 "There was an error validating the file: {} "
159 "with error: {}".format(result["path"], result["error"])
160 )
161 result = self._client.package_tool.build(charm_folder)
162 if "Created" in result:
163 filename = "{}.tar.gz".format(charm_folder)
164 else:
165 raise ClientException(
166 "Failed in {}tar.gz creation".format(charm_folder)
167 )
168 self.create(filename, overwrite, update_endpoint)
169 else:
170 self._client.get_token()
171 mime_type = magic.from_file(filename, mime=True)
172 if mime_type is None:
173 raise ClientException(
174 "Unexpected MIME type for file {}: MIME type {}".format(
175 filename, mime_type
176 )
177 )
178 headers = self._client._headers
179 if mime_type in ["application/yaml", "text/plain"]:
180 headers["Content-Type"] = "application/yaml"
181 elif mime_type in ["application/gzip", "application/x-gzip"]:
182 headers["Content-Type"] = "application/gzip"
183 # headers['Content-Type'] = 'application/binary'
184 # Next three lines are to be removed in next version
185 # headers['Content-Filename'] = basename(filename)
186 # file_size = stat(filename).st_size
187 # headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
188 else:
189 raise ClientException(
190 "Unexpected MIME type for file {}: MIME type {}".format(
191 filename, mime_type
192 )
193 )
194 headers["Content-File-MD5"] = utils.md5(filename)
195 self._http.set_http_header(headers)
196 if update_endpoint:
197 http_code, resp = self._http.put_cmd(
198 endpoint=update_endpoint, filename=filename
199 )
200 else:
201 ow_string = ""
202 if overwrite:
203 ow_string = "?{}".format(overwrite)
204 self._apiResource = "/netslice_templates_content"
205 self._apiBase = "{}{}{}".format(
206 self._apiName, self._apiVersion, self._apiResource
207 )
208 endpoint = "{}{}".format(self._apiBase, ow_string)
209 http_code, resp = self._http.post_cmd(
210 endpoint=endpoint, filename=filename
211 )
212 # print('HTTP CODE: {}'.format(http_code))
213 # print('RESP: {}'.format(resp))
214 # if http_code in (200, 201, 202, 204):
215 if resp:
216 resp = json.loads(resp)
217 if not resp or "id" not in resp:
218 raise ClientException(
219 "unexpected response from server - {}".format(resp)
220 )
221 print(resp["id"])
222 # else:
223 # msg = "Error {}".format(http_code)
224 # if resp:
225 # try:
226 # msg = "{} - {}".format(msg, json.loads(resp))
227 # except ValueError:
228 # msg = "{} - {}".format(msg, resp)
229 # raise ClientException("failed to create/update nst - {}".format(msg))
230
231 def update(self, name, filename):
232 self._logger.debug("")
233 nst = self.get(name)
234 endpoint = "{}/{}/nst_content".format(self._apiBase, nst["_id"])
235 self.create(filename=filename, update_endpoint=endpoint)