blob: 8b8c0cd0b19a707425bda514eb924916d1584b73 [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."""
Amin Hassanibf9e0402021-02-23 19:41:00 -080053 # pylint: disable=unnecessary-pass
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070054 pass
55
56
57class NebraskaWrapper(object):
58 """Class that contains functionality that handles Chrome OS update pings."""
59
60 # Define regexes for properties file. These patterns are the same as the ones
61 # defined in chromite/lib/xbuddy/build_artifact.py. Only the '.*' in the
62 # beginning and '$' at the end is different as in this class, we need to
63 # compare the full gs URL of the file without a newline at the end to this
64 # regex pattern.
65 _FULL_PAYLOAD_PROPS_PATTERN = r'.*chromeos_.*_full_dev.*bin(\.json)$'
66 _DELTA_PAYLOAD_PROPS_PATTERN = r'.*chromeos_.*_delta_dev.*bin(\.json)$'
67
68 def __init__(self, label, server_addr, full_update):
69 """Initializes the class.
70
71 Args:
72 label: Label (string) for the update, typically in the format
Amin Hassani89c7fac2020-12-10 12:16:26 -080073 <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070074 server_addr: IP address (string) for the server on which gs cache is
75 running.
76 full_update: Indicates whether the requested update is full or delta. The
77 string values for this argument can be 'True', 'False', or
78 'unspecified'.
79 """
Amin Hassani89c7fac2020-12-10 12:16:26 -080080 self._label = self._GetLabel(label)
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070081 self._gs_cache_base_url = 'http://%s:%s' % (server_addr, GS_CACHE_PORT)
82
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070083 # When full_update parameter is not specified in the request, the update
Amin Hassani89c7fac2020-12-10 12:16:26 -080084 # type is 'delta'.
85 self._is_full_update = full_update.lower().strip() == 'true'
Sanika Kulkarni92f96a42020-06-16 11:31:14 -070086
87 self._props_dir = tempfile.mkdtemp(prefix='gsc-update')
88 self._payload_props_file = None
89
90 def __enter__(self):
91 """Called while entering context manager; does nothing."""
92 return self
93
94 def __exit__(self, exc_type, exc_value, traceback):
95 """Called while exiting context manager; cleans up temp dirs."""
96 try:
97 shutil.rmtree(self._props_dir)
98 except Exception as e:
99 _log('Something went wrong. Could not delete %s due to exception: %s',
100 self._props_dir, e, level=logging.WARNING)
101
102 @property
103 def _PayloadPropsFilename(self):
104 """Get the name of the payload properties file.
105
106 The name of the properties file is obtained from the list of files returned
107 by the list_dir RPC by matching the name of the file with the update_type
108 and file extension.
109
110 Returns:
111 Name of the payload properties file.
112
113 Raises:
114 NebraskaWrapperError if the list_dir calls returns 4xx/5xx or if the
115 correct file could not be determined.
116 """
117 if self._payload_props_file:
118 return self._payload_props_file
119
120 urlbase = self._GetListDirURL()
121 url = urllib.parse.urljoin(urlbase, self._label)
122
123 resp = requests.get(url)
124 try:
125 resp.raise_for_status()
126 except Exception as e:
127 raise NebraskaWrapperError('An error occurred while trying to complete '
128 'the request: %s' % e)
129
130 if self._is_full_update:
131 pattern = re.compile(self._FULL_PAYLOAD_PROPS_PATTERN)
132 else:
133 pattern = re.compile(self._DELTA_PAYLOAD_PROPS_PATTERN)
134
135 # Iterate through all listed files to determine the correct payload
136 # properties file. Since the listed files will be in the format
137 # gs://<gs_bucket>/<board>/<version>/<filename>, return the filename only
138 # once a match is determined.
139 for fname in [x.strip() for x in resp.content.strip().split('\n')]:
140 if pattern.match(fname):
141 self._payload_props_file = fname.rsplit('/', 1)[-1]
142 return self._payload_props_file
143
144 raise NebraskaWrapperError(
145 'Request to %s returned a %s but gs_archive_server was unable to '
146 'determine the name of the properties file.' %
147 (url, resp.status_code))
148
Amin Hassani89c7fac2020-12-10 12:16:26 -0800149 def _GetLabel(self, label):
150 """Gets the label for the request.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700151
Amin Hassani89c7fac2020-12-10 12:16:26 -0800152 Removes a trailing /au_nton from the label argument.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700153
154 Args:
155 label: A string obtained from the request.
156
157 Returns:
158 A string in the format <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>.
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700159 """
Amin Hassani89c7fac2020-12-10 12:16:26 -0800160 # TODO(crbug.com/1102552): Remove this logic once all clients stopped
161 # sending au_nton in the request.
162 return label[:-len('/au_nton')] if label.endswith('/au_nton') else label
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700163
164 def _GetDownloadURL(self):
165 """Returns the static url base that should prefix all payload responses."""
166 _log('Handling update ping as %s', self._gs_cache_base_url)
167 return self._GetURL(GS_CACHE_DWLD_RPC)
168
169 def _GetListDirURL(self):
170 """Returns the static url base that should prefix all list_dir requests."""
171 _log('Using base URL to list contents: %s', self._gs_cache_base_url)
172 return self._GetURL(GS_CACHE_LIST_DIR_RPC)
173
174 def _GetURL(self, rpc_name):
175 """Construct gs_cache URL for the given RPC.
176
177 Args:
178 rpc_name: Name of the RPC for which the URL needs to be built.
179
180 Returns:
181 Base URL to be used.
182 """
183 urlbase = urllib.parse.urljoin(self._gs_cache_base_url,
184 '%s/%s/' % (rpc_name, GS_ARCHIVE_BUCKET))
185 _log('Using static url base %s', urlbase)
186 return urlbase
187
188 def _GetPayloadPropertiesDir(self, urlbase):
189 """Download payload properties file from GS Archive
190
191 Args:
192 urlbase: Base url that should be used to form the download request.
193
194 Returns:
195 The path to the /tmp directory which stores the payload properties file
196 that nebraska will use.
197
198 Raises:
199 NebraskaWrapperError is raised if the method is unable to
200 download the file for some reason.
201 """
202 local_payload_dir = self._props_dir
203 partial_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
204 _log('Downloading %s from bucket %s.', self._PayloadPropsFilename,
205 partial_url, level=logging.INFO)
206
207 try:
208 resp = requests.get(urllib.parse.urljoin(partial_url,
209 self._PayloadPropsFilename))
210 resp.raise_for_status()
211 file_path = os.path.join(local_payload_dir, self._PayloadPropsFilename)
212 # We are not worried about multiple threads writing to the same file as
213 # we are creating a different directory for each initialization of this
214 # class anyway.
215 with open(file_path, 'w') as f:
216 f.write(resp.content)
217 except Exception as e:
218 raise NebraskaWrapperError('An error occurred while trying to complete '
219 'the request: %s' % e)
220 _log('Path to downloaded payload properties file: %s' % file_path)
221 return local_payload_dir
222
223 def HandleUpdatePing(self, data, **kwargs):
224 """Handles an update ping from an update client.
225
226 Args:
227 data: XML blob from client.
228 kwargs: The map of query strings passed to the /update API.
229
230 Returns:
231 Update payload message for client.
232 """
233 # Get the static url base that will form that base of our update url e.g.
234 # http://<GS_CACHE_IP>:<GS_CACHE_PORT>/download/chromeos-image-archive/.
235 urlbase = self._GetDownloadURL()
236 # Change the URL's string query dictionary provided by cherrypy to a
237 # valid dictionary that has proper values for its keys. e.g. True
238 # instead of 'True'.
239 kwargs = nebraska.QueryDictToDict(kwargs)
240
241 try:
242 # Process attributes of the update check.
243 request = nebraska.Request(data)
244 if request.request_type == nebraska.Request.RequestType.EVENT:
245 _log('A non-update event notification received. Returning an ack.',
246 level=logging.INFO)
Amin Hassanibf9e0402021-02-23 19:41:00 -0800247 n = nebraska.Nebraska()
248 n.UpdateConfig(**kwargs)
249 return n.GetResponseToRequest(request)
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700250
251 _log('Update Check Received.')
252
253 base_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
254 _log('Responding to client to use url %s to get image', base_url,
255 level=logging.INFO)
256
257 local_payload_dir = self._GetPayloadPropertiesDir(urlbase=urlbase)
258 _log('Using %s as the update_metadata_dir for NebraskaProperties.',
259 local_payload_dir)
260
Amin Hassanibf9e0402021-02-23 19:41:00 -0800261 n = nebraska.Nebraska()
262 n.UpdateConfig(update_payloads_address=base_url,
263 update_app_index=nebraska.AppIndex(local_payload_dir))
264 return n.GetResponseToRequest(request)
Sanika Kulkarni92f96a42020-06-16 11:31:14 -0700265
266 except Exception as e:
267 raise NebraskaWrapperError('An error occurred while processing the '
268 'update request: %s' % e)