Fix: Make osmclient Python 3 compatible.
[osm/osmclient.git] / osmclient / sol005 / package.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 package API handling
19 """
20
21 #from os import stat
22 #from os.path import basename
23 from osmclient.common.exceptions import ClientException
24 from osmclient.common import utils
25 import json
26
27
28 class Package(object):
29 def __init__(self, http=None, client=None):
30 self._client = client
31 self._http = http
32
33 def get_key_val_from_pkg(self, descriptor_file):
34 return utils.get_key_val_from_pkg(descriptor_file)
35
36 def upload(self, filename):
37 pkg_type = utils.get_key_val_from_pkg(filename)
38 if pkg_type is None:
39 raise ClientException("Cannot determine package type")
40 if pkg_type['type'] == 'nsd':
41 endpoint = '/nsd/v1/ns_descriptors_content'
42 else:
43 endpoint = '/vnfpkgm/v1/vnf_packages_content'
44 #endpoint = '/nsds' if pkg_type['type'] == 'nsd' else '/vnfds'
45 #print 'Endpoint: {}'.format(endpoint)
46 headers = self._client._headers
47 headers['Content-Type'] = 'application/gzip'
48 #headers['Content-Type'] = 'application/binary'
49 # Next three lines are to be removed in next version
50 #headers['Content-Filename'] = basename(filename)
51 #file_size = stat(filename).st_size
52 #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
53 headers["Content-File-MD5"] = utils.md5(filename)
54 http_header = ['{}: {}'.format(key,val)
55 for (key,val) in list(headers.items())]
56 self._http.set_http_header(http_header)
57 http_code, resp = self._http.post_cmd(endpoint=endpoint, filename=filename)
58 #print 'HTTP CODE: {}'.format(http_code)
59 #print 'RESP: {}'.format(resp)
60 if http_code in (200, 201, 202, 204):
61 if resp:
62 resp = json.loads(resp)
63 if not resp or 'id' not in resp:
64 raise ClientException('unexpected response from server - {}'.format(
65 resp))
66 print(resp['id'])
67 else:
68 msg = ""
69 if resp:
70 try:
71 msg = json.loads(resp)
72 except ValueError:
73 msg = resp
74 raise ClientException("failed to upload package - {}".format(msg))
75