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