Capability to upload a package from a source folder
[osm/osmclient.git] / osmclient / sol005 / vnfd.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 vnfd 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 Vnfd(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 = '/vnfpkgm'
39 self._apiVersion = '/v1'
40 self._apiResource = '/vnf_packages'
41 self._apiBase = '{}{}{}'.format(self._apiName,
42 self._apiVersion, self._apiResource)
43 #self._apiBase='/vnfds'
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 if resp:
53 return json.loads(resp)
54 return list()
55
56 def get(self, name):
57 self._logger.debug("")
58 self._client.get_token()
59 if utils.validate_uuid4(name):
60 for vnfd in self.list():
61 if name == vnfd['_id']:
62 return vnfd
63 else:
64 for vnfd in self.list():
65 if 'name' in vnfd and name == vnfd['name']:
66 return vnfd
67 raise NotFound("vnfd {} not found".format(name))
68
69 def get_individual(self, name):
70 self._logger.debug("")
71 vnfd = self.get(name)
72 # It is redundant, since the previous one already gets the whole vnfpkginfo
73 # The only difference is that a different primitive is exercised
74 try:
75 _, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase, vnfd['_id']))
76 #print(yaml.safe_dump(resp))
77 if resp:
78 return json.loads(resp)
79 except NotFound:
80 raise NotFound("vnfd '{}' not found".format(name))
81 raise NotFound("vnfd '{}' not found".format(name))
82
83 def get_thing(self, name, thing, filename):
84 self._logger.debug("")
85 vnfd = self.get(name)
86 headers = self._client._headers
87 headers['Accept'] = 'application/binary'
88 http_code, resp = self._http.get2_cmd('{}/{}/{}'.format(self._apiBase, vnfd['_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, 'vnfd', 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 self._client.get_token()
119 vnfd = self.get(name)
120 querystring = ''
121 if force:
122 querystring = '?FORCE=True'
123 http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
124 vnfd['_id'], querystring))
125 #print('HTTP CODE: {}'.format(http_code))
126 #print('RESP: {}'.format(resp))
127 if http_code == 202:
128 print('Deletion in progress')
129 elif http_code == 204:
130 print('Deleted')
131 else:
132 msg = resp or ""
133 # if resp:
134 # try:
135 # msg = json.loads(resp)
136 # except ValueError:
137 # msg = resp
138 raise ClientException("failed to delete vnfd {} - {}".format(name, msg))
139
140 def create(self, filename, overwrite=None, update_endpoint=None, skip_charm_build=False):
141 self._logger.debug("")
142 if os.path.isdir(filename):
143 filename = filename.rstrip('/')
144 filename = self._client.package_tool.build(filename, skip_validation=False, skip_charm_build=skip_charm_build)
145 self.create(filename, overwrite=overwrite, update_endpoint=update_endpoint)
146 else:
147 self._client.get_token()
148 mime_type = magic.from_file(filename, mime=True)
149 if mime_type is None:
150 raise ClientException(
151 "Unexpected MIME type for file {}: MIME type {}".format(
152 filename, mime_type)
153 )
154 headers= self._client._headers
155 headers['Content-Filename'] = basename(filename)
156 if mime_type in ['application/yaml', 'text/plain', 'application/json']:
157 headers['Content-Type'] = 'text/plain'
158 elif mime_type in ['application/gzip', 'application/x-gzip']:
159 headers['Content-Type'] = 'application/gzip'
160 #headers['Content-Type'] = 'application/binary'
161 # Next three lines are to be removed in next version
162 #headers['Content-Filename'] = basename(filename)
163 #file_size = stat(filename).st_size
164 #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
165 else:
166 raise ClientException(
167 "Unexpected MIME type for file {}: MIME type {}".format(
168 filename, mime_type)
169 )
170 headers["Content-File-MD5"] = utils.md5(filename)
171 http_header = ['{}: {}'.format(key,val)
172 for (key,val) in list(headers.items())]
173 self._http.set_http_header(http_header)
174 if update_endpoint:
175 http_code, resp = self._http.put_cmd(endpoint=update_endpoint, filename=filename)
176 else:
177 ow_string = ''
178 if overwrite:
179 ow_string = '?{}'.format(overwrite)
180 self._apiResource = '/vnf_packages_content'
181 self._apiBase = '{}{}{}'.format(self._apiName,
182 self._apiVersion, self._apiResource)
183 endpoint = '{}{}'.format(self._apiBase,ow_string)
184 http_code, resp = self._http.post_cmd(endpoint=endpoint, filename=filename)
185 #print('HTTP CODE: {}'.format(http_code))
186 #print('RESP: {}'.format(resp))
187 if http_code in (200, 201, 202):
188 if resp:
189 resp = json.loads(resp)
190 if not resp or 'id' not in resp:
191 raise ClientException('unexpected response from server: '.format(resp))
192 print(resp['id'])
193 elif http_code == 204:
194 print('Updated')
195 # else:
196 # msg = "Error {}".format(http_code)
197 # if resp:
198 # try:
199 # msg = "{} - {}".format(msg, json.loads(resp))
200 # except ValueError:
201 # msg = "{} - {}".format(msg, resp)
202 # raise ClientException("failed to create/update vnfd - {}".format(msg))
203
204 def update(self, name, filename):
205 self._logger.debug("")
206 self._client.get_token()
207 vnfd = self.get(name)
208 endpoint = '{}/{}/package_content'.format(self._apiBase, vnfd['_id'])
209 self.create(filename=filename, update_endpoint=endpoint)
210