blob: 7a3f7240f16192cf94ccc004d77a83a48e2dcb87 [file] [log] [blame]
Sanika Kulkarni92f96a42020-06-16 11:31:14 -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 Nebraska Wrapper to handle update client requests."""
7
8from __future__ import print_function
9
10import os
11import re
12import shutil
13import tempfile
14
15import requests
16from six.moves import urllib
17
18import cherrypy # pylint: disable=import-error
19
Sanika Kulkarnib78e16b2020-07-13 15:14:27 -070020# Nebraska.py has been added to PYTHONPATH, so gs_archive_server should be able
21# to import nebraska.py directly. But if gs_archive_server is triggered from
22# ~/chromiumos/src/platform/dev, it will import nebraska, the python package,
23# instead of nebraska.py, thus throwing an AttributeError when the module is
24# eventually used. To mitigate this, catch the exception and import nebraska.py
25# from the nebraska package directly.
26try:
27 import nebraska
28 nebraska.QueryDictToDict({})
29except AttributeError as e:
30 from nebraska import nebraska
31
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070032from chromite.lib import cros_logging as logging
33
34
35# Define module logger.
36_logger = logging.getLogger(__file__)
37
38# Define all GS Cache related constants.
39GS_CACHE_PORT = '8888'
40GS_ARCHIVE_BUCKET = 'chromeos-image-archive'
41GS_CACHE_DWLD_RPC = 'download'
42GS_CACHE_LIST_DIR_RPC = 'list_dir'
43
44
45def _log(*args, **kwargs):
46 """A wrapper function of logging.debug/info, etc."""
47 level = kwargs.pop('level', logging.DEBUG)
48 _logger.log(level, extra=cherrypy.request.headers, *args, **kwargs)
49
50
51class NebraskaWrapperError(Exception):
52 """Exception class used by this module."""
53 pass
54
55
56class NebraskaWrapper(object):
57 """Class that contains functionality that handles Chrome OS update pings."""
58
59 # Define regexes for properties file. These patterns are the same as the ones
60 # defined in chromite/lib/xbuddy/build_artifact.py. Only the '.*' in the
61 # beginning and '$' at the end is different as in this class, we need to
62 # compare the full gs URL of the file without a newline at the end to this
63 # regex pattern.
64 _FULL_PAYLOAD_PROPS_PATTERN = r'.*chromeos_.*_full_dev.*bin(\.json)$'
65 _DELTA_PAYLOAD_PROPS_PATTERN = r'.*chromeos_.*_delta_dev.*bin(\.json)$'
66
67 def __init__(self, label, server_addr, full_update):
68 """Initializes the class.
69
70 Args:
71 label: Label (string) for the update, typically in the format
Amin Hassani89c7fac2020-12-10 12:16:26 -080072 <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070073 server_addr: IP address (string) for the server on which gs cache is
74 running.
75 full_update: Indicates whether the requested update is full or delta. The
76 string values for this argument can be 'True', 'False', or
77 'unspecified'.
78 """
Amin Hassani89c7fac2020-12-10 12:16:26 -080079 self._label = self._GetLabel(label)
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070080 self._gs_cache_base_url = 'http://%s:%s' % (server_addr, GS_CACHE_PORT)
81
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070082 # When full_update parameter is not specified in the request, the update
Amin Hassani89c7fac2020-12-10 12:16:26 -080083 # type is 'delta'.
84 self._is_full_update = full_update.lower().strip() == 'true'
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070085
86 self._props_dir = tempfile.mkdtemp(prefix='gsc-update')
87 self._payload_props_file = None
88
89 def __enter__(self):
90 """Called while entering context manager; does nothing."""
91 return self
92
93 def __exit__(self, exc_type, exc_value, traceback):
94 """Called while exiting context manager; cleans up temp dirs."""
95 try:
96 shutil.rmtree(self._props_dir)
97 except Exception as e:
98 _log('Something went wrong. Could not delete %s due to exception: %s',
99 self._props_dir, e, level=logging.WARNING)
100
101 @property
102 def _PayloadPropsFilename(self):
103 """Get the name of the payload properties file.
104
105 The name of the properties file is obtained from the list of files returned
106 by the list_dir RPC by matching the name of the file with the update_type
107 and file extension.
108
109 Returns:
110 Name of the payload properties file.
111
112 Raises:
113 NebraskaWrapperError if the list_dir calls returns 4xx/5xx or if the
114 correct file could not be determined.
115 """
116 if self._payload_props_file:
117 return self._payload_props_file
118
119 urlbase = self._GetListDirURL()
120 url = urllib.parse.urljoin(urlbase, self._label)
121
122 resp = requests.get(url)
123 try:
124 resp.raise_for_status()
125 except Exception as e:
126 raise NebraskaWrapperError('An error occurred while trying to complete '
127 'the request: %s' % e)
128
129 if self._is_full_update:
130 pattern = re.compile(self._FULL_PAYLOAD_PROPS_PATTERN)
131 else:
132 pattern = re.compile(self._DELTA_PAYLOAD_PROPS_PATTERN)
133
134 # Iterate through all listed files to determine the correct payload
135 # properties file. Since the listed files will be in the format
136 # gs://<gs_bucket>/<board>/<version>/<filename>, return the filename only
137 # once a match is determined.
138 for fname in [x.strip() for x in resp.content.strip().split('\n')]:
139 if pattern.match(fname):
140 self._payload_props_file = fname.rsplit('/', 1)[-1]
141 return self._payload_props_file
142
143 raise NebraskaWrapperError(
144 'Request to %s returned a %s but gs_archive_server was unable to '
145 'determine the name of the properties file.' %
146 (url, resp.status_code))
147
Amin Hassani89c7fac2020-12-10 12:16:26 -0800148 def _GetLabel(self, label):
149 """Gets the label for the request.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700150
Amin Hassani89c7fac2020-12-10 12:16:26 -0800151 Removes a trailing /au_nton from the label argument.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700152
153 Args:
154 label: A string obtained from the request.
155
156 Returns:
157 A string in the format <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700158 """
Amin Hassani89c7fac2020-12-10 12:16:26 -0800159 # TODO(crbug.com/1102552): Remove this logic once all clients stopped
160 # sending au_nton in the request.
161 return label[:-len('/au_nton')] if label.endswith('/au_nton') else label
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700162
163 def _GetDownloadURL(self):
164 """Returns the static url base that should prefix all payload responses."""
165 _log('Handling update ping as %s', self._gs_cache_base_url)
166 return self._GetURL(GS_CACHE_DWLD_RPC)
167
168 def _GetListDirURL(self):
169 """Returns the static url base that should prefix all list_dir requests."""
170 _log('Using base URL to list contents: %s', self._gs_cache_base_url)
171 return self._GetURL(GS_CACHE_LIST_DIR_RPC)
172
173 def _GetURL(self, rpc_name):
174 """Construct gs_cache URL for the given RPC.
175
176 Args:
177 rpc_name: Name of the RPC for which the URL needs to be built.
178
179 Returns:
180 Base URL to be used.
181 """
182 urlbase = urllib.parse.urljoin(self._gs_cache_base_url,
183 '%s/%s/' % (rpc_name, GS_ARCHIVE_BUCKET))
184 _log('Using static url base %s', urlbase)
185 return urlbase
186
187 def _GetPayloadPropertiesDir(self, urlbase):
188 """Download payload properties file from GS Archive
189
190 Args:
191 urlbase: Base url that should be used to form the download request.
192
193 Returns:
194 The path to the /tmp directory which stores the payload properties file
195 that nebraska will use.
196
197 Raises:
198 NebraskaWrapperError is raised if the method is unable to
199 download the file for some reason.
200 """
201 local_payload_dir = self._props_dir
202 partial_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
203 _log('Downloading %s from bucket %s.', self._PayloadPropsFilename,
204 partial_url, level=logging.INFO)
205
206 try:
207 resp = requests.get(urllib.parse.urljoin(partial_url,
208 self._PayloadPropsFilename))
209 resp.raise_for_status()
210 file_path = os.path.join(local_payload_dir, self._PayloadPropsFilename)
211 # We are not worried about multiple threads writing to the same file as
212 # we are creating a different directory for each initialization of this
213 # class anyway.
214 with open(file_path, 'w') as f:
215 f.write(resp.content)
216 except Exception as e:
217 raise NebraskaWrapperError('An error occurred while trying to complete '
218 'the request: %s' % e)
219 _log('Path to downloaded payload properties file: %s' % file_path)
220 return local_payload_dir
221
222 def HandleUpdatePing(self, data, **kwargs):
223 """Handles an update ping from an update client.
224
225 Args:
226 data: XML blob from client.
227 kwargs: The map of query strings passed to the /update API.
228
229 Returns:
230 Update payload message for client.
231 """
232 # Get the static url base that will form that base of our update url e.g.
233 # http://<GS_CACHE_IP>:<GS_CACHE_PORT>/download/chromeos-image-archive/.
234 urlbase = self._GetDownloadURL()
235 # Change the URL's string query dictionary provided by cherrypy to a
236 # valid dictionary that has proper values for its keys. e.g. True
237 # instead of 'True'.
238 kwargs = nebraska.QueryDictToDict(kwargs)
239
240 try:
241 # Process attributes of the update check.
242 request = nebraska.Request(data)
243 if request.request_type == nebraska.Request.RequestType.EVENT:
244 _log('A non-update event notification received. Returning an ack.',
245 level=logging.INFO)
246 return nebraska.Nebraska().GetResponseToRequest(
247 request, response_props=nebraska.ResponseProperties(**kwargs))
248
249 _log('Update Check Received.')
250
251 base_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
252 _log('Responding to client to use url %s to get image', base_url,
253 level=logging.INFO)
254
255 local_payload_dir = self._GetPayloadPropertiesDir(urlbase=urlbase)
256 _log('Using %s as the update_metadata_dir for NebraskaProperties.',
257 local_payload_dir)
258
259 nebraska_props = nebraska.NebraskaProperties(
260 update_payloads_address=base_url,
261 update_metadata_dir=local_payload_dir)
262 nebraska_obj = nebraska.Nebraska(nebraska_props=nebraska_props)
263
264 return nebraska_obj.GetResponseToRequest(
265 request, response_props=nebraska.ResponseProperties(**kwargs))
266
267 except Exception as e:
268 raise NebraskaWrapperError('An error occurred while processing the '
269 'update request: %s' % e)