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
21 from osmclient
.common
.exceptions
import NotFound
22 from osmclient
.common
.exceptions
import ClientException
23 from osmclient
.common
import utils
26 from os
.path
import basename
34 def __init__(self
, http
=None, client
=None):
37 self
._logger
= logging
.getLogger('osmclient')
38 self
._apiName
= '/nsd'
39 self
._apiVersion
= '/v1'
40 self
._apiResource
= '/ns_descriptors'
41 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
42 self
._apiVersion
, self
._apiResource
)
43 #self._apiBase='/nsds'
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 nsd
in self
.list():
62 if name
== nsd
['_id']:
65 for nsd
in self
.list():
66 if 'name' in nsd
and name
== nsd
['name']:
68 raise NotFound("nsd {} not found".format(name
))
70 def get_individual(self
, name
):
71 self
._logger
.debug("")
72 # Call to get_token not required, because will be implicitly called by get.
75 # It is redundant, since the previous one already gets the whole nsdinfo
76 # The only difference is that a different primitive is exercised
77 _
, resp
= self
._http
.get2_cmd('{}/{}'.format(self
._apiBase
, nsd
['_id']))
78 #print(yaml.safe_dump(resp))
80 return json
.loads(resp
)
82 raise NotFound("nsd '{}' not found".format(name
))
83 raise NotFound("nsd '{}' not found".format(name
))
85 def get_thing(self
, name
, thing
, filename
):
86 self
._logger
.debug("")
87 # Call to get_token not required, because will be implicitly called by get.
89 headers
= self
._client
._headers
90 headers
['Accept'] = 'application/binary'
91 http_code
, resp
= self
._http
.get2_cmd('{}/{}/{}'.format(self
._apiBase
, nsd
['_id'], thing
))
92 #print('HTTP CODE: {}'.format(http_code))
93 #print('RESP: {}'.format(resp))
94 #if http_code in (200, 201, 202, 204):
97 return json
.loads(resp
)
102 # msg = json.loads(resp)
105 raise ClientException("failed to get {} from {} - {}".format(thing
, name
, msg
))
107 def get_descriptor(self
, name
, filename
):
108 self
._logger
.debug("")
109 self
.get_thing(name
, 'nsd', filename
)
111 def get_package(self
, name
, filename
):
112 self
._logger
.debug("")
113 self
.get_thing(name
, 'package_content', filename
)
115 def get_artifact(self
, name
, artifact
, filename
):
116 self
._logger
.debug("")
117 self
.get_thing(name
, 'artifacts/{}'.format(artifact
), filename
)
119 def delete(self
, name
, force
=False):
120 self
._logger
.debug("")
124 querystring
= '?FORCE=True'
125 http_code
, resp
= self
._http
.delete_cmd('{}/{}{}'.format(self
._apiBase
,
126 nsd
['_id'], querystring
))
127 #print('HTTP CODE: {}'.format(http_code))
128 #print('RESP: {}'.format(resp))
130 print('Deletion in progress')
131 elif http_code
== 204:
137 # msg = json.loads(resp)
140 raise ClientException("failed to delete nsd {} - {}".format(name
, msg
))
142 def create(self
, filename
, overwrite
=None, update_endpoint
=None, skip_charm_build
=False):
143 self
._logger
.debug("")
144 if os
.path
.isdir(filename
):
145 filename
= filename
.rstrip('/')
146 filename
= self
._client
.package_tool
.build(filename
, skip_validation
=False, skip_charm_build
=skip_charm_build
)
147 self
.create(filename
, overwrite
=overwrite
, update_endpoint
=update_endpoint
)
149 self
._client
.get_token()
150 mime_type
= magic
.from_file(filename
, mime
=True)
151 if mime_type
is None:
152 raise ClientException(
153 "Unexpected MIME type for file {}: MIME type {}".format(
156 headers
= self
._client
._headers
157 headers
['Content-Filename'] = basename(filename
)
158 if mime_type
in ['application/yaml', 'text/plain', 'application/json']:
159 headers
['Content-Type'] = 'text/plain'
160 elif mime_type
in ['application/gzip', 'application/x-gzip']:
161 headers
['Content-Type'] = 'application/gzip'
162 #headers['Content-Type'] = 'application/binary'
163 # Next three lines are to be removed in next version
164 #headers['Content-Filename'] = basename(filename)
165 #file_size = stat(filename).st_size
166 #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
168 raise ClientException(
169 "Unexpected MIME type for file {}: MIME type {}".format(
172 headers
["Content-File-MD5"] = utils
.md5(filename
)
173 http_header
= ['{}: {}'.format(key
,val
)
174 for (key
,val
) in list(headers
.items())]
175 self
._http
.set_http_header(http_header
)
177 http_code
, resp
= self
._http
.put_cmd(endpoint
=update_endpoint
, filename
=filename
)
181 ow_string
= '?{}'.format(overwrite
)
182 self
._apiResource
= '/ns_descriptors_content'
183 self
._apiBase
= '{}{}{}'.format(self
._apiName
,
184 self
._apiVersion
, self
._apiResource
)
185 endpoint
= '{}{}'.format(self
._apiBase
,ow_string
)
186 http_code
, resp
= self
._http
.post_cmd(endpoint
=endpoint
, filename
=filename
)
187 #print('HTTP CODE: {}'.format(http_code))
188 #print('RESP: {}'.format(resp))
189 if http_code
in (200, 201, 202):
191 resp
= json
.loads(resp
)
192 if not resp
or 'id' not in resp
:
193 raise ClientException('unexpected response from server - {}'.format(resp
))
195 elif http_code
== 204:
198 # msg = "Error {}".format(http_code)
201 # msg = "{} - {}".format(msg, json.loads(resp))
203 # msg = "{} - {}".format(msg, resp)
204 # raise ClientException("failed to create/update nsd - {}".format(msg))
206 def update(self
, name
, filename
):
207 self
._logger
.debug("")
209 endpoint
= '{}/{}/nsd_content'.format(self
._apiBase
, nsd
['_id'])
210 self
.create(filename
=filename
, update_endpoint
=endpoint
)