blob: 0909fefba07500a1ade0d587d9a7ff4ac25733d8 [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
72 <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>[/au_nton].
73 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 """
79 self._label, au_nton = self._GetLabelAndNToN(label)
80 self._gs_cache_base_url = 'http://%s:%s' % (server_addr, GS_CACHE_PORT)
81
82 full_update = full_update.lower().strip()
83 # When full_update parameter is not specified in the request, the update
84 # type is 'delta' when au_nton is True and 'full' when au_nton is False.
85 self._is_full_update = (not au_nton if full_update == 'unspecified'
86 else full_update == 'true')
87
88 self._props_dir = tempfile.mkdtemp(prefix='gsc-update')
89 self._payload_props_file = None
90
91 def __enter__(self):
92 """Called while entering context manager; does nothing."""
93 return self
94
95 def __exit__(self, exc_type, exc_value, traceback):
96 """Called while exiting context manager; cleans up temp dirs."""
97 try:
98 shutil.rmtree(self._props_dir)
99 except Exception as e:
100 _log('Something went wrong. Could not delete %s due to exception: %s',
101 self._props_dir, e, level=logging.WARNING)
102
103 @property
104 def _PayloadPropsFilename(self):
105 """Get the name of the payload properties file.
106
107 The name of the properties file is obtained from the list of files returned
108 by the list_dir RPC by matching the name of the file with the update_type
109 and file extension.
110
111 Returns:
112 Name of the payload properties file.
113
114 Raises:
115 NebraskaWrapperError if the list_dir calls returns 4xx/5xx or if the
116 correct file could not be determined.
117 """
118 if self._payload_props_file:
119 return self._payload_props_file
120
121 urlbase = self._GetListDirURL()
122 url = urllib.parse.urljoin(urlbase, self._label)
123
124 resp = requests.get(url)
125 try:
126 resp.raise_for_status()
127 except Exception as e:
128 raise NebraskaWrapperError('An error occurred while trying to complete '
129 'the request: %s' % e)
130
131 if self._is_full_update:
132 pattern = re.compile(self._FULL_PAYLOAD_PROPS_PATTERN)
133 else:
134 pattern = re.compile(self._DELTA_PAYLOAD_PROPS_PATTERN)
135
136 # Iterate through all listed files to determine the correct payload
137 # properties file. Since the listed files will be in the format
138 # gs://<gs_bucket>/<board>/<version>/<filename>, return the filename only
139 # once a match is determined.
140 for fname in [x.strip() for x in resp.content.strip().split('\n')]:
141 if pattern.match(fname):
142 self._payload_props_file = fname.rsplit('/', 1)[-1]
143 return self._payload_props_file
144
145 raise NebraskaWrapperError(
146 'Request to %s returned a %s but gs_archive_server was unable to '
147 'determine the name of the properties file.' %
148 (url, resp.status_code))
149
150 def _GetLabelAndNToN(self, label):
151 """Gets the label for the request and whether the update is N-to-N.
152
153 Removes a trailing /au_nton from the label argument which determines whether
154 this specific request is an N-to-N update or not.
155
156 Args:
157 label: A string obtained from the request.
158
159 Returns:
160 A string in the format <board>-<XXXX>/Rxx-xxxxx.x.x-<unique string>.
161 A boolean that indicates whether the update is N-to-N or not.
162 """
163 # TODO(crbug.com/1102552): Remove this logic once au_nton is removed from
164 # the request.
165 if label.endswith('/au_nton'):
166 return label[:-len('/au_nton')], True
167 return label, False
168
169 def _GetDownloadURL(self):
170 """Returns the static url base that should prefix all payload responses."""
171 _log('Handling update ping as %s', self._gs_cache_base_url)
172 return self._GetURL(GS_CACHE_DWLD_RPC)
173
174 def _GetListDirURL(self):
175 """Returns the static url base that should prefix all list_dir requests."""
176 _log('Using base URL to list contents: %s', self._gs_cache_base_url)
177 return self._GetURL(GS_CACHE_LIST_DIR_RPC)
178
179 def _GetURL(self, rpc_name):
180 """Construct gs_cache URL for the given RPC.
181
182 Args:
183 rpc_name: Name of the RPC for which the URL needs to be built.
184
185 Returns:
186 Base URL to be used.
187 """
188 urlbase = urllib.parse.urljoin(self._gs_cache_base_url,
189 '%s/%s/' % (rpc_name, GS_ARCHIVE_BUCKET))
190 _log('Using static url base %s', urlbase)
191 return urlbase
192
193 def _GetPayloadPropertiesDir(self, urlbase):
194 """Download payload properties file from GS Archive
195
196 Args:
197 urlbase: Base url that should be used to form the download request.
198
199 Returns:
200 The path to the /tmp directory which stores the payload properties file
201 that nebraska will use.
202
203 Raises:
204 NebraskaWrapperError is raised if the method is unable to
205 download the file for some reason.
206 """
207 local_payload_dir = self._props_dir
208 partial_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
209 _log('Downloading %s from bucket %s.', self._PayloadPropsFilename,
210 partial_url, level=logging.INFO)
211
212 try:
213 resp = requests.get(urllib.parse.urljoin(partial_url,
214 self._PayloadPropsFilename))
215 resp.raise_for_status()
216 file_path = os.path.join(local_payload_dir, self._PayloadPropsFilename)
217 # We are not worried about multiple threads writing to the same file as
218 # we are creating a different directory for each initialization of this
219 # class anyway.
220 with open(file_path, 'w') as f:
221 f.write(resp.content)
222 except Exception as e:
223 raise NebraskaWrapperError('An error occurred while trying to complete '
224 'the request: %s' % e)
225 _log('Path to downloaded payload properties file: %s' % file_path)
226 return local_payload_dir
227
228 def HandleUpdatePing(self, data, **kwargs):
229 """Handles an update ping from an update client.
230
231 Args:
232 data: XML blob from client.
233 kwargs: The map of query strings passed to the /update API.
234
235 Returns:
236 Update payload message for client.
237 """
238 # Get the static url base that will form that base of our update url e.g.
239 # http://<GS_CACHE_IP>:<GS_CACHE_PORT>/download/chromeos-image-archive/.
240 urlbase = self._GetDownloadURL()
241 # Change the URL's string query dictionary provided by cherrypy to a
242 # valid dictionary that has proper values for its keys. e.g. True
243 # instead of 'True'.
244 kwargs = nebraska.QueryDictToDict(kwargs)
245
246 try:
247 # Process attributes of the update check.
248 request = nebraska.Request(data)
249 if request.request_type == nebraska.Request.RequestType.EVENT:
250 _log('A non-update event notification received. Returning an ack.',
251 level=logging.INFO)
252 return nebraska.Nebraska().GetResponseToRequest(
253 request, response_props=nebraska.ResponseProperties(**kwargs))
254
255 _log('Update Check Received.')
256
257 base_url = urllib.parse.urljoin(urlbase, '%s/' % self._label)
258 _log('Responding to client to use url %s to get image', base_url,
259 level=logging.INFO)
260
261 local_payload_dir = self._GetPayloadPropertiesDir(urlbase=urlbase)
262 _log('Using %s as the update_metadata_dir for NebraskaProperties.',
263 local_payload_dir)
264
265 nebraska_props = nebraska.NebraskaProperties(
266 update_payloads_address=base_url,
267 update_metadata_dir=local_payload_dir)
268 nebraska_obj = nebraska.Nebraska(nebraska_props=nebraska_props)
269
270 return nebraska_obj.GetResponseToRequest(
271 request, response_props=nebraska.ResponseProperties(**kwargs))
272
273 except Exception as e:
274 raise NebraskaWrapperError('An error occurred while processing the '
275 'update request: %s' % e)