1 # Copyright (c) 2020 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.
22 from os import rename, mkdir
23 from os.path import join
24 from http.client import responses, IncompleteRead
25 from zipfile import ZipFile, is_zipfile, BadZipfile
29 from requests.adapters import HTTPAdapter, Retry
30 from requests.exceptions import RequestException
31 from requests import codes
33 from pal_errors import PresentationError
36 # Chunk size used for file download
39 # Separator used in file names
42 REGEX_RELEASE = re.compile(r'(\D*)(\d{4}|master)(\D*)')
45 def _download_file(url, file_name, arch=False, verify=True, repeat=1):
46 """Download a file with input data.
48 :param url: URL to the file to download.
49 :param file_name: Name of file to download.
50 :param arch: If True, also .gz file is downloaded.
51 :param verify: If true, verify the certificate.
52 :param repeat: The number of attempts to download the file.
58 :returns: True if the download was successful, otherwise False.
62 def requests_retry_session(retries=3,
64 status_forcelist=(500, 502, 504)):
67 :param retries: Total number of retries to allow.
68 :param backoff_factor: A backoff factor to apply between attempts after
70 :param status_forcelist: A set of integer HTTP status codes that are
73 :type backoff_factor: float
74 :type status_forcelist: iterable
75 :returns: Session object.
76 :rtype: requests.Session
83 backoff_factor=backoff_factor,
84 status_forcelist=status_forcelist,
86 adapter = HTTPAdapter(max_retries=retry)
87 session = requests.Session()
88 session.mount(u"http://", adapter)
89 session.mount(u"https://", adapter)
97 logging.info(f" Connecting to {url} ...")
98 session = requests_retry_session()
99 response = session.get(url, stream=True, verify=verify)
100 code = response.status_code
101 logging.info(f" {code}: {responses[code]}")
103 if code != codes[u"OK"]:
106 url = url.replace(u"_info", u"")
107 logging.info(f" Connecting to {url} ...")
108 session = requests_retry_session()
109 response = session.get(url, stream=True, verify=verify)
110 code = response.status_code
111 logging.info(f" {code}: {responses[code]}")
112 if code != codes[u"OK"]:
113 return False, file_name
114 file_name = file_name.replace(u"_info", u"")
116 dst_file_name = file_name.replace(u".gz", u"")
117 logging.info(f" Downloading the file {url} to {dst_file_name}")
118 with open(dst_file_name, u"wb") as file_handle:
119 for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
121 file_handle.write(chunk)
123 if arch and u".gz" in file_name:
126 logging.info(f" Downloading the file {url} to {file_name}")
127 session = requests_retry_session()
128 response = session.get(url, stream=True, verify=verify)
129 if response.status_code == codes[u"OK"]:
130 with open(file_name, u"wb") as file_handle:
131 file_handle.write(response.raw.read())
134 f"Not possible to download the file "
135 f"{url} to {file_name}"
140 except IncompleteRead as err:
141 logging.error(f"Connection broken:\n{repr(err)}")
142 except RequestException as err:
143 logging.error(f"HTTP Request exception:\n{repr(err)}")
144 except (IOError, ValueError, KeyError) as err:
145 logging.error(f"Download failed.\n{repr(err)}")
150 logging.info(u" Download finished.")
151 return success, file_name
154 def _unzip_file(spec, build, pid):
155 """Unzip downloaded source file.
157 :param spec: Specification read form the specification file.
158 :param build: Information about the build.
159 :type spec: Specification
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 logging.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 f" Renaming the file {join(tmp_dir, data_file)} to {new_name}"
187 rename(join(tmp_dir, data_file), new_name)
188 build[u"file-name"] = new_name
190 except (BadZipfile, RuntimeError) as err:
191 logging.error(f"Failed to unzip the file {file_name}: {repr(err)}.")
193 except OSError as err:
194 logging.error(f"Failed to rename the file {data_file}: {repr(err)}.")
198 def download_and_unzip_data_file(spec, job, build, pid):
199 """Download and unzip a source file.
201 :param spec: Specification read form the specification file.
202 :param job: Name of the Jenkins job.
203 :param build: Information about the build.
204 :param pid: PID of the process executing this method.
205 :type spec: Specification
209 :returns: True if the download was successful, otherwise False.
213 # Try to download .gz from s3_storage
214 file_name = spec.input[u"file-name"]
215 url = u"{0}/{1}".format(
216 spec.environment[u'urls'][u'URL[S3_STORAGE,LOG]'],
217 spec.input[u'download-path'].format(
218 job=job, build=build[u'build'], filename=file_name
222 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
223 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
226 logging.info(f"Trying to download {url}")
228 arch = bool(spec.configuration.get(u"archive-inputs", True))
229 success, downloaded_name = _download_file(
230 url, new_name, arch=arch, verify=False, repeat=3
234 # Try to download .gz from logs.fd.io
235 file_name = spec.input[u"file-name"]
236 url = u"{0}/{1}".format(
237 spec.environment[u'urls'][u'URL[NEXUS,LOG]'],
238 spec.input[u'download-path'].format(
239 job=job, build=build[u'build'], filename=file_name
243 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
244 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
247 logging.info(f"Trying to download {url}")
249 arch = bool(spec.configuration.get(u"archive-inputs", True))
250 success, downloaded_name = _download_file(url, new_name, arch=arch)
254 # Try to download .gz or .zip from docs.fd.io
255 file_name = (spec.input[u"file-name"], spec.input[u"zip-file-name"])
256 release = re.search(REGEX_RELEASE, job).group(2)
257 for idx, rls in enumerate((release, u"master", )):
259 rls = f"rls{int(rls)}"
264 f"{spec.environment[u'urls'][u'URL[NEXUS,DOC]']}/"
266 f"{spec.environment[u'urls'][u'DIR[NEXUS,DOC]']}/"
267 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name[idx]}"
270 logging.info(f"Downloading {url}")
273 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
274 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name[idx]}"
276 success, downloaded_name = _download_file(url, new_name, arch=arch)
278 file_name = file_name[idx]
279 if file_name.endswith(u".gz"):
280 with gzip.open(downloaded_name[:-3], u"rb") as gzip_file:
281 file_content = gzip_file.read()
282 with open(downloaded_name[:-3], u"wb") as xml_file:
283 xml_file.write(file_content)
288 # Try to download .zip from jenkins.fd.io
289 file_name = spec.input[u"zip-file-name"]
290 download_path = spec.input[u"zip-download-path"]
291 if job.startswith(u"csit-"):
292 url = spec.environment[u"urls"][u"URL[JENKINS,CSIT]"]
294 raise PresentationError(f"No url defined for the job {job}.")
296 full_name = download_path.format(
297 job=job, build=build[u"build"], filename=file_name
299 url = u"{0}/{1}".format(url, full_name)
301 spec.environment[u"paths"][u"DIR[WORKING,DATA]"],
302 f"{job}{SEPARATOR}{build[u'build']}{SEPARATOR}{file_name}"
305 logging.info(f"Downloading {url}")
307 success, downloaded_name = _download_file(url, new_name)
309 if success and downloaded_name.endswith(u".zip"):
310 if not is_zipfile(downloaded_name):
311 logging.error(f"Zip file {new_name} is corrupted.")
315 build[u"file-name"] = downloaded_name
317 if file_name.endswith(u".gz"):
318 build[u"file-name"] = downloaded_name[:-3]
320 if downloaded_name.endswith(u".zip"):
321 success = _unzip_file(spec, build, pid)