1ca38641bccdb310d5d1266fcfa76112d9ac4b50
[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.exceptions import NotFound
25 from osmclient.common import utils
26 import json
27 import logging
28
29
30 class Package(object):
31 def __init__(self, http=None, client=None):
32 self._client = client
33 self._http = http
34 self._logger = logging.getLogger('osmclient')
35
36 def get_key_val_from_pkg(self, descriptor_file):
37 self._logger.debug("")
38 return utils.get_key_val_from_pkg(descriptor_file)
39
40 def _wait_for_package(self, pkg_type):
41 self._logger.debug("")
42 if 'vnfd' in pkg_type['type']:
43 get_method = self._client.vnfd.get
44 elif 'nsd' in pkg_type['type']:
45 get_method = self._client.nsd.get
46 else:
47 raise ClientException("no valid package type found")
48
49 # helper method to check if pkg exists
50 def check_exists(func):
51 self._logger.debug("")
52 try:
53 func()
54 except NotFound:
55 return False
56 return True
57
58 return utils.wait_for_value(lambda:
59 check_exists(lambda:
60 get_method(pkg_type['name'])))
61
62 def wait_for_upload(self, filename):
63 """wait(block) for an upload to succeed.
64 The filename passed is assumed to be a descriptor tarball.
65 """
66 self._logger.debug("")
67 self._client.get_token()
68 pkg_type = utils.get_key_val_from_pkg(filename)
69
70 if pkg_type is None:
71 raise ClientException("Cannot determine package type")
72
73 if not self._wait_for_package(pkg_type):
74 raise ClientException("package {} failed to upload"
75 .format(filename))
76
77 def upload(self, filename):
78 self._logger.debug("")
79 self._client.get_token()
80 pkg_type = utils.get_key_val_from_pkg(filename)
81 if pkg_type is None:
82 raise ClientException("Cannot determine package type")
83 if pkg_type['type'] == 'nsd':
84 endpoint = '/nsd/v1/ns_descriptors_content'
85 else:
86 endpoint = '/vnfpkgm/v1/vnf_packages_content'
87 #endpoint = '/nsds' if pkg_type['type'] == 'nsd' else '/vnfds'
88 #print('Endpoint: {}'.format(endpoint))
89 headers = self._client._headers
90 headers['Content-Type'] = 'application/gzip'
91 #headers['Content-Type'] = 'application/binary'
92 # Next three lines are to be removed in next version
93 #headers['Content-Filename'] = basename(filename)
94 #file_size = stat(filename).st_size
95 #headers['Content-Range'] = 'bytes 0-{}/{}'.format(file_size - 1, file_size)
96 headers["Content-File-MD5"] = utils.md5(filename)
97 http_header = ['{}: {}'.format(key,val)
98 for (key,val) in list(headers.items())]
99 self._http.set_http_header(http_header)
100 http_code, resp = self._http.post_cmd(endpoint=endpoint, filename=filename)
101 #print('HTTP CODE: {}'.format(http_code))
102 #print('RESP: {}'.format(resp))
103 #if http_code in (200, 201, 202, 204):
104 if resp:
105 resp = json.loads(resp)
106 if not resp or 'id' not in resp:
107 raise ClientException('unexpected response from server - {}'.format(
108 resp))
109 print(resp['id'])
110 # else:
111 # msg = ""
112 # if resp:
113 # try:
114 # msg = json.loads(resp)
115 # except ValueError:
116 # msg = resp
117 # raise ClientException("failed to upload package - {}".format(msg))