blob: 618e89d139f62280481caf5b1dc820d6cd333dc9 [file] [log] [blame]
rtc@google.comded22402009-10-26 22:36:21 +00001# Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2# 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
7
8import os
Darin Petkov798fe7d2010-03-22 15:18:13 -07009import shutil
Andrew de los Reyes52620802010-04-12 13:40:07 -070010import sys
rtc@google.comded22402009-10-26 22:36:21 +000011import web
12
rtc@google.com64244662009-11-12 00:52:08 +000013class Autoupdate(BuildObject):
Darin Petkov798fe7d2010-03-22 15:18:13 -070014 # Basic functionality of handling ChromeOS autoupdate pings
rtc@google.com21a5ca32009-11-04 18:23:23 +000015 # and building/serving update images.
16 # TODO(rtc): Clean this code up and write some tests.
rtc@google.comded22402009-10-26 22:36:21 +000017
Sean O'Connor1f7fd362010-04-07 16:34:52 -070018 def __init__(self, serve_only=None, test_image=False, urlbase=None,
Andrew de los Reyes52620802010-04-12 13:40:07 -070019 factory_config_path=None, validate_factory_config=None,
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -070020 client_prefix=None,
Sean O'Connor1f7fd362010-04-07 16:34:52 -070021 *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070022 super(Autoupdate, self).__init__(*args, **kwargs)
Sean O'Connor1f7fd362010-04-07 16:34:52 -070023 self.serve_only = serve_only
Sean O'Connor1b4b0762010-06-02 17:37:32 -070024 self.factory_config = factory_config_path
Chris Sosaa73ec162010-05-03 20:18:02 -070025 self.test_image = test_image
Sean O'Connor1f7fd362010-04-07 16:34:52 -070026 self.static_urlbase = urlbase
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -070027 self.client_prefix=client_prefix
Sean O'Connor1f7fd362010-04-07 16:34:52 -070028 if serve_only:
29 # If we're serving out of an archived build dir (e.g. a
30 # buildbot), prepare this webserver's magic 'static/' dir with a
31 # link to the build archive.
32 web.debug('Autoupdate in "serve update images only" mode.')
33 if os.path.exists('static/archive'):
Sean O'Connor1b4b0762010-06-02 17:37:32 -070034 if self.static_dir != os.readlink('static/archive'):
Sean O'Connor1f7fd362010-04-07 16:34:52 -070035 web.debug('removing stale symlink to %s' % self.static_dir)
36 os.unlink('static/archive')
Sean O'Connor1b4b0762010-06-02 17:37:32 -070037 os.symlink(self.static_dir, 'static/archive')
Sean O'Connor1f7fd362010-04-07 16:34:52 -070038 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -070039 os.symlink(self.static_dir, 'static/archive')
Andrew de los Reyes52620802010-04-12 13:40:07 -070040 if factory_config_path is not None:
41 self.ImportFactoryConfigFile(factory_config_path, validate_factory_config)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070042
rtc@google.com21a5ca32009-11-04 18:23:23 +000043 def GetUpdatePayload(self, hash, size, url):
44 payload = """<?xml version="1.0" encoding="UTF-8"?>
45 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
46 <app appid="{%s}" status="ok">
47 <ping status="ok"/>
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070048 <updatecheck
49 codebase="%s"
50 hash="%s"
51 needsadmin="false"
52 size="%s"
rtc@google.com21a5ca32009-11-04 18:23:23 +000053 status="ok"/>
54 </app>
55 </gupdate>
56 """
57 return payload % (self.app_id, url, hash, size)
rtc@google.comded22402009-10-26 22:36:21 +000058
rtc@google.com21a5ca32009-11-04 18:23:23 +000059 def GetNoUpdatePayload(self):
60 payload = """<?xml version="1.0" encoding="UTF-8"?>
61 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
62 <app appid="{%s}" status="ok">
63 <ping status="ok"/>
64 <updatecheck status="noupdate"/>
65 </app>
66 </gupdate>
67 """
68 return payload % self.app_id
rtc@google.comded22402009-10-26 22:36:21 +000069
Andrew de los Reyes9a528712010-06-30 10:29:43 -070070 def GetDefaultBoardID(self):
71 board_file = '%s/.default_board' % (self.scripts_dir)
72 try:
73 return open(board_file).read()
74 except IOError:
75 return 'x86-generic'
76
Sam Leffler76382042010-02-18 09:58:42 -080077 def GetLatestImagePath(self, board_id):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070078 cmd = '%s/get_latest_image.sh --board %s' % (self.scripts_dir, board_id)
rtc@google.com21a5ca32009-11-04 18:23:23 +000079 return os.popen(cmd).read().strip()
rtc@google.comded22402009-10-26 22:36:21 +000080
rtc@google.com21a5ca32009-11-04 18:23:23 +000081 def GetLatestVersion(self, latest_image_path):
82 latest_version = latest_image_path.split('/')[-1]
Ryan Cairns1b05beb2010-02-05 17:05:24 -080083
84 # Removes the portage build prefix.
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070085 latest_version = latest_version.lstrip('g-')
rtc@google.com21a5ca32009-11-04 18:23:23 +000086 return latest_version.split('-')[0]
rtc@google.comded22402009-10-26 22:36:21 +000087
rtc@google.com21a5ca32009-11-04 18:23:23 +000088 def CanUpdate(self, client_version, latest_version):
89 """
90 Returns true iff the latest_version is greater than the client_version.
91 """
Vincent Scheib904c6642010-05-18 14:57:39 -070092 client_tokens = client_version.replace('_','').split('.')
93 latest_tokens = latest_version.replace('_','').split('.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070094 web.debug('client version %s latest version %s' \
Charlie Lee8c993082010-02-24 13:27:37 -080095 % (client_version, latest_version))
Chris Sosaa73ec162010-05-03 20:18:02 -070096 for i in range(4):
rtc@google.com21a5ca32009-11-04 18:23:23 +000097 if int(latest_tokens[i]) == int(client_tokens[i]):
98 continue
99 return int(latest_tokens[i]) > int(client_tokens[i])
rtc@google.comded22402009-10-26 22:36:21 +0000100 return False
rtc@google.comded22402009-10-26 22:36:21 +0000101
Sean O'Connora7f867e2010-05-27 17:53:32 -0700102 def UnpackImage(self, image_path, image_file, stateful_file,
103 kernel_file, rootfs_file):
Chris Sosaa73ec162010-05-03 20:18:02 -0700104 unpack_command = 'cd %s && ./unpack_partitions.sh %s' % \
105 (image_path, image_file)
106 if os.system(unpack_command) == 0:
107 shutil.move(os.path.join(image_path, 'part_1'), stateful_file)
108 shutil.move(os.path.join(image_path, 'part_2'), kernel_file)
109 shutil.move(os.path.join(image_path, 'part_3'), rootfs_file)
110 os.system('cd %s && rm part_*' % image_path)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700111 return True
Chris Sosaa73ec162010-05-03 20:18:02 -0700112 return False
113
114 def UnpackZip(self, image_path, image_file):
Sean O'Connora7f867e2010-05-27 17:53:32 -0700115 image = os.path.join(image_path, image_file)
116 if os.path.exists(image):
117 return True
118 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -0700119 # -n, never clobber an existing file, in case we get invoked
120 # simultaneously by multiple request handlers. This means that
121 # we're assuming each image.zip file lives in a versioned
122 # directory (a la Buildbot).
123 return os.system('cd %s && unzip -n image.zip %s unpack_partitions.sh' %
Sean O'Connora7f867e2010-05-27 17:53:32 -0700124 (image_path, image_file)) == 0
Chris Sosaa73ec162010-05-03 20:18:02 -0700125
126 def GetImageBinPath(self, image_path):
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700127 if self.test_image:
128 image_file = 'chromiumos_test_image.bin'
129 else:
130 image_file = 'chromiumos_image.bin'
Chris Sosaa73ec162010-05-03 20:18:02 -0700131 return image_file
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700132
rtc@google.com21a5ca32009-11-04 18:23:23 +0000133 def BuildUpdateImage(self, image_path):
Chris Sosaa73ec162010-05-03 20:18:02 -0700134 stateful_file = '%s/stateful.image' % image_path
Darin Petkov55604f12010-04-12 11:09:25 -0700135 kernel_file = '%s/kernel.image' % image_path
136 rootfs_file = '%s/rootfs.image' % image_path
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700137
Chris Sosaa73ec162010-05-03 20:18:02 -0700138 image_file = self.GetImageBinPath(image_path)
139 bin_path = os.path.join(image_path, image_file)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700140
Chris Sosaa73ec162010-05-03 20:18:02 -0700141 # Get appropriate update.gz to compare timestamps.
142 if self.serve_only:
143 cached_update_file = os.path.join(image_path, 'update.gz')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700144 else:
Chris Sosaa73ec162010-05-03 20:18:02 -0700145 cached_update_file = os.path.join(self.static_dir, 'update.gz')
146
Sean O'Connora7f867e2010-05-27 17:53:32 -0700147 # If the rootfs image is newer, re-create everything.
Chris Sosaa73ec162010-05-03 20:18:02 -0700148 if (os.path.exists(cached_update_file) and
149 os.path.getmtime(cached_update_file) >= os.path.getmtime(bin_path)):
150 web.debug('Using cached update image at %s instead of %s' %
151 (cached_update_file, bin_path))
152 else:
153 # Unpack zip file if we are serving from a directory.
154 if self.serve_only and not self.UnpackZip(image_path, image_file):
155 web.debug('unzip image.zip failed.')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000156 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700157
158 if not self.UnpackImage(image_path, image_file, stateful_file,
159 kernel_file, rootfs_file):
160 web.debug('Failed to unpack image.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700161 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700162
163 update_file = os.path.join(image_path, 'update.gz')
164 web.debug('Generating update image %s' % update_file)
165 mkupdate_command = '%s/mk_memento_images.sh %s %s' % \
166 (self.scripts_dir, kernel_file, rootfs_file)
167 if os.system(mkupdate_command) != 0:
168 web.debug('Failed to create update image')
169 return False
170
Sean O'Connora7f867e2010-05-27 17:53:32 -0700171 mkstatefulupdate_command = 'gzip -f %s' % stateful_file
Chris Sosaa73ec162010-05-03 20:18:02 -0700172 if os.system(mkstatefulupdate_command) != 0:
173 web.debug('Failed to create stateful update image')
174 return False
175
176 # Add gz suffix
177 stateful_file = '%s.gz' % stateful_file
178
179 # Cleanup of image files
180 os.remove(kernel_file)
181 os.remove(rootfs_file)
182 if not self.serve_only:
183 try:
184 web.debug('Found a new image to serve, copying it to static')
185 shutil.copy(update_file, self.static_dir)
186 shutil.copy(stateful_file, self.static_dir)
187 os.remove(update_file)
188 os.remove(stateful_file)
189 except Exception, e:
190 web.debug('%s' % e)
191 return False
rtc@google.com21a5ca32009-11-04 18:23:23 +0000192 return True
rtc@google.comded22402009-10-26 22:36:21 +0000193
rtc@google.com21a5ca32009-11-04 18:23:23 +0000194 def GetSize(self, update_path):
195 return os.path.getsize(update_path)
rtc@google.comded22402009-10-26 22:36:21 +0000196
rtc@google.com21a5ca32009-11-04 18:23:23 +0000197 def GetHash(self, update_path):
Darin Petkov8ef83452010-03-23 16:52:29 -0700198 cmd = "cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';" \
199 % update_path
Andrew de los Reyes52620802010-04-12 13:40:07 -0700200 return os.popen(cmd).read().rstrip()
Darin Petkov8ef83452010-03-23 16:52:29 -0700201
Andrew de los Reyes52620802010-04-12 13:40:07 -0700202 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
203 """Imports a factory-floor server configuration file. The file should
204 be in this format:
205 config = [
206 {
207 'qual_ids': set([1, 2, 3, "x86-generic"]),
208 'factory_image': 'generic-factory.gz',
209 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
210 'release_image': 'generic-release.gz',
211 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
212 'oempartitionimg_image': 'generic-oem.gz',
213 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700214 'efipartitionimg_image': 'generic-efi.gz',
215 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700216 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800217 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800218 'firmware_image': 'generic-firmware.gz',
219 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700220 },
221 {
222 'qual_ids': set([6]),
223 'factory_image': '6-factory.gz',
224 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
225 'release_image': '6-release.gz',
226 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
227 'oempartitionimg_image': '6-oem.gz',
228 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700229 'efipartitionimg_image': '6-efi.gz',
230 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700231 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800232 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800233 'firmware_image': '6-firmware.gz',
234 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700235 },
236 ]
237 The server will look for the files by name in the static files
238 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700239
Andrew de los Reyes52620802010-04-12 13:40:07 -0700240 If validate_checksums is True, validates checksums and exits. If
241 a checksum mismatch is found, it's printed to the screen.
242 """
243 f = open(filename, 'r')
244 output = {}
245 exec(f.read(), output)
246 self.factory_config = output['config']
247 success = True
248 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800249 for key in stanza.copy().iterkeys():
250 suffix = '_image'
251 if key.endswith(suffix):
252 kind = key[:-len(suffix)]
253 stanza[kind + '_size'] = \
254 os.path.getsize(self.static_dir + '/' + stanza[kind + '_image'])
255 if validate_checksums:
256 factory_checksum = self.GetHash(self.static_dir + '/' +
257 stanza[kind + '_image'])
258 if factory_checksum != stanza[kind + '_checksum']:
259 print 'Error: checksum mismatch for %s. Expected "%s" but file ' \
260 'has checksum "%s".' % (stanza[kind + '_image'],
261 stanza[kind + '_checksum'],
262 factory_checksum)
263 success = False
Andrew de los Reyes52620802010-04-12 13:40:07 -0700264 if validate_checksums:
265 if success is False:
266 raise Exception('Checksum mismatch in conf file.')
267 print 'Config file looks good.'
268
269 def GetFactoryImage(self, board_id, channel):
270 kind = channel.rsplit('-', 1)[0]
271 for stanza in self.factory_config:
272 if board_id not in stanza['qual_ids']:
273 continue
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700274 if kind + '_image' not in stanza:
275 break
Andrew de los Reyes52620802010-04-12 13:40:07 -0700276 return (stanza[kind + '_image'],
277 stanza[kind + '_checksum'],
278 stanza[kind + '_size'])
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700279 return (None, None, None)
rtc@google.comded22402009-10-26 22:36:21 +0000280
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700281 def HandleUpdatePing(self, data, label=None):
Darin Petkovd35ee242010-07-14 16:45:31 -0700282 web.debug('handle update ping: %s' % data)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000283 update_dom = minidom.parseString(data)
284 root = update_dom.firstChild
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700285 if root.hasAttribute('updaterversion') and \
286 not root.getAttribute('updaterversion').startswith(
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -0700287 self.client_prefix):
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700288 web.debug('Got update from unsupported updater:' + \
289 root.getAttribute('updaterversion'))
290 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700291 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800292 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700293 channel = query.getAttribute('track')
Charlie Lee8c993082010-02-24 13:27:37 -0800294 board_id = query.hasAttribute('board') and query.getAttribute('board') \
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700295 or self.GetDefaultBoardID()
Charlie Lee8c993082010-02-24 13:27:37 -0800296 latest_image_path = self.GetLatestImagePath(board_id)
297 latest_version = self.GetLatestVersion(latest_image_path)
Andrew de los Reyes52620802010-04-12 13:40:07 -0700298 hostname = web.ctx.host
299
300 # If this is a factory floor server, return the image here:
301 if self.factory_config:
302 (filename, checksum, size) = \
303 self.GetFactoryImage(board_id, channel)
304 if filename is None:
305 web.debug('unable to find image for board %s' % board_id)
306 return self.GetNoUpdatePayload()
307 url = 'http://%s/static/%s' % (hostname, filename)
308 web.debug('returning update payload ' + url)
309 return self.GetUpdatePayload(checksum, size, url)
310
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700311 if client_version != 'ForcedUpdate' \
Charlie Lee8c993082010-02-24 13:27:37 -0800312 and not self.CanUpdate(client_version, latest_version):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700313 web.debug('no update')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000314 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700315 if label:
316 web.debug('Client requested version %s' % label)
317 # Check that matching build exists
318 image_path = '%s/%s' % (self.static_dir, label)
319 if not os.path.exists(image_path):
320 web.debug('%s not found.' % image_path)
321 return self.GetNoUpdatePayload()
322 # Construct a response
323 ok = self.BuildUpdateImage(image_path)
324 if ok != True:
325 web.debug('Failed to build an update image')
326 return self.GetNoUpdatePayload()
327 web.debug('serving update: ')
328 hash = self.GetHash('%s/%s/update.gz' % (self.static_dir, label))
329 size = self.GetSize('%s/%s/update.gz' % (self.static_dir, label))
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700330 # In case we configured images to be hosted elsewhere
331 # (e.g. buildbot's httpd), use that. Otherwise, serve it
332 # ourselves using web.py's static resource handler.
333 if self.static_urlbase:
334 urlbase = self.static_urlbase
335 else:
336 urlbase = 'http://%s/static/archive/' % hostname
337
338 url = '%s/%s/update.gz' % (urlbase, label)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700339 return self.GetUpdatePayload(hash, size, url)
Chris Sosaa73ec162010-05-03 20:18:02 -0700340 web.debug('DONE')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700341 else:
342 web.debug('update found %s ' % latest_version)
343 ok = self.BuildUpdateImage(latest_image_path)
344 if ok != True:
345 web.debug('Failed to build an update image')
346 return self.GetNoUpdatePayload()
rtc@google.comded22402009-10-26 22:36:21 +0000347
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700348 hash = self.GetHash('%s/update.gz' % self.static_dir)
349 size = self.GetSize('%s/update.gz' % self.static_dir)
350
351 url = 'http://%s/static/update.gz' % hostname
352 return self.GetUpdatePayload(hash, size, url)