blob: 91876995f8a6355ef68deec5c1c43361e5a156d9 [file] [log] [blame]
Darin Petkovc3fd90c2011-05-11 21:23:001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
[email protected]ded22402009-10-26 22:36:212# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Gilad Arnoldd8d595c2014-03-21 20:00:415"""Devserver module for handling update client requests."""
6
Don Garrettfb15e322016-06-22 02:12:087from __future__ import print_function
8
David Zeuthen52ccd012013-10-31 19:58:269import base64
Gilad Arnolde7819e72014-03-21 19:50:4810import collections
Matthew Sartori497105b2015-12-08 22:01:5711import fcntl
Dale Curtisc9aaf3a2011-08-09 22:47:4012import json
[email protected]ded22402009-10-26 22:36:2113import os
Chris Sosa05491b12010-11-09 01:14:1614import subprocess
Gilad Arnolde74b3812013-04-22 18:27:3815import sys
Gilad Arnoldd0c71752013-12-06 19:48:4516import threading
Darin Petkov2b2ff4b2010-07-27 22:02:0917import time
Gilad Arnold0c9c8602012-10-03 06:58:5818import urllib2
Don Garrett0ad09372010-12-07 00:20:3019import urlparse
Chris Sosa7c931362010-10-12 02:49:0120
Gilad Arnoldabb352e2012-09-23 08:24:2721import cherrypy
22
joychen921e1fb2013-06-28 18:12:2023import build_util
Chris Sosa52148582012-11-15 23:35:5824import autoupdate_lib
Gilad Arnold55a2a372012-10-02 16:46:3225import common_util
joychen7c2054a2013-07-25 18:14:0726import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 22:17:4827import log_util
Gilad Arnolde74b3812013-04-22 18:27:3828# pylint: disable=F0401
Amin Hassani51780c62017-08-10 20:55:3529
30# Allow importing from aosp/system/update_engine/scripts when running from
31# source tree. Used for importing update_payload if it is not in the system
32# path.
33lib_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'aosp',
34 'system', 'update_engine', 'scripts')
35if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
36 sys.path.insert(1, lib_dir)
Gilad Arnolde74b3812013-04-22 18:27:3837import update_payload
Chris Sosa05491b12010-11-09 01:14:1638
Gilad Arnoldc65330c2012-09-20 22:17:4839
joychen121fc9b2013-08-02 21:30:3040# If used by client in place of an pre-update version string, forces an update
41# to the client regardless of the relative versions of the payload and client.
42FORCED_UPDATE = 'ForcedUpdate'
43
Gilad Arnoldc65330c2012-09-20 22:17:4844# Module-local log function.
Chris Sosa6a3697f2013-01-30 00:44:4345def _Log(message, *args):
46 return log_util.LogWithTag('UPDATE', message, *args)
Gilad Arnoldc65330c2012-09-20 22:17:4847
[email protected]ded22402009-10-26 22:36:2148
Gilad Arnold0c9c8602012-10-03 06:58:5849class AutoupdateError(Exception):
50 """Exception classes used by this module."""
51 pass
52
53
Don Garrett0ad09372010-12-07 00:20:3054def _ChangeUrlPort(url, new_port):
55 """Return the URL passed in with a different port"""
56 scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
57 host_port = netloc.split(':')
58
59 if len(host_port) == 1:
60 host_port.append(new_port)
61 else:
62 host_port[1] = new_port
63
Don Garrettfb15e322016-06-22 02:12:0864 print(host_port)
joychen121fc9b2013-08-02 21:30:3065 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-07 00:20:3066
67 return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
68
Chris Sosa6a3697f2013-01-30 00:44:4369def _NonePathJoin(*args):
70 """os.path.join that filters None's from the argument list."""
71 return os.path.join(*filter(None, args))
Don Garrett0ad09372010-12-07 00:20:3072
Chris Sosa6a3697f2013-01-30 00:44:4373
74class HostInfo(object):
Gilad Arnold286a0062012-01-12 21:47:0275 """Records information about an individual host.
76
77 Members:
78 attrs: Static attributes (legacy)
79 log: Complete log of recorded client entries
80 """
81
82 def __init__(self):
83 # A dictionary of current attributes pertaining to the host.
84 self.attrs = {}
85
86 # A list of pairs consisting of a timestamp and a dictionary of recorded
87 # attributes.
88 self.log = []
89
90 def __repr__(self):
91 return 'attrs=%s, log=%s' % (self.attrs, self.log)
92
93 def AddLogEntry(self, entry):
94 """Append a new log entry."""
95 # Append a timestamp.
96 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
97 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
98 # Add entry to hosts' message log.
99 self.log.append(entry)
100
Gilad Arnold286a0062012-01-12 21:47:02101
Chris Sosa6a3697f2013-01-30 00:44:43102class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 21:47:02103 """Records information about a set of hosts who engage in update activity.
104
105 Members:
106 table: Table of information on hosts.
107 """
108
109 def __init__(self):
110 # A dictionary of host information. Keys are normally IP addresses.
111 self.table = {}
112
113 def __repr__(self):
114 return '%s' % self.table
115
116 def GetInitHostInfo(self, host_id):
117 """Return a host's info object, or create a new one if none exists."""
118 return self.table.setdefault(host_id, HostInfo())
119
120 def GetHostInfo(self, host_id):
121 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-30 01:07:27122 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 21:47:02123
124
Chris Sosa6a3697f2013-01-30 00:44:43125class UpdateMetadata(object):
126 """Object containing metadata about an update payload."""
127
David Zeuthen52ccd012013-10-31 19:58:26128 def __init__(self, sha1, sha256, size, is_delta_format, metadata_size,
129 metadata_hash):
Chris Sosa6a3697f2013-01-30 00:44:43130 self.sha1 = sha1
131 self.sha256 = sha256
132 self.size = size
133 self.is_delta_format = is_delta_format
David Zeuthen52ccd012013-10-31 19:58:26134 self.metadata_size = metadata_size
135 self.metadata_hash = metadata_hash
Chris Sosa6a3697f2013-01-30 00:44:43136
137
joychen921e1fb2013-06-28 18:12:20138class Autoupdate(build_util.BuildObject):
Chris Sosa0356d3b2010-09-16 22:46:22139 """Class that contains functionality that handles Chrome OS update pings.
140
141 Members:
Gilad Arnold0c9c8602012-10-03 06:58:58142 forced_image: path to an image to use for all updates.
143 payload_path: path to pre-generated payload to serve.
144 src_image: if specified, creates a delta payload from this image.
145 proxy_port: port of local proxy to tell client to connect to you
146 through.
Gilad Arnold0c9c8602012-10-03 06:58:58147 board: board for the image. Needed for pre-generating of updates.
148 copy_to_static_root: copies images generated from the cache to ~/static.
David Zeuthen52ccd012013-10-31 19:58:26149 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 19:52:23150 critical_update: whether provisioned payload is critical.
Gilad Arnold8318eac2012-10-04 19:52:23151 max_updates: maximum number of updates we'll try to provision.
152 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 22:46:22153 """
[email protected]ded22402009-10-26 22:36:21154
joychened64b222013-06-21 23:39:34155 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-03 06:58:58156 _PAYLOAD_URL_PREFIX = '/static/'
157 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
158
Chris Sosa6a3697f2013-01-30 00:44:43159 SHA1_ATTR = 'sha1'
160 SHA256_ATTR = 'sha256'
161 SIZE_ATTR = 'size'
162 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 19:58:26163 METADATA_SIZE_ATTR = 'metadata_size'
164 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-30 00:44:43165
Amin Hassanic9dd11e2019-07-11 22:33:55166 def __init__(self, xbuddy, forced_image=None, payload_path=None,
Gabe Black70994862014-09-05 07:50:58167 proxy_port=None, src_image='', board=None,
Amin Hassaniabedfaa2019-06-03 04:30:48168 copy_to_static_root=True, public_key=None,
Amin Hassanic9dd11e2019-07-11 22:33:55169 critical_update=False, max_updates=-1, host_log=False,
170 *args, **kwargs):
Sean O'Connor14b6a0a2010-03-21 06:23:48171 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 21:30:30172 self.xbuddy = xbuddy
Chris Sosa0356d3b2010-09-16 22:46:22173 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-03 06:58:58174 self.payload_path = payload_path
Chris Sosa62f720b2010-10-27 04:39:48175 self.src_image = src_image
Don Garrett0ad09372010-12-07 00:20:30176 self.proxy_port = proxy_port
joychen562699a2013-08-13 22:22:14177 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-20 00:08:02178 self.copy_to_static_root = copy_to_static_root
David Zeuthen52ccd012013-10-31 19:58:26179 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 17:36:32180 self.critical_update = critical_update
Jay Srinivasanac69d262012-10-31 02:05:53181 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 19:52:23182 self.host_log = host_log
Don Garrettfff4c322010-11-19 21:37:12183
Chris Sosa417e55d2011-01-26 00:40:48184 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-21 06:23:48185
Dale Curtisc9aaf3a2011-08-09 22:47:40186 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 21:47:02187 # information about a given host. A host is identified by its IP address.
188 # The info stored for each host includes a complete log of events for this
189 # host, as well as a dictionary of current attributes derived from events.
190 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 22:47:40191
Gilad Arnolde7819e72014-03-21 19:50:48192 self._update_count_lock = threading.Lock()
Gilad Arnoldd0c71752013-12-06 19:48:45193
Chris Sosa6a3697f2013-01-30 00:44:43194 @classmethod
195 def _ReadMetadataFromStream(cls, stream):
196 """Returns metadata obj from input json stream that implements .read()."""
Chung-yih Wangdcf798a2016-06-23 16:03:24197 data = None
Chris Sosa6a3697f2013-01-30 00:44:43198 file_attr_dict = {}
199 try:
Chung-yih Wangdcf798a2016-06-23 16:03:24200 data = stream.read()
201 file_attr_dict = json.loads(data)
202 except (IOError, ValueError):
203 _Log('Failed to load metadata:%s' % data)
Chris Sosa6a3697f2013-01-30 00:44:43204 return None
205
206 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
207 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
208 size = file_attr_dict.get(cls.SIZE_ATTR)
209 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 19:58:26210 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
211 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
212 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
213 metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43214
215 @staticmethod
216 def _ReadMetadataFromFile(payload_dir):
217 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 21:54:16218 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43219 if os.path.exists(metadata_file):
Matthew Sartori497105b2015-12-08 22:01:57220 metadata_stream = open(metadata_file, 'r')
221 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_SH)
222 metadata = Autoupdate._ReadMetadataFromStream(metadata_stream)
223 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_UN)
224 return metadata
Chris Sosa6a3697f2013-01-30 00:44:43225
226 @classmethod
227 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
228 """Stores metadata object into the metadata_file of the payload_dir"""
229 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
230 cls.SHA256_ATTR: metadata_obj.sha256,
231 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 19:58:26232 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
233 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
234 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 21:54:16235 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Matthew Sartori497105b2015-12-08 22:01:57236 file_handle = open(metadata_file, 'w')
237 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_EX)
238 json.dump(file_dict, file_handle)
239 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_UN)
Chris Sosa6a3697f2013-01-30 00:44:43240
Chris Sosa52148582012-11-15 23:35:58241 @staticmethod
242 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 22:46:22243 """Returns the version of the image based on the name of the directory."""
244 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 15:52:52245 parts = latest_version.split('-')
joychen121fc9b2013-08-02 21:30:30246 # If we can't get a version number from the directory, default to a high
247 # number to allow the update to happen
Paul Hobbs5e7b5a72017-10-04 18:02:39248 # TODO(phobbs) refactor this.
249 return parts[1] if len(parts) == 3 else "999999.0.0"
Chris Sosa0356d3b2010-09-16 22:46:22250
Chris Sosa52148582012-11-15 23:35:58251 @staticmethod
252 def _CanUpdate(client_version, latest_version):
Don Garrettfb15e322016-06-22 02:12:08253 """True if the latest_version is greater than the client_version."""
Chris Sosa6a3697f2013-01-30 00:44:43254 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 15:52:52255
256 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52257 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52258
Paul Hobbs5e7b5a72017-10-04 18:02:39259 def _SafeInt(part):
260 try:
261 return int(part)
262 except ValueError:
263 return part
264
joychen121fc9b2013-08-02 21:30:30265 if len(latest_tokens) == len(client_tokens) == 3:
Paul Hobbs5e7b5a72017-10-04 18:02:39266 return map(_SafeInt, latest_tokens) > map(_SafeInt, client_tokens)
Chris Sosa0356d3b2010-09-16 22:46:22267 else:
joychen121fc9b2013-08-02 21:30:30268 # If the directory name isn't a version number, let it pass.
269 return True
Chris Sosa0356d3b2010-09-16 22:46:22270
Chris Sosa52148582012-11-15 23:35:58271 @staticmethod
Gilad Arnolde74b3812013-04-22 18:27:38272 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-26 00:34:49273 try:
Gilad Arnolde74b3812013-04-22 18:27:38274 with open(filename) as payload_file:
275 payload = update_payload.Payload(payload_file)
276 payload.Init()
277 return payload.IsDelta()
278 except (IOError, update_payload.PayloadError):
279 # For unit tests we may not have real files, so it's ok to ignore these
280 # errors.
Andrew de los Reyes5679b972010-10-26 00:34:49281 return False
282
Don Garrettf90edf02010-11-17 01:36:14283 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 22:46:22284 """Generates an update gz given a full path to an image.
285
286 Args:
Gilad Arnoldd8d595c2014-03-21 20:00:41287 src_image: Path to a source image.
Chris Sosa0356d3b2010-09-16 22:46:22288 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 20:00:41289 output_dir: Path to the generated update file.
290
Chris Sosa6a3697f2013-01-30 00:44:43291 Raises:
292 subprocess.CalledProcessError if the update generator fails to generate a
293 stateful payload.
Chris Sosa0356d3b2010-09-16 22:46:22294 """
joychen7c2054a2013-07-25 18:14:07295 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43296 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 22:46:22297
Chris Sosa0f1ec842011-02-15 00:33:22298 update_command = [
Chris Sosa5b8b5eb2012-03-27 18:15:27299 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-30 00:44:43300 '--image', image_path,
David Zeuthen52ccd012013-10-31 19:58:26301 '--out_metadata_hash_file', os.path.join(output_dir,
302 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-30 00:44:43303 '--output', update_path,
Chris Sosa0f1ec842011-02-15 00:33:22304 ]
Chris Sosa4136e692010-10-29 06:42:37305
Chris Sosa52148582012-11-15 23:35:58306 if src_image:
Chris Sosa6a3697f2013-01-30 00:44:43307 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 23:35:58308
Chris Sosa6a3697f2013-01-30 00:44:43309 _Log('Running %s', ' '.join(update_command))
310 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 22:46:22311
Chris Sosa52148582012-11-15 23:35:58312 @staticmethod
313 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14314 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 22:46:22315
316 Args:
317 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 20:00:41318 output_dir: Directory for emitting the stateful update payload.
319
Chris Sosa908fd6f2010-11-11 01:31:18320 Raises:
Chris Sosa6a3697f2013-01-30 00:44:43321 subprocess.CalledProcessError if the update generator fails to generate a
Chris Sosa908fd6f2010-11-11 01:31:18322 stateful payload.
Chris Sosa0356d3b2010-09-16 22:46:22323 """
Chris Sosa6a3697f2013-01-30 00:44:43324 update_command = [
325 'cros_generate_stateful_update_payload',
326 '--image', image_path,
327 '--output_dir', output_dir,
328 ]
329 _Log('Running %s', ' '.join(update_command))
330 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 22:46:22331
Don Garrettf90edf02010-11-17 01:36:14332 def FindCachedUpdateImageSubDir(self, src_image, dest_image):
333 """Find directory to store a cached update.
334
Gilad Arnold55a2a372012-10-02 16:46:32335 Given one, or two images for an update, this finds which cache directory
336 should hold the update files, even if they don't exist yet.
Don Garrettf90edf02010-11-17 01:36:14337
Gilad Arnold55a2a372012-10-02 16:46:32338 Returns:
339 A directory path for storing a cached update, of the following form:
340 Non-delta updates:
341 CACHE_DIR/<dest_hash>
342 Delta updates:
343 CACHE_DIR/<src_hash>_<dest_hash>
Chris Sosa744e1472011-09-08 02:32:50344 """
Gilad Arnold55a2a372012-10-02 16:46:32345 update_dir = ''
Chris Sosa744e1472011-09-08 02:32:50346 if src_image:
Gilad Arnold55a2a372012-10-02 16:46:32347 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-17 01:36:14348
Gilad Arnold55a2a372012-10-02 16:46:32349 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-08 02:32:50350
joychen25d25972013-07-30 21:54:16351 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-17 01:36:14352
Don Garrettfff4c322010-11-19 21:37:12353 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14354 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 22:46:22355
Chris Sosade91f672010-11-16 18:05:44356 Args:
Don Garrettf90edf02010-11-17 01:36:14357 image_path: full path to the image.
Chris Sosa6a3697f2013-01-30 00:44:43358 output_dir: the directory to write the update payloads to
Gilad Arnoldd8d595c2014-03-21 20:00:41359
Chris Sosa6a3697f2013-01-30 00:44:43360 Raises:
361 AutoupdateError if it failed to generate either update or stateful
362 payload.
Chris Sosade91f672010-11-16 18:05:44363 """
Chris Sosa6a3697f2013-01-30 00:44:43364 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 17:29:43365
Chris Sosa6a3697f2013-01-30 00:44:43366 # Delete any previous state in this directory.
367 os.system('rm -rf "%s"' % output_dir)
368 os.makedirs(output_dir)
[email protected]ded22402009-10-26 22:36:21369
Chris Sosa6a3697f2013-01-30 00:44:43370 try:
371 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
372 self.GenerateStatefulFile(image_path, output_dir)
373 except subprocess.CalledProcessError:
374 os.system('rm -rf "%s"' % output_dir)
375 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-17 01:36:14376
Chris Sosa75490802013-10-01 00:21:45377 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-17 01:36:14378 """Force generates an update payload based on the given image_path.
[email protected]ded22402009-10-26 22:36:21379
Chris Sosa0356d3b2010-09-16 22:46:22380 Args:
381 image_path: full path to the image.
Gilad Arnoldd8d595c2014-03-21 20:00:41382
Chris Sosa0356d3b2010-09-16 22:46:22383 Returns:
joychen121fc9b2013-08-02 21:30:30384 update directory relative to static_image_dir.
Gilad Arnoldd8d595c2014-03-21 20:00:41385
Chris Sosa6a3697f2013-01-30 00:44:43386 Raises:
387 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 22:46:22388 """
Chris Sosa6a3697f2013-01-30 00:44:43389 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f12010-11-05 00:33:16390
joychen121fc9b2013-08-02 21:30:30391 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-26 00:40:48392 if self.pregenerated_path:
393 return self.pregenerated_path
Don Garrettfff4c322010-11-19 21:37:12394
Chris Sosa75490802013-10-01 00:21:45395 # Which sub_dir should hold our cached update image.
396 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-30 00:44:43397 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-26 00:40:48398
joychen121fc9b2013-08-02 21:30:30399 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-10-01 00:21:45400 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 21:30:30401
402 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 18:14:07403 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 21:30:30404 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 21:54:16405 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-26 00:40:48406 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 21:30:30407 if not (os.path.exists(cache_update_payload) and
408 os.path.exists(cache_stateful_payload)):
409 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-17 01:36:14410
joychen121fc9b2013-08-02 21:30:30411 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-30 00:44:43412 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-22 02:59:21413
Chris Sosa6a3697f2013-01-30 00:44:43414 # Generate the cache file.
joychen121fc9b2013-08-02 21:30:30415 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14416
joychen121fc9b2013-08-02 21:30:30417 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 22:46:22418
Chris Sosa75490802013-10-01 00:21:45419 def _SymlinkUpdateFiles(self, target_dir, link_dir):
420 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 21:30:30421
422 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-10-01 00:21:45423 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 22:46:22424
425 Args:
Chris Sosa75490802013-10-01 00:21:45426 target_dir: Location of the target files.
427 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 22:46:22428 """
Chris Sosa75490802013-10-01 00:21:45429 _Log('Linking %s to %s', target_dir, link_dir)
430 if link_dir == target_dir:
431 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 21:30:30432 return
Amin Hassanicf2e4022019-04-30 15:48:38433 for _, _, files in os.walk(target_dir):
434 for target in files:
435 link = os.path.join(link_dir, target)
436 target = os.path.join(target_dir, target)
437 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 22:46:22438
joychen121fc9b2013-08-02 21:30:30439 def GetUpdateForLabel(self, client_version, label,
440 image_name=constants.TEST_IMAGE_FILE):
441 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 22:46:22442
joychen121fc9b2013-08-02 21:30:30443 Args:
444 client_version: Current version of the client or FORCED_UPDATE
445 label: the relative directory inside the static dir
446 image_name: If the image type was specified by the update rpc, we try to
447 find an image with this file name first. This is by default
448 "chromiumos_test_image.bin" but can also take any of the values in
449 devserver_constants.ALL_IMAGES
Gilad Arnoldd8d595c2014-03-21 20:00:41450
Chris Sosa6a3697f2013-01-30 00:44:43451 Returns:
joychen121fc9b2013-08-02 21:30:30452 A relative path to the directory with the update payload.
453 This is the label if an update did not need to be generated, but can
454 be label/cache/hashed_dir_for_update.
Gilad Arnoldd8d595c2014-03-21 20:00:41455
Chris Sosa6a3697f2013-01-30 00:44:43456 Raises:
joychen121fc9b2013-08-02 21:30:30457 AutoupdateError: If client version is higher than available update found
458 at the directory given by the label.
Don Garrettf90edf02010-11-17 01:36:14459 """
joychen121fc9b2013-08-02 21:30:30460 _Log('Update label/file: %s/%s', label, image_name)
461 static_image_dir = _NonePathJoin(self.static_dir, label)
462 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
463 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 18:14:07464
joychen121fc9b2013-08-02 21:30:30465 # Update the client only if client version is older than available update.
466 latest_version = self._GetVersionFromDir(static_image_dir)
467 if not (client_version == FORCED_UPDATE or
468 self._CanUpdate(client_version, latest_version)):
469 raise AutoupdateError(
470 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 20:09:35471
joychen121fc9b2013-08-02 21:30:30472 if label and os.path.exists(static_update_path):
473 # An update payload was found for the given label, return it.
474 return label
475 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
476 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45477 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
478 # Add links from the static directory to the update.
479 cache_path = _NonePathJoin(self.static_dir, rel_path)
480 self._SymlinkUpdateFiles(cache_path, static_image_dir)
481 return label
Don Garrett0c880e22010-11-18 02:13:37482
joychen121fc9b2013-08-02 21:30:30483 # The label didn't resolve.
484 return None
Chris Sosa2c048f12010-10-27 23:05:27485
486 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-26 00:40:48487 """Pre-generates an update and prints out the relative path it.
488
Chris Sosa6a3697f2013-01-30 00:44:43489 Returns relative path of the update.
Chris Sosa65d339b2013-01-22 02:59:21490
Chris Sosa6a3697f2013-01-30 00:44:43491 Raises:
492 AutoupdateError if it failed to generate the payload.
493 """
494 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 21:30:30495 # Does not work with labels so just use static dir. (empty label)
496 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Don Garrettfb15e322016-06-22 02:12:08497 print('PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
498 constants.UPDATE_FILE))
Chris Sosa417e55d2011-01-26 00:40:48499 return pregenerated_update
Chris Sosa2c048f12010-10-27 23:05:27500
David Zeuthen52ccd012013-10-31 19:58:26501 @staticmethod
502 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 18:38:16503 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 19:58:26504
505 Args:
506 payload_dir: The payload directory.
Gilad Arnoldd8d595c2014-03-21 20:00:41507
David Zeuthen52ccd012013-10-31 19:58:26508 Returns:
David Zeuthenf27f1502013-11-13 18:38:16509 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 19:58:26510 """
511 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 18:38:16512 if os.path.exists(path):
513 return base64.b64encode(open(path, 'rb').read())
514 else:
515 return None
David Zeuthen52ccd012013-10-31 19:58:26516
517 @staticmethod
518 def _GetMetadataSize(payload_filename):
519 """Gets the size of the metadata in a payload file.
520
521 Args:
522 payload_filename: Path to the payload file.
Gilad Arnoldd8d595c2014-03-21 20:00:41523
David Zeuthen52ccd012013-10-31 19:58:26524 Returns:
525 The size of the payload metadata, as reported in the payload header.
526 """
Alex Deymoa6ac00d2015-10-15 16:14:58527 try:
528 with open(payload_filename) as payload_file:
529 payload = update_payload.Payload(payload_file)
530 payload.Init()
531 return payload.metadata_size
532 except (IOError, update_payload.PayloadError):
533 # For unit tests we may not have real files, so it's ok to ignore these
534 # errors.
David Zeuthen52ccd012013-10-31 19:58:26535 return 0
David Zeuthen52ccd012013-10-31 19:58:26536
Chris Sosa6a3697f2013-01-30 00:44:43537 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-03 06:58:58538 """Returns hashes, size and delta flag of a local update payload.
539
540 Args:
Chris Sosa6a3697f2013-01-30 00:44:43541 payload_dir: Path to the directory the payload is in.
Gilad Arnoldd8d595c2014-03-21 20:00:41542
Gilad Arnold0c9c8602012-10-03 06:58:58543 Returns:
David Zeuthen52ccd012013-10-31 19:58:26544 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-03 06:58:58545 """
joychen7c2054a2013-07-25 18:14:07546 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43547 if not os.path.exists(filename):
548 raise AutoupdateError('update.gz not present in payload dir %s' %
549 payload_dir)
Gilad Arnold0c9c8602012-10-03 06:58:58550
Chris Sosa6a3697f2013-01-30 00:44:43551 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
552 if not metadata_obj or not (metadata_obj.sha1 and
553 metadata_obj.sha256 and
554 metadata_obj.size):
555 sha1 = common_util.GetFileSha1(filename)
556 sha256 = common_util.GetFileSha256(filename)
557 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 18:27:38558 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 19:58:26559 metadata_size = self._GetMetadataSize(filename)
560 metadata_hash = self._GetMetadataHash(payload_dir)
561 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
562 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43563 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 22:46:22564
Chris Sosa6a3697f2013-01-30 00:44:43565 return metadata_obj
566
567 def _ProcessUpdateComponents(self, app, event):
Gilad Arnolde7819e72014-03-21 19:50:48568 """Processes the components of an update request.
Chris Sosa6a3697f2013-01-30 00:44:43569
Gilad Arnolde7819e72014-03-21 19:50:48570 Args:
571 app: An app component of an update request.
572 event: An event component of an update request.
573
574 Returns:
575 A named tuple containing attributes of the update requests as the
576 following fields: 'forced_update_label', 'client_version', 'board',
577 'event_result' and 'event_type'.
Chris Sosa0356d3b2010-09-16 22:46:22578 """
Chris Sosa6a3697f2013-01-30 00:44:43579 # Initialize an empty dictionary for event attributes to log.
580 log_message = {}
Jay Srinivasanac69d262012-10-31 02:05:53581
Dale Curtisc9aaf3a2011-08-09 22:47:40582 # Determine request IP, strip any IPv6 data for simplicity.
583 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 21:47:02584 # Obtain (or init) info object for this client.
585 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
586
joychen121fc9b2013-08-02 21:30:30587 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-30 00:44:43588 board = None
589 if app:
590 client_version = app.getAttribute('version')
591 channel = app.getAttribute('track')
592 board = (app.hasAttribute('board') and app.getAttribute('board')
Don Garrettfb15e322016-06-22 02:12:08593 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-30 00:44:43594 # Add attributes to log message
595 log_message['version'] = client_version
596 log_message['track'] = channel
597 log_message['board'] = board
598 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 22:47:40599
Gilad Arnolde7819e72014-03-21 19:50:48600 event_result = None
601 event_type = None
Dale Curtisc9aaf3a2011-08-09 22:47:40602 if event:
Gilad Arnold286a0062012-01-12 21:47:02603 event_result = int(event[0].getAttribute('eventresult'))
604 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 22:33:21605 client_previous_version = (event[0].getAttribute('previousversion')
606 if event[0].hasAttribute('previousversion')
607 else None)
Gilad Arnold286a0062012-01-12 21:47:02608 # Store attributes to legacy host info structure
609 curr_host_info.attrs['last_event_status'] = event_result
610 curr_host_info.attrs['last_event_type'] = event_type
611 # Add attributes to log message
612 log_message['event_result'] = event_result
613 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 22:33:21614 if client_previous_version is not None:
615 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 21:47:02616
Gilad Arnold8318eac2012-10-04 19:52:23617 # Log host event, if so instructed.
618 if self.host_log:
619 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 22:47:40620
Gilad Arnolde7819e72014-03-21 19:50:48621 UpdateRequestAttrs = collections.namedtuple(
622 'UpdateRequestAttrs',
623 ('forced_update_label', 'client_version', 'board', 'event_result',
624 'event_type'))
625
626 return UpdateRequestAttrs(
627 curr_host_info.attrs.pop('forced_update_label', None),
628 client_version, board, event_result, event_type)
Chris Sosa6a3697f2013-01-30 00:44:43629
Chris Sosa4b951602014-04-10 03:26:07630 @classmethod
631 def _CheckOmahaRequest(cls, app):
632 """Checks |app| component of Omaha Request for correctly formed data.
633
634 Raises:
635 common_util.DevServerHTTPError: if any check fails. All 400 error codes to
636 indicate a bad HTTP request.
637 """
638 if not app:
639 raise common_util.DevServerHTTPError(
640 400, 'Missing app component in Omaha Request')
641
642 hardware_class = app.getAttribute('hardware_class')
643 if not hardware_class:
644 raise common_util.DevServerHTTPError(
645 400, 'hardware_class is required in Omaha Request')
646
647 track = app.getAttribute('track')
Chris Sosafc715442014-04-10 03:45:23648 if not (track and track.endswith('-channel')):
Chris Sosa4b951602014-04-10 03:26:07649 raise common_util.DevServerHTTPError(
Chris Sosafc715442014-04-10 03:45:23650 400, 'Omaha requests need a valid update channel')
Chris Sosa4b951602014-04-10 03:26:07651
David Rileyee75de22017-11-02 17:48:15652 def GetDevserverUrl(self):
653 """Returns the devserver url base."""
Chris Sosa6a3697f2013-01-30 00:44:43654 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
655 if x_forwarded_host:
656 hostname = 'http://' + x_forwarded_host
657 else:
658 hostname = cherrypy.request.base
659
David Rileyee75de22017-11-02 17:48:15660 return hostname
661
662 def GetStaticUrl(self):
663 """Returns the static url base that should prefix all payload responses."""
664 hostname = self.GetDevserverUrl()
665
Amin Hassanic9dd11e2019-07-11 22:33:55666 static_urlbase = '%s/static' % hostname
Chris Sosa6a3697f2013-01-30 00:44:43667 # If we have a proxy port, adjust the URL we instruct the client to
668 # use to go through the proxy.
669 if self.proxy_port:
670 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
671
672 _Log('Using static url base %s', static_urlbase)
673 _Log('Handling update ping as %s', hostname)
674 return static_urlbase
675
joychen121fc9b2013-08-02 21:30:30676 def GetPathToPayload(self, label, client_version, board):
677 """Find a payload locally.
678
679 See devserver's update rpc for documentation.
680
681 Args:
682 label: from update request
683 client_version: from update request
684 board: from update request
Gilad Arnoldd8d595c2014-03-21 20:00:41685
686 Returns:
joychen121fc9b2013-08-02 21:30:30687 The relative path to an update from the static_dir
Gilad Arnoldd8d595c2014-03-21 20:00:41688
joychen121fc9b2013-08-02 21:30:30689 Raises:
690 AutoupdateError: If the update could not be found.
691 """
692 path_to_payload = None
693 #TODO(joychen): deprecate --payload flag
694 if self.payload_path:
695 # Copy the image from the path to '/forced_payload'
696 label = 'forced_payload'
697 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
698 dest_stateful = os.path.join(self.static_dir, label,
699 constants.STATEFUL_FILE)
Alex Deymo48e970d2015-09-23 21:34:41700 dest_meta = os.path.join(self.static_dir, label, constants.METADATA_FILE)
joychen121fc9b2013-08-02 21:30:30701
702 src_path = os.path.abspath(self.payload_path)
703 src_stateful = os.path.join(os.path.dirname(src_path),
704 constants.STATEFUL_FILE)
705 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-04 04:49:41706 common_util.SymlinkFile(src_path, dest_path)
Alex Deymo48e970d2015-09-23 21:34:41707 # The old metadata file should be regenerated whenever a new payload is
708 # used.
709 try:
710 os.unlink(dest_meta)
711 except OSError:
712 pass
joychen121fc9b2013-08-02 21:30:30713 if os.path.exists(src_stateful):
714 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-04 04:49:41715 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 21:30:30716 else:
717 _Log('WARN: %s not found. Expected for dev and test builds',
718 constants.STATEFUL_FILE)
719 if os.path.exists(dest_stateful):
720 os.remove(dest_stateful)
721 path_to_payload = self.GetUpdateForLabel(client_version, label)
722 #TODO(joychen): deprecate --image flag
723 elif self.forced_image:
joychendbfe6c92013-08-17 03:03:49724 if self.forced_image.startswith('xbuddy:'):
725 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-17 03:03:49726 xbuddy_label = self.forced_image.split(':')[1]
727 self.forced_image = None
joychen365a5742013-08-21 17:41:18728 # Make sure the xbuddy path target is in the directory.
729 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
730 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 23:45:12731 self.GetPathToPayload(xbuddy_label, client_version, board)
732 else:
733 src_path = os.path.abspath(self.forced_image)
734 if os.path.exists(src_path) and common_util.IsInsideChroot():
735 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45736 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
737 # Add links from the static directory to the update.
738 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
739 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 21:30:30740 else:
741 label = label or ''
742 label_list = label.split('/')
743 # Suppose that the path follows old protocol of indexing straight
744 # into static_dir with board/version label.
745 # Attempt to get the update in that directory, generating if necc.
746 path_to_payload = self.GetUpdateForLabel(client_version, label)
747 if path_to_payload is None:
748 # There was no update or image found in the directory.
749 # Let XBuddy find an image, and then generate an update to it.
750 if label_list[0] == 'xbuddy':
751 # If path explicitly calls xbuddy, pop off the tag.
752 label_list.pop()
Chris Sosa75490802013-10-01 00:21:45753 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 21:30:30754 if image_name not in constants.ALL_IMAGES:
755 raise AutoupdateError(
756 "Use an image alias: dev, base, test, or recovery.")
757 # Path has been resolved, try to get the image.
758 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
759 image_name)
760 if path_to_payload is None:
761 # Neither image nor update payload found after translation.
762 # Try to get an update to a test image from GS using the label.
763 path_to_payload, _image_name = self.xbuddy.Get(
764 ['remote', label, 'full_payload'])
765
766 # One of the above options should have gotten us a relative path.
767 if path_to_payload is None:
768 raise AutoupdateError('Failed to get an update for: %s' % label)
769 else:
Chris Sosa75490802013-10-01 00:21:45770 return path_to_payload
joychen121fc9b2013-08-02 21:30:30771
772 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-30 00:44:43773 """Handles an update ping from an update client.
774
775 Args:
776 data: XML blob from client.
777 label: optional label for the update.
Gilad Arnoldd8d595c2014-03-21 20:00:41778
Chris Sosa6a3697f2013-01-30 00:44:43779 Returns:
780 Update payload message for client.
781 """
782 # Get the static url base that will form that base of our update url e.g.
783 # http://hostname:8080/static/update.gz.
David Rileyee75de22017-11-02 17:48:15784 static_urlbase = self.GetStaticUrl()
Chris Sosa6a3697f2013-01-30 00:44:43785
786 # Parse the XML we got into the components we care about.
787 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
Amin Hassanid7a913a2018-03-13 22:19:24788 appid = app.getAttribute('appid')
Chris Sosa6a3697f2013-01-30 00:44:43789
Chris Sosab26b1202013-08-16 23:40:55790 # Process attributes of the update check.
Gilad Arnolde7819e72014-03-21 19:50:48791 request_attrs = self._ProcessUpdateComponents(app, event)
Chris Sosab26b1202013-08-16 23:40:55792
joychen121fc9b2013-08-02 21:30:30793 if not update_check:
Gilad Arnolde7819e72014-03-21 19:50:48794 if ((request_attrs.event_type ==
795 autoupdate_lib.EVENT_TYPE_UPDATE_DOWNLOAD_STARTED) and
796 request_attrs.event_result == autoupdate_lib.EVENT_RESULT_SUCCESS):
797 with self._update_count_lock:
798 if self.max_updates == 0:
799 _Log('Received too many download_started notifications. This '
800 'probably means a bug in the test environment, such as too '
801 'many clients running concurrently. Alternatively, it could '
802 'be a bug in the update client.')
803 elif self.max_updates > 0:
804 self.max_updates -= 1
joychen121fc9b2013-08-02 21:30:30805
Gilad Arnolde7819e72014-03-21 19:50:48806 _Log('A non-update event notification received. Returning an ack.')
Amin Hassanid7a913a2018-03-13 22:19:24807 return autoupdate_lib.GetEventResponse(protocol, appid)
Gilad Arnolde7819e72014-03-21 19:50:48808
809 if request_attrs.forced_update_label:
Chris Sosa6a3697f2013-01-30 00:44:43810 if label:
811 _Log('Label: %s set but being overwritten to %s by request', label,
Gilad Arnolde7819e72014-03-21 19:50:48812 request_attrs.forced_update_label)
813 label = request_attrs.forced_update_label
Chris Sosa6a3697f2013-01-30 00:44:43814
Gilad Arnolde7819e72014-03-21 19:50:48815 # Make sure that we did not already exceed the max number of allowed update
816 # responses. Note that the counter is only decremented when the client
817 # reports an actual download, to avoid race conditions between concurrent
818 # update requests from the same client due to a timeout.
joychen121fc9b2013-08-02 21:30:30819 if self.max_updates == 0:
Gilad Arnolde7819e72014-03-21 19:50:48820 _Log('Request received but max number of updates already served.')
Amin Hassanid7a913a2018-03-13 22:19:24821 return autoupdate_lib.GetNoUpdateResponse(protocol, appid)
joychen121fc9b2013-08-02 21:30:30822
Gilad Arnolde7819e72014-03-21 19:50:48823 _Log('Update Check Received. Client is using protocol version: %s',
824 protocol)
joychen121fc9b2013-08-02 21:30:30825
Chris Sosa6a3697f2013-01-30 00:44:43826 # Finally its time to generate the omaha response to give to client that
827 # lets them know where to find the payload and its associated metadata.
828 metadata_obj = None
829
830 try:
Amin Hassanic9dd11e2019-07-11 22:33:55831 path_to_payload = self.GetPathToPayload(
832 label, request_attrs.client_version, request_attrs.board)
833 url = _NonePathJoin(static_urlbase, path_to_payload,
834 constants.UPDATE_FILE)
835 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
836 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-30 00:44:43837 except AutoupdateError as e:
838 # Raised if we fail to generate an update payload.
839 _Log('Failed to process an update: %r', e)
Amin Hassanid7a913a2018-03-13 22:19:24840 return autoupdate_lib.GetNoUpdateResponse(protocol, appid)
Chris Sosa6a3697f2013-01-30 00:44:43841
David Zeuthen52ccd012013-10-31 19:58:26842 # Include public key, if requested.
843 public_key_data = None
844 if self.public_key:
845 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
846
Chris Sosa4b951602014-04-10 03:26:07847 update_response = autoupdate_lib.GetUpdateResponse(
Chris Sosa6a3697f2013-01-30 00:44:43848 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 19:58:26849 metadata_obj.is_delta_format, metadata_obj.metadata_size,
Amin Hassaniabedfaa2019-06-03 04:30:48850 None, public_key_data, protocol, appid,
Amin Hassanid7a913a2018-03-13 22:19:24851 self.critical_update)
Dale Curtisc9aaf3a2011-08-09 22:47:40852
Gilad Arnolde7819e72014-03-21 19:50:48853 _Log('Responding to client to use url %s to get image', url)
Gilad Arnoldd0c71752013-12-06 19:48:45854 return update_response
855
Dale Curtisc9aaf3a2011-08-09 22:47:40856 def HandleHostInfoPing(self, ip):
857 """Returns host info dictionary for the given IP in JSON format."""
858 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 21:47:02859 if ip in self.host_infos.table:
860 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
861
862 def HandleHostLogPing(self, ip):
863 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 22:28:27864 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 21:47:02865 if ip == 'all':
866 return json.dumps(
867 dict([(key, self.host_infos.table[key].log)
868 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 22:28:27869
870 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 21:47:02871 if ip in self.host_infos.table:
872 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 22:47:40873
Gilad Arnold4ba437d2012-10-05 22:28:27874 # If no events were logged for this IP, return an empty log.
875 return json.dumps([])
876
Dale Curtisc9aaf3a2011-08-09 22:47:40877 def HandleSetUpdatePing(self, ip, label):
878 """Sets forced_update_label for a given host."""
879 assert ip, 'No ip provided.'
880 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 21:47:02881 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label