Sanika Kulkarni | 78dd7f8 | 2021-01-08 11:47:23 -0800 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2021 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """A class that sets up the environment for telemetry testing.""" |
| 6 | |
| 7 | from __future__ import absolute_import |
| 8 | from __future__ import division |
| 9 | from __future__ import print_function |
| 10 | |
| 11 | from autotest_lib.client.common_lib.cros import dev_server |
| 12 | |
| 13 | import contextlib |
| 14 | import errno |
| 15 | import fcntl |
| 16 | import logging |
| 17 | import os |
| 18 | import shutil |
| 19 | import subprocess |
| 20 | import tempfile |
| 21 | |
| 22 | import requests |
| 23 | |
| 24 | _READ_BUFFER_SIZE_BYTES = 1024 * 1024 # 1 MB |
| 25 | |
| 26 | |
| 27 | @contextlib.contextmanager |
| 28 | def lock_dir(dir_name): |
| 29 | """Lock a directory exclusively by placing a file lock in it. |
| 30 | |
| 31 | Args: |
| 32 | dir_name: the directory name to be locked. |
| 33 | """ |
| 34 | lock_file = os.path.join(dir_name, '.lock') |
| 35 | with open(lock_file, 'w+') as f: |
| 36 | fcntl.flock(f, fcntl.LOCK_EX) |
| 37 | try: |
| 38 | yield |
| 39 | finally: |
| 40 | fcntl.flock(f, fcntl.LOCK_UN) |
| 41 | |
| 42 | |
| 43 | class TelemetrySetupError(Exception): |
| 44 | """Exception class used by this module.""" |
| 45 | pass |
| 46 | |
| 47 | |
| 48 | class TelemetrySetup(object): |
| 49 | """Class that sets up the environment for telemetry testing.""" |
| 50 | |
| 51 | # Relevant directory paths. |
| 52 | _BASE_DIR_PATH = '/tmp/telemetry-workdir' |
| 53 | _PARTIAL_DEPENDENCY_DIR_PATH = 'autotest/packages' |
| 54 | |
| 55 | # Relevant directory names. |
| 56 | _TELEMETRY_SRC_DIR_NAME = 'telemetry_src' |
| 57 | _TEST_SRC_DIR_NAME = 'test_src' |
| 58 | _SRC_DIR_NAME = 'src' |
| 59 | |
| 60 | # Names of the telemetry dependency tarballs. |
| 61 | _DEPENDENCIES = [ |
| 62 | 'dep-telemetry_dep.tar.bz2', |
| 63 | 'dep-page_cycler_dep.tar.bz2', |
| 64 | 'dep-chrome_test.tar.bz2', |
| 65 | 'dep-perf_data_dep.tar.bz2', |
| 66 | ] |
| 67 | |
| 68 | # Partial devserver URLs. |
| 69 | _STATIC_URL_TEMPLATE = '%s/static/%s/autotest/packages/%s' |
| 70 | |
| 71 | def __init__(self, build): |
| 72 | """Initializes the TelemetrySetup class. |
| 73 | |
| 74 | Args: |
| 75 | build: The build for which telemetry environment should be setup. It is |
| 76 | typically in the format <board>/<version>. |
| 77 | """ |
| 78 | self._build = build |
| 79 | self._ds = dev_server.ImageServer.resolve(self._build) |
| 80 | self._setup_dir_path = tempfile.mkdtemp(prefix='telemetry-setupdir_') |
| 81 | self._tmp_build_dir = os.path.join(self._BASE_DIR_PATH, self._build) |
| 82 | self._tlm_src_dir_path = os.path.join(self._tmp_build_dir, |
| 83 | self._TELEMETRY_SRC_DIR_NAME) |
| 84 | |
| 85 | def Setup(self): |
| 86 | """Sets up the environment for telemetry testing. |
| 87 | |
| 88 | This method downloads the telemetry dependency tarballs and extracts |
| 89 | them into a 'src' directory. |
| 90 | |
| 91 | Returns: |
| 92 | Path to the src directory where the telemetry dependencies have been |
| 93 | downloaded and extracted. |
| 94 | """ |
| 95 | src_folder = os.path.join(self._tlm_src_dir_path, self._SRC_DIR_NAME) |
| 96 | test_src = os.path.join(self._tlm_src_dir_path, |
| 97 | self._TEST_SRC_DIR_NAME) |
| 98 | self._MkDirP(self._tlm_src_dir_path) |
| 99 | with lock_dir(self._tlm_src_dir_path): |
| 100 | if not os.path.exists(src_folder): |
| 101 | # Download the required dependency tarballs. |
| 102 | for dep in self._DEPENDENCIES: |
| 103 | dep_path = self._DownloadFilesFromDevserver( |
| 104 | dep, self._setup_dir_path) |
| 105 | if os.path.exists(dep_path): |
| 106 | self._ExtractTarball(dep_path, self._tlm_src_dir_path) |
| 107 | |
| 108 | # By default all the tarballs extract to test_src but some parts |
| 109 | # of the telemetry code specifically hardcoded to exist inside |
| 110 | # of 'src'. |
| 111 | try: |
| 112 | shutil.move(test_src, src_folder) |
| 113 | except shutil.Error: |
| 114 | raise TelemetrySetupError( |
| 115 | 'Failure in telemetry setup for build %s. Appears ' |
| 116 | 'that the test_src to src move failed.' % |
| 117 | self._build) |
| 118 | return src_folder |
| 119 | |
| 120 | def _DownloadFilesFromDevserver(self, filename, dest_path): |
| 121 | """Downloads the given tar.bz2 file from the devserver. |
| 122 | |
| 123 | Args: |
| 124 | filename: Name of the tar.bz2 file to be downloaded. |
| 125 | dest_path: Full path to the directory where it should be downloaded. |
| 126 | |
| 127 | Returns: |
| 128 | Full path to the downloaded file. |
| 129 | |
| 130 | Raises: |
| 131 | TelemetrySetupError when the download cannot be completed for any |
| 132 | reason. |
| 133 | """ |
| 134 | dep_path = os.path.join(dest_path, filename) |
| 135 | url = (self._STATIC_URL_TEMPLATE % |
| 136 | (self._ds.url(), self._build, filename)) |
| 137 | resp = requests.get(url) |
| 138 | try: |
| 139 | resp.raise_for_status() |
| 140 | with open(dep_path, 'w') as f: |
| 141 | for content in resp.iter_content(_READ_BUFFER_SIZE_BYTES): |
| 142 | f.write(content) |
| 143 | except Exception as e: |
| 144 | if (isinstance(e, requests.exceptions.HTTPError) |
| 145 | and resp.status_code == 404): |
| 146 | logging.error( |
| 147 | 'The request %s returned a 404 Not Found status.' |
| 148 | 'This dependency could be new and therefore does not ' |
| 149 | 'exist. Hence, squashing the exception and proceeding.', |
| 150 | url) |
| 151 | else: |
| 152 | raise TelemetrySetupError( |
| 153 | 'An error occurred while trying to complete %s: %s' % |
| 154 | (url, e)) |
| 155 | return dep_path |
| 156 | |
| 157 | def _ExtractTarball(self, tarball_path, dest_path): |
| 158 | """Extracts the given tarball into the destination directory. |
| 159 | |
| 160 | Args: |
| 161 | tarball_path: Full path to the tarball to be extracted. |
| 162 | dest_path: Full path to the directory where the tarball should be |
| 163 | extracted. |
| 164 | |
| 165 | Raises: |
| 166 | TelemetrySetupError if the method is unable to extract the tarball for |
| 167 | any reason. |
| 168 | """ |
| 169 | cmd = ['tar', 'xf', tarball_path, '--directory', dest_path] |
| 170 | try: |
| 171 | proc = subprocess.Popen(cmd, |
| 172 | stdout=subprocess.PIPE, |
| 173 | stderr=subprocess.PIPE) |
| 174 | proc.communicate() |
| 175 | except Exception as e: |
| 176 | shutil.rmtree(dest_path) |
| 177 | raise TelemetrySetupError( |
| 178 | 'An exception occurred while trying to untar %s into %s: %s' |
| 179 | % (tarball_path, dest_path, str(e))) |
| 180 | |
| 181 | def _MkDirP(self, path): |
| 182 | """Recursively creates the given directory. |
| 183 | |
| 184 | Args: |
| 185 | path: Full path to the directory that needs to the created. |
| 186 | |
| 187 | Raises: |
| 188 | TelemetrySetupError is the method is unable to create directories for |
| 189 | any reason except OSError EEXIST which indicates that the |
| 190 | directory already exists. |
| 191 | """ |
| 192 | try: |
| 193 | os.makedirs(path) |
| 194 | except Exception as e: |
| 195 | if not isinstance(e, OSError) or e.errno != errno.EEXIST: |
| 196 | raise TelemetrySetupError( |
| 197 | 'Could not create directory %s due to %s.' % |
| 198 | (path, str(e))) |
| 199 | |
| 200 | def Cleanup(self): |
| 201 | """Cleans up telemetry setup and work environment.""" |
| 202 | try: |
| 203 | shutil.rmtree(self._setup_dir_path) |
| 204 | except Exception as e: |
| 205 | logging.error('Something went wrong. Could not delete %s: %s', |
| 206 | self._setup_dir_path, e) |
| 207 | try: |
| 208 | shutil.rmtree(self._tlm_src_dir_path) |
| 209 | except Exception as e: |
| 210 | logging.error('Something went wrong. Could not delete %s: %s', |
| 211 | self._tlm_src_dir_path, e) |