blob: 538c9923da824298885323c569e6727492e487c8 [file] [log] [blame]
Amin Hassani8d718d12019-06-02 21:28:39 -07001# -*- coding: utf-8 -*-
Darin Petkovc3fd90c2011-05-11 14:23:00 -07002# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
rtc@google.comded22402009-10-26 22:36:21 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Gilad Arnoldd8d595c2014-03-21 13:00:41 -07006"""Devserver module for handling update client requests."""
7
Don Garrettfb15e322016-06-21 19:12:08 -07008from __future__ import print_function
9
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070010import json
rtc@google.comded22402009-10-26 22:36:21 +000011import os
Gilad Arnoldd0c71752013-12-06 11:48:45 -080012import threading
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070013import time
Chris Sosa7c931362010-10-11 19:49:01 -070014
Amin Hassani4f1e4622019-10-03 10:40:50 -070015from six.moves import urllib
16
17import cherrypy # pylint: disable=import-error
Gilad Arnoldabb352e2012-09-23 01:24:27 -070018
Amin Hassani8d718d12019-06-02 21:28:39 -070019# TODO(crbug.com/872441): We try to import nebraska from different places
20# because when we install the devserver, we copy the nebraska.py into the main
21# directory. Once this bug is resolved, we can always import from nebraska
22# directory.
23try:
24 from nebraska import nebraska
25except ImportError:
26 import nebraska
Chris Sosa05491b12010-11-08 17:14:16 -080027
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070028import setup_chromite # pylint: disable=unused-import
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070029from chromite.lib.xbuddy import cherrypy_log_util
30from chromite.lib.xbuddy import common_util
31from chromite.lib.xbuddy import devserver_constants as constants
32
Gilad Arnoldc65330c2012-09-20 15:17:48 -070033
34# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080035def _Log(message, *args):
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070036 return cherrypy_log_util.LogWithTag('UPDATE', message, *args)
rtc@google.comded22402009-10-26 22:36:21 +000037
Gilad Arnold0c9c8602012-10-02 23:58:58 -070038class AutoupdateError(Exception):
39 """Exception classes used by this module."""
40 pass
41
42
Don Garrett0ad09372010-12-06 16:20:30 -080043def _ChangeUrlPort(url, new_port):
44 """Return the URL passed in with a different port"""
Amin Hassani4f1e4622019-10-03 10:40:50 -070045 scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
Don Garrett0ad09372010-12-06 16:20:30 -080046 host_port = netloc.split(':')
47
48 if len(host_port) == 1:
49 host_port.append(new_port)
50 else:
51 host_port[1] = new_port
52
Don Garrettfb15e322016-06-21 19:12:08 -070053 print(host_port)
joychen121fc9b2013-08-02 14:30:30 -070054 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-06 16:20:30 -080055
Amin Hassani4f1e4622019-10-03 10:40:50 -070056 # pylint: disable=too-many-function-args
57 return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment))
Don Garrett0ad09372010-12-06 16:20:30 -080058
Chris Sosa6a3697f2013-01-29 16:44:43 -080059def _NonePathJoin(*args):
60 """os.path.join that filters None's from the argument list."""
Amin Hassani4f1e4622019-10-03 10:40:50 -070061 return os.path.join(*[x for x in args if x is not None])
Don Garrett0ad09372010-12-06 16:20:30 -080062
Chris Sosa6a3697f2013-01-29 16:44:43 -080063
64class HostInfo(object):
Gilad Arnold286a0062012-01-12 13:47:02 -080065 """Records information about an individual host.
66
Amin Hassanie7ead902019-10-11 16:42:43 -070067 Attributes:
Gilad Arnold286a0062012-01-12 13:47:02 -080068 attrs: Static attributes (legacy)
69 log: Complete log of recorded client entries
70 """
71
72 def __init__(self):
73 # A dictionary of current attributes pertaining to the host.
74 self.attrs = {}
75
76 # A list of pairs consisting of a timestamp and a dictionary of recorded
77 # attributes.
78 self.log = []
79
80 def __repr__(self):
81 return 'attrs=%s, log=%s' % (self.attrs, self.log)
82
83 def AddLogEntry(self, entry):
84 """Append a new log entry."""
85 # Append a timestamp.
86 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
87 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
88 # Add entry to hosts' message log.
89 self.log.append(entry)
90
Gilad Arnold286a0062012-01-12 13:47:02 -080091
Chris Sosa6a3697f2013-01-29 16:44:43 -080092class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 13:47:02 -080093 """Records information about a set of hosts who engage in update activity.
94
Amin Hassanie7ead902019-10-11 16:42:43 -070095 Attributes:
Gilad Arnold286a0062012-01-12 13:47:02 -080096 table: Table of information on hosts.
97 """
98
99 def __init__(self):
100 # A dictionary of host information. Keys are normally IP addresses.
101 self.table = {}
102
103 def __repr__(self):
104 return '%s' % self.table
105
106 def GetInitHostInfo(self, host_id):
107 """Return a host's info object, or create a new one if none exists."""
108 return self.table.setdefault(host_id, HostInfo())
109
110 def GetHostInfo(self, host_id):
111 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-29 17:07:27 -0800112 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 13:47:02 -0800113
114
Amin Hassani4b5d5ab2020-03-22 19:57:46 -0700115class Autoupdate(object):
Amin Hassanie9ffb862019-09-25 17:10:40 -0700116 """Class that contains functionality that handles Chrome OS update pings."""
rtc@google.comded22402009-10-26 22:36:21 +0000117
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700118 _PAYLOAD_URL_PREFIX = '/static/'
Chris Sosa6a3697f2013-01-29 16:44:43 -0800119
Amin Hassani4b5d5ab2020-03-22 19:57:46 -0700120 def __init__(self, xbuddy, static_dir=None, payload_path=None,
Amin Hassani5190a882020-03-24 10:28:41 -0700121 proxy_port=None, critical_update=False, host_log=False):
Amin Hassanie9ffb862019-09-25 17:10:40 -0700122 """Initializes the class.
123
124 Args:
125 xbuddy: The xbuddy path.
Amin Hassani4b5d5ab2020-03-22 19:57:46 -0700126 static_dir: The path to the devserver static directory.
Amin Hassanie9ffb862019-09-25 17:10:40 -0700127 payload_path: The path to pre-generated payload to serve.
128 proxy_port: The port of local proxy to tell client to connect to you
129 through.
130 critical_update: Whether provisioned payload is critical.
Amin Hassanie9ffb862019-09-25 17:10:40 -0700131 host_log: Record full history of host update events.
132 """
joychen121fc9b2013-08-02 14:30:30 -0700133 self.xbuddy = xbuddy
Amin Hassani4b5d5ab2020-03-22 19:57:46 -0700134 self.static_dir = static_dir
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700135 self.payload_path = payload_path
Don Garrett0ad09372010-12-06 16:20:30 -0800136 self.proxy_port = proxy_port
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800137 self.critical_update = critical_update
Gilad Arnold8318eac2012-10-04 12:52:23 -0700138 self.host_log = host_log
Don Garrettfff4c322010-11-19 13:37:12 -0800139
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700140 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 13:47:02 -0800141 # information about a given host. A host is identified by its IP address.
142 # The info stored for each host includes a complete log of events for this
143 # host, as well as a dictionary of current attributes derived from events.
144 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700145
Gilad Arnolde7819e72014-03-21 12:50:48 -0700146 self._update_count_lock = threading.Lock()
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800147
Amin Hassanie9ffb862019-09-25 17:10:40 -0700148 def GetUpdateForLabel(self, label):
joychen121fc9b2013-08-02 14:30:30 -0700149 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700150
joychen121fc9b2013-08-02 14:30:30 -0700151 Args:
joychen121fc9b2013-08-02 14:30:30 -0700152 label: the relative directory inside the static dir
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700153
Chris Sosa6a3697f2013-01-29 16:44:43 -0800154 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700155 A relative path to the directory with the update payload.
156 This is the label if an update did not need to be generated, but can
157 be label/cache/hashed_dir_for_update.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700158
Chris Sosa6a3697f2013-01-29 16:44:43 -0800159 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700160 AutoupdateError: If client version is higher than available update found
161 at the directory given by the label.
Don Garrettf90edf02010-11-16 17:36:14 -0800162 """
Amin Hassanie9ffb862019-09-25 17:10:40 -0700163 _Log('Update label: %s', label)
164 static_update_path = _NonePathJoin(self.static_dir, label,
165 constants.UPDATE_FILE)
Don Garrettee25e552010-11-23 12:09:35 -0800166
joychen121fc9b2013-08-02 14:30:30 -0700167 if label and os.path.exists(static_update_path):
168 # An update payload was found for the given label, return it.
169 return label
Don Garrett0c880e22010-11-17 18:13:37 -0800170
joychen121fc9b2013-08-02 14:30:30 -0700171 # The label didn't resolve.
Amin Hassanie9ffb862019-09-25 17:10:40 -0700172 _Log('Did not found any update payload for label %s.', label)
joychen121fc9b2013-08-02 14:30:30 -0700173 return None
Chris Sosa2c048f12010-10-27 16:05:27 -0700174
Amin Hassanie7ead902019-10-11 16:42:43 -0700175 def _LogRequest(self, request):
176 """Logs the incoming request in the hostlog.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800177
Gilad Arnolde7819e72014-03-21 12:50:48 -0700178 Args:
Amin Hassani8d718d12019-06-02 21:28:39 -0700179 request: A nebraska.Request object representing the update request.
Gilad Arnolde7819e72014-03-21 12:50:48 -0700180
181 Returns:
182 A named tuple containing attributes of the update requests as the
Amin Hassani542b5492019-09-26 14:53:26 -0700183 following fields: 'board', 'event_result' and 'event_type'.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700184 """
Amin Hassanie7ead902019-10-11 16:42:43 -0700185 if not self.host_log:
186 return
187
188 # Add attributes to log message. Some of these values might be None.
189 log_message = {
190 'version': request.version,
191 'track': request.track,
Amin Hassani4b5d5ab2020-03-22 19:57:46 -0700192 'board': request.board,
Amin Hassanie7ead902019-10-11 16:42:43 -0700193 'event_result': request.app_requests[0].event_result,
194 'event_type': request.app_requests[0].event_type,
195 'previous_version': request.app_requests[0].previous_version,
196 }
197 if log_message['previous_version'] is None:
198 del log_message['previous_version']
Jay Srinivasanac69d262012-10-30 19:05:53 -0700199
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700200 # Determine request IP, strip any IPv6 data for simplicity.
201 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 13:47:02 -0800202 # Obtain (or init) info object for this client.
203 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
Amin Hassanie7ead902019-10-11 16:42:43 -0700204 curr_host_info.AddLogEntry(log_message)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800205
David Rileyee75de22017-11-02 10:48:15 -0700206 def GetDevserverUrl(self):
207 """Returns the devserver url base."""
Chris Sosa6a3697f2013-01-29 16:44:43 -0800208 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
209 if x_forwarded_host:
210 hostname = 'http://' + x_forwarded_host
211 else:
212 hostname = cherrypy.request.base
213
David Rileyee75de22017-11-02 10:48:15 -0700214 return hostname
215
216 def GetStaticUrl(self):
217 """Returns the static url base that should prefix all payload responses."""
218 hostname = self.GetDevserverUrl()
219
Amin Hassanic9dd11e2019-07-11 15:33:55 -0700220 static_urlbase = '%s/static' % hostname
Chris Sosa6a3697f2013-01-29 16:44:43 -0800221 # If we have a proxy port, adjust the URL we instruct the client to
222 # use to go through the proxy.
223 if self.proxy_port:
224 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
225
226 _Log('Using static url base %s', static_urlbase)
227 _Log('Handling update ping as %s', hostname)
228 return static_urlbase
229
Amin Hassanie9ffb862019-09-25 17:10:40 -0700230 def GetPathToPayload(self, label, board):
joychen121fc9b2013-08-02 14:30:30 -0700231 """Find a payload locally.
232
233 See devserver's update rpc for documentation.
234
235 Args:
236 label: from update request
joychen121fc9b2013-08-02 14:30:30 -0700237 board: from update request
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700238
239 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700240 The relative path to an update from the static_dir
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700241
joychen121fc9b2013-08-02 14:30:30 -0700242 Raises:
243 AutoupdateError: If the update could not be found.
244 """
245 path_to_payload = None
Amin Hassanie9ffb862019-09-25 17:10:40 -0700246 # TODO(crbug.com/1006305): deprecate --payload flag
joychen121fc9b2013-08-02 14:30:30 -0700247 if self.payload_path:
248 # Copy the image from the path to '/forced_payload'
249 label = 'forced_payload'
250 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
251 dest_stateful = os.path.join(self.static_dir, label,
252 constants.STATEFUL_FILE)
Amin Hassani8d718d12019-06-02 21:28:39 -0700253 dest_meta = os.path.join(self.static_dir, label,
254 constants.UPDATE_METADATA_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700255
256 src_path = os.path.abspath(self.payload_path)
Amin Hassanie9ffb862019-09-25 17:10:40 -0700257 src_meta = os.path.abspath(self.payload_path + '.json')
joychen121fc9b2013-08-02 14:30:30 -0700258 src_stateful = os.path.join(os.path.dirname(src_path),
259 constants.STATEFUL_FILE)
260 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-03 21:49:41 -0700261 common_util.SymlinkFile(src_path, dest_path)
Amin Hassanie9ffb862019-09-25 17:10:40 -0700262 common_util.SymlinkFile(src_meta, dest_meta)
joychen121fc9b2013-08-02 14:30:30 -0700263 if os.path.exists(src_stateful):
264 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-03 21:49:41 -0700265 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 14:30:30 -0700266 else:
267 _Log('WARN: %s not found. Expected for dev and test builds',
268 constants.STATEFUL_FILE)
269 if os.path.exists(dest_stateful):
270 os.remove(dest_stateful)
Amin Hassanie9ffb862019-09-25 17:10:40 -0700271 path_to_payload = self.GetUpdateForLabel(label)
joychen121fc9b2013-08-02 14:30:30 -0700272 else:
273 label = label or ''
274 label_list = label.split('/')
275 # Suppose that the path follows old protocol of indexing straight
276 # into static_dir with board/version label.
277 # Attempt to get the update in that directory, generating if necc.
Amin Hassanie9ffb862019-09-25 17:10:40 -0700278 path_to_payload = self.GetUpdateForLabel(label)
joychen121fc9b2013-08-02 14:30:30 -0700279 if path_to_payload is None:
Amin Hassanie9ffb862019-09-25 17:10:40 -0700280 # There was no update found in the directory. Let XBuddy find the
281 # payloads.
joychen121fc9b2013-08-02 14:30:30 -0700282 if label_list[0] == 'xbuddy':
283 # If path explicitly calls xbuddy, pop off the tag.
284 label_list.pop()
Amin Hassanie9ffb862019-09-25 17:10:40 -0700285 x_label, _ = self.xbuddy.Translate(label_list, board=board)
286 # Path has been resolved, try to get the payload.
287 path_to_payload = self.GetUpdateForLabel(x_label)
joychen121fc9b2013-08-02 14:30:30 -0700288 if path_to_payload is None:
Amin Hassanie9ffb862019-09-25 17:10:40 -0700289 # No update payload found after translation. Try to get an update to
290 # a test image from GS using the label.
joychen121fc9b2013-08-02 14:30:30 -0700291 path_to_payload, _image_name = self.xbuddy.Get(
292 ['remote', label, 'full_payload'])
293
294 # One of the above options should have gotten us a relative path.
295 if path_to_payload is None:
296 raise AutoupdateError('Failed to get an update for: %s' % label)
Amin Hassani8d718d12019-06-02 21:28:39 -0700297
298 return path_to_payload
joychen121fc9b2013-08-02 14:30:30 -0700299
Amin Hassani6eec8792020-01-09 14:06:48 -0800300 def HandleUpdatePing(self, data, label='', **kwargs):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800301 """Handles an update ping from an update client.
302
303 Args:
304 data: XML blob from client.
305 label: optional label for the update.
Amin Hassani6eec8792020-01-09 14:06:48 -0800306 kwargs: The map of query strings passed to the /update API.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700307
Chris Sosa6a3697f2013-01-29 16:44:43 -0800308 Returns:
309 Update payload message for client.
310 """
311 # Get the static url base that will form that base of our update url e.g.
312 # http://hostname:8080/static/update.gz.
David Rileyee75de22017-11-02 10:48:15 -0700313 static_urlbase = self.GetStaticUrl()
Amin Hassani86c6fb52020-02-28 11:03:52 -0800314 # Change the URL's string query dictionary provided by cherrypy to a valid
315 # dictionary that has proper values for its keys. e.g. True instead of
316 # 'True'.
317 kwargs = nebraska.QueryDictToDict(kwargs)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800318
Chris Sosab26b1202013-08-16 16:40:55 -0700319 # Process attributes of the update check.
Amin Hassani8d718d12019-06-02 21:28:39 -0700320 request = nebraska.Request(data)
Amin Hassanie7ead902019-10-11 16:42:43 -0700321 self._LogRequest(request)
Chris Sosab26b1202013-08-16 16:40:55 -0700322
Amin Hassani8d718d12019-06-02 21:28:39 -0700323 if request.request_type == nebraska.Request.RequestType.EVENT:
Gilad Arnolde7819e72014-03-21 12:50:48 -0700324 _Log('A non-update event notification received. Returning an ack.')
Amin Hassani083e3fe2020-02-13 11:39:18 -0800325 return nebraska.Nebraska().GetResponseToRequest(
326 request, response_props=nebraska.ResponseProperties(**kwargs))
Chris Sosa6a3697f2013-01-29 16:44:43 -0800327
Amin Hassani8d718d12019-06-02 21:28:39 -0700328 _Log('Update Check Received.')
Chris Sosa6a3697f2013-01-29 16:44:43 -0800329
330 try:
Amin Hassanie7ead902019-10-11 16:42:43 -0700331 path_to_payload = self.GetPathToPayload(label, request.board)
Amin Hassani8d718d12019-06-02 21:28:39 -0700332 base_url = _NonePathJoin(static_urlbase, path_to_payload)
Amin Hassanic9dd11e2019-07-11 15:33:55 -0700333 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800334 except AutoupdateError as e:
335 # Raised if we fail to generate an update payload.
Amin Hassani8d718d12019-06-02 21:28:39 -0700336 _Log('Failed to process an update request, but we will defer to '
337 'nebraska to respond with no-update. The error was %s', e)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800338
Amin Hassani6eec8792020-01-09 14:06:48 -0800339 if self.critical_update:
340 kwargs['critical_update'] = True
341
Amin Hassani8d718d12019-06-02 21:28:39 -0700342 _Log('Responding to client to use url %s to get image', base_url)
Amin Hassanic91fc0d2019-12-04 11:07:16 -0800343 nebraska_props = nebraska.NebraskaProperties(
344 update_payloads_address=base_url,
345 update_metadata_dir=local_payload_dir)
Amin Hassanic91fc0d2019-12-04 11:07:16 -0800346 nebraska_obj = nebraska.Nebraska(nebraska_props=nebraska_props)
Amin Hassani083e3fe2020-02-13 11:39:18 -0800347 return nebraska_obj.GetResponseToRequest(
348 request, response_props=nebraska.ResponseProperties(**kwargs))
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800349
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700350 def HandleHostInfoPing(self, ip):
351 """Returns host info dictionary for the given IP in JSON format."""
352 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800353 if ip in self.host_infos.table:
354 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
355
356 def HandleHostLogPing(self, ip):
357 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700358 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 13:47:02 -0800359 if ip == 'all':
360 return json.dumps(
361 dict([(key, self.host_infos.table[key].log)
362 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700363
364 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 13:47:02 -0800365 if ip in self.host_infos.table:
366 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700367
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700368 # If no events were logged for this IP, return an empty log.
369 return json.dumps([])