a2a19028595aa473d9fd8d0027400abd3c08fa3f
[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.exceptions import OsmHttpException
24 from osmclient.common import utils
25 import json
26 import magic
27 from os.path import basename
28 import logging
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 nsd = self.get(name)
74 # It is redundant, since the previous one already gets the whole nsdinfo
75 # The only difference is that a different primitive is exercised
76 _, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase, nsd['_id']))
77 #print(yaml.safe_dump(resp))
78 if resp:
79 return json.loads(resp)
80 raise NotFound("nsd {} not found".format(name))
81
82 def get_thing(self, name, thing, filename):
83 self._logger.debug("")
84 # Call to get_token not required, because will be implicitly called by get.
85 nsd = self.get(name)
86 headers = self._client._headers
87 headers['Accept'] = 'application/binary'
88 http_code, resp = self._http.get2_cmd('{}/{}/{}'.format(self._apiBase, nsd['_id'], thing))
89 #print('HTTP CODE: {}'.format(http_code))
90 #print('RESP: {}'.format(resp))
91 #if http_code in (200, 201, 202, 204):
92 if resp:
93 #store in a file
94 return json.loads(resp)
95 #else:
96 # msg = ""
97 # if resp:
98 # try:
99 # msg = json.loads(resp)
100 # except ValueError:
101 # msg = resp
102 # raise ClientException("failed to get {} from {} - {}".format(thing, name, msg))
103
104 def get_descriptor(self, name, filename):
105 self._logger.debug("")
106 self.get_thing(name, 'nsd', filename)
107
108 def get_package(self, name, filename):
109 self._logger.debug("")
110 self.get_thing(name, 'package_content', filename)
111
112 def get_artifact(self, name, artifact, filename):
113 self._logger.debug("")
114 self.get_thing(name, 'artifacts/{}'.format(artifact), filename)
115
116 def delete(self, name, force=False):
117 self._logger.debug("")
118 nsd = self.get(name)
119 querystring = ''
120 if force:
121 querystring = '?FORCE=True'
122 http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
123 nsd['_id'], querystring))
124 #print('HTTP CODE: {}'.format(http_code))
125 #print('RESP: {}'.format(resp))
126 if http_code == 202:
127 print('Deletion in progress')
128 elif http_code == 204:
129 print('Deleted')
130 else:
131 msg = ""
132 if resp:
133 try:
134 msg = json.loads(resp)
135 except ValueError:
136 msg = resp
137 raise OsmHttpException("failed to delete nsd {} - {}".format(name, msg))
138
139 def create(self, filename, overwrite=None, update_endpoint=None):
140 self._logger.debug("")
141 self._client.get_token()
142 mime_type = magic.from_file(filename, mime=True)
143 if mime_type is None:
144 raise ClientException(
145 "failed to guess MIME type for file '{}'".format(filename))
146 headers= self._client._headers
147 headers['Content-Filename'] = basename(filename)
148 if mime_type in ['application/yaml', 'text/plain', 'application/json']:
149 headers['Content-Type'] = 'text/plain'
150 elif mime_type in ['application/gzip', 'application/x-gzip']:
151 headers['Content-Type'] = 'application/gzip'
152 #headers['Content-Type'] = 'application/binary'
153 # Next three lines are to be removed in next version
154 #headers['Content-Filename'] = basename(filename)
155 #file_size = stat(filename).st_size
156 #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
157 else:
158 raise ClientException(
159 "Unexpected MIME type for file {}: MIME type {}".format(
160 filename, mime_type)
161 )
162 headers["Content-File-MD5"] = utils.md5(filename)
163 http_header = ['{}: {}'.format(key,val)
164 for (key,val) in list(headers.items())]
165 self._http.set_http_header(http_header)
166 if update_endpoint:
167 http_code, resp = self._http.put_cmd(endpoint=update_endpoint, filename=filename)
168 else:
169 ow_string = ''
170 if overwrite:
171 ow_string = '?{}'.format(overwrite)
172 self._apiResource = '/ns_descriptors_content'
173 self._apiBase = '{}{}{}'.format(self._apiName,
174 self._apiVersion, self._apiResource)
175 endpoint = '{}{}'.format(self._apiBase,ow_string)
176 http_code, resp = self._http.post_cmd(endpoint=endpoint, filename=filename)
177 #print('HTTP CODE: {}'.format(http_code))
178 #print('RESP: {}'.format(resp))
179 if http_code in (200, 201, 202):
180 if resp:
181 resp = json.loads(resp)
182 if not resp or 'id' not in resp:
183 raise OsmHttpException('unexpected response from server - {}'.format(resp))
184 print(resp['id'])
185 elif http_code == 204:
186 print('Updated')
187 # else:
188 # msg = "Error {}".format(http_code)
189 # if resp:
190 # try:
191 # msg = "{} - {}".format(msg, json.loads(resp))
192 # except ValueError:
193 # msg = "{} - {}".format(msg, resp)
194 # raise ClientException("failed to create/update nsd - {}".format(msg))
195
196 def update(self, name, filename):
197 self._logger.debug("")
198 nsd = self.get(name)
199 endpoint = '{}/{}/nsd_content'.format(self._apiBase, nsd['_id'])
200 self.create(filename=filename, update_endpoint=endpoint)
201