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 NST (Network Slice Template) API handling
21 from osmclient
.common
.exceptions
import NotFound
22 from osmclient
.common
.exceptions
import ClientException
23 from osmclient
.common
import utils
30 # from os.path import basename
34 def __init__(self
, http
=None, client
=None):
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
45 def list(self
, filter=None):
46 self
._logger
.debug("")
47 self
._client
.get_token()
50 filter_string
= "?{}".format(filter)
51 _
, resp
= self
._http
.get2_cmd("{}{}".format(self
._apiBase
, filter_string
))
52 # print(yaml.safe_dump(resp))
54 return json
.loads(resp
)
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"]:
65 for nst
in self
.list():
66 if "name" in nst
and name
== nst
["name"]:
68 raise NotFound("nst {} not found".format(name
))
70 def get_individual(self
, name
):
71 self
._logger
.debug("")
73 # It is redundant, since the previous one already gets the whole nstinfo
74 # The only difference is that a different primitive is exercised
76 _
, resp
= self
._http
.get2_cmd("{}/{}".format(self
._apiBase
, nst
["_id"]))
77 # print(yaml.safe_dump(resp))
79 return json
.loads(resp
)
81 raise NotFound("nst '{}' not found".format(name
))
82 raise NotFound("nst '{}' not found".format(name
))
84 def get_thing(self
, name
, thing
, filename
):
85 self
._logger
.debug("")
87 headers
= self
._client
._headers
88 headers
["Accept"] = "application/binary"
90 http_code
, resp
= self
._http
.get2_cmd(
91 "{}/{}/{}".format(self
._apiBase
, nst
["_id"], thing
)
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):
100 return json
.loads(resp
)
105 # msg = json.loads(resp)
108 # raise ClientException("failed to get {} from {} - {}".format(thing, name, msg))
110 def get_descriptor(self
, name
, filename
):
111 self
._logger
.debug("")
112 self
.get_thing(name
, "nst", filename
)
114 def get_package(self
, name
, filename
):
115 self
._logger
.debug("")
116 self
.get_thing(name
, "nst_content", filename
)
118 def get_artifact(self
, name
, artifact
, filename
):
119 self
._logger
.debug("")
120 self
.get_thing(name
, "artifacts/{}".format(artifact
), filename
)
122 def delete(self
, name
, force
=False):
123 self
._logger
.debug("")
127 querystring
= "?FORCE=True"
128 http_code
, resp
= self
._http
.delete_cmd(
129 "{}/{}{}".format(self
._apiBase
, nst
["_id"], querystring
)
131 # print('HTTP CODE: {}'.format(http_code))
132 # print('RESP: {}'.format(resp))
134 print("Deletion in progress")
135 elif http_code
== 204:
141 # resp = json.loads(resp)
144 raise ClientException("failed to delete nst {} - {}".format(name
, msg
))
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
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"])
161 result
= self
._client
.package_tool
.build(charm_folder
)
162 if "Created" in result
:
163 filename
= "{}.tar.gz".format(charm_folder
)
165 raise ClientException(
166 "Failed in {}tar.gz creation".format(charm_folder
)
168 self
.create(filename
, overwrite
, update_endpoint
)
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(
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)
189 raise ClientException(
190 "Unexpected MIME type for file {}: MIME type {}".format(
194 headers
["Content-File-MD5"] = utils
.md5(filename
)
196 "{}: {}".format(key
, val
) for (key
, val
) in list(headers
.items())
198 self
._http
.set_http_header(http_header
)
200 http_code
, resp
= self
._http
.put_cmd(
201 endpoint
=update_endpoint
, filename
=filename
206 ow_string
= "?{}".format(overwrite
)
207 self
._apiResource
= "/netslice_templates_content"
208 self
._apiBase
= "{}{}{}".format(
209 self
._apiName
, self
._apiVersion
, self
._apiResource
211 endpoint
= "{}{}".format(self
._apiBase
, ow_string
)
212 http_code
, resp
= self
._http
.post_cmd(
213 endpoint
=endpoint
, filename
=filename
215 # print('HTTP CODE: {}'.format(http_code))
216 # print('RESP: {}'.format(resp))
217 # if http_code in (200, 201, 202, 204):
219 resp
= json
.loads(resp
)
220 if not resp
or "id" not in resp
:
221 raise ClientException(
222 "unexpected response from server - {}".format(resp
)
226 # msg = "Error {}".format(http_code)
229 # msg = "{} - {}".format(msg, json.loads(resp))
231 # msg = "{} - {}".format(msg, resp)
232 # raise ClientException("failed to create/update nst - {}".format(msg))
234 def update(self
, name
, filename
):
235 self
._logger
.debug("")
237 endpoint
= "{}/{}/nst_content".format(self
._apiBase
, nst
["_id"])
238 self
.create(filename
=filename
, update_endpoint
=endpoint
)