blob: 93d6b0d194841ba1b2ff226f7681dbceddc3a7fd [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,
Sean O'Connor1f7fd362010-04-07 16:34:52 -070020 *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070021 super(Autoupdate, self).__init__(*args, **kwargs)
Sean O'Connor1f7fd362010-04-07 16:34:52 -070022 self.serve_only = serve_only
Sean O'Connor1b4b0762010-06-02 17:37:32 -070023 self.factory_config = factory_config_path
Chris Sosaa73ec162010-05-03 20:18:02 -070024 self.test_image = test_image
Sean O'Connor1f7fd362010-04-07 16:34:52 -070025 self.static_urlbase = urlbase
26 if serve_only:
27 # If we're serving out of an archived build dir (e.g. a
28 # buildbot), prepare this webserver's magic 'static/' dir with a
29 # link to the build archive.
30 web.debug('Autoupdate in "serve update images only" mode.')
31 if os.path.exists('static/archive'):
Sean O'Connor1b4b0762010-06-02 17:37:32 -070032 if self.static_dir != os.readlink('static/archive'):
Sean O'Connor1f7fd362010-04-07 16:34:52 -070033 web.debug('removing stale symlink to %s' % self.static_dir)
34 os.unlink('static/archive')
Sean O'Connor1b4b0762010-06-02 17:37:32 -070035 os.symlink(self.static_dir, 'static/archive')
Sean O'Connor1f7fd362010-04-07 16:34:52 -070036 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -070037 os.symlink(self.static_dir, 'static/archive')
Andrew de los Reyes52620802010-04-12 13:40:07 -070038 if factory_config_path is not None:
39 self.ImportFactoryConfigFile(factory_config_path, validate_factory_config)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070040
rtc@google.com21a5ca32009-11-04 18:23:23 +000041 def GetUpdatePayload(self, hash, size, url):
42 payload = """<?xml version="1.0" encoding="UTF-8"?>
43 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
44 <app appid="{%s}" status="ok">
45 <ping status="ok"/>
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070046 <updatecheck
47 codebase="%s"
48 hash="%s"
49 needsadmin="false"
50 size="%s"
rtc@google.com21a5ca32009-11-04 18:23:23 +000051 status="ok"/>
52 </app>
53 </gupdate>
54 """
55 return payload % (self.app_id, url, hash, size)
rtc@google.comded22402009-10-26 22:36:21 +000056
rtc@google.com21a5ca32009-11-04 18:23:23 +000057 def GetNoUpdatePayload(self):
58 payload = """<?xml version="1.0" encoding="UTF-8"?>
59 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
60 <app appid="{%s}" status="ok">
61 <ping status="ok"/>
62 <updatecheck status="noupdate"/>
63 </app>
64 </gupdate>
65 """
66 return payload % self.app_id
rtc@google.comded22402009-10-26 22:36:21 +000067
Sam Leffler76382042010-02-18 09:58:42 -080068 def GetLatestImagePath(self, board_id):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070069 cmd = '%s/get_latest_image.sh --board %s' % (self.scripts_dir, board_id)
rtc@google.com21a5ca32009-11-04 18:23:23 +000070 return os.popen(cmd).read().strip()
rtc@google.comded22402009-10-26 22:36:21 +000071
rtc@google.com21a5ca32009-11-04 18:23:23 +000072 def GetLatestVersion(self, latest_image_path):
73 latest_version = latest_image_path.split('/')[-1]
Ryan Cairns1b05beb2010-02-05 17:05:24 -080074
75 # Removes the portage build prefix.
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070076 latest_version = latest_version.lstrip('g-')
rtc@google.com21a5ca32009-11-04 18:23:23 +000077 return latest_version.split('-')[0]
rtc@google.comded22402009-10-26 22:36:21 +000078
rtc@google.com21a5ca32009-11-04 18:23:23 +000079 def CanUpdate(self, client_version, latest_version):
80 """
81 Returns true iff the latest_version is greater than the client_version.
82 """
Vincent Scheib904c6642010-05-18 14:57:39 -070083 client_tokens = client_version.replace('_','').split('.')
84 latest_tokens = latest_version.replace('_','').split('.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070085 web.debug('client version %s latest version %s' \
Charlie Lee8c993082010-02-24 13:27:37 -080086 % (client_version, latest_version))
Chris Sosaa73ec162010-05-03 20:18:02 -070087 for i in range(4):
rtc@google.com21a5ca32009-11-04 18:23:23 +000088 if int(latest_tokens[i]) == int(client_tokens[i]):
89 continue
90 return int(latest_tokens[i]) > int(client_tokens[i])
rtc@google.comded22402009-10-26 22:36:21 +000091 return False
rtc@google.comded22402009-10-26 22:36:21 +000092
Sean O'Connora7f867e2010-05-27 17:53:32 -070093 def UnpackImage(self, image_path, image_file, stateful_file,
94 kernel_file, rootfs_file):
Chris Sosaa73ec162010-05-03 20:18:02 -070095 unpack_command = 'cd %s && ./unpack_partitions.sh %s' % \
96 (image_path, image_file)
97 if os.system(unpack_command) == 0:
98 shutil.move(os.path.join(image_path, 'part_1'), stateful_file)
99 shutil.move(os.path.join(image_path, 'part_2'), kernel_file)
100 shutil.move(os.path.join(image_path, 'part_3'), rootfs_file)
101 os.system('cd %s && rm part_*' % image_path)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700102 return True
Chris Sosaa73ec162010-05-03 20:18:02 -0700103 return False
104
105 def UnpackZip(self, image_path, image_file):
Sean O'Connora7f867e2010-05-27 17:53:32 -0700106 image = os.path.join(image_path, image_file)
107 if os.path.exists(image):
108 return True
109 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -0700110 # -n, never clobber an existing file, in case we get invoked
111 # simultaneously by multiple request handlers. This means that
112 # we're assuming each image.zip file lives in a versioned
113 # directory (a la Buildbot).
114 return os.system('cd %s && unzip -n image.zip %s unpack_partitions.sh' %
Sean O'Connora7f867e2010-05-27 17:53:32 -0700115 (image_path, image_file)) == 0
Chris Sosaa73ec162010-05-03 20:18:02 -0700116
117 def GetImageBinPath(self, image_path):
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700118 if self.test_image:
119 image_file = 'chromiumos_test_image.bin'
120 else:
121 image_file = 'chromiumos_image.bin'
Chris Sosaa73ec162010-05-03 20:18:02 -0700122 return image_file
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700123
rtc@google.com21a5ca32009-11-04 18:23:23 +0000124 def BuildUpdateImage(self, image_path):
Chris Sosaa73ec162010-05-03 20:18:02 -0700125 stateful_file = '%s/stateful.image' % image_path
Darin Petkov55604f12010-04-12 11:09:25 -0700126 kernel_file = '%s/kernel.image' % image_path
127 rootfs_file = '%s/rootfs.image' % image_path
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700128
Chris Sosaa73ec162010-05-03 20:18:02 -0700129 image_file = self.GetImageBinPath(image_path)
130 bin_path = os.path.join(image_path, image_file)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700131
Chris Sosaa73ec162010-05-03 20:18:02 -0700132 # Get appropriate update.gz to compare timestamps.
133 if self.serve_only:
134 cached_update_file = os.path.join(image_path, 'update.gz')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700135 else:
Chris Sosaa73ec162010-05-03 20:18:02 -0700136 cached_update_file = os.path.join(self.static_dir, 'update.gz')
137
Sean O'Connora7f867e2010-05-27 17:53:32 -0700138 # If the rootfs image is newer, re-create everything.
Chris Sosaa73ec162010-05-03 20:18:02 -0700139 if (os.path.exists(cached_update_file) and
140 os.path.getmtime(cached_update_file) >= os.path.getmtime(bin_path)):
141 web.debug('Using cached update image at %s instead of %s' %
142 (cached_update_file, bin_path))
143 else:
144 # Unpack zip file if we are serving from a directory.
145 if self.serve_only and not self.UnpackZip(image_path, image_file):
146 web.debug('unzip image.zip failed.')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000147 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700148
149 if not self.UnpackImage(image_path, image_file, stateful_file,
150 kernel_file, rootfs_file):
151 web.debug('Failed to unpack image.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700152 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700153
154 update_file = os.path.join(image_path, 'update.gz')
155 web.debug('Generating update image %s' % update_file)
156 mkupdate_command = '%s/mk_memento_images.sh %s %s' % \
157 (self.scripts_dir, kernel_file, rootfs_file)
158 if os.system(mkupdate_command) != 0:
159 web.debug('Failed to create update image')
160 return False
161
Sean O'Connora7f867e2010-05-27 17:53:32 -0700162 mkstatefulupdate_command = 'gzip -f %s' % stateful_file
Chris Sosaa73ec162010-05-03 20:18:02 -0700163 if os.system(mkstatefulupdate_command) != 0:
164 web.debug('Failed to create stateful update image')
165 return False
166
167 # Add gz suffix
168 stateful_file = '%s.gz' % stateful_file
169
170 # Cleanup of image files
171 os.remove(kernel_file)
172 os.remove(rootfs_file)
173 if not self.serve_only:
174 try:
175 web.debug('Found a new image to serve, copying it to static')
176 shutil.copy(update_file, self.static_dir)
177 shutil.copy(stateful_file, self.static_dir)
178 os.remove(update_file)
179 os.remove(stateful_file)
180 except Exception, e:
181 web.debug('%s' % e)
182 return False
rtc@google.com21a5ca32009-11-04 18:23:23 +0000183 return True
rtc@google.comded22402009-10-26 22:36:21 +0000184
rtc@google.com21a5ca32009-11-04 18:23:23 +0000185 def GetSize(self, update_path):
186 return os.path.getsize(update_path)
rtc@google.comded22402009-10-26 22:36:21 +0000187
rtc@google.com21a5ca32009-11-04 18:23:23 +0000188 def GetHash(self, update_path):
Darin Petkov8ef83452010-03-23 16:52:29 -0700189 cmd = "cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';" \
190 % update_path
Andrew de los Reyes52620802010-04-12 13:40:07 -0700191 return os.popen(cmd).read().rstrip()
Darin Petkov8ef83452010-03-23 16:52:29 -0700192
Andrew de los Reyes52620802010-04-12 13:40:07 -0700193 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
194 """Imports a factory-floor server configuration file. The file should
195 be in this format:
196 config = [
197 {
198 'qual_ids': set([1, 2, 3, "x86-generic"]),
199 'factory_image': 'generic-factory.gz',
200 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
201 'release_image': 'generic-release.gz',
202 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
203 'oempartitionimg_image': 'generic-oem.gz',
204 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700205 'efipartitionimg_image': 'generic-efi.gz',
206 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700207 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800208 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
209 'systemrom_image': 'generic-systemrom.gz',
210 'systemrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
211 'ecrom_image': 'generic-ecrom.gz',
212 'ecrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700213 },
214 {
215 'qual_ids': set([6]),
216 'factory_image': '6-factory.gz',
217 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
218 'release_image': '6-release.gz',
219 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
220 'oempartitionimg_image': '6-oem.gz',
221 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700222 'efipartitionimg_image': '6-efi.gz',
223 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700224 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800225 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
226 'systemrom_image': '6-systemrom.gz',
227 'systemrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
228 'ecrom_image': '6-ecrom.gz',
229 'ecrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700230 },
231 ]
232 The server will look for the files by name in the static files
233 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700234
Andrew de los Reyes52620802010-04-12 13:40:07 -0700235 If validate_checksums is True, validates checksums and exits. If
236 a checksum mismatch is found, it's printed to the screen.
237 """
238 f = open(filename, 'r')
239 output = {}
240 exec(f.read(), output)
241 self.factory_config = output['config']
242 success = True
243 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800244 for key in stanza.copy().iterkeys():
245 suffix = '_image'
246 if key.endswith(suffix):
247 kind = key[:-len(suffix)]
248 stanza[kind + '_size'] = \
249 os.path.getsize(self.static_dir + '/' + stanza[kind + '_image'])
250 if validate_checksums:
251 factory_checksum = self.GetHash(self.static_dir + '/' +
252 stanza[kind + '_image'])
253 if factory_checksum != stanza[kind + '_checksum']:
254 print 'Error: checksum mismatch for %s. Expected "%s" but file ' \
255 'has checksum "%s".' % (stanza[kind + '_image'],
256 stanza[kind + '_checksum'],
257 factory_checksum)
258 success = False
Andrew de los Reyes52620802010-04-12 13:40:07 -0700259 if validate_checksums:
260 if success is False:
261 raise Exception('Checksum mismatch in conf file.')
262 print 'Config file looks good.'
263
264 def GetFactoryImage(self, board_id, channel):
265 kind = channel.rsplit('-', 1)[0]
266 for stanza in self.factory_config:
267 if board_id not in stanza['qual_ids']:
268 continue
269 return (stanza[kind + '_image'],
270 stanza[kind + '_checksum'],
271 stanza[kind + '_size'])
rtc@google.comded22402009-10-26 22:36:21 +0000272
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700273 def HandleUpdatePing(self, data, label=None):
Andrew de los Reyes52620802010-04-12 13:40:07 -0700274 web.debug('handle update ping')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000275 update_dom = minidom.parseString(data)
276 root = update_dom.firstChild
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700277 if root.hasAttribute('updaterversion') and \
278 not root.getAttribute('updaterversion').startswith(
279 'MementoSoftwareUpdate'):
280 web.debug('Got update from unsupported updater:' + \
281 root.getAttribute('updaterversion'))
282 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700283 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800284 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700285 channel = query.getAttribute('track')
Charlie Lee8c993082010-02-24 13:27:37 -0800286 board_id = query.hasAttribute('board') and query.getAttribute('board') \
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700287 or 'x86-generic'
Charlie Lee8c993082010-02-24 13:27:37 -0800288 latest_image_path = self.GetLatestImagePath(board_id)
289 latest_version = self.GetLatestVersion(latest_image_path)
Andrew de los Reyes52620802010-04-12 13:40:07 -0700290 hostname = web.ctx.host
291
292 # If this is a factory floor server, return the image here:
293 if self.factory_config:
294 (filename, checksum, size) = \
295 self.GetFactoryImage(board_id, channel)
296 if filename is None:
297 web.debug('unable to find image for board %s' % board_id)
298 return self.GetNoUpdatePayload()
299 url = 'http://%s/static/%s' % (hostname, filename)
300 web.debug('returning update payload ' + url)
301 return self.GetUpdatePayload(checksum, size, url)
302
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700303 if client_version != 'ForcedUpdate' \
Charlie Lee8c993082010-02-24 13:27:37 -0800304 and not self.CanUpdate(client_version, latest_version):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700305 web.debug('no update')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000306 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700307 if label:
308 web.debug('Client requested version %s' % label)
309 # Check that matching build exists
310 image_path = '%s/%s' % (self.static_dir, label)
311 if not os.path.exists(image_path):
312 web.debug('%s not found.' % image_path)
313 return self.GetNoUpdatePayload()
314 # Construct a response
315 ok = self.BuildUpdateImage(image_path)
316 if ok != True:
317 web.debug('Failed to build an update image')
318 return self.GetNoUpdatePayload()
319 web.debug('serving update: ')
320 hash = self.GetHash('%s/%s/update.gz' % (self.static_dir, label))
321 size = self.GetSize('%s/%s/update.gz' % (self.static_dir, label))
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700322 # In case we configured images to be hosted elsewhere
323 # (e.g. buildbot's httpd), use that. Otherwise, serve it
324 # ourselves using web.py's static resource handler.
325 if self.static_urlbase:
326 urlbase = self.static_urlbase
327 else:
328 urlbase = 'http://%s/static/archive/' % hostname
329
330 url = '%s/%s/update.gz' % (urlbase, label)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700331 return self.GetUpdatePayload(hash, size, url)
Chris Sosaa73ec162010-05-03 20:18:02 -0700332 web.debug('DONE')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700333 else:
334 web.debug('update found %s ' % latest_version)
335 ok = self.BuildUpdateImage(latest_image_path)
336 if ok != True:
337 web.debug('Failed to build an update image')
338 return self.GetNoUpdatePayload()
rtc@google.comded22402009-10-26 22:36:21 +0000339
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700340 hash = self.GetHash('%s/update.gz' % self.static_dir)
341 size = self.GetSize('%s/update.gz' % self.static_dir)
342
343 url = 'http://%s/static/update.gz' % hostname
344 return self.GetUpdatePayload(hash, size, url)