blob: f91811f1b3639d9e84b05a53785b8f3e9f42aeb0 [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
David Zeuthen52ccd012013-10-31 19:58:265import base64
Dale Curtisc9aaf3a2011-08-09 22:47:406import json
[email protected]ded22402009-10-26 22:36:217import os
Gilad Arnoldd0c71752013-12-06 19:48:458import random
David Zeuthen52ccd012013-10-31 19:58:269import struct
Chris Sosa05491b12010-11-09 01:14:1610import subprocess
Gilad Arnolde74b3812013-04-22 18:27:3811import sys
Gilad Arnoldd0c71752013-12-06 19:48:4512import threading
Darin Petkov2b2ff4b2010-07-27 22:02:0913import time
Gilad Arnold0c9c8602012-10-03 06:58:5814import urllib2
Don Garrett0ad09372010-12-07 00:20:3015import urlparse
Chris Sosa7c931362010-10-12 02:49:0116
Gilad Arnoldabb352e2012-09-23 08:24:2717import cherrypy
18
Gilad Arnolde74b3812013-04-22 18:27:3819# Allow importing from dev/host/lib when running from source tree.
20lib_dir = os.path.join(os.path.dirname(__file__), 'host', 'lib')
21if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
22 sys.path.insert(1, lib_dir)
23
joychen921e1fb2013-06-28 18:12:2024import build_util
Chris Sosa52148582012-11-15 23:35:5825import autoupdate_lib
Gilad Arnold55a2a372012-10-02 16:46:3226import common_util
joychen7c2054a2013-07-25 18:14:0727import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 22:17:4828import log_util
Gilad Arnolde74b3812013-04-22 18:27:3829# pylint: disable=F0401
30import update_payload
Chris Sosa05491b12010-11-09 01:14:1631
Gilad Arnoldc65330c2012-09-20 22:17:4832
joychen121fc9b2013-08-02 21:30:3033# If used by client in place of an pre-update version string, forces an update
34# to the client regardless of the relative versions of the payload and client.
35FORCED_UPDATE = 'ForcedUpdate'
36
37# Files needed to serve an update.
38UPDATE_FILES = (
39 constants.UPDATE_FILE,
40 constants.STATEFUL_FILE,
41 constants.METADATA_FILE
42)
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
64 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 urlbase: base URL, other than devserver, for update images.
143 forced_image: path to an image to use for all updates.
144 payload_path: path to pre-generated payload to serve.
145 src_image: if specified, creates a delta payload from this image.
146 proxy_port: port of local proxy to tell client to connect to you
147 through.
Chris Sosa3ae4dc12013-03-29 18:47:00148 patch_kernel: Patch the kernel when generating updates
Gilad Arnold0c9c8602012-10-03 06:58:58149 board: board for the image. Needed for pre-generating of updates.
150 copy_to_static_root: copies images generated from the cache to ~/static.
151 private_key: path to private key in PEM format.
David Zeuthen52ccd012013-10-31 19:58:26152 private_key_for_metadata_hash_signature: path to private key in PEM format.
153 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 19:52:23154 critical_update: whether provisioned payload is critical.
155 remote_payload: whether provisioned payload is remotely staged.
156 max_updates: maximum number of updates we'll try to provision.
157 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 22:46:22158 """
[email protected]ded22402009-10-26 22:36:21159
joychened64b222013-06-21 23:39:34160 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-03 06:58:58161 _PAYLOAD_URL_PREFIX = '/static/'
162 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
163
Chris Sosa6a3697f2013-01-30 00:44:43164 SHA1_ATTR = 'sha1'
165 SHA256_ATTR = 'sha256'
166 SIZE_ATTR = 'size'
167 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 19:58:26168 METADATA_SIZE_ATTR = 'metadata_size'
169 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-30 00:44:43170
joychen121fc9b2013-08-02 21:30:30171 def __init__(self, xbuddy, urlbase=None, forced_image=None, payload_path=None,
Chris Sosa3ae4dc12013-03-29 18:47:00172 proxy_port=None, src_image='', patch_kernel=True, board=None,
Chris Sosa0f1ec842011-02-15 00:33:22173 copy_to_static_root=True, private_key=None,
David Zeuthen52ccd012013-10-31 19:58:26174 private_key_for_metadata_hash_signature=None, public_key=None,
Chris Sosa52148582012-11-15 23:35:58175 critical_update=False, remote_payload=False, max_updates= -1,
Chris Sosa6a3697f2013-01-30 00:44:43176 host_log=False, *args, **kwargs):
Sean O'Connor14b6a0a2010-03-21 06:23:48177 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 21:30:30178 self.xbuddy = xbuddy
179 self.urlbase = urlbase or None
Chris Sosa0356d3b2010-09-16 22:46:22180 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-03 06:58:58181 self.payload_path = payload_path
Chris Sosa62f720b2010-10-27 04:39:48182 self.src_image = src_image
Don Garrett0ad09372010-12-07 00:20:30183 self.proxy_port = proxy_port
Chris Sosa3ae4dc12013-03-29 18:47:00184 self.patch_kernel = patch_kernel
joychen562699a2013-08-13 22:22:14185 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-20 00:08:02186 self.copy_to_static_root = copy_to_static_root
Chris Sosa0f1ec842011-02-15 00:33:22187 self.private_key = private_key
David Zeuthen52ccd012013-10-31 19:58:26188 self.private_key_for_metadata_hash_signature = \
189 private_key_for_metadata_hash_signature
190 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 17:36:32191 self.critical_update = critical_update
Gilad Arnold0c9c8602012-10-03 06:58:58192 self.remote_payload = remote_payload
Jay Srinivasanac69d262012-10-31 02:05:53193 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 19:52:23194 self.host_log = host_log
Don Garrettfff4c322010-11-19 21:37:12195
Chris Sosa417e55d2011-01-26 00:40:48196 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-21 06:23:48197
Dale Curtisc9aaf3a2011-08-09 22:47:40198 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 21:47:02199 # information about a given host. A host is identified by its IP address.
200 # The info stored for each host includes a complete log of events for this
201 # host, as well as a dictionary of current attributes derived from events.
202 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 22:47:40203
Gilad Arnoldd0c71752013-12-06 19:48:45204 self.curr_request_id = -1
205 self._update_response_lock = threading.Lock()
206
Chris Sosa6a3697f2013-01-30 00:44:43207 @classmethod
208 def _ReadMetadataFromStream(cls, stream):
209 """Returns metadata obj from input json stream that implements .read()."""
210 file_attr_dict = {}
211 try:
212 file_attr_dict = json.loads(stream.read())
213 except IOError:
214 return None
215
216 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
217 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
218 size = file_attr_dict.get(cls.SIZE_ATTR)
219 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 19:58:26220 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
221 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
222 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
223 metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43224
225 @staticmethod
226 def _ReadMetadataFromFile(payload_dir):
227 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 21:54:16228 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43229 if os.path.exists(metadata_file):
230 with open(metadata_file, 'r') as metadata_stream:
231 return Autoupdate._ReadMetadataFromStream(metadata_stream)
232
233 @classmethod
234 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
235 """Stores metadata object into the metadata_file of the payload_dir"""
236 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
237 cls.SHA256_ATTR: metadata_obj.sha256,
238 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 19:58:26239 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
240 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
241 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 21:54:16242 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43243 with open(metadata_file, 'w') as file_handle:
244 json.dump(file_dict, file_handle)
245
Chris Sosa52148582012-11-15 23:35:58246 @staticmethod
247 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 22:46:22248 """Returns the version of the image based on the name of the directory."""
249 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 15:52:52250 parts = latest_version.split('-')
joychen121fc9b2013-08-02 21:30:30251 # If we can't get a version number from the directory, default to a high
252 # number to allow the update to happen
253 return parts[1] if len(parts) == 3 else "9999.0.0"
Chris Sosa0356d3b2010-09-16 22:46:22254
Chris Sosa52148582012-11-15 23:35:58255 @staticmethod
256 def _CanUpdate(client_version, latest_version):
Don Garrettf90edf02010-11-17 01:36:14257 """Returns true if the latest_version is greater than the client_version.
258 """
Chris Sosa6a3697f2013-01-30 00:44:43259 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 15:52:52260
261 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52262 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52263
joychen121fc9b2013-08-02 21:30:30264 if len(latest_tokens) == len(client_tokens) == 3:
265 return latest_tokens > client_tokens
Chris Sosa0356d3b2010-09-16 22:46:22266 else:
joychen121fc9b2013-08-02 21:30:30267 # If the directory name isn't a version number, let it pass.
268 return True
Chris Sosa0356d3b2010-09-16 22:46:22269
Chris Sosa52148582012-11-15 23:35:58270 @staticmethod
Gilad Arnolde74b3812013-04-22 18:27:38271 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-26 00:34:49272 try:
Gilad Arnolde74b3812013-04-22 18:27:38273 with open(filename) as payload_file:
274 payload = update_payload.Payload(payload_file)
275 payload.Init()
276 return payload.IsDelta()
277 except (IOError, update_payload.PayloadError):
278 # For unit tests we may not have real files, so it's ok to ignore these
279 # errors.
Andrew de los Reyes5679b972010-10-26 00:34:49280 return False
281
Don Garrettf90edf02010-11-17 01:36:14282 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 22:46:22283 """Generates an update gz given a full path to an image.
284
285 Args:
286 image_path: Full path to image.
Chris Sosa6a3697f2013-01-30 00:44:43287 Raises:
288 subprocess.CalledProcessError if the update generator fails to generate a
289 stateful payload.
Chris Sosa0356d3b2010-09-16 22:46:22290 """
joychen7c2054a2013-07-25 18:14:07291 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43292 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 22:46:22293
Chris Sosa0f1ec842011-02-15 00:33:22294 update_command = [
Chris Sosa5b8b5eb2012-03-27 18:15:27295 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-30 00:44:43296 '--image', image_path,
David Zeuthen52ccd012013-10-31 19:58:26297 '--out_metadata_hash_file', os.path.join(output_dir,
298 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-30 00:44:43299 '--output', update_path,
Chris Sosa0f1ec842011-02-15 00:33:22300 ]
Chris Sosa4136e692010-10-29 06:42:37301
Chris Sosa52148582012-11-15 23:35:58302 if src_image:
Chris Sosa6a3697f2013-01-30 00:44:43303 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 23:35:58304
Chris Sosa3ae4dc12013-03-29 18:47:00305 if self.patch_kernel:
Chris Sosa52148582012-11-15 23:35:58306 update_command.append('--patch_kernel')
307
308 if self.private_key:
Chris Sosa6a3697f2013-01-30 00:44:43309 update_command.extend(['--private_key', self.private_key])
Chris Sosa0f1ec842011-02-15 00:33:22310
Chris Sosa6a3697f2013-01-30 00:44:43311 _Log('Running %s', ' '.join(update_command))
312 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 22:46:22313
Chris Sosa52148582012-11-15 23:35:58314 @staticmethod
315 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14316 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 22:46:22317
318 Args:
319 image_path: Full path to image.
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>
344 Signed updates (self.private_key):
345 CACHE_DIR/<src_hash>_<dest_hash>+<private_key_hash>
Chris Sosa744e1472011-09-08 02:32:50346 """
Gilad Arnold55a2a372012-10-02 16:46:32347 update_dir = ''
Chris Sosa744e1472011-09-08 02:32:50348 if src_image:
Gilad Arnold55a2a372012-10-02 16:46:32349 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-17 01:36:14350
Gilad Arnold55a2a372012-10-02 16:46:32351 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-08 02:32:50352 if self.private_key:
Gilad Arnold55a2a372012-10-02 16:46:32353 update_dir += '+' + common_util.GetFileMd5(self.private_key)
Chris Sosa744e1472011-09-08 02:32:50354
Chris Sosa3ae4dc12013-03-29 18:47:00355 if self.patch_kernel:
Gilad Arnold55a2a372012-10-02 16:46:32356 update_dir += '+patched_kernel'
Chris Sosa9fba7562012-01-31 18:15:47357
joychen25d25972013-07-30 21:54:16358 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-17 01:36:14359
Don Garrettfff4c322010-11-19 21:37:12360 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14361 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 22:46:22362
Chris Sosade91f672010-11-16 18:05:44363 Args:
Don Garrettf90edf02010-11-17 01:36:14364 image_path: full path to the image.
Chris Sosa6a3697f2013-01-30 00:44:43365 output_dir: the directory to write the update payloads to
366 Raises:
367 AutoupdateError if it failed to generate either update or stateful
368 payload.
Chris Sosade91f672010-11-16 18:05:44369 """
Chris Sosa6a3697f2013-01-30 00:44:43370 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 17:29:43371
Chris Sosa6a3697f2013-01-30 00:44:43372 # Delete any previous state in this directory.
373 os.system('rm -rf "%s"' % output_dir)
374 os.makedirs(output_dir)
[email protected]ded22402009-10-26 22:36:21375
Chris Sosa6a3697f2013-01-30 00:44:43376 try:
377 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
378 self.GenerateStatefulFile(image_path, output_dir)
379 except subprocess.CalledProcessError:
380 os.system('rm -rf "%s"' % output_dir)
381 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-17 01:36:14382
Chris Sosa75490802013-10-01 00:21:45383 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-17 01:36:14384 """Force generates an update payload based on the given image_path.
[email protected]ded22402009-10-26 22:36:21385
Chris Sosa0356d3b2010-09-16 22:46:22386 Args:
387 image_path: full path to the image.
Chris Sosa0356d3b2010-09-16 22:46:22388 Returns:
joychen121fc9b2013-08-02 21:30:30389 update directory relative to static_image_dir.
Chris Sosa6a3697f2013-01-30 00:44:43390 Raises:
391 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 22:46:22392 """
Chris Sosa6a3697f2013-01-30 00:44:43393 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f12010-11-05 00:33:16394
joychen121fc9b2013-08-02 21:30:30395 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-26 00:40:48396 if self.pregenerated_path:
397 return self.pregenerated_path
Don Garrettfff4c322010-11-19 21:37:12398
Chris Sosa75490802013-10-01 00:21:45399 # Which sub_dir should hold our cached update image.
400 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-30 00:44:43401 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-26 00:40:48402
joychen121fc9b2013-08-02 21:30:30403 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-10-01 00:21:45404 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 21:30:30405
406 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 18:14:07407 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 21:30:30408 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 21:54:16409 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-26 00:40:48410 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 21:30:30411 if not (os.path.exists(cache_update_payload) and
412 os.path.exists(cache_stateful_payload)):
413 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-17 01:36:14414
joychen121fc9b2013-08-02 21:30:30415 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-30 00:44:43416 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-22 02:59:21417
Chris Sosa6a3697f2013-01-30 00:44:43418 # Generate the cache file.
joychen121fc9b2013-08-02 21:30:30419 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14420
joychen121fc9b2013-08-02 21:30:30421 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 22:46:22422
Chris Sosa75490802013-10-01 00:21:45423 def _SymlinkUpdateFiles(self, target_dir, link_dir):
424 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 21:30:30425
426 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-10-01 00:21:45427 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 22:46:22428
429 Args:
Chris Sosa75490802013-10-01 00:21:45430 target_dir: Location of the target files.
431 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 22:46:22432 """
Chris Sosa75490802013-10-01 00:21:45433 _Log('Linking %s to %s', target_dir, link_dir)
434 if link_dir == target_dir:
435 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 21:30:30436 return
437 for f in UPDATE_FILES:
Chris Sosa75490802013-10-01 00:21:45438 link = os.path.join(link_dir, f)
439 target = os.path.join(target_dir, f)
Alex Deymo3e2d4952013-09-04 04:49:41440 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 22:46:22441
joychen121fc9b2013-08-02 21:30:30442 def GetUpdateForLabel(self, client_version, label,
443 image_name=constants.TEST_IMAGE_FILE):
444 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 22:46:22445
joychen121fc9b2013-08-02 21:30:30446 Args:
447 client_version: Current version of the client or FORCED_UPDATE
448 label: the relative directory inside the static dir
449 image_name: If the image type was specified by the update rpc, we try to
450 find an image with this file name first. This is by default
451 "chromiumos_test_image.bin" but can also take any of the values in
452 devserver_constants.ALL_IMAGES
Chris Sosa6a3697f2013-01-30 00:44:43453 Returns:
joychen121fc9b2013-08-02 21:30:30454 A relative path to the directory with the update payload.
455 This is the label if an update did not need to be generated, but can
456 be label/cache/hashed_dir_for_update.
Chris Sosa6a3697f2013-01-30 00:44:43457 Raises:
joychen121fc9b2013-08-02 21:30:30458 AutoupdateError: If client version is higher than available update found
459 at the directory given by the label.
Don Garrettf90edf02010-11-17 01:36:14460 """
joychen121fc9b2013-08-02 21:30:30461 _Log('Update label/file: %s/%s', label, image_name)
462 static_image_dir = _NonePathJoin(self.static_dir, label)
463 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
464 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 18:14:07465
joychen121fc9b2013-08-02 21:30:30466 # Update the client only if client version is older than available update.
467 latest_version = self._GetVersionFromDir(static_image_dir)
468 if not (client_version == FORCED_UPDATE or
469 self._CanUpdate(client_version, latest_version)):
470 raise AutoupdateError(
471 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 20:09:35472
joychen121fc9b2013-08-02 21:30:30473 if label and os.path.exists(static_update_path):
474 # An update payload was found for the given label, return it.
475 return label
476 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
477 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45478 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
479 # Add links from the static directory to the update.
480 cache_path = _NonePathJoin(self.static_dir, rel_path)
481 self._SymlinkUpdateFiles(cache_path, static_image_dir)
482 return label
Don Garrett0c880e22010-11-18 02:13:37483
joychen121fc9b2013-08-02 21:30:30484 # The label didn't resolve.
485 return None
Chris Sosa2c048f12010-10-27 23:05:27486
487 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-26 00:40:48488 """Pre-generates an update and prints out the relative path it.
489
Chris Sosa6a3697f2013-01-30 00:44:43490 Returns relative path of the update.
Chris Sosa65d339b2013-01-22 02:59:21491
Chris Sosa6a3697f2013-01-30 00:44:43492 Raises:
493 AutoupdateError if it failed to generate the payload.
494 """
495 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 21:30:30496 # Does not work with labels so just use static dir. (empty label)
497 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Chris Sosa6a3697f2013-01-30 00:44:43498 print 'PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
joychen7c2054a2013-07-25 18:14:07499 constants.UPDATE_FILE)
Chris Sosa417e55d2011-01-26 00:40:48500 return pregenerated_update
Chris Sosa2c048f12010-10-27 23:05:27501
Gilad Arnold0c9c8602012-10-03 06:58:58502 def _GetRemotePayloadAttrs(self, url):
503 """Returns hashes, size and delta flag of a remote update payload.
504
505 Obtain attributes of a payload file available on a remote devserver. This
506 is based on the assumption that the payload URL uses the /static prefix. We
507 need to make sure that both clients (requests) and remote devserver
508 (provisioning) preserve this invariant.
509
510 Args:
511 url: URL of statically staged remote file (http://host:port/static/...)
512 Returns:
David Zeuthen52ccd012013-10-31 19:58:26513 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-03 06:58:58514 """
515 if self._PAYLOAD_URL_PREFIX not in url:
516 raise AutoupdateError(
517 'Payload URL does not have the expected prefix (%s)' %
518 self._PAYLOAD_URL_PREFIX)
Chris Sosa6a3697f2013-01-30 00:44:43519
joychened64b222013-06-21 23:39:34520 if self._OLD_PAYLOAD_URL_PREFIX in url:
521 fileinfo_url = url.replace(self._OLD_PAYLOAD_URL_PREFIX,
522 self._FILEINFO_URL_PREFIX)
523 else:
524 fileinfo_url = url.replace(self._PAYLOAD_URL_PREFIX,
525 self._FILEINFO_URL_PREFIX)
526
Chris Sosa6a3697f2013-01-30 00:44:43527 _Log('Retrieving file info for remote payload via %s', fileinfo_url)
Gilad Arnold0c9c8602012-10-03 06:58:58528 try:
529 conn = urllib2.urlopen(fileinfo_url)
Chris Sosa6a3697f2013-01-30 00:44:43530 metadata_obj = Autoupdate._ReadMetadataFromStream(conn)
531 # These fields are required for remote calls.
532 if not metadata_obj:
533 raise AutoupdateError('Failed to obtain remote payload info')
Gilad Arnold0c9c8602012-10-03 06:58:58534
Chris Sosa6a3697f2013-01-30 00:44:43535 return metadata_obj
536 except IOError as e:
537 raise AutoupdateError('Failed to obtain remote payload info: %s', e)
538
David Zeuthen52ccd012013-10-31 19:58:26539 @staticmethod
540 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 18:38:16541 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 19:58:26542
543 Args:
544 payload_dir: The payload directory.
545 Returns:
David Zeuthenf27f1502013-11-13 18:38:16546 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 19:58:26547 """
548 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 18:38:16549 if os.path.exists(path):
550 return base64.b64encode(open(path, 'rb').read())
551 else:
552 return None
David Zeuthen52ccd012013-10-31 19:58:26553
554 @staticmethod
555 def _GetMetadataSize(payload_filename):
556 """Gets the size of the metadata in a payload file.
557
558 Args:
559 payload_filename: Path to the payload file.
560 Returns:
561 The size of the payload metadata, as reported in the payload header.
562 """
563 # Handle corner-case where unit tests pass in empty payload files.
564 if os.path.getsize(payload_filename) < 20:
565 return 0
566 stream = open(payload_filename, 'rb')
567 stream.seek(16)
568 return struct.unpack('>I', stream.read(4))[0] + 20
569
Chris Sosa6a3697f2013-01-30 00:44:43570 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-03 06:58:58571 """Returns hashes, size and delta flag of a local update payload.
572
573 Args:
Chris Sosa6a3697f2013-01-30 00:44:43574 payload_dir: Path to the directory the payload is in.
Gilad Arnold0c9c8602012-10-03 06:58:58575 Returns:
David Zeuthen52ccd012013-10-31 19:58:26576 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-03 06:58:58577 """
joychen7c2054a2013-07-25 18:14:07578 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43579 if not os.path.exists(filename):
580 raise AutoupdateError('update.gz not present in payload dir %s' %
581 payload_dir)
Gilad Arnold0c9c8602012-10-03 06:58:58582
Chris Sosa6a3697f2013-01-30 00:44:43583 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
584 if not metadata_obj or not (metadata_obj.sha1 and
585 metadata_obj.sha256 and
586 metadata_obj.size):
587 sha1 = common_util.GetFileSha1(filename)
588 sha256 = common_util.GetFileSha256(filename)
589 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 18:27:38590 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 19:58:26591 metadata_size = self._GetMetadataSize(filename)
592 metadata_hash = self._GetMetadataHash(payload_dir)
593 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
594 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43595 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 22:46:22596
Chris Sosa6a3697f2013-01-30 00:44:43597 return metadata_obj
598
599 def _ProcessUpdateComponents(self, app, event):
600 """Processes the app and event components of an update request.
601
602 Returns tuple containing forced_update_label, client_version, and board.
Chris Sosa0356d3b2010-09-16 22:46:22603 """
Chris Sosa6a3697f2013-01-30 00:44:43604 # Initialize an empty dictionary for event attributes to log.
605 log_message = {}
Jay Srinivasanac69d262012-10-31 02:05:53606
Dale Curtisc9aaf3a2011-08-09 22:47:40607 # Determine request IP, strip any IPv6 data for simplicity.
608 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 21:47:02609 # Obtain (or init) info object for this client.
610 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
611
joychen121fc9b2013-08-02 21:30:30612 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-30 00:44:43613 board = None
614 if app:
615 client_version = app.getAttribute('version')
616 channel = app.getAttribute('track')
617 board = (app.hasAttribute('board') and app.getAttribute('board')
joychenb0dfe552013-07-30 17:02:06618 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-30 00:44:43619 # Add attributes to log message
620 log_message['version'] = client_version
621 log_message['track'] = channel
622 log_message['board'] = board
623 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 22:47:40624
Dale Curtisc9aaf3a2011-08-09 22:47:40625 if event:
Gilad Arnold286a0062012-01-12 21:47:02626 event_result = int(event[0].getAttribute('eventresult'))
627 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 22:33:21628 client_previous_version = (event[0].getAttribute('previousversion')
629 if event[0].hasAttribute('previousversion')
630 else None)
Gilad Arnold286a0062012-01-12 21:47:02631 # Store attributes to legacy host info structure
632 curr_host_info.attrs['last_event_status'] = event_result
633 curr_host_info.attrs['last_event_type'] = event_type
634 # Add attributes to log message
635 log_message['event_result'] = event_result
636 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 22:33:21637 if client_previous_version is not None:
638 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 21:47:02639
Gilad Arnold8318eac2012-10-04 19:52:23640 # Log host event, if so instructed.
641 if self.host_log:
642 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 22:47:40643
Chris Sosa6a3697f2013-01-30 00:44:43644 return (curr_host_info.attrs.pop('forced_update_label', None),
645 client_version, board)
646
647 def _GetStaticUrl(self):
648 """Returns the static url base that should prefix all payload responses."""
649 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
650 if x_forwarded_host:
651 hostname = 'http://' + x_forwarded_host
652 else:
653 hostname = cherrypy.request.base
654
655 if self.urlbase:
656 static_urlbase = self.urlbase
Chris Sosa6a3697f2013-01-30 00:44:43657 else:
658 static_urlbase = '%s/static' % hostname
659
660 # If we have a proxy port, adjust the URL we instruct the client to
661 # use to go through the proxy.
662 if self.proxy_port:
663 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
664
665 _Log('Using static url base %s', static_urlbase)
666 _Log('Handling update ping as %s', hostname)
667 return static_urlbase
668
joychen121fc9b2013-08-02 21:30:30669 def GetPathToPayload(self, label, client_version, board):
670 """Find a payload locally.
671
672 See devserver's update rpc for documentation.
673
674 Args:
675 label: from update request
676 client_version: from update request
677 board: from update request
678 Return:
679 The relative path to an update from the static_dir
680 Raises:
681 AutoupdateError: If the update could not be found.
682 """
683 path_to_payload = None
684 #TODO(joychen): deprecate --payload flag
685 if self.payload_path:
686 # Copy the image from the path to '/forced_payload'
687 label = 'forced_payload'
688 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
689 dest_stateful = os.path.join(self.static_dir, label,
690 constants.STATEFUL_FILE)
691
692 src_path = os.path.abspath(self.payload_path)
693 src_stateful = os.path.join(os.path.dirname(src_path),
694 constants.STATEFUL_FILE)
695 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-04 04:49:41696 common_util.SymlinkFile(src_path, dest_path)
joychen121fc9b2013-08-02 21:30:30697 if os.path.exists(src_stateful):
698 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-04 04:49:41699 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 21:30:30700 else:
701 _Log('WARN: %s not found. Expected for dev and test builds',
702 constants.STATEFUL_FILE)
703 if os.path.exists(dest_stateful):
704 os.remove(dest_stateful)
705 path_to_payload = self.GetUpdateForLabel(client_version, label)
706 #TODO(joychen): deprecate --image flag
707 elif self.forced_image:
joychendbfe6c92013-08-17 03:03:49708 if self.forced_image.startswith('xbuddy:'):
709 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-17 03:03:49710 xbuddy_label = self.forced_image.split(':')[1]
711 self.forced_image = None
joychen365a5742013-08-21 17:41:18712 # Make sure the xbuddy path target is in the directory.
713 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
714 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 23:45:12715 self.GetPathToPayload(xbuddy_label, client_version, board)
716 else:
717 src_path = os.path.abspath(self.forced_image)
718 if os.path.exists(src_path) and common_util.IsInsideChroot():
719 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45720 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
721 # Add links from the static directory to the update.
722 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
723 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 21:30:30724 else:
725 label = label or ''
726 label_list = label.split('/')
727 # Suppose that the path follows old protocol of indexing straight
728 # into static_dir with board/version label.
729 # Attempt to get the update in that directory, generating if necc.
730 path_to_payload = self.GetUpdateForLabel(client_version, label)
731 if path_to_payload is None:
732 # There was no update or image found in the directory.
733 # Let XBuddy find an image, and then generate an update to it.
734 if label_list[0] == 'xbuddy':
735 # If path explicitly calls xbuddy, pop off the tag.
736 label_list.pop()
Chris Sosa75490802013-10-01 00:21:45737 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 21:30:30738 if image_name not in constants.ALL_IMAGES:
739 raise AutoupdateError(
740 "Use an image alias: dev, base, test, or recovery.")
741 # Path has been resolved, try to get the image.
742 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
743 image_name)
744 if path_to_payload is None:
745 # Neither image nor update payload found after translation.
746 # Try to get an update to a test image from GS using the label.
747 path_to_payload, _image_name = self.xbuddy.Get(
748 ['remote', label, 'full_payload'])
749
750 # One of the above options should have gotten us a relative path.
751 if path_to_payload is None:
752 raise AutoupdateError('Failed to get an update for: %s' % label)
753 else:
Chris Sosa75490802013-10-01 00:21:45754 return path_to_payload
joychen121fc9b2013-08-02 21:30:30755
David Zeuthen52ccd012013-10-31 19:58:26756 @staticmethod
757 def _SignMetadataHash(private_key_path, metadata_hash):
758 """Signs metadata hash.
759
760 Signs a metadata hash with a private key. This includes padding the
761 hash with PKCS#1 v1.5 padding as well as an ASN.1 header.
762
763 Args:
764 private_key_path: The path to a private key to use for signing.
765 metadata_hash: A raw SHA-256 hash (32 bytes).
766 Returns:
767 The raw signature.
768 """
769 args = ['openssl', 'rsautl', '-pkcs', '-sign', '-inkey', private_key_path]
770 padded_metadata_hash = ('\x30\x31\x30\x0d\x06\x09\x60\x86'
771 '\x48\x01\x65\x03\x04\x02\x01\x05'
772 '\x00\x04\x20') + metadata_hash
773 child = subprocess.Popen(args,
774 stdin=subprocess.PIPE,
775 stdout=subprocess.PIPE)
776 signature, _ = child.communicate(input=padded_metadata_hash)
777 return signature
778
joychen121fc9b2013-08-02 21:30:30779 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-30 00:44:43780 """Handles an update ping from an update client.
781
782 Args:
783 data: XML blob from client.
784 label: optional label for the update.
785 Returns:
786 Update payload message for client.
787 """
788 # Get the static url base that will form that base of our update url e.g.
789 # http://hostname:8080/static/update.gz.
790 static_urlbase = self._GetStaticUrl()
791
792 # Parse the XML we got into the components we care about.
793 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
794
Chris Sosab26b1202013-08-16 23:40:55795 # Process attributes of the update check.
796 forced_update_label, client_version, board = self._ProcessUpdateComponents(
797 app, event)
798
joychen121fc9b2013-08-02 21:30:30799 if not update_check:
800 # TODO(sosa): Generate correct non-updatecheck payload to better test
801 # update clients.
802 _Log('Non-update check received. Returning blank payload')
803 return autoupdate_lib.GetNoUpdateResponse(protocol)
804
Chris Sosa6a3697f2013-01-30 00:44:43805 if forced_update_label:
806 if label:
807 _Log('Label: %s set but being overwritten to %s by request', label,
808 forced_update_label)
Chris Sosa6a3697f2013-01-30 00:44:43809 label = forced_update_label
810
Gilad Arnoldd0c71752013-12-06 19:48:45811 # Make sure that we did not already exceed the max number of allowed
812 # responses; note that this is merely an optimization, as the definitive
813 # check and updating of the counter is done later, right before returning a
814 # response.
joychen121fc9b2013-08-02 21:30:30815 if self.max_updates == 0:
joychen121fc9b2013-08-02 21:30:30816 _Log('Request received but max number of updates handled')
817 return autoupdate_lib.GetNoUpdateResponse(protocol)
818
Gilad Arnoldd0c71752013-12-06 19:48:45819 request_id = random.randint(0, sys.maxint)
820 self.curr_request_id = request_id
821 _Log('Update Check Received (id=%d). Client is using protocol version: %s',
822 request_id, protocol)
joychen121fc9b2013-08-02 21:30:30823
Chris Sosa6a3697f2013-01-30 00:44:43824 # Finally its time to generate the omaha response to give to client that
825 # lets them know where to find the payload and its associated metadata.
826 metadata_obj = None
827
828 try:
Gilad Arnold0c9c8602012-10-03 06:58:58829 # Are we provisioning a remote or local payload?
830 if self.remote_payload:
831 # If no explicit label was provided, use the value of --payload.
Chris Sosa6a3697f2013-01-30 00:44:43832 if not label:
Gilad Arnold0c9c8602012-10-03 06:58:58833 label = self.payload_path
Chris Sosa0356d3b2010-09-16 22:46:22834
Chris Sosa52f15bc2013-08-14 00:14:15835 # TODO(sosa): Remove backwards-compatible hack.
Chris Sosab26b1202013-08-16 23:40:55836 if not '.bin' in label:
Chris Sosa52f15bc2013-08-14 00:14:15837 url = _NonePathJoin(static_urlbase, label, 'update.gz')
838 else:
839 url = _NonePathJoin(static_urlbase, label)
Chris Sosa5d342a22010-09-28 23:54:41840
Gilad Arnold0c9c8602012-10-03 06:58:58841 # Get remote payload attributes.
Chris Sosa6a3697f2013-01-30 00:44:43842 metadata_obj = self._GetRemotePayloadAttrs(url)
Gilad Arnold0c9c8602012-10-03 06:58:58843 else:
joychen121fc9b2013-08-02 21:30:30844 path_to_payload = self.GetPathToPayload(label, client_version, board)
845 url = _NonePathJoin(static_urlbase, path_to_payload,
joychen7c2054a2013-07-25 18:14:07846 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 21:30:30847 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-30 00:44:43848 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-30 00:44:43849 except AutoupdateError as e:
850 # Raised if we fail to generate an update payload.
851 _Log('Failed to process an update: %r', e)
852 return autoupdate_lib.GetNoUpdateResponse(protocol)
853
David Zeuthen52ccd012013-10-31 19:58:26854 # Sign the metadata hash, if requested.
855 signed_metadata_hash = None
856 if self.private_key_for_metadata_hash_signature:
857 signed_metadata_hash = base64.b64encode(Autoupdate._SignMetadataHash(
858 self.private_key_for_metadata_hash_signature,
859 base64.b64decode(metadata_obj.metadata_hash)))
860
861 # Include public key, if requested.
862 public_key_data = None
863 if self.public_key:
864 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
865
Gilad Arnoldd0c71752013-12-06 19:48:45866 update_response = autoupdate_lib.GetUpdateResponse(
Chris Sosa6a3697f2013-01-30 00:44:43867 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 19:58:26868 metadata_obj.is_delta_format, metadata_obj.metadata_size,
869 signed_metadata_hash, public_key_data, protocol, self.critical_update)
Dale Curtisc9aaf3a2011-08-09 22:47:40870
Gilad Arnoldd0c71752013-12-06 19:48:45871 # Make sure we can proceed with the response (critical section).
872 with self._update_response_lock:
873 # If the number of responses sent already exceeds the max allowed, abort.
874 if self.max_updates == 0:
875 _Log('Max allowed number of update responses already sent, '
876 'aborting this one (id=%d)', request_id)
877 return autoupdate_lib.GetNoUpdateResponse(protocol)
878
879 # If there's been a more recent request, we assume the client timed out
880 # on this request and should not respond to it.
881 # IMPORTANT: we want to do this as close as posible to where we commit to
882 # making a response, i.e. right before we update the response tally. This
883 # is why this check happens in the critical section.
884 curr_request_id = self.curr_request_id
885 if curr_request_id != request_id:
886 _Log('A more recent request was received (id=%d), aborting this one '
887 '(id=%d)', curr_request_id, request_id)
888 return autoupdate_lib.GetNoUpdateResponse(protocol)
889
890 # Update the counter, committing to make the response.
891 self.max_updates -= 1
892
893 # At this point, we're good to go with the response.
894 _Log('Responding to client to use url %s to get image (id=%d)', url,
895 request_id)
896 return update_response
897
Dale Curtisc9aaf3a2011-08-09 22:47:40898 def HandleHostInfoPing(self, ip):
899 """Returns host info dictionary for the given IP in JSON format."""
900 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 21:47:02901 if ip in self.host_infos.table:
902 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
903
904 def HandleHostLogPing(self, ip):
905 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 22:28:27906 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 21:47:02907 if ip == 'all':
908 return json.dumps(
909 dict([(key, self.host_infos.table[key].log)
910 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 22:28:27911
912 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 21:47:02913 if ip in self.host_infos.table:
914 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 22:47:40915
Gilad Arnold4ba437d2012-10-05 22:28:27916 # If no events were logged for this IP, return an empty log.
917 return json.dumps([])
918
Dale Curtisc9aaf3a2011-08-09 22:47:40919 def HandleSetUpdatePing(self, ip, label):
920 """Sets forced_update_label for a given host."""
921 assert ip, 'No ip provided.'
922 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 21:47:02923 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label