blob: e20d78d72a509508128e0435a5bdc693be9edaf0 [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
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070011import time
rtc@google.comded22402009-10-26 22:36:21 +000012import web
13
rtc@google.com64244662009-11-12 00:52:08 +000014class Autoupdate(BuildObject):
Darin Petkov798fe7d2010-03-22 15:18:13 -070015 # Basic functionality of handling ChromeOS autoupdate pings
rtc@google.com21a5ca32009-11-04 18:23:23 +000016 # and building/serving update images.
17 # TODO(rtc): Clean this code up and write some tests.
rtc@google.comded22402009-10-26 22:36:21 +000018
Sean O'Connor1f7fd362010-04-07 16:34:52 -070019 def __init__(self, serve_only=None, test_image=False, urlbase=None,
Andrew de los Reyes52620802010-04-12 13:40:07 -070020 factory_config_path=None, validate_factory_config=None,
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -070021 client_prefix=None,
Sean O'Connor1f7fd362010-04-07 16:34:52 -070022 *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070023 super(Autoupdate, self).__init__(*args, **kwargs)
Sean O'Connor1f7fd362010-04-07 16:34:52 -070024 self.serve_only = serve_only
Sean O'Connor1b4b0762010-06-02 17:37:32 -070025 self.factory_config = factory_config_path
Chris Sosaa73ec162010-05-03 20:18:02 -070026 self.test_image = test_image
Sean O'Connor1f7fd362010-04-07 16:34:52 -070027 self.static_urlbase = urlbase
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -070028 self.client_prefix=client_prefix
Sean O'Connor1f7fd362010-04-07 16:34:52 -070029 if serve_only:
30 # If we're serving out of an archived build dir (e.g. a
31 # buildbot), prepare this webserver's magic 'static/' dir with a
32 # link to the build archive.
33 web.debug('Autoupdate in "serve update images only" mode.')
34 if os.path.exists('static/archive'):
Sean O'Connor1b4b0762010-06-02 17:37:32 -070035 if self.static_dir != os.readlink('static/archive'):
Sean O'Connor1f7fd362010-04-07 16:34:52 -070036 web.debug('removing stale symlink to %s' % self.static_dir)
37 os.unlink('static/archive')
Sean O'Connor1b4b0762010-06-02 17:37:32 -070038 os.symlink(self.static_dir, 'static/archive')
Sean O'Connor1f7fd362010-04-07 16:34:52 -070039 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -070040 os.symlink(self.static_dir, 'static/archive')
Andrew de los Reyes52620802010-04-12 13:40:07 -070041 if factory_config_path is not None:
42 self.ImportFactoryConfigFile(factory_config_path, validate_factory_config)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070043
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070044 def GetSecondsSinceMidnight(self):
45 now = time.localtime()
46 return now[3] * 3600 + now[4] * 60 + now[5]
47
rtc@google.com21a5ca32009-11-04 18:23:23 +000048 def GetUpdatePayload(self, hash, size, url):
49 payload = """<?xml version="1.0" encoding="UTF-8"?>
50 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070051 <daystart elapsed_seconds="%s"/>
rtc@google.com21a5ca32009-11-04 18:23:23 +000052 <app appid="{%s}" status="ok">
53 <ping status="ok"/>
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070054 <updatecheck
55 codebase="%s"
56 hash="%s"
57 needsadmin="false"
58 size="%s"
rtc@google.com21a5ca32009-11-04 18:23:23 +000059 status="ok"/>
60 </app>
61 </gupdate>
62 """
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070063 return payload % (self.GetSecondsSinceMidnight(),
64 self.app_id, url, hash, size)
rtc@google.comded22402009-10-26 22:36:21 +000065
rtc@google.com21a5ca32009-11-04 18:23:23 +000066 def GetNoUpdatePayload(self):
67 payload = """<?xml version="1.0" encoding="UTF-8"?>
68 <gupdate xmlns="http://www.google.com/update2/response" protocol="2.0">
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070069 <daystart elapsed_seconds="%s"/>
rtc@google.com21a5ca32009-11-04 18:23:23 +000070 <app appid="{%s}" status="ok">
71 <ping status="ok"/>
72 <updatecheck status="noupdate"/>
73 </app>
74 </gupdate>
75 """
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070076 return payload % (self.GetSecondsSinceMidnight(), self.app_id)
rtc@google.comded22402009-10-26 22:36:21 +000077
Andrew de los Reyes9a528712010-06-30 10:29:43 -070078 def GetDefaultBoardID(self):
79 board_file = '%s/.default_board' % (self.scripts_dir)
80 try:
81 return open(board_file).read()
82 except IOError:
83 return 'x86-generic'
84
Sam Leffler76382042010-02-18 09:58:42 -080085 def GetLatestImagePath(self, board_id):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070086 cmd = '%s/get_latest_image.sh --board %s' % (self.scripts_dir, board_id)
rtc@google.com21a5ca32009-11-04 18:23:23 +000087 return os.popen(cmd).read().strip()
rtc@google.comded22402009-10-26 22:36:21 +000088
rtc@google.com21a5ca32009-11-04 18:23:23 +000089 def GetLatestVersion(self, latest_image_path):
90 latest_version = latest_image_path.split('/')[-1]
Ryan Cairns1b05beb2010-02-05 17:05:24 -080091
92 # Removes the portage build prefix.
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070093 latest_version = latest_version.lstrip('g-')
rtc@google.com21a5ca32009-11-04 18:23:23 +000094 return latest_version.split('-')[0]
rtc@google.comded22402009-10-26 22:36:21 +000095
rtc@google.com21a5ca32009-11-04 18:23:23 +000096 def CanUpdate(self, client_version, latest_version):
97 """
98 Returns true iff the latest_version is greater than the client_version.
99 """
Vincent Scheib904c6642010-05-18 14:57:39 -0700100 client_tokens = client_version.replace('_','').split('.')
101 latest_tokens = latest_version.replace('_','').split('.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700102 web.debug('client version %s latest version %s' \
Charlie Lee8c993082010-02-24 13:27:37 -0800103 % (client_version, latest_version))
Chris Sosaa73ec162010-05-03 20:18:02 -0700104 for i in range(4):
rtc@google.com21a5ca32009-11-04 18:23:23 +0000105 if int(latest_tokens[i]) == int(client_tokens[i]):
106 continue
107 return int(latest_tokens[i]) > int(client_tokens[i])
rtc@google.comded22402009-10-26 22:36:21 +0000108 return False
rtc@google.comded22402009-10-26 22:36:21 +0000109
Sean O'Connora7f867e2010-05-27 17:53:32 -0700110 def UnpackImage(self, image_path, image_file, stateful_file,
111 kernel_file, rootfs_file):
Chris Sosaa73ec162010-05-03 20:18:02 -0700112 unpack_command = 'cd %s && ./unpack_partitions.sh %s' % \
113 (image_path, image_file)
114 if os.system(unpack_command) == 0:
115 shutil.move(os.path.join(image_path, 'part_1'), stateful_file)
116 shutil.move(os.path.join(image_path, 'part_2'), kernel_file)
117 shutil.move(os.path.join(image_path, 'part_3'), rootfs_file)
118 os.system('cd %s && rm part_*' % image_path)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700119 return True
Chris Sosaa73ec162010-05-03 20:18:02 -0700120 return False
121
122 def UnpackZip(self, image_path, image_file):
Sean O'Connora7f867e2010-05-27 17:53:32 -0700123 image = os.path.join(image_path, image_file)
124 if os.path.exists(image):
125 return True
126 else:
Sean O'Connor1b4b0762010-06-02 17:37:32 -0700127 # -n, never clobber an existing file, in case we get invoked
128 # simultaneously by multiple request handlers. This means that
129 # we're assuming each image.zip file lives in a versioned
130 # directory (a la Buildbot).
131 return os.system('cd %s && unzip -n image.zip %s unpack_partitions.sh' %
Sean O'Connora7f867e2010-05-27 17:53:32 -0700132 (image_path, image_file)) == 0
Chris Sosaa73ec162010-05-03 20:18:02 -0700133
134 def GetImageBinPath(self, image_path):
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700135 if self.test_image:
136 image_file = 'chromiumos_test_image.bin'
137 else:
138 image_file = 'chromiumos_image.bin'
Chris Sosaa73ec162010-05-03 20:18:02 -0700139 return image_file
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700140
rtc@google.com21a5ca32009-11-04 18:23:23 +0000141 def BuildUpdateImage(self, image_path):
Chris Sosaa73ec162010-05-03 20:18:02 -0700142 stateful_file = '%s/stateful.image' % image_path
Darin Petkov55604f12010-04-12 11:09:25 -0700143 kernel_file = '%s/kernel.image' % image_path
144 rootfs_file = '%s/rootfs.image' % image_path
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700145
Chris Sosaa73ec162010-05-03 20:18:02 -0700146 image_file = self.GetImageBinPath(image_path)
147 bin_path = os.path.join(image_path, image_file)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700148
Chris Sosaa73ec162010-05-03 20:18:02 -0700149 # Get appropriate update.gz to compare timestamps.
150 if self.serve_only:
151 cached_update_file = os.path.join(image_path, 'update.gz')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700152 else:
Chris Sosaa73ec162010-05-03 20:18:02 -0700153 cached_update_file = os.path.join(self.static_dir, 'update.gz')
154
Sean O'Connora7f867e2010-05-27 17:53:32 -0700155 # If the rootfs image is newer, re-create everything.
Chris Sosaa73ec162010-05-03 20:18:02 -0700156 if (os.path.exists(cached_update_file) and
157 os.path.getmtime(cached_update_file) >= os.path.getmtime(bin_path)):
158 web.debug('Using cached update image at %s instead of %s' %
159 (cached_update_file, bin_path))
160 else:
161 # Unpack zip file if we are serving from a directory.
162 if self.serve_only and not self.UnpackZip(image_path, image_file):
163 web.debug('unzip image.zip failed.')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000164 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700165
166 if not self.UnpackImage(image_path, image_file, stateful_file,
167 kernel_file, rootfs_file):
168 web.debug('Failed to unpack image.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700169 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700170
171 update_file = os.path.join(image_path, 'update.gz')
172 web.debug('Generating update image %s' % update_file)
173 mkupdate_command = '%s/mk_memento_images.sh %s %s' % \
174 (self.scripts_dir, kernel_file, rootfs_file)
175 if os.system(mkupdate_command) != 0:
176 web.debug('Failed to create update image')
177 return False
178
Sean O'Connora7f867e2010-05-27 17:53:32 -0700179 mkstatefulupdate_command = 'gzip -f %s' % stateful_file
Chris Sosaa73ec162010-05-03 20:18:02 -0700180 if os.system(mkstatefulupdate_command) != 0:
181 web.debug('Failed to create stateful update image')
182 return False
183
184 # Add gz suffix
185 stateful_file = '%s.gz' % stateful_file
186
187 # Cleanup of image files
188 os.remove(kernel_file)
189 os.remove(rootfs_file)
190 if not self.serve_only:
191 try:
192 web.debug('Found a new image to serve, copying it to static')
193 shutil.copy(update_file, self.static_dir)
194 shutil.copy(stateful_file, self.static_dir)
195 os.remove(update_file)
196 os.remove(stateful_file)
197 except Exception, e:
198 web.debug('%s' % e)
199 return False
rtc@google.com21a5ca32009-11-04 18:23:23 +0000200 return True
rtc@google.comded22402009-10-26 22:36:21 +0000201
rtc@google.com21a5ca32009-11-04 18:23:23 +0000202 def GetSize(self, update_path):
203 return os.path.getsize(update_path)
rtc@google.comded22402009-10-26 22:36:21 +0000204
rtc@google.com21a5ca32009-11-04 18:23:23 +0000205 def GetHash(self, update_path):
Darin Petkov8ef83452010-03-23 16:52:29 -0700206 cmd = "cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';" \
207 % update_path
Andrew de los Reyes52620802010-04-12 13:40:07 -0700208 return os.popen(cmd).read().rstrip()
Darin Petkov8ef83452010-03-23 16:52:29 -0700209
Andrew de los Reyes52620802010-04-12 13:40:07 -0700210 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
211 """Imports a factory-floor server configuration file. The file should
212 be in this format:
213 config = [
214 {
215 'qual_ids': set([1, 2, 3, "x86-generic"]),
216 'factory_image': 'generic-factory.gz',
217 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
218 'release_image': 'generic-release.gz',
219 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
220 'oempartitionimg_image': 'generic-oem.gz',
221 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700222 'efipartitionimg_image': 'generic-efi.gz',
223 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700224 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800225 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800226 'firmware_image': 'generic-firmware.gz',
227 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700228 },
229 {
230 'qual_ids': set([6]),
231 'factory_image': '6-factory.gz',
232 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
233 'release_image': '6-release.gz',
234 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
235 'oempartitionimg_image': '6-oem.gz',
236 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700237 'efipartitionimg_image': '6-efi.gz',
238 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700239 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800240 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Tom Wai-Hong Tamdac3df12010-06-14 09:56:15 +0800241 'firmware_image': '6-firmware.gz',
242 'firmware_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700243 },
244 ]
245 The server will look for the files by name in the static files
246 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700247
Andrew de los Reyes52620802010-04-12 13:40:07 -0700248 If validate_checksums is True, validates checksums and exits. If
249 a checksum mismatch is found, it's printed to the screen.
250 """
251 f = open(filename, 'r')
252 output = {}
253 exec(f.read(), output)
254 self.factory_config = output['config']
255 success = True
256 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800257 for key in stanza.copy().iterkeys():
258 suffix = '_image'
259 if key.endswith(suffix):
260 kind = key[:-len(suffix)]
261 stanza[kind + '_size'] = \
262 os.path.getsize(self.static_dir + '/' + stanza[kind + '_image'])
263 if validate_checksums:
264 factory_checksum = self.GetHash(self.static_dir + '/' +
265 stanza[kind + '_image'])
266 if factory_checksum != stanza[kind + '_checksum']:
267 print 'Error: checksum mismatch for %s. Expected "%s" but file ' \
268 'has checksum "%s".' % (stanza[kind + '_image'],
269 stanza[kind + '_checksum'],
270 factory_checksum)
271 success = False
Andrew de los Reyes52620802010-04-12 13:40:07 -0700272 if validate_checksums:
273 if success is False:
274 raise Exception('Checksum mismatch in conf file.')
275 print 'Config file looks good.'
276
277 def GetFactoryImage(self, board_id, channel):
278 kind = channel.rsplit('-', 1)[0]
279 for stanza in self.factory_config:
280 if board_id not in stanza['qual_ids']:
281 continue
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700282 if kind + '_image' not in stanza:
283 break
Andrew de los Reyes52620802010-04-12 13:40:07 -0700284 return (stanza[kind + '_image'],
285 stanza[kind + '_checksum'],
286 stanza[kind + '_size'])
Nick Sanders15cd6ae2010-06-30 12:30:56 -0700287 return (None, None, None)
rtc@google.comded22402009-10-26 22:36:21 +0000288
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700289 def HandleUpdatePing(self, data, label=None):
Darin Petkovd35ee242010-07-14 16:45:31 -0700290 web.debug('handle update ping: %s' % data)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000291 update_dom = minidom.parseString(data)
292 root = update_dom.firstChild
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700293 if root.hasAttribute('updaterversion') and \
294 not root.getAttribute('updaterversion').startswith(
Andrew de los Reyesfb4444b2010-06-29 18:11:28 -0700295 self.client_prefix):
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700296 web.debug('Got update from unsupported updater:' + \
297 root.getAttribute('updaterversion'))
298 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700299 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800300 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700301 channel = query.getAttribute('track')
Charlie Lee8c993082010-02-24 13:27:37 -0800302 board_id = query.hasAttribute('board') and query.getAttribute('board') \
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700303 or self.GetDefaultBoardID()
Charlie Lee8c993082010-02-24 13:27:37 -0800304 latest_image_path = self.GetLatestImagePath(board_id)
305 latest_version = self.GetLatestVersion(latest_image_path)
Andrew de los Reyes52620802010-04-12 13:40:07 -0700306 hostname = web.ctx.host
307
308 # If this is a factory floor server, return the image here:
309 if self.factory_config:
310 (filename, checksum, size) = \
311 self.GetFactoryImage(board_id, channel)
312 if filename is None:
313 web.debug('unable to find image for board %s' % board_id)
314 return self.GetNoUpdatePayload()
315 url = 'http://%s/static/%s' % (hostname, filename)
316 web.debug('returning update payload ' + url)
317 return self.GetUpdatePayload(checksum, size, url)
318
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700319 if client_version != 'ForcedUpdate' \
Charlie Lee8c993082010-02-24 13:27:37 -0800320 and not self.CanUpdate(client_version, latest_version):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700321 web.debug('no update')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000322 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700323 if label:
324 web.debug('Client requested version %s' % label)
325 # Check that matching build exists
326 image_path = '%s/%s' % (self.static_dir, label)
327 if not os.path.exists(image_path):
328 web.debug('%s not found.' % image_path)
329 return self.GetNoUpdatePayload()
330 # Construct a response
331 ok = self.BuildUpdateImage(image_path)
332 if ok != True:
333 web.debug('Failed to build an update image')
334 return self.GetNoUpdatePayload()
335 web.debug('serving update: ')
336 hash = self.GetHash('%s/%s/update.gz' % (self.static_dir, label))
337 size = self.GetSize('%s/%s/update.gz' % (self.static_dir, label))
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700338 # In case we configured images to be hosted elsewhere
339 # (e.g. buildbot's httpd), use that. Otherwise, serve it
340 # ourselves using web.py's static resource handler.
341 if self.static_urlbase:
342 urlbase = self.static_urlbase
343 else:
344 urlbase = 'http://%s/static/archive/' % hostname
345
346 url = '%s/%s/update.gz' % (urlbase, label)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700347 return self.GetUpdatePayload(hash, size, url)
Chris Sosaa73ec162010-05-03 20:18:02 -0700348 web.debug('DONE')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700349 else:
350 web.debug('update found %s ' % latest_version)
351 ok = self.BuildUpdateImage(latest_image_path)
352 if ok != True:
353 web.debug('Failed to build an update image')
354 return self.GetNoUpdatePayload()
rtc@google.comded22402009-10-26 22:36:21 +0000355
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700356 hash = self.GetHash('%s/update.gz' % self.static_dir)
357 size = self.GetSize('%s/update.gz' % self.static_dir)
358
359 url = 'http://%s/static/update.gz' % hostname
360 return self.GetUpdatePayload(hash, size, url)