1 # Copyright (c) 2017 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
20 from os import rename, remove
21 from os.path import join, getsize
22 from shutil import move
23 from zipfile import ZipFile, is_zipfile, BadZipfile
24 from httplib import responses
25 from requests import get, codes, RequestException, Timeout, TooManyRedirects, \
26 HTTPError, ConnectionError
28 from errors import PresentationError
31 # Chunk size used for file download
34 # Separator used in file names
38 def download_data_files(spec):
39 """Download all data specified in the specification file in the section
40 type: input --> builds.
42 :param spec: Specification.
43 :type spec: Specification
44 :raises: PresentationError if there is no url defined for the job.
47 for job, builds in spec.builds.items():
49 if job.startswith("csit-"):
50 url = spec.environment["urls"]["URL[JENKINS,CSIT]"]
51 elif job.startswith("hc2vpp-"):
52 url = spec.environment["urls"]["URL[JENKINS,HC]"]
54 raise PresentationError("No url defined for the job '{}'.".
56 file_name = spec.input["file-name"]
57 full_name = spec.input["download-path"].\
58 format(job=job, build=build["build"], filename=file_name)
59 url = "{0}/{1}".format(url, full_name)
61 spec.environment["paths"]["DIR[WORKING,DATA]"],
62 "{job}{sep}{build}{sep}{name}".format(job=job, sep=SEPARATOR,
66 logging.info("Downloading the file '{0}' to '{1}'.".
67 format(url, new_name))
71 response = get(url, stream=True)
72 code = response.status_code
73 if code != codes["OK"]:
74 logging.error("{0}: {1}".format(code, responses[code]))
75 spec.set_input_state(job, build["build"], "not found")
78 file_handle = open(new_name, "wb")
79 for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
81 file_handle.write(chunk)
84 expected_length = None
86 expected_length = int(response.headers["Content-Length"])
87 logging.debug(" Expected file size: {0}B".
88 format(expected_length))
90 logging.debug(" No information about expected size.")
92 real_length = getsize(new_name)
93 logging.debug(" Downloaded size: {0}B".format(real_length))
96 if real_length == expected_length:
98 logging.info("{0}: {1}".format(code, responses[code]))
100 logging.error("The file size differs from the expected "
103 status = "downloaded"
104 logging.info("{0}: {1}".format(code, responses[code]))
106 except ConnectionError as err:
107 logging.error("Not possible to connect to '{0}'.".format(url))
109 except HTTPError as err:
110 logging.error("Invalid HTTP response from '{0}'.".format(url))
112 except TooManyRedirects as err:
113 logging.error("Request exceeded the configured number "
114 "of maximum re-directions.")
116 except Timeout as err:
117 logging.error("Request timed out.")
119 except RequestException as err:
120 logging.error("Unexpected HTTP request exception.")
122 except (IOError, ValueError, KeyError) as err:
123 logging.error("Download failed.")
124 logging.debug("Reason: {0}".format(err))
126 spec.set_input_state(job, build["build"], status)
127 spec.set_input_file_name(job, build["build"], new_name)
129 if status == "failed":
130 logging.info("Removing the file '{0}'".format(new_name))
133 except OSError as err:
134 logging.warning(str(err))
135 spec.set_input_file_name(job, build["build"], None)
140 def unzip_files(spec):
141 """Unzip downloaded zip files
143 :param spec: Specification.
144 :type spec: Specification
145 :raises: PresentationError if the zip file does not exist or it is not a
150 data_file = spec.debug["extract"]
152 data_file = spec.input["extract"]
154 for job, builds in spec.builds.items():
156 if build["status"] == "failed" or build["status"] == "not found":
160 directory = spec.environment["paths"]["DIR[WORKING,DATA]"]
161 file_name = join(build["file-name"])
163 if build["status"] == "downloaded" and is_zipfile(file_name):
164 logging.info("Unziping: '{0}' from '{1}'.".
165 format(data_file, file_name))
166 new_name = "{0}{1}{2}".format(file_name.rsplit('.')[-2],
168 data_file.split("/")[-1])
170 with ZipFile(file_name, 'r') as zip_file:
171 zip_file.extract(data_file, directory)
172 logging.info("Moving {0} to {1} ...".
173 format(join(directory, data_file),
175 move(join(directory, data_file), directory)
176 logging.info("Renaming the file '{0}' to '{1}'".
177 format(join(directory,
178 data_file.split("/")[-1]),
180 rename(join(directory, data_file.split("/")[-1]),
183 spec.set_input_state(job, build["build"], status)
184 spec.set_input_file_name(job, build["build"],
186 except (BadZipfile, RuntimeError) as err:
187 logging.error("Failed to unzip the file '{0}': {1}.".
188 format(file_name, str(err)))
189 except OSError as err:
190 logging.error("Failed to rename the file '{0}': {1}.".
191 format(data_file, str(err)))
193 if status == "failed":
194 spec.set_input_file_name(job, build["build"],
197 raise PresentationError("The file '{0}' does not exist or "
198 "it is not a zip file".
201 spec.set_input_state(job, build["build"], status)