blob: a8e02fed285101f1682a02396285daf8f9466267 [file] [log] [blame]
Chris Sosa0356d3b2010-09-16 15:46:22 -07001# Copyright (c) 2009-2010 The Chromium OS Authors. All rights reserved.
rtc@google.comded22402009-10-26 22:36:21 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
rtc@google.com64244662009-11-12 00:52:08 +00005from buildutil import BuildObject
rtc@google.comded22402009-10-26 22:36:21 +00006from xml.dom import minidom
Chris Sosa7c931362010-10-11 19:49:01 -07007import cherrypy
rtc@google.comded22402009-10-26 22:36:21 +00008import os
Darin Petkov798fe7d2010-03-22 15:18:13 -07009import shutil
Chris Sosa05491b12010-11-08 17:14:16 -080010import subprocess
11import tempfile
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070012import time
Chris Sosa7c931362010-10-11 19:49:01 -070013
Chris Sosa05491b12010-11-08 17:14:16 -080014
Chris Sosa7c931362010-10-11 19:49:01 -070015def _LogMessage(message):
16 cherrypy.log(message, 'UPDATE')
rtc@google.comded22402009-10-26 22:36:21 +000017
Chris Sosa0356d3b2010-09-16 15:46:22 -070018
rtc@google.com64244662009-11-12 00:52:08 +000019class Autoupdate(BuildObject):
Chris Sosa0356d3b2010-09-16 15:46:22 -070020 """Class that contains functionality that handles Chrome OS update pings.
21
22 Members:
23 serve_only: Serve images from a pre-built image.zip file. static_dir
24 must be set to the location of the image.zip.
25 factory_config: Path to the factory config file if handling factory
26 requests.
27 use_test_image: Use chromiumos_test_image.bin rather than the standard.
28 static_url_base: base URL, other than devserver, for update images.
29 client_prefix: The prefix for the update engine client.
30 forced_image: Path to an image to use for all updates.
31 """
rtc@google.comded22402009-10-26 22:36:21 +000032
Sean O'Connor1f7fd362010-04-07 16:34:52 -070033 def __init__(self, serve_only=None, test_image=False, urlbase=None,
Chris Sosa0356d3b2010-09-16 15:46:22 -070034 factory_config_path=None, client_prefix=None, forced_image=None,
Chris Sosae67b78f2010-11-04 17:33:16 -070035 use_cached=False, port=8080, src_image='', vm=False, board=None,
36 *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070037 super(Autoupdate, self).__init__(*args, **kwargs)
Sean O'Connor1f7fd362010-04-07 16:34:52 -070038 self.serve_only = serve_only
Sean O'Connor1b4b0762010-06-02 17:37:32 -070039 self.factory_config = factory_config_path
Chris Sosa0356d3b2010-09-16 15:46:22 -070040 self.use_test_image = test_image
Chris Sosa5d342a22010-09-28 16:54:41 -070041 if urlbase:
Chris Sosa9841e1c2010-10-14 10:51:45 -070042 self.urlbase = urlbase
Chris Sosa5d342a22010-09-28 16:54:41 -070043 else:
Chris Sosa9841e1c2010-10-14 10:51:45 -070044 self.urlbase = None
Chris Sosa5d342a22010-09-28 16:54:41 -070045
Chris Sosab63a9282010-09-02 10:43:23 -070046 self.client_prefix = client_prefix
Chris Sosa0356d3b2010-09-16 15:46:22 -070047 self.forced_image = forced_image
Chris Sosa5d342a22010-09-28 16:54:41 -070048 self.use_cached = use_cached
Chris Sosa62f720b2010-10-26 21:39:48 -070049 self.src_image = src_image
Chris Sosa4136e692010-10-28 23:42:37 -070050 self.vm = vm
Chris Sosae67b78f2010-11-04 17:33:16 -070051 self.board = board
Chris Sosa05491b12010-11-08 17:14:16 -080052 self.crosutils = os.path.join(os.path.dirname(__file__), '../../scripts')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070053
Chris Sosa0356d3b2010-09-16 15:46:22 -070054 def _GetSecondsSinceMidnight(self):
55 """Returns the seconds since midnight as a decimal value."""
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070056 now = time.localtime()
57 return now[3] * 3600 + now[4] * 60 + now[5]
58
Chris Sosa0356d3b2010-09-16 15:46:22 -070059 def _GetDefaultBoardID(self):
60 """Returns the default board id stored in .default_board."""
61 board_file = '%s/.default_board' % (self.scripts_dir)
62 try:
63 return open(board_file).read()
64 except IOError:
65 return 'x86-generic'
66
67 def _GetLatestImageDir(self, board_id):
68 """Returns the latest image dir based on shell script."""
69 cmd = '%s/get_latest_image.sh --board %s' % (self.scripts_dir, board_id)
70 return os.popen(cmd).read().strip()
71
72 def _GetVersionFromDir(self, image_dir):
73 """Returns the version of the image based on the name of the directory."""
74 latest_version = os.path.basename(image_dir)
75 return latest_version.split('-')[0]
76
77 def _CanUpdate(self, client_version, latest_version):
78 """Returns true if the latest_version is greater than the client_version."""
79 client_tokens = client_version.replace('_', '').split('.')
80 latest_tokens = latest_version.replace('_', '').split('.')
Chris Sosa7c931362010-10-11 19:49:01 -070081 _LogMessage('client version %s latest version %s'
Chris Sosa0356d3b2010-09-16 15:46:22 -070082 % (client_version, latest_version))
83 for i in range(4):
84 if int(latest_tokens[i]) == int(client_tokens[i]):
85 continue
86 return int(latest_tokens[i]) > int(client_tokens[i])
87 return False
88
Chris Sosa0356d3b2010-09-16 15:46:22 -070089 def _UnpackZip(self, image_dir):
90 """Unpacks an image.zip into a given directory."""
91 image = os.path.join(image_dir, self._GetImageName())
92 if os.path.exists(image):
93 return True
94 else:
95 # -n, never clobber an existing file, in case we get invoked
96 # simultaneously by multiple request handlers. This means that
97 # we're assuming each image.zip file lives in a versioned
98 # directory (a la Buildbot).
99 return os.system('cd %s && unzip -n image.zip' % image_dir) == 0
100
101 def _GetImageName(self):
102 """Returns the name of the image that should be used."""
103 if self.use_test_image:
104 image_name = 'chromiumos_test_image.bin'
105 else:
106 image_name = 'chromiumos_image.bin'
107 return image_name
108
109 def _IsImageNewerThanCached(self, image_path, cached_file_path):
110 """Returns true if the image is newer than the cached image."""
111 if os.path.exists(cached_file_path) and os.path.exists(image_path):
Chris Sosa7c931362010-10-11 19:49:01 -0700112 _LogMessage('Usable cached image found at %s.' % cached_file_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700113 return os.path.getmtime(image_path) > os.path.getmtime(cached_file_path)
114 elif not os.path.exists(cached_file_path) and not os.path.exists(image_path):
115 raise Exception('Image does not exist and cached image missing')
116 else:
117 # Only one is missing, figure out which one.
118 if os.path.exists(image_path):
Chris Sosa7c931362010-10-11 19:49:01 -0700119 _LogMessage('No cached image found - image generation required.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700120 return True
121 else:
Chris Sosa7c931362010-10-11 19:49:01 -0700122 _LogMessage('Cached image found to serve at %s.' % cached_file_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700123 return False
124
125 def _GetSize(self, update_path):
126 """Returns the size of the file given."""
127 return os.path.getsize(update_path)
128
129 def _GetHash(self, update_path):
130 """Returns the sha1 of the file given."""
131 cmd = ('cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';'
132 % update_path)
133 return os.popen(cmd).read().rstrip()
134
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700135 def _IsDeltaFormatFile(self, filename):
136 try:
137 file_handle = open(filename, 'r')
138 delta_magic = 'CrAU'
139 magic = file_handle.read(len(delta_magic))
140 return magic == delta_magic
141 except Exception:
142 return False
143
Darin Petkov91436cb2010-09-28 08:52:17 -0700144 # TODO(petkov): Consider optimizing getting both SHA-1 and SHA-256 so that
145 # it takes advantage of reduced I/O and multiple processors. Something like:
146 # % tee < FILE > /dev/null \
147 # >( openssl dgst -sha256 -binary | openssl base64 ) \
148 # >( openssl sha1 -binary | openssl base64 )
149 def _GetSHA256(self, update_path):
150 """Returns the sha256 of the file given."""
151 cmd = ('cat %s | openssl dgst -sha256 -binary | openssl base64' %
152 update_path)
153 return os.popen(cmd).read().rstrip()
154
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700155 def GetUpdatePayload(self, hash, sha256, size, url, is_delta_format):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700156 """Returns a payload to the client corresponding to a new update.
157
158 Args:
159 hash: hash of update blob
Darin Petkov91436cb2010-09-28 08:52:17 -0700160 sha256: SHA-256 hash of update blob
Chris Sosa0356d3b2010-09-16 15:46:22 -0700161 size: size of update blob
162 url: where to find update blob
163 Returns:
164 Xml string to be passed back to client.
165 """
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700166 delta = 'false'
167 if is_delta_format:
168 delta = 'true'
rtc@google.com21a5ca32009-11-04 18:23:23 +0000169 payload = """<?xml version="1.0" encoding="UTF-8"?>
170 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
Darin Petkov2b2ff4b2010-07-27 15:02:09 -0700171 <daystart elapsed_seconds="%s"/>
rtc@google.com21a5ca32009-11-04 18:23:23 +0000172 <app appid="{%s}" status="ok">
173 <ping status="ok"/>
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700174 <updatecheck
175 codebase="%s"
176 hash="%s"
Darin Petkov91436cb2010-09-28 08:52:17 -0700177 sha256="%s"
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700178 needsadmin="false"
179 size="%s"
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700180 IsDelta="%s"
rtc@google.com21a5ca32009-11-04 18:23:23 +0000181 status="ok"/>
182 </app>
183 </gupdate>
184 """
Chris Sosa0356d3b2010-09-16 15:46:22 -0700185 return payload % (self._GetSecondsSinceMidnight(),
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700186 self.app_id, url, hash, sha256, size, delta)
rtc@google.comded22402009-10-26 22:36:21 +0000187
rtc@google.com21a5ca32009-11-04 18:23:23 +0000188 def GetNoUpdatePayload(self):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700189 """Returns a payload to the client corresponding to no update."""
190 payload = """ < ?xml version = "1.0" encoding = "UTF-8"? >
191 < gupdate xmlns = "http://www.google.com/update2/response" protocol = "2.0" >
192 < daystart elapsed_seconds = "%s" />
193 < app appid = "{%s}" status = "ok" >
194 < ping status = "ok" />
195 < updatecheck status = "noupdate" />
196 </ app >
197 </ gupdate >
rtc@google.com21a5ca32009-11-04 18:23:23 +0000198 """
Chris Sosa0356d3b2010-09-16 15:46:22 -0700199 return payload % (self._GetSecondsSinceMidnight(), self.app_id)
rtc@google.comded22402009-10-26 22:36:21 +0000200
Chris Sosa0356d3b2010-09-16 15:46:22 -0700201 def GenerateUpdateFile(self, image_path):
202 """Generates an update gz given a full path to an image.
203
204 Args:
205 image_path: Full path to image.
206 Returns:
207 Path to created update_payload or None on error.
208 """
209 image_dir = os.path.dirname(image_path)
210 update_path = os.path.join(image_dir, 'update.gz')
Chris Sosa4136e692010-10-28 23:42:37 -0700211 patch_kernel_flag = '--patch_kernel'
Chris Sosa7c931362010-10-11 19:49:01 -0700212 _LogMessage('Generating update image %s' % update_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700213
Chris Sosa4136e692010-10-28 23:42:37 -0700214 # Don't patch the kernel for vm images as they don't need the patch.
215 if self.vm:
216 patch_kernel_flag = ''
217
Chris Sosa0356d3b2010-09-16 15:46:22 -0700218 mkupdate_command = (
Chris Sosa62f720b2010-10-26 21:39:48 -0700219 '%s/cros_generate_update_payload --image="%s" --output="%s" '
Chris Sosa4136e692010-10-28 23:42:37 -0700220 '%s --noold_style --src_image="%s"' % (
221 self.scripts_dir, image_path, update_path, patch_kernel_flag,
222 self.src_image))
Chris Sosa62f720b2010-10-26 21:39:48 -0700223 _LogMessage(mkupdate_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700224 if os.system(mkupdate_command) != 0:
Chris Sosa7c931362010-10-11 19:49:01 -0700225 _LogMessage('Failed to create base update file')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700226 return None
227
228 return update_path
229
230 def GenerateStatefulFile(self, image_path):
231 """Generates a stateful update gz given a full path to an image.
232
233 Args:
234 image_path: Full path to image.
235 Returns:
236 Path to created stateful update_payload or None on error.
237 """
Chris Sosa05491b12010-11-08 17:14:16 -0800238 _LogMessage('Generating stateful update file.')
239 from_dir = os.path.dirname(image_path)
240 image = os.path.basename(image_path)
241 output_gz = os.path.join(from_dir, 'stateful.tgz')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700242
Chris Sosa05491b12010-11-08 17:14:16 -0800243 # Temporary directories for this function.
244 rootfs_dir = tempfile.mkdtemp(suffix='rootfs', prefix='tmp')
245 stateful_dir = tempfile.mkdtemp(suffix='stateful', prefix='tmp')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700246
Chris Sosa05491b12010-11-08 17:14:16 -0800247 # Mount the image to pull out the important directories.
248 try:
249 # Only need stateful partition, but this saves us having to manage our
250 # own loopback device.
251 subprocess.check_call(['%s/mount_gpt_image.sh' % self.crosutils,
252 '--from=%s' % from_dir,
253 '--image=%s' % image,
254 '--read_only',
255 '--rootfs_mountpt=%s' % rootfs_dir,
256 '--stateful_mountpt=%s' % stateful_dir,
257 ])
258 _LogMessage('Tarring up /usr/local and /var!')
259 subprocess.check_call(['sudo',
260 'tar',
261 '-czf',
262 output_gz,
263 '--directory=%s' % stateful_dir,
264 'dev_image',
265 'var',
266 ])
267 except:
268 _LogMessage('Failed to create stateful update file')
269 raise
270 finally:
271 # Unmount best effort regardless.
272 subprocess.call(['%s/mount_gpt_image.sh' % self.crosutils,
273 '--unmount',
274 '--rootfs_mountpt=%s' % rootfs_dir,
275 '--stateful_mountpt=%s' % stateful_dir,
276 ])
277 # Clean up our directories.
278 os.rmdir(rootfs_dir)
279 os.rmdir(stateful_dir)
280
281 _LogMessage('Successfully generated %s' % output_gz)
282 return output_gz
Chris Sosa0356d3b2010-09-16 15:46:22 -0700283
284 def MoveImagesToStaticDir(self, update_path, stateful_update_path,
285 static_image_dir):
286 """Moves gz files from their directories to serving directories.
287
288 Args:
289 update_path: full path to main update gz.
290 stateful_update_path: full path to stateful partition gz.
291 static_image_dir: where to put files.
292 Returns:
293 Returns True if the files were moved over successfully.
294 """
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700295 try:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700296 shutil.copy(update_path, static_image_dir)
297 shutil.copy(stateful_update_path, static_image_dir)
298 os.remove(update_path)
299 os.remove(stateful_update_path)
300 except Exception:
Chris Sosa7c931362010-10-11 19:49:01 -0700301 _LogMessage('Failed to move %s and %s to %s' % (update_path,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700302 stateful_update_path,
303 static_image_dir))
304 return False
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700305
rtc@google.com21a5ca32009-11-04 18:23:23 +0000306 return True
rtc@google.comded22402009-10-26 22:36:21 +0000307
Chris Sosa0356d3b2010-09-16 15:46:22 -0700308 def GenerateUpdateImage(self, image_path, move_to_static_dir=False,
309 static_image_dir=None):
310 """Force generates an update payload based on the given image_path.
rtc@google.comded22402009-10-26 22:36:21 +0000311
Chris Sosa0356d3b2010-09-16 15:46:22 -0700312 Args:
313 image_path: full path to the image.
314 move_to_static_dir: Moves the files from their dir to the static dir.
315 static_image_dir: the directory to move images to after generating.
316 Returns:
317 True if the update payload was created successfully.
318 """
Chris Sosa7c931362010-10-11 19:49:01 -0700319 _LogMessage('Generating update for image %s' % image_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700320 update_path = self.GenerateUpdateFile(image_path)
Chris Sosae67b78f2010-11-04 17:33:16 -0700321 if update_path:
322 stateful_update_path = self.GenerateStatefulFile(image_path)
323 if stateful_update_path:
324 if move_to_static_dir:
325 return self.MoveImagesToStaticDir(update_path, stateful_update_path,
326 static_image_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700327
Chris Sosae67b78f2010-11-04 17:33:16 -0700328 return True
329
330 _LogMessage('Failed to generate update')
331 return False
Chris Sosa0356d3b2010-09-16 15:46:22 -0700332
333 def GenerateLatestUpdateImage(self, board_id, client_version,
334 static_image_dir=None):
335 """Generates an update using the latest image that has been built.
336
337 This will only generate an update if the newest update is newer than that
338 on the client or client_version is 'ForcedUpdate'.
339
340 Args:
341 board_id: Name of the board.
342 client_version: Current version of the client or 'ForcedUpdate'
343 static_image_dir: the directory to move images to after generating.
344 Returns:
345 True if the update payload was created successfully.
346 """
347 latest_image_dir = self._GetLatestImageDir(board_id)
348 latest_version = self._GetVersionFromDir(latest_image_dir)
349 latest_image_path = os.path.join(latest_image_dir, self._GetImageName())
350
Chris Sosa7c931362010-10-11 19:49:01 -0700351 _LogMessage('Preparing to generate update from latest built image %s.' %
Chris Sosa0356d3b2010-09-16 15:46:22 -0700352 latest_image_path)
353
354 # Check to see whether or not we should update.
355 if client_version != 'ForcedUpdate' and not self._CanUpdate(
356 client_version, latest_version):
Chris Sosa7c931362010-10-11 19:49:01 -0700357 _LogMessage('no update')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700358 return False
359
360 cached_file_path = os.path.join(static_image_dir, 'update.gz')
361 if (os.path.exists(cached_file_path) and
362 not self._IsImageNewerThanCached(latest_image_path, cached_file_path)):
363 return True
364
365 return self.GenerateUpdateImage(latest_image_path, move_to_static_dir=True,
366 static_image_dir=static_image_dir)
367
368 def GenerateImageFromZip(self, static_image_dir):
369 """Generates an update from an image zip file.
370
371 This method assumes you have an image.zip in directory you are serving
372 from. If this file is newer than a previously cached file, it will unzip
373 this file, create a payload and serve it.
374
375 Args:
376 static_image_dir: Directory where the zip file exists.
377 Returns:
378 True if the update payload was created successfully.
379 """
Chris Sosa7c931362010-10-11 19:49:01 -0700380 _LogMessage('Preparing to generate update from zip in %s.' % static_image_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700381 image_path = os.path.join(static_image_dir, self._GetImageName())
382 cached_file_path = os.path.join(static_image_dir, 'update.gz')
383 zip_file_path = os.path.join(static_image_dir, 'image.zip')
384 if not self._IsImageNewerThanCached(zip_file_path, cached_file_path):
385 return True
386
387 if not self._UnpackZip(static_image_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700388 _LogMessage('unzip image.zip failed.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700389 return False
390
391 return self.GenerateUpdateImage(image_path, move_to_static_dir=False,
392 static_image_dir=None)
Darin Petkov8ef83452010-03-23 16:52:29 -0700393
Andrew de los Reyes52620802010-04-12 13:40:07 -0700394 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
395 """Imports a factory-floor server configuration file. The file should
396 be in this format:
397 config = [
398 {
399 'qual_ids': set([1, 2, 3, "x86-generic"]),
400 'factory_image': 'generic-factory.gz',
401 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
402 'release_image': 'generic-release.gz',
403 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
404 'oempartitionimg_image': 'generic-oem.gz',
405 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700406 'efipartitionimg_image': 'generic-efi.gz',
407 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700408 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800409 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800410 'firmware_image': 'generic-firmware.gz',
411 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700412 },
413 {
414 'qual_ids': set([6]),
415 'factory_image': '6-factory.gz',
416 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
417 'release_image': '6-release.gz',
418 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
419 'oempartitionimg_image': '6-oem.gz',
420 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700421 'efipartitionimg_image': '6-efi.gz',
422 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700423 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800424 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800425 'firmware_image': '6-firmware.gz',
426 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700427 },
428 ]
429 The server will look for the files by name in the static files
430 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700431
Andrew de los Reyes52620802010-04-12 13:40:07 -0700432 If validate_checksums is True, validates checksums and exits. If
433 a checksum mismatch is found, it's printed to the screen.
434 """
435 f = open(filename, 'r')
436 output = {}
437 exec(f.read(), output)
438 self.factory_config = output['config']
439 success = True
440 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800441 for key in stanza.copy().iterkeys():
442 suffix = '_image'
443 if key.endswith(suffix):
444 kind = key[:-len(suffix)]
Chris Sosa0356d3b2010-09-16 15:46:22 -0700445 stanza[kind + '_size'] = self._GetSize(os.path.join(
446 self.static_dir, stanza[kind + '_image']))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800447 if validate_checksums:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700448 factory_checksum = self._GetHash(os.path.join(self.static_dir,
449 stanza[kind + '_image']))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800450 if factory_checksum != stanza[kind + '_checksum']:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700451 print ('Error: checksum mismatch for %s. Expected "%s" but file '
452 'has checksum "%s".' % (stanza[kind + '_image'],
453 stanza[kind + '_checksum'],
454 factory_checksum))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800455 success = False
Chris Sosa0356d3b2010-09-16 15:46:22 -0700456
Andrew de los Reyes52620802010-04-12 13:40:07 -0700457 if validate_checksums:
458 if success is False:
459 raise Exception('Checksum mismatch in conf file.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700460
Andrew de los Reyes52620802010-04-12 13:40:07 -0700461 print 'Config file looks good.'
462
463 def GetFactoryImage(self, board_id, channel):
Nick Sanders723f3262010-09-16 05:18:41 -0700464 kind = channel.rsplit('-', 1)[0]
Andrew de los Reyes52620802010-04-12 13:40:07 -0700465 for stanza in self.factory_config:
466 if board_id not in stanza['qual_ids']:
467 continue
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700468 if kind + '_image' not in stanza:
469 break
Andrew de los Reyes52620802010-04-12 13:40:07 -0700470 return (stanza[kind + '_image'],
471 stanza[kind + '_checksum'],
472 stanza[kind + '_size'])
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700473 return (None, None, None)
rtc@google.comded22402009-10-26 22:36:21 +0000474
Chris Sosa7c931362010-10-11 19:49:01 -0700475 def HandleFactoryRequest(self, board_id, channel):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700476 (filename, checksum, size) = self.GetFactoryImage(board_id, channel)
477 if filename is None:
Chris Sosa7c931362010-10-11 19:49:01 -0700478 _LogMessage('unable to find image for board %s' % board_id)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700479 return self.GetNoUpdatePayload()
Chris Sosa05f95162010-10-14 18:01:52 -0700480 url = '%s/static/%s' % (self.hostname, filename)
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700481 is_delta_format = self._IsDeltaFormatFile(filename)
Chris Sosa7c931362010-10-11 19:49:01 -0700482 _LogMessage('returning update payload ' + url)
Darin Petkov91436cb2010-09-28 08:52:17 -0700483 # Factory install is using memento updater which is using the sha-1 hash so
484 # setting sha-256 to an empty string.
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700485 return self.GetUpdatePayload(checksum, '', size, url, is_delta_format)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700486
Chris Sosa151643e2010-10-28 14:40:57 -0700487 def GenerateUpdatePayloadForNonFactory(self, board_id, client_version,
488 static_image_dir):
Chris Sosa2c048f12010-10-27 16:05:27 -0700489 """Generates an update for non-factory and returns True on success."""
490 if self.use_cached and os.path.exists(os.path.join(static_image_dir,
491 'update.gz')):
492 _LogMessage('Using cached image regardless of timestamps.')
493 return True
494 else:
495 if self.forced_image:
496 has_built_image = self.GenerateUpdateImage(
497 self.forced_image, move_to_static_dir=True,
498 static_image_dir=static_image_dir)
Chris Sosae67b78f2010-11-04 17:33:16 -0700499 return has_built_image
Chris Sosa2c048f12010-10-27 16:05:27 -0700500 elif self.serve_only:
501 return self.GenerateImageFromZip(static_image_dir)
Chris Sosa151643e2010-10-28 14:40:57 -0700502 else:
Chris Sosae67b78f2010-11-04 17:33:16 -0700503 if board_id:
504 return self.GenerateLatestUpdateImage(board_id,
505 client_version,
506 static_image_dir)
507
508 _LogMessage('You must set --board for pre-generating latest update.')
Chris Sosa151643e2010-10-28 14:40:57 -0700509 return False
Chris Sosa2c048f12010-10-27 16:05:27 -0700510
511 def PreGenerateUpdate(self):
Chris Sosae67b78f2010-11-04 17:33:16 -0700512 """Pre-generates an update. Returns True on success."""
Chris Sosa2c048f12010-10-27 16:05:27 -0700513 # Does not work with factory config.
514 assert(not self.factory_config)
515 _LogMessage('Pre-generating the update payload.')
516 # Does not work with labels so just use static dir.
Chris Sosae67b78f2010-11-04 17:33:16 -0700517 if self.GenerateUpdatePayloadForNonFactory(self.board, '0.0.0.0',
518 self.static_dir):
Chris Sosa2c048f12010-10-27 16:05:27 -0700519 # Force the devserver to use the pre-generated payload.
520 self.use_cached = True
Chris Sosae67b78f2010-11-04 17:33:16 -0700521 _LogMessage('Pre-generated update successfully.')
522 return True
Chris Sosa2c048f12010-10-27 16:05:27 -0700523 else:
524 _LogMessage('Failed to pre-generate update.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700525 return False
Chris Sosa2c048f12010-10-27 16:05:27 -0700526
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700527 def HandleUpdatePing(self, data, label=None):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700528 """Handles an update ping from an update client.
529
530 Args:
531 data: xml blob from client.
532 label: optional label for the update.
533 Returns:
534 Update payload message for client.
535 """
Chris Sosa9841e1c2010-10-14 10:51:45 -0700536 # Set hostname as the hostname that the client is calling to and set up
537 # the url base.
538 self.hostname = cherrypy.request.base
539 if self.urlbase:
540 static_urlbase = self.urlbase
541 elif self.serve_only:
542 static_urlbase = '%s/static/archive' % self.hostname
543 else:
544 static_urlbase = '%s/static' % self.hostname
545
546 _LogMessage('Using static url base %s' % static_urlbase)
547 _LogMessage('Handling update ping as %s: %s' % (self.hostname, data))
Chris Sosa0356d3b2010-09-16 15:46:22 -0700548
549 # Check the client prefix to make sure you can support this type of update.
Chris Sosa9841e1c2010-10-14 10:51:45 -0700550 update_dom = minidom.parseString(data)
551 root = update_dom.firstChild
Chris Sosa0356d3b2010-09-16 15:46:22 -0700552 if (root.hasAttribute('updaterversion') and
553 not root.getAttribute('updaterversion').startswith(self.client_prefix)):
Chris Sosa7c931362010-10-11 19:49:01 -0700554 _LogMessage('Got update from unsupported updater:' +
Chris Sosa0356d3b2010-09-16 15:46:22 -0700555 root.getAttribute('updaterversion'))
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700556 return self.GetNoUpdatePayload()
Chris Sosa0356d3b2010-09-16 15:46:22 -0700557
558 # We only generate update payloads for updatecheck requests.
559 update_check = root.getElementsByTagName('o:updatecheck')
560 if not update_check:
Chris Sosa7c931362010-10-11 19:49:01 -0700561 _LogMessage('Non-update check received. Returning blank payload.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700562 # TODO(sosa): Generate correct non-updatecheck payload to better test
563 # update clients.
564 return self.GetNoUpdatePayload()
565
566 # Since this is an updatecheck, get information about the requester.
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700567 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800568 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700569 channel = query.getAttribute('track')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700570 board_id = (query.hasAttribute('board') and query.getAttribute('board')
571 or self._GetDefaultBoardID())
Andrew de los Reyes52620802010-04-12 13:40:07 -0700572
Chris Sosa0356d3b2010-09-16 15:46:22 -0700573 # Separate logic as Factory requests have static url's that override
574 # other options.
Andrew de los Reyes52620802010-04-12 13:40:07 -0700575 if self.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700576 return self.HandleFactoryRequest(board_id, channel)
Nick Sanders723f3262010-09-16 05:18:41 -0700577 else:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700578 static_image_dir = self.static_dir
579 if label:
580 static_image_dir = os.path.join(static_image_dir, label)
581
Chris Sosa151643e2010-10-28 14:40:57 -0700582 if self.GenerateUpdatePayloadForNonFactory(board_id, client_version,
583 static_image_dir):
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700584 filename = os.path.join(static_image_dir, 'update.gz')
585 hash = self._GetHash(filename)
586 sha256 = self._GetSHA256(filename)
587 size = self._GetSize(filename)
588 is_delta_format = self._IsDeltaFormatFile(filename)
Chris Sosa5d342a22010-09-28 16:54:41 -0700589 if label:
Chris Sosa9841e1c2010-10-14 10:51:45 -0700590 url = '%s/%s/update.gz' % (static_urlbase, label)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700591 else:
Chris Sosa9841e1c2010-10-14 10:51:45 -0700592 url = '%s/update.gz' % static_urlbase
Chris Sosa5d342a22010-09-28 16:54:41 -0700593
Chris Sosa7c931362010-10-11 19:49:01 -0700594 _LogMessage('Responding to client to use url %s to get image.' % url)
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700595 return self.GetUpdatePayload(hash, sha256, size, url, is_delta_format)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700596 else:
Nick Sanders723f3262010-09-16 05:18:41 -0700597 return self.GetNoUpdatePayload()