blob: f920364f9761f8e6f50705d75ece084dc7ff2225 [file] [log] [blame]
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -07001# -*- coding: utf-8 -*-
2# Copyright 2020 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
6"""A class that sets up the environment for telemetry testing."""
7
8
9from __future__ import absolute_import
10from __future__ import division
11from __future__ import print_function
12
Congbin Guo36914412020-07-31 14:13:53 -070013import contextlib
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070014import errno
Congbin Guo36914412020-07-31 14:13:53 -070015import fcntl
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070016import os
17import shutil
18import subprocess
19import tempfile
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070020
21import requests
22
23import cherrypy # pylint: disable=import-error
24
Congbin Guo36914412020-07-31 14:13:53 -070025import constants
26
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070027from chromite.lib import cros_logging as logging
28
29
30# Define module logger.
31_logger = logging.getLogger(__file__)
32
33# Define all GS Cache related constants.
34GS_CACHE_HOSTNAME = '127.0.0.1'
35GS_CACHE_PORT = '8888'
36GS_CACHE_EXRTACT_RPC = 'extract'
37GS_CACHE_BASE_URL = ('http://%s:%s/%s' %
38 (GS_CACHE_HOSTNAME, GS_CACHE_PORT, GS_CACHE_EXRTACT_RPC))
39
40
41def _log(*args, **kwargs):
42 """A wrapper function of logging.debug/info, etc."""
43 level = kwargs.pop('level', logging.DEBUG)
44 _logger.log(level, extra=cherrypy.request.headers, *args, **kwargs)
45
46
47def _GetBucketAndBuild(archive_url):
48 """Gets the build name from the archive_url.
49
50 Args:
51 archive_url: The archive_url is typically in the format
52 gs://<gs_bucket>/<build_name>. Deduce the bucket and build name from
53 this URL by splitting at the appropriate '/'.
54
55 Returns:
56 Name of the GS bucket as a string.
57 Name of the build as a string.
58 """
59 clean_url = archive_url.strip('gs://')
60 parts = clean_url.split('/')
61 return parts[0], '/'.join(parts[1:])
62
63
Congbin Guo36914412020-07-31 14:13:53 -070064@contextlib.contextmanager
65def lock_dir(dir_name):
66 """Lock a directory exclusively by placing a file lock in it.
67
68 Args:
69 dir_name: the directory name to be locked.
70 """
71 lock_file = os.path.join(dir_name, '.lock')
72 with open(lock_file, 'w+') as f:
73 fcntl.flock(f, fcntl.LOCK_EX)
74 try:
75 yield
76 finally:
77 fcntl.flock(f, fcntl.LOCK_UN)
78
79
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070080class TelemetrySetupError(Exception):
81 """Exception class used by this module."""
82 pass
83
84
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -070085class TelemetrySetup(object):
86 """Class that sets up the environment for telemetry testing."""
87
88 # Relevant directory paths.
89 _BASE_DIR_PATH = '/home/chromeos-test/images'
90 _PARTIAL_DEPENDENCY_DIR_PATH = 'autotest/packages'
91
92 # Relevant directory names.
93 _TELEMETRY_SRC_DIR_NAME = 'telemetry_src'
94 _TEST_SRC_DIR_NAME = 'test_src'
95 _SRC_DIR_NAME = 'src'
96
97 # Names of the telemetry dependency tarballs.
98 _DEPENDENCIES = [
99 'dep-telemetry_dep.tar.bz2',
100 'dep-page_cycler_dep.tar.bz2',
101 'dep-chrome_test.tar.bz2',
102 'dep-perf_data_dep.tar.bz2',
103 ]
104
105 def __init__(self, archive_url):
106 """Initializes the TelemetrySetup class.
107
108 Args:
109 archive_url: The URL of the archive supplied through the /setup_telemetry
110 request. It is typically in the format gs://<gs_bucket>/<build_name>
111 """
112 self._bucket, self._build = _GetBucketAndBuild(archive_url)
113 self._build_dir = os.path.join(self._BASE_DIR_PATH, self._build)
114 self._temp_dir_path = tempfile.mkdtemp(prefix='gsc-telemetry')
115 self._tlm_src_dir_path = os.path.join(self._build_dir,
116 self._TELEMETRY_SRC_DIR_NAME)
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -0700117
118 def __enter__(self):
119 """Called while entering context manager; does nothing."""
120 return self
121
122 def __exit__(self, exc_type, exc_value, traceback):
123 """Called while exiting context manager; cleans up temp dirs."""
124 try:
125 shutil.rmtree(self._temp_dir_path)
126 except Exception as e:
127 _log('Something went wrong. Could not delete %s due to exception: %s',
128 self._temp_dir_path, e, level=logging.WARNING)
129
130 def Setup(self):
131 """Sets up the environment for telemetry testing.
132
133 This method downloads the telemetry dependency tarballs and extracts them
134 into a 'src' directory.
135
136 Returns:
137 Path to the src directry where the telemetry dependencies have been
138 downloaded and extracted.
139 """
140 src_folder = os.path.join(self._tlm_src_dir_path, self._SRC_DIR_NAME)
141 test_src = os.path.join(self._tlm_src_dir_path, self._TEST_SRC_DIR_NAME)
142
Congbin Guo36914412020-07-31 14:13:53 -0700143 self._MkDirP(self._tlm_src_dir_path)
144 with lock_dir(self._tlm_src_dir_path):
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -0700145 if not os.path.exists(src_folder):
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -0700146
147 # Download the required dependency tarballs.
148 for dep in self._DEPENDENCIES:
149 dep_path = self._DownloadFilesFromTar(dep, self._temp_dir_path)
150 if os.path.exists(dep_path):
151 self._ExtractTarball(dep_path, self._tlm_src_dir_path)
152
153 # By default all the tarballs extract to test_src but some parts of
154 # the telemetry code specifically hardcoded to exist inside of 'src'.
155 try:
156 shutil.move(test_src, src_folder)
157 except shutil.Error:
158 raise TelemetrySetupError(
159 'Failure in telemetry setup for build %s. Appears that the '
160 'test_src to src move failed.' % self._build)
161
162 return src_folder
163
164 def _DownloadFilesFromTar(self, filename, dest_path):
165 """Downloads the given tar.bz2 file.
166
167 The given tar.bz2 file is downloaded by calling the 'extract' RPC of
168 gs_archive_server.
169
170 Args:
171 filename: Name of the tar.bz2 file to be downloaded.
172 dest_path: Full path to the directory where it should be downloaded.
173
174 Returns:
175 Full path to the downloaded file.
176
177 Raises:
178 TelemetrySetupError when the download cannot be completed for any reason.
179 """
180 dep_path = os.path.join(dest_path, filename)
181 params = 'file=%s/%s' % (self._PARTIAL_DEPENDENCY_DIR_PATH, filename)
182 partial_url = ('%s/%s/%s/autotest_packages.tar' %
183 (GS_CACHE_BASE_URL, self._bucket, self._build))
184 url = '%s?%s' % (partial_url, params)
185 resp = requests.get(url)
186 try:
187 resp.raise_for_status()
188 with open(dep_path, 'w') as f:
Congbin Guo36914412020-07-31 14:13:53 -0700189 for content in resp.iter_content(constants.READ_BUFFER_SIZE_BYTES):
Sanika Kulkarni80e5bd72020-07-21 18:34:34 -0700190 f.write(content)
191 except Exception as e:
192 if (isinstance(e, requests.exceptions.HTTPError)
193 and resp.status_code == 404):
194 _log('The request %s returned a 404 Not Found status. This dependency '
195 'could be new and therefore does not exist in this specific '
196 'tarball. Hence, squashing the exception and proceeding.',
197 url, level=logging.ERROR)
198 else:
199 raise TelemetrySetupError('An error occurred while trying to complete '
200 'the extract request %s: %s' % (url, str(e)))
201 return dep_path
202
203 def _ExtractTarball(self, tarball_path, dest_path):
204 """Extracts the given tarball into the destination directory.
205
206 Args:
207 tarball_path: Full path to the tarball to be extracted.
208 dest_path: Full path to the directory where the tarball should be
209 extracted.
210
211 Raises:
212 TelemetrySetupError if the method is unable to extract the tarball for
213 any reason.
214 """
215 cmd = ['tar', 'xf', tarball_path, '--directory', dest_path]
216 try:
217 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
218 stderr=subprocess.PIPE)
219 proc.communicate()
220 except Exception as e:
221 shutil.rmtree(dest_path)
222 raise TelemetrySetupError(
223 'An exception occurred while trying to untar %s into %s: %s' %
224 (tarball_path, dest_path, str(e)))
225
226 def _MkDirP(self, path):
227 """Recursively creates the given directory.
228
229 Args:
230 path: Full path to the directory that needs to the created.
231
232 Raises:
233 TelemetrySetupError is the method is unable to create directories for any
234 reason except OSError EEXIST which indicates that the directory
235 already exists.
236 """
237 try:
238 os.makedirs(path)
239 except Exception as e:
240 if not isinstance(e, OSError) or e.errno != errno.EEXIST:
241 raise TelemetrySetupError(
242 'Could not create directory %s due to %s.' % (path, str(e)))