blob: ac66d517b7ba3f0b8de0209271c9c85433af536f [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
23 self.test_image=test_image
24 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 """
83 client_tokens = client_version.split('.')
84 latest_tokens = latest_version.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))
rtc@google.com21a5ca32009-11-04 18:23:23 +000087 for i in range(0,4):
88 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
Darin Petkov55604f12010-04-12 11:09:25 -070093 def UnpackImage(self, image_path, kernel_file, rootfs_file):
94 if os.path.exists(rootfs_file) and os.path.exists(kernel_file):
Darin Petkovcbcd2bd2010-04-06 10:14:08 -070095 return True
96 if self.test_image:
97 image_file = 'chromiumos_test_image.bin'
98 else:
99 image_file = 'chromiumos_image.bin'
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700100 if self.serve_only:
Darin Petkov55604f12010-04-12 11:09:25 -0700101 os.system('cd %s && unzip -o image.zip' %
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700102 (image_path, image_file))
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700103 os.system('rm -f %s/part_*' % image_path)
104 os.system('cd %s && ./unpack_partitions.sh %s' % (image_path, image_file))
Darin Petkov55604f12010-04-12 11:09:25 -0700105 shutil.move(os.path.join(image_path, 'part_2'), kernel_file)
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700106 shutil.move(os.path.join(image_path, 'part_3'), rootfs_file)
107 os.system('rm -f %s/part_*' % image_path)
108 return True
109
rtc@google.com21a5ca32009-11-04 18:23:23 +0000110 def BuildUpdateImage(self, image_path):
Darin Petkov55604f12010-04-12 11:09:25 -0700111 kernel_file = '%s/kernel.image' % image_path
112 rootfs_file = '%s/rootfs.image' % image_path
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700113
Darin Petkov55604f12010-04-12 11:09:25 -0700114 if not self.UnpackImage(image_path, kernel_file, rootfs_file):
115 web.debug('failed to unpack image.')
Darin Petkovcbcd2bd2010-04-06 10:14:08 -0700116 return False
117
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700118 update_file = '%s/update.gz' % image_path
119 if (os.path.exists(update_file) and
Darin Petkov55604f12010-04-12 11:09:25 -0700120 os.path.getmtime(update_file) >= os.path.getmtime(rootfs_file)):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700121 web.debug('Found cached update image %s/update.gz' % image_path)
122 else:
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700123 web.debug('generating update image %s' % update_file)
Darin Petkov55604f12010-04-12 11:09:25 -0700124 mkupdate = ('%s/mk_memento_images.sh %s %s' %
125 (self.scripts_dir, kernel_file, rootfs_file))
rtc@google.com21a5ca32009-11-04 18:23:23 +0000126 web.debug(mkupdate)
127 err = os.system(mkupdate)
128 if err != 0:
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700129 web.debug('failed to create update image')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000130 return False
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700131 if not self.serve_only:
132 web.debug('Found an image, copying it to static')
133 try:
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700134 shutil.copy(update_file, self.static_dir)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700135 except Exception, e:
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700136 web.debug('Unable to copy %s to %s' % (update_file, self.static_dir))
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700137 return False
rtc@google.com21a5ca32009-11-04 18:23:23 +0000138 return True
rtc@google.comded22402009-10-26 22:36:21 +0000139
rtc@google.com21a5ca32009-11-04 18:23:23 +0000140 def GetSize(self, update_path):
141 return os.path.getsize(update_path)
rtc@google.comded22402009-10-26 22:36:21 +0000142
rtc@google.com21a5ca32009-11-04 18:23:23 +0000143 def GetHash(self, update_path):
Darin Petkov8ef83452010-03-23 16:52:29 -0700144 cmd = "cat %s | openssl sha1 -binary | openssl base64 | tr \'\\n\' \' \';" \
145 % update_path
Andrew de los Reyes52620802010-04-12 13:40:07 -0700146 return os.popen(cmd).read().rstrip()
Darin Petkov8ef83452010-03-23 16:52:29 -0700147
Andrew de los Reyes52620802010-04-12 13:40:07 -0700148 def ImportFactoryConfigFile(self, filename, validate_checksums=False):
149 """Imports a factory-floor server configuration file. The file should
150 be in this format:
151 config = [
152 {
153 'qual_ids': set([1, 2, 3, "x86-generic"]),
154 'factory_image': 'generic-factory.gz',
155 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
156 'release_image': 'generic-release.gz',
157 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
158 'oempartitionimg_image': 'generic-oem.gz',
159 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
160 'stateimg_image': 'generic-state.gz',
161 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM='
162 },
163 {
164 'qual_ids': set([6]),
165 'factory_image': '6-factory.gz',
166 'factory_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
167 'release_image': '6-release.gz',
168 'release_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
169 'oempartitionimg_image': '6-oem.gz',
170 'oempartitionimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM=',
171 'stateimg_image': '6-state.gz',
172 'stateimg_checksum': 'AtiI8B64agHVN+yeBAyiNMX3+HM='
173 },
174 ]
175 The server will look for the files by name in the static files
176 directory.
177
178 If validate_checksums is True, validates checksums and exits. If
179 a checksum mismatch is found, it's printed to the screen.
180 """
181 f = open(filename, 'r')
182 output = {}
183 exec(f.read(), output)
184 self.factory_config = output['config']
185 success = True
186 for stanza in self.factory_config:
187 for kind in ('factory', 'oempartitionimg', 'release', 'stateimg'):
188 stanza[kind + '_size'] = \
189 os.path.getsize(self.static_dir + '/' + stanza[kind + '_image'])
190 if validate_checksums:
191 factory_checksum = self.GetHash(self.static_dir + '/' +
192 stanza[kind + '_image'])
193 if factory_checksum != stanza[kind + '_checksum']:
194 print 'Error: checksum mismatch for %s. Expected "%s" but file ' \
195 'has checksum "%s".' % (stanza[kind + '_image'],
196 stanza[kind + '_checksum'],
197 factory_checksum)
198 success = False
199 if validate_checksums:
200 if success is False:
201 raise Exception('Checksum mismatch in conf file.')
202 print 'Config file looks good.'
203
204 def GetFactoryImage(self, board_id, channel):
205 kind = channel.rsplit('-', 1)[0]
206 for stanza in self.factory_config:
207 if board_id not in stanza['qual_ids']:
208 continue
209 return (stanza[kind + '_image'],
210 stanza[kind + '_checksum'],
211 stanza[kind + '_size'])
rtc@google.comded22402009-10-26 22:36:21 +0000212
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700213 def HandleUpdatePing(self, data, label=None):
Andrew de los Reyes52620802010-04-12 13:40:07 -0700214 web.debug('handle update ping')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000215 update_dom = minidom.parseString(data)
216 root = update_dom.firstChild
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700217 query = root.getElementsByTagName('o:app')[0]
Charlie Lee8c993082010-02-24 13:27:37 -0800218 client_version = query.getAttribute('version')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700219 channel = query.getAttribute('track')
Charlie Lee8c993082010-02-24 13:27:37 -0800220 board_id = query.hasAttribute('board') and query.getAttribute('board') \
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700221 or 'x86-generic'
Charlie Lee8c993082010-02-24 13:27:37 -0800222 latest_image_path = self.GetLatestImagePath(board_id)
223 latest_version = self.GetLatestVersion(latest_image_path)
Andrew de los Reyes52620802010-04-12 13:40:07 -0700224 hostname = web.ctx.host
225
226 # If this is a factory floor server, return the image here:
227 if self.factory_config:
228 (filename, checksum, size) = \
229 self.GetFactoryImage(board_id, channel)
230 if filename is None:
231 web.debug('unable to find image for board %s' % board_id)
232 return self.GetNoUpdatePayload()
233 url = 'http://%s/static/%s' % (hostname, filename)
234 web.debug('returning update payload ' + url)
235 return self.GetUpdatePayload(checksum, size, url)
236
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700237 if client_version != 'ForcedUpdate' \
Charlie Lee8c993082010-02-24 13:27:37 -0800238 and not self.CanUpdate(client_version, latest_version):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700239 web.debug('no update')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000240 return self.GetNoUpdatePayload()
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700241 if label:
242 web.debug('Client requested version %s' % label)
243 # Check that matching build exists
244 image_path = '%s/%s' % (self.static_dir, label)
245 if not os.path.exists(image_path):
246 web.debug('%s not found.' % image_path)
247 return self.GetNoUpdatePayload()
248 # Construct a response
249 ok = self.BuildUpdateImage(image_path)
250 if ok != True:
251 web.debug('Failed to build an update image')
252 return self.GetNoUpdatePayload()
253 web.debug('serving update: ')
254 hash = self.GetHash('%s/%s/update.gz' % (self.static_dir, label))
255 size = self.GetSize('%s/%s/update.gz' % (self.static_dir, label))
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700256 # In case we configured images to be hosted elsewhere
257 # (e.g. buildbot's httpd), use that. Otherwise, serve it
258 # ourselves using web.py's static resource handler.
259 if self.static_urlbase:
260 urlbase = self.static_urlbase
261 else:
262 urlbase = 'http://%s/static/archive/' % hostname
263
264 url = '%s/%s/update.gz' % (urlbase, label)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700265 return self.GetUpdatePayload(hash, size, url)
266 web.debug( 'DONE')
267 else:
268 web.debug('update found %s ' % latest_version)
269 ok = self.BuildUpdateImage(latest_image_path)
270 if ok != True:
271 web.debug('Failed to build an update image')
272 return self.GetNoUpdatePayload()
rtc@google.comded22402009-10-26 22:36:21 +0000273
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700274 hash = self.GetHash('%s/update.gz' % self.static_dir)
275 size = self.GetSize('%s/update.gz' % self.static_dir)
276
277 url = 'http://%s/static/update.gz' % hostname
278 return self.GetUpdatePayload(hash, size, url)