9aca93011bec06a1cf7df34b1a3b22795e11df4e
[osm/osmclient.git] / osmclient / sol005 / nsd.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 nsd 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 from os.path import basename
27 import logging
28 import os.path
29 #from os import stat
30
31
32 class Nsd(object):
33
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 = '/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'
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 nsd in self.list():
62 if name == nsd['_id']:
63 return nsd
64 else:
65 for nsd in self.list():
66 if 'name' in nsd and name == nsd['name']:
67 return nsd
68 raise NotFound("nsd {} not found".format(name))
69
70 def get_individual(self, name):
71 self._logger.debug("")
72 # Call to get_token not required, because will be implicitly called by get.
73 try:
74 nsd = self.get(name)
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))
79 if resp:
80 return json.loads(resp)
81 except NotFound:
82 raise NotFound("nsd '{}' not found".format(name))
83 raise NotFound("nsd '{}' not found".format(name))
84
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.
88 nsd = self.get(name)
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):
95 if resp:
96 #store in a file
97 return json.loads(resp)
98 else:
99 msg = resp or ""
100 # if resp:
101 # try:
102 # msg = json.loads(resp)
103 # except ValueError:
104 # msg = resp
105 raise ClientException("failed to get {} from {} - {}".format(thing, name, msg))
106
107 def get_descriptor(self, name, filename):
108 self._logger.debug("")
109 self.get_thing(name, 'nsd', filename)
110
111 def get_package(self, name, filename):
112 self._logger.debug("")
113 self.get_thing(name, 'package_content', filename)
114
115 def get_artifact(self, name, artifact, filename):
116 self._logger.debug("")
117 self.get_thing(name, 'artifacts/{}'.format(artifact), filename)
118
119 def delete(self, name, force=False):
120 self._logger.debug("")
121 nsd = self.get(name)
122 querystring = ''
123 if force:
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))
129 if http_code == 202:
130 print('Deletion in progress')
131 elif http_code == 204:
132 print('Deleted')
133 else:
134 msg = resp or ""
135 # if resp:
136 # try:
137 # msg = json.loads(resp)
138 # except ValueError:
139 # msg = resp
140 raise ClientException("failed to delete nsd {} - {}".format(name, msg))
141
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)
148 else:
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(
154 filename, mime_type)
155 )
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)
167 else:
168 raise ClientException(
169 "Unexpected MIME type for file {}: MIME type {}".format(
170 filename, mime_type)
171 )
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)
176 if update_endpoint:
177 http_code, resp = self._http.put_cmd(endpoint=update_endpoint, filename=filename)
178 else:
179 ow_string = ''
180 if overwrite:
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):
190 if resp:
191 resp = json.loads(resp)
192 if not resp or 'id' not in resp:
193 raise ClientException('unexpected response from server - {}'.format(resp))
194 print(resp['id'])
195 elif http_code == 204:
196 print('Updated')
197 # else:
198 # msg = "Error {}".format(http_code)
199 # if resp:
200 # try:
201 # msg = "{} - {}".format(msg, json.loads(resp))
202 # except ValueError:
203 # msg = "{} - {}".format(msg, resp)
204 # raise ClientException("failed to create/update nsd - {}".format(msg))
205
206 def update(self, name, filename):
207 self._logger.debug("")
208 nsd = self.get(name)
209 endpoint = '{}/{}/nsd_content'.format(self._apiBase, nsd['_id'])
210 self.create(filename=filename, update_endpoint=endpoint)
211