blob: 23392a36eeafa9a3d9bc50cf8959410f5a74aab4 [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,
Chris Sosa4195fad2010-11-09 14:47:35 -0800264 '--transform=s,^dev_image,dev_image_new,',
265 '--transform=s,^var,var_new,',
Chris Sosa05491b12010-11-08 17:14:16 -0800266 'dev_image',
267 'var',
268 ])
269 except:
270 _LogMessage('Failed to create stateful update file')
271 raise
272 finally:
273 # Unmount best effort regardless.
274 subprocess.call(['%s/mount_gpt_image.sh' % self.crosutils,
275 '--unmount',
276 '--rootfs_mountpt=%s' % rootfs_dir,
277 '--stateful_mountpt=%s' % stateful_dir,
278 ])
279 # Clean up our directories.
280 os.rmdir(rootfs_dir)
281 os.rmdir(stateful_dir)
282
283 _LogMessage('Successfully generated %s' % output_gz)
284 return output_gz
Chris Sosa0356d3b2010-09-16 15:46:22 -0700285
286 def MoveImagesToStaticDir(self, update_path, stateful_update_path,
287 static_image_dir):
288 """Moves gz files from their directories to serving directories.
289
290 Args:
291 update_path: full path to main update gz.
292 stateful_update_path: full path to stateful partition gz.
293 static_image_dir: where to put files.
294 Returns:
295 Returns True if the files were moved over successfully.
296 """
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700297 try:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700298 shutil.copy(update_path, static_image_dir)
299 shutil.copy(stateful_update_path, static_image_dir)
300 os.remove(update_path)
301 os.remove(stateful_update_path)
302 except Exception:
Chris Sosa7c931362010-10-11 19:49:01 -0700303 _LogMessage('Failed to move %s and %s to %s' % (update_path,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700304 stateful_update_path,
305 static_image_dir))
306 return False
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700307
rtc@google.com21a5ca32009-11-04 18:23:23 +0000308 return True
rtc@google.comded22402009-10-26 22:36:21 +0000309
Chris Sosa0356d3b2010-09-16 15:46:22 -0700310 def GenerateUpdateImage(self, image_path, move_to_static_dir=False,
311 static_image_dir=None):
312 """Force generates an update payload based on the given image_path.
rtc@google.comded22402009-10-26 22:36:21 +0000313
Chris Sosa0356d3b2010-09-16 15:46:22 -0700314 Args:
315 image_path: full path to the image.
316 move_to_static_dir: Moves the files from their dir to the static dir.
317 static_image_dir: the directory to move images to after generating.
318 Returns:
319 True if the update payload was created successfully.
320 """
Chris Sosa7c931362010-10-11 19:49:01 -0700321 _LogMessage('Generating update for image %s' % image_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700322 update_path = self.GenerateUpdateFile(image_path)
Chris Sosae67b78f2010-11-04 17:33:16 -0700323 if update_path:
324 stateful_update_path = self.GenerateStatefulFile(image_path)
325 if stateful_update_path:
326 if move_to_static_dir:
327 return self.MoveImagesToStaticDir(update_path, stateful_update_path,
328 static_image_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700329
Chris Sosae67b78f2010-11-04 17:33:16 -0700330 return True
331
332 _LogMessage('Failed to generate update')
333 return False
Chris Sosa0356d3b2010-09-16 15:46:22 -0700334
335 def GenerateLatestUpdateImage(self, board_id, client_version,
336 static_image_dir=None):
337 """Generates an update using the latest image that has been built.
338
339 This will only generate an update if the newest update is newer than that
340 on the client or client_version is 'ForcedUpdate'.
341
342 Args:
343 board_id: Name of the board.
344 client_version: Current version of the client or 'ForcedUpdate'
345 static_image_dir: the directory to move images to after generating.
346 Returns:
347 True if the update payload was created successfully.
348 """
349 latest_image_dir = self._GetLatestImageDir(board_id)
350 latest_version = self._GetVersionFromDir(latest_image_dir)
351 latest_image_path = os.path.join(latest_image_dir, self._GetImageName())
352
Chris Sosa7c931362010-10-11 19:49:01 -0700353 _LogMessage('Preparing to generate update from latest built image %s.' %
Chris Sosa0356d3b2010-09-16 15:46:22 -0700354 latest_image_path)
355
356 # Check to see whether or not we should update.
357 if client_version != 'ForcedUpdate' and not self._CanUpdate(
358 client_version, latest_version):
Chris Sosa7c931362010-10-11 19:49:01 -0700359 _LogMessage('no update')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700360 return False
361
362 cached_file_path = os.path.join(static_image_dir, 'update.gz')
363 if (os.path.exists(cached_file_path) and
364 not self._IsImageNewerThanCached(latest_image_path, cached_file_path)):
365 return True
366
367 return self.GenerateUpdateImage(latest_image_path, move_to_static_dir=True,
368 static_image_dir=static_image_dir)
369
370 def GenerateImageFromZip(self, static_image_dir):
371 """Generates an update from an image zip file.
372
373 This method assumes you have an image.zip in directory you are serving
374 from. If this file is newer than a previously cached file, it will unzip
375 this file, create a payload and serve it.
376
377 Args:
378 static_image_dir: Directory where the zip file exists.
379 Returns:
380 True if the update payload was created successfully.
381 """
Chris Sosa7c931362010-10-11 19:49:01 -0700382 _LogMessage('Preparing to generate update from zip in %s.' % static_image_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700383 image_path = os.path.join(static_image_dir, self._GetImageName())
384 cached_file_path = os.path.join(static_image_dir, 'update.gz')
385 zip_file_path = os.path.join(static_image_dir, 'image.zip')
386 if not self._IsImageNewerThanCached(zip_file_path, cached_file_path):
387 return True
388
389 if not self._UnpackZip(static_image_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700390 _LogMessage('unzip image.zip failed.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700391 return False
392
393 return self.GenerateUpdateImage(image_path, move_to_static_dir=False,
394 static_image_dir=None)
Darin Petkov8ef83452010-03-23 16:52:29 -0700395
Andrew de los Reyes52620802010-04-12 13:40:07 -0700396 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
397 """Imports a factory-floor server configuration file. The file should
398 be in this format:
399 config = [
400 {
401 'qual_ids': set([1, 2, 3, "x86-generic"]),
402 'factory_image': 'generic-factory.gz',
403 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
404 'release_image': 'generic-release.gz',
405 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
406 'oempartitionimg_image': 'generic-oem.gz',
407 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700408 'efipartitionimg_image': 'generic-efi.gz',
409 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700410 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800411 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800412 'firmware_image': 'generic-firmware.gz',
413 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700414 },
415 {
416 'qual_ids': set([6]),
417 'factory_image': '6-factory.gz',
418 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
419 'release_image': '6-release.gz',
420 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
421 'oempartitionimg_image': '6-oem.gz',
422 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700423 'efipartitionimg_image': '6-efi.gz',
424 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700425 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800426 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800427 'firmware_image': '6-firmware.gz',
428 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700429 },
430 ]
431 The server will look for the files by name in the static files
432 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700433
Andrew de los Reyes52620802010-04-12 13:40:07 -0700434 If validate_checksums is True, validates checksums and exits. If
435 a checksum mismatch is found, it's printed to the screen.
436 """
437 f = open(filename, 'r')
438 output = {}
439 exec(f.read(), output)
440 self.factory_config = output['config']
441 success = True
442 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800443 for key in stanza.copy().iterkeys():
444 suffix = '_image'
445 if key.endswith(suffix):
446 kind = key[:-len(suffix)]
Chris Sosa0356d3b2010-09-16 15:46:22 -0700447 stanza[kind + '_size'] = self._GetSize(os.path.join(
448 self.static_dir, stanza[kind + '_image']))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800449 if validate_checksums:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700450 factory_checksum = self._GetHash(os.path.join(self.static_dir,
451 stanza[kind + '_image']))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800452 if factory_checksum != stanza[kind + '_checksum']:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700453 print ('Error: checksum mismatch for %s. Expected "%s" but file '
454 'has checksum "%s".' % (stanza[kind + '_image'],
455 stanza[kind + '_checksum'],
456 factory_checksum))
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800457 success = False
Chris Sosa0356d3b2010-09-16 15:46:22 -0700458
Andrew de los Reyes52620802010-04-12 13:40:07 -0700459 if validate_checksums:
460 if success is False:
461 raise Exception('Checksum mismatch in conf file.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700462
Andrew de los Reyes52620802010-04-12 13:40:07 -0700463 print 'Config file looks good.'
464
465 def GetFactoryImage(self, board_id, channel):
Nick Sanders723f3262010-09-16 05:18:41 -0700466 kind = channel.rsplit('-', 1)[0]
Andrew de los Reyes52620802010-04-12 13:40:07 -0700467 for stanza in self.factory_config:
468 if board_id not in stanza['qual_ids']:
469 continue
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700470 if kind + '_image' not in stanza:
471 break
Andrew de los Reyes52620802010-04-12 13:40:07 -0700472 return (stanza[kind + '_image'],
473 stanza[kind + '_checksum'],
474 stanza[kind + '_size'])
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700475 return (None, None, None)
rtc@google.comded22402009-10-26 22:36:21 +0000476
Chris Sosa7c931362010-10-11 19:49:01 -0700477 def HandleFactoryRequest(self, board_id, channel):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700478 (filename, checksum, size) = self.GetFactoryImage(board_id, channel)
479 if filename is None:
Chris Sosa7c931362010-10-11 19:49:01 -0700480 _LogMessage('unable to find image for board %s' % board_id)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700481 return self.GetNoUpdatePayload()
Chris Sosa05f95162010-10-14 18:01:52 -0700482 url = '%s/static/%s' % (self.hostname, filename)
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700483 is_delta_format = self._IsDeltaFormatFile(filename)
Chris Sosa7c931362010-10-11 19:49:01 -0700484 _LogMessage('returning update payload ' + url)
Darin Petkov91436cb2010-09-28 08:52:17 -0700485 # Factory install is using memento updater which is using the sha-1 hash so
486 # setting sha-256 to an empty string.
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700487 return self.GetUpdatePayload(checksum, '', size, url, is_delta_format)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700488
Chris Sosa151643e2010-10-28 14:40:57 -0700489 def GenerateUpdatePayloadForNonFactory(self, board_id, client_version,
490 static_image_dir):
Chris Sosa2c048f12010-10-27 16:05:27 -0700491 """Generates an update for non-factory and returns True on success."""
492 if self.use_cached and os.path.exists(os.path.join(static_image_dir,
493 'update.gz')):
494 _LogMessage('Using cached image regardless of timestamps.')
495 return True
496 else:
497 if self.forced_image:
498 has_built_image = self.GenerateUpdateImage(
499 self.forced_image, move_to_static_dir=True,
500 static_image_dir=static_image_dir)
Chris Sosae67b78f2010-11-04 17:33:16 -0700501 return has_built_image
Chris Sosa2c048f12010-10-27 16:05:27 -0700502 elif self.serve_only:
503 return self.GenerateImageFromZip(static_image_dir)
Chris Sosa151643e2010-10-28 14:40:57 -0700504 else:
Chris Sosae67b78f2010-11-04 17:33:16 -0700505 if board_id:
506 return self.GenerateLatestUpdateImage(board_id,
507 client_version,
508 static_image_dir)
509
510 _LogMessage('You must set --board for pre-generating latest update.')
Chris Sosa151643e2010-10-28 14:40:57 -0700511 return False
Chris Sosa2c048f12010-10-27 16:05:27 -0700512
513 def PreGenerateUpdate(self):
Chris Sosae67b78f2010-11-04 17:33:16 -0700514 """Pre-generates an update. Returns True on success."""
Chris Sosa2c048f12010-10-27 16:05:27 -0700515 # Does not work with factory config.
516 assert(not self.factory_config)
517 _LogMessage('Pre-generating the update payload.')
518 # Does not work with labels so just use static dir.
Chris Sosae67b78f2010-11-04 17:33:16 -0700519 if self.GenerateUpdatePayloadForNonFactory(self.board, '0.0.0.0',
520 self.static_dir):
Chris Sosa2c048f12010-10-27 16:05:27 -0700521 # Force the devserver to use the pre-generated payload.
522 self.use_cached = True
Chris Sosae67b78f2010-11-04 17:33:16 -0700523 _LogMessage('Pre-generated update successfully.')
524 return True
Chris Sosa2c048f12010-10-27 16:05:27 -0700525 else:
526 _LogMessage('Failed to pre-generate update.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700527 return False
Chris Sosa2c048f12010-10-27 16:05:27 -0700528
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700529 def HandleUpdatePing(self, data, label=None):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700530 """Handles an update ping from an update client.
531
532 Args:
533 data: xml blob from client.
534 label: optional label for the update.
535 Returns:
536 Update payload message for client.
537 """
Chris Sosa9841e1c2010-10-14 10:51:45 -0700538 # Set hostname as the hostname that the client is calling to and set up
539 # the url base.
540 self.hostname = cherrypy.request.base
541 if self.urlbase:
542 static_urlbase = self.urlbase
543 elif self.serve_only:
544 static_urlbase = '%s/static/archive' % self.hostname
545 else:
546 static_urlbase = '%s/static' % self.hostname
547
548 _LogMessage('Using static url base %s' % static_urlbase)
549 _LogMessage('Handling update ping as %s: %s' % (self.hostname, data))
Chris Sosa0356d3b2010-09-16 15:46:22 -0700550
551 # Check the client prefix to make sure you can support this type of update.
Chris Sosa9841e1c2010-10-14 10:51:45 -0700552 update_dom = minidom.parseString(data)
553 root = update_dom.firstChild
Chris Sosa0356d3b2010-09-16 15:46:22 -0700554 if (root.hasAttribute('updaterversion') and
555 not root.getAttribute('updaterversion').startswith(self.client_prefix)):
Chris Sosa7c931362010-10-11 19:49:01 -0700556 _LogMessage('Got update from unsupported updater:' +
Chris Sosa0356d3b2010-09-16 15:46:22 -0700557 root.getAttribute('updaterversion'))
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700558 return self.GetNoUpdatePayload()
Chris Sosa0356d3b2010-09-16 15:46:22 -0700559
560 # We only generate update payloads for updatecheck requests.
561 update_check = root.getElementsByTagName('o:updatecheck')
562 if not update_check:
Chris Sosa7c931362010-10-11 19:49:01 -0700563 _LogMessage('Non-update check received. Returning blank payload.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700564 # TODO(sosa): Generate correct non-updatecheck payload to better test
565 # update clients.
566 return self.GetNoUpdatePayload()
567
568 # Since this is an updatecheck, get information about the requester.
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700569 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800570 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700571 channel = query.getAttribute('track')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700572 board_id = (query.hasAttribute('board') and query.getAttribute('board')
573 or self._GetDefaultBoardID())
Andrew de los Reyes52620802010-04-12 13:40:07 -0700574
Chris Sosa0356d3b2010-09-16 15:46:22 -0700575 # Separate logic as Factory requests have static url's that override
576 # other options.
Andrew de los Reyes52620802010-04-12 13:40:07 -0700577 if self.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700578 return self.HandleFactoryRequest(board_id, channel)
Nick Sanders723f3262010-09-16 05:18:41 -0700579 else:
Chris Sosa0356d3b2010-09-16 15:46:22 -0700580 static_image_dir = self.static_dir
581 if label:
582 static_image_dir = os.path.join(static_image_dir, label)
583
Chris Sosa151643e2010-10-28 14:40:57 -0700584 if self.GenerateUpdatePayloadForNonFactory(board_id, client_version,
585 static_image_dir):
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700586 filename = os.path.join(static_image_dir, 'update.gz')
587 hash = self._GetHash(filename)
588 sha256 = self._GetSHA256(filename)
589 size = self._GetSize(filename)
590 is_delta_format = self._IsDeltaFormatFile(filename)
Chris Sosa5d342a22010-09-28 16:54:41 -0700591 if label:
Chris Sosa9841e1c2010-10-14 10:51:45 -0700592 url = '%s/%s/update.gz' % (static_urlbase, label)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700593 else:
Chris Sosa9841e1c2010-10-14 10:51:45 -0700594 url = '%s/update.gz' % static_urlbase
Chris Sosa5d342a22010-09-28 16:54:41 -0700595
Chris Sosa7c931362010-10-11 19:49:01 -0700596 _LogMessage('Responding to client to use url %s to get image.' % url)
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700597 return self.GetUpdatePayload(hash, sha256, size, url, is_delta_format)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700598 else:
Nick Sanders723f3262010-09-16 05:18:41 -0700599 return self.GetNoUpdatePayload()