1 # Copyright (c) 2018 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.
21 from os import rename, mkdir
22 from os.path import join
23 from http.client import responses
24 from zipfile import ZipFile, is_zipfile, BadZipfile
28 from requests.adapters import HTTPAdapter, Retry
29 from requests.exceptions import RequestException
30 from requests import codes
32 from pal_errors import PresentationError
35 # Chunk size used for file download
38 # Separator used in file names
41 REGEX_RELEASE = re.compile(r'(\D*)(\d{4}|master)(\D*)')
44 def _download_file(url, file_name, log, arch=False):
45 """Download a file with input data.
47 :param url: URL to the file to download.
48 :param file_name: Name of file to download.
49 :param log: List of log messages.
50 :param arch: If True, also .gz file is downloaded
53 :type log: list of tuples (severity, msg)
55 :returns: True if the download was successful, otherwise False.
59 def requests_retry_session(retries=3,
61 status_forcelist=(500, 502, 504)):
64 :param retries: Total number of retries to allow.
65 :param backoff_factor: A backoff factor to apply between attempts after
67 :param status_forcelist: A set of integer HTTP status codes that are
70 :type backoff_factor: float
71 :type status_forcelist: iterable
72 :returns: Session object.
73 :rtype: requests.Session
80 backoff_factor=backoff_factor,
81 status_forcelist=status_forcelist,
83 adapter = HTTPAdapter(max_retries=retry)
84 session = requests.Session()
85 session.mount(u"http://", adapter)
86 session.mount(u"https://", adapter)
92 log.append((u"INFO", f" Connecting to {url} ..."))
93 session = requests_retry_session()
94 response = session.get(url, stream=True)
95 code = response.status_code
96 log.append((u"INFO", f" {code}: {responses[code]}"))
98 if code != codes[u"OK"]:
101 url = url.replace(u"_info", u"")
102 log.append((u"INFO", f" Connecting to {url} ..."))
103 session = requests_retry_session()
104 response = session.get(url, stream=True)
105 code = response.status_code
106 log.append((u"INFO", f" {code}: {responses[code]}"))
107 if code != codes[u"OK"]:
108 return False, file_name
109 file_name = file_name.replace(u"_info", u"")
111 dst_file_name = file_name.replace(u".gz", u"")
113 (u"INFO", f" Downloading the file {url} to {dst_file_name} ...")
115 with open(dst_file_name, u"wb") as file_handle:
116 for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
118 file_handle.write(chunk)
120 if arch and u".gz" in file_name:
124 (u"INFO", f" Downloading the file {url} to {file_name} ...")
126 session = requests_retry_session()
127 response = session.get(url, stream=True)
128 if response.status_code == codes[u"OK"]:
129 with open(file_name, u"wb") as file_handle:
130 file_handle.write(response.raw.read())
133 (u"ERROR", f"Not possible to download the file {url} to "
138 except RequestException as err:
140 (u"ERROR", f"HTTP Request exception:\n{repr(err)}")
142 except (IOError, ValueError, KeyError) as err:
143 log.append((u"ERROR", f"Download failed.\n{repr(err)}"))
148 log.append((u"INFO", u" Download finished."))
149 return success, file_name
152 def _unzip_file(spec, build, pid, log):
153 """Unzip downloaded source file.
155 :param spec: Specification read form the specification file.
156 :param build: Information about the build.
157 :param log: List of log messages.
158 :type spec: Specification
160 :type log: list of tuples (severity, msg)
161 :returns: True if the download was successful, otherwise False.
165 file_name = build[u"file-name"]
166 if u".zip" in file_name:
167 data_file = spec.input[u"zip-extract"]
169 data_file = spec.input[u"extract"]
171 directory = spec.environment[u"paths"][u"DIR[WORKING,DATA]"]
172 tmp_dir = join(directory, str(pid))
178 f"{file_name.rsplit(u'.')[-2]}{SEPARATOR}{data_file.split(u'/')[-1]}"
180 log.append((u"INFO", f" Unzipping: {data_file} from {file_name}."))
182 with ZipFile(file_name, u'r') as zip_file:
183 zip_file.extract(data_file, tmp_dir)
185 (u"INFO", f" Renaming the file {join(tmp_dir, data_file)} to "
188 rename(join(tmp_dir, data_file), new_name)
189 build[u"file-name"] = new_name
191 except (BadZipfile, RuntimeError) as err:
193 (u"ERROR", f"Failed to unzip the file {file_name}: {repr(err)}.")
196 except OSError as err:
198 (u"ERROR", f"Failed to rename the file {data_file}: {repr(err)}.")
203 def download_and_unzip_data_file(spec, job, build, pid, log):
204 """Download and unzip a source file.
206 :param spec: Specification read form the specification file.
207 :param job: Name of the Jenkins job.
208 :param build: Information about the build.
209 :param pid: PID of the process executing this method.
210 :param log: List of log messages.
211 :type spec: Specification
215 :type log: list of tuples (severity, msg)
216 :returns: True if the download was successful, otherwise False.
220 # Try to download .gz from logs.fd.io
222 file_name = spec.input[u"file-name"]
223 url = u"{0}/{1}".format(
224 spec.environment[u'urls'][u'URL[NEXUS,LOG]'],
225 spec.input[u'download-path'].format(
226 job=job, build=build[u'build'], filename=file_name
230 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
231 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
234 logging.info(f"Trying to download {url}")
236 arch = bool(spec.configuration.get(u"archive-inputs", True))
237 success, downloaded_name = _download_file(url, new_name, log, arch=arch)
241 # Try to download .gz from docs.fd.io
243 file_name = spec.input[u"file-name"]
244 url = u"{0}/{1}".format(
245 spec.environment[u"urls"][u"URL[NEXUS,DOC]"],
246 spec.input[u"download-path"].format(
247 job=job, build=build[u"build"], filename=file_name
251 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
252 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
255 logging.info(f"Downloading {url}")
257 success, downloaded_name = _download_file(url, new_name, log, arch=arch)
261 # Try to download .zip from docs.fd.io
263 file_name = spec.input[u"zip-file-name"]
265 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
266 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
268 release = re.search(REGEX_RELEASE, job).group(2)
269 for rls in (release, u"master"):
271 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
273 rls = f"rls{int(rls)}"
278 f"{spec.environment[u'urls'][u'URL[NEXUS,DOC]']}/"
280 f"{spec.environment[u'urls'][u'DIR[NEXUS,DOC]']}/"
284 logging.info(f"Downloading {url}")
286 success, downloaded_name = _download_file(url, new_name, log)
292 # Try to download .zip from jenkins.fd.io
294 file_name = spec.input[u"zip-file-name"]
295 download_path = spec.input[u"zip-download-path"]
296 if job.startswith(u"csit-"):
297 url = spec.environment[u"urls"][u"URL[JENKINS,CSIT]"]
298 elif job.startswith(u"hc2vpp-"):
299 url = spec.environment[u"urls"][u"URL[JENKINS,HC]"]
301 raise PresentationError(f"No url defined for the job {job}.")
303 full_name = download_path.format(
304 job=job, build=build[u"build"], filename=file_name
306 url = u"{0}/{1}".format(url, full_name)
308 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
309 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
312 logging.info(f"Downloading {url}")
314 success, downloaded_name = _download_file(url, new_name, log)
316 if success and downloaded_name.endswith(u".zip"):
317 if not is_zipfile(downloaded_name):
318 log.append((u"ERROR", f"Zip file {new_name} is corrupted."))
322 build[u"file-name"] = downloaded_name
324 if file_name.endswith(u".gz"):
325 build[u"file-name"] = downloaded_name[:-3]
327 if downloaded_name.endswith(u".zip"):
328 success = _unzip_file(spec, build, pid, log)