blob: c541f6a13a70c3bdefa9414fc6ab5e2e7fe1a193 [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
Chris Sosaa73ec162010-05-03 20:18:02 -070023 self.test_image = test_image
Sean O'Connor1f7fd362010-04-07 16:34:52 -070024 self.static_urlbase = urlbase
25 if serve_only:
26 # If we're serving out of an archived build dir (e.g. a
27 # buildbot), prepare this webserver's magic 'static/' dir with a
28 # link to the build archive.
29 web.debug('Autoupdate in "serve update images only" mode.')
30 if os.path.exists('static/archive'):
31 archive_symlink = os.readlink('static/archive')
32 if archive_symlink != self.static_dir:
33 web.debug('removing stale symlink to %s' % self.static_dir)
34 os.unlink('static/archive')
35 else:
36 os.symlink(self.static_dir, 'static/archive')
Darin Petkov98da5db2010-04-13 10:11:40 -070037 self.factory_config = None
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:
110 return os.system('cd %s && unzip -o image.zip %s unpack_partitions.sh' %
111 (image_path, image_file)) == 0
Chris Sosaa73ec162010-05-03 20:18:02 -0700112
113 def GetImageBinPath(self, image_path):
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700114 if self.test_image:
115 image_file = 'chromiumos_test_image.bin'
116 else:
117 image_file = 'chromiumos_image.bin'
Chris Sosaa73ec162010-05-03 20:18:02 -0700118 return image_file
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700119
rtc@google.com21a5ca32009-11-04 18:23:23 +0000120 def BuildUpdateImage(self, image_path):
Chris Sosaa73ec162010-05-03 20:18:02 -0700121 stateful_file = '%s/stateful.image' % image_path
Darin Petkov55604f12010-04-12 11:09:25 -0700122 kernel_file = '%s/kernel.image' % image_path
123 rootfs_file = '%s/rootfs.image' % image_path
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700124
Chris Sosaa73ec162010-05-03 20:18:02 -0700125 image_file = self.GetImageBinPath(image_path)
126 bin_path = os.path.join(image_path, image_file)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700127
Chris Sosaa73ec162010-05-03 20:18:02 -0700128 # Get appropriate update.gz to compare timestamps.
129 if self.serve_only:
130 cached_update_file = os.path.join(image_path, 'update.gz')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700131 else:
Chris Sosaa73ec162010-05-03 20:18:02 -0700132 cached_update_file = os.path.join(self.static_dir, 'update.gz')
133
Sean O'Connora7f867e2010-05-27 17:53:32 -0700134 # If the rootfs image is newer, re-create everything.
Chris Sosaa73ec162010-05-03 20:18:02 -0700135 if (os.path.exists(cached_update_file) and
136 os.path.getmtime(cached_update_file) >= os.path.getmtime(bin_path)):
137 web.debug('Using cached update image at %s instead of %s' %
138 (cached_update_file, bin_path))
139 else:
140 # Unpack zip file if we are serving from a directory.
141 if self.serve_only and not self.UnpackZip(image_path, image_file):
142 web.debug('unzip image.zip failed.')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000143 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700144
145 if not self.UnpackImage(image_path, image_file, stateful_file,
146 kernel_file, rootfs_file):
147 web.debug('Failed to unpack image.')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700148 return False
Chris Sosaa73ec162010-05-03 20:18:02 -0700149
150 update_file = os.path.join(image_path, 'update.gz')
151 web.debug('Generating update image %s' % update_file)
152 mkupdate_command = '%s/mk_memento_images.sh %s %s' % \
153 (self.scripts_dir, kernel_file, rootfs_file)
154 if os.system(mkupdate_command) != 0:
155 web.debug('Failed to create update image')
156 return False
157
Sean O'Connora7f867e2010-05-27 17:53:32 -0700158 mkstatefulupdate_command = 'gzip -f %s' % stateful_file
Chris Sosaa73ec162010-05-03 20:18:02 -0700159 if os.system(mkstatefulupdate_command) != 0:
160 web.debug('Failed to create stateful update image')
161 return False
162
163 # Add gz suffix
164 stateful_file = '%s.gz' % stateful_file
165
166 # Cleanup of image files
167 os.remove(kernel_file)
168 os.remove(rootfs_file)
169 if not self.serve_only:
170 try:
171 web.debug('Found a new image to serve, copying it to static')
172 shutil.copy(update_file, self.static_dir)
173 shutil.copy(stateful_file, self.static_dir)
174 os.remove(update_file)
175 os.remove(stateful_file)
176 except Exception, e:
177 web.debug('%s' % e)
178 return False
rtc@google.com21a5ca32009-11-04 18:23:23 +0000179 return True
rtc@google.comded22402009-10-26 22:36:21 +0000180
rtc@google.com21a5ca32009-11-04 18:23:23 +0000181 def GetSize(self, update_path):
182 return os.path.getsize(update_path)
rtc@google.comded22402009-10-26 22:36:21 +0000183
rtc@google.com21a5ca32009-11-04 18:23:23 +0000184 def GetHash(self, update_path):
Darin Petkov8ef83452010-03-23 16:52:29 -0700185 cmd = "cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';" \
186 % update_path
Andrew de los Reyes52620802010-04-12 13:40:07 -0700187 return os.popen(cmd).read().rstrip()
Darin Petkov8ef83452010-03-23 16:52:29 -0700188
Andrew de los Reyes52620802010-04-12 13:40:07 -0700189 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
190 """Imports a factory-floor server configuration file. The file should
191 be in this format:
192 config = [
193 {
194 'qual_ids': set([1, 2, 3, "x86-generic"]),
195 'factory_image': 'generic-factory.gz',
196 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
197 'release_image': 'generic-release.gz',
198 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
199 'oempartitionimg_image': 'generic-oem.gz',
200 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700201 'efipartitionimg_image': 'generic-efi.gz',
202 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700203 'stateimg_image': 'generic-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800204 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
205 'systemrom_image': 'generic-systemrom.gz',
206 'systemrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
207 'ecrom_image': 'generic-ecrom.gz',
208 'ecrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700209 },
210 {
211 'qual_ids': set([6]),
212 'factory_image': '6-factory.gz',
213 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
214 'release_image': '6-release.gz',
215 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
216 'oempartitionimg_image': '6-oem.gz',
217 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Nick Sanderse1eea922010-05-19 22:17:08 -0700218 'efipartitionimg_image': '6-efi.gz',
219 'efipartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700220 'stateimg_image': '6-state.gz',
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800221 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
222 'systemrom_image': '6-systemrom.gz',
223 'systemrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
224 'ecrom_image': '6-ecrom.gz',
225 'ecrom_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
Andrew de los Reyes52620802010-04-12 13:40:07 -0700226 },
227 ]
228 The server will look for the files by name in the static files
229 directory.
Chris Sosaa73ec162010-05-03 20:18:02 -0700230
Andrew de los Reyes52620802010-04-12 13:40:07 -0700231 If validate_checksums is True, validates checksums and exits. If
232 a checksum mismatch is found, it's printed to the screen.
233 """
234 f = open(filename, 'r')
235 output = {}
236 exec(f.read(), output)
237 self.factory_config = output['config']
238 success = True
239 for stanza in self.factory_config:
Tom Wai-Hong Tam65fc6072010-05-20 11:44:26 +0800240 for key in stanza.copy().iterkeys():
241 suffix = '_image'
242 if key.endswith(suffix):
243 kind = key[:-len(suffix)]
244 stanza[kind + '_size'] = \
245 os.path.getsize(self.static_dir + '/' + stanza[kind + '_image'])
246 if validate_checksums:
247 factory_checksum = self.GetHash(self.static_dir + '/' +
248 stanza[kind + '_image'])
249 if factory_checksum != stanza[kind + '_checksum']:
250 print 'Error: checksum mismatch for %s. Expected "%s" but file ' \
251 'has checksum "%s".' % (stanza[kind + '_image'],
252 stanza[kind + '_checksum'],
253 factory_checksum)
254 success = False
Andrew de los Reyes52620802010-04-12 13:40:07 -0700255 if validate_checksums:
256 if success is False:
257 raise Exception('Checksum mismatch in conf file.')
258 print 'Config file looks good.'
259
260 def GetFactoryImage(self, board_id, channel):
261 kind = channel.rsplit('-', 1)[0]
262 for stanza in self.factory_config:
263 if board_id not in stanza['qual_ids']:
264 continue
265 return (stanza[kind + '_image'],
266 stanza[kind + '_checksum'],
267 stanza[kind + '_size'])
rtc@google.comded22402009-10-26 22:36:21 +0000268
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700269 def HandleUpdatePing(self, data, label=None):
Andrew de los Reyes52620802010-04-12 13:40:07 -0700270 web.debug('handle update ping')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000271 update_dom = minidom.parseString(data)
272 root = update_dom.firstChild
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700273 if root.hasAttribute('updaterversion') and \
274 not root.getAttribute('updaterversion').startswith(
275 'MementoSoftwareUpdate'):
276 web.debug('Got update from unsupported updater:' + \
277 root.getAttribute('updaterversion'))
278 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700279 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800280 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700281 channel = query.getAttribute('track')
Charlie Lee8c993082010-02-24 13:27:37 -0800282 board_id = query.hasAttribute('board') and query.getAttribute('board') \
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700283 or 'x86-generic'
Charlie Lee8c993082010-02-24 13:27:37 -0800284 latest_image_path = self.GetLatestImagePath(board_id)
285 latest_version = self.GetLatestVersion(latest_image_path)
Andrew de los Reyes52620802010-04-12 13:40:07 -0700286 hostname = web.ctx.host
287
288 # If this is a factory floor server, return the image here:
289 if self.factory_config:
290 (filename, checksum, size) = \
291 self.GetFactoryImage(board_id, channel)
292 if filename is None:
293 web.debug('unable to find image for board %s' % board_id)
294 return self.GetNoUpdatePayload()
295 url = 'http://%s/static/%s' % (hostname, filename)
296 web.debug('returning update payload ' + url)
297 return self.GetUpdatePayload(checksum, size, url)
298
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700299 if client_version != 'ForcedUpdate' \
Charlie Lee8c993082010-02-24 13:27:37 -0800300 and not self.CanUpdate(client_version, latest_version):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700301 web.debug('no update')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000302 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700303 if label:
304 web.debug('Client requested version %s' % label)
305 # Check that matching build exists
306 image_path = '%s/%s' % (self.static_dir, label)
307 if not os.path.exists(image_path):
308 web.debug('%s not found.' % image_path)
309 return self.GetNoUpdatePayload()
310 # Construct a response
311 ok = self.BuildUpdateImage(image_path)
312 if ok != True:
313 web.debug('Failed to build an update image')
314 return self.GetNoUpdatePayload()
315 web.debug('serving update: ')
316 hash = self.GetHash('%s/%s/update.gz' % (self.static_dir, label))
317 size = self.GetSize('%s/%s/update.gz' % (self.static_dir, label))
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700318 # In case we configured images to be hosted elsewhere
319 # (e.g. buildbot's httpd), use that. Otherwise, serve it
320 # ourselves using web.py's static resource handler.
321 if self.static_urlbase:
322 urlbase = self.static_urlbase
323 else:
324 urlbase = 'http://%s/static/archive/' % hostname
325
326 url = '%s/%s/update.gz' % (urlbase, label)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700327 return self.GetUpdatePayload(hash, size, url)
Chris Sosaa73ec162010-05-03 20:18:02 -0700328 web.debug('DONE')
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700329 else:
330 web.debug('update found %s ' % latest_version)
331 ok = self.BuildUpdateImage(latest_image_path)
332 if ok != True:
333 web.debug('Failed to build an update image')
334 return self.GetNoUpdatePayload()
rtc@google.comded22402009-10-26 22:36:21 +0000335
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700336 hash = self.GetHash('%s/update.gz' % self.static_dir)
337 size = self.GetSize('%s/update.gz' % self.static_dir)
338
339 url = 'http://%s/static/update.gz' % hostname
340 return self.GetUpdatePayload(hash, size, url)