blob: 4185407c2b016844626ed4a06c20bafa04cf3f82 [file] [log] [blame]
Chris Sosa7c931362010-10-12 02:49:011#!/usr/bin/python
2
Chris Sosa0356d3b2010-09-16 22:46:223# Copyright (c) 2009-2010 The Chromium OS Authors. All rights reserved.
[email protected]ded22402009-10-26 22:36:214# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Chris Sosa7c931362010-10-12 02:49:017"""A CherryPy-based webserver to host images and build packages."""
8
9import cherrypy
Sean O'Connor14b6a0a2010-03-21 06:23:4810import optparse
[email protected]ded22402009-10-26 22:36:2111import os
Scott Zawalski4647ce62012-01-03 22:17:2812import re
[email protected]4dc25812009-10-27 23:46:2613import sys
[email protected]ded22402009-10-26 22:36:2114
Chris Sosa0356d3b2010-09-16 22:46:2215import autoupdate
Chris Sosa0356d3b2010-09-16 22:46:2216
Frank Farzan40160872011-12-13 02:39:1817
Chris Sosa417e55d2011-01-26 00:40:4818CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-17 01:36:1419
Chris Sosa0356d3b2010-09-16 22:46:2220# Sets up global to share between classes.
[email protected]21a5ca32009-11-04 18:23:2321global updater
22updater = None
[email protected]ded22402009-10-26 22:36:2123
Frank Farzan40160872011-12-13 02:39:1824
Scott Zawalski4647ce62012-01-03 22:17:2825def _LeadingWhiteSpaceCount(string):
26 """Count the amount of leading whitespace in a string.
27
28 Args:
29 string: The string to count leading whitespace in.
30 Returns:
31 number of white space chars before characters start.
32 """
33 matched = re.match('^\s+', string)
34 if matched:
35 return len(matched.group())
36
37 return 0
38
39
40def _PrintDocStringAsHTML(func):
41 """Make a functions docstring somewhat HTML style.
42
43 Args:
44 func: The function to return the docstring from.
45 Returns:
46 A string that is somewhat formated for a web browser.
47 """
48 # TODO(scottz): Make this parse Args/Returns in a prettier way.
49 # Arguments could be bolded and indented etc.
50 html_doc = []
51 for line in func.__doc__.splitlines():
52 leading_space = _LeadingWhiteSpaceCount(line)
53 if leading_space > 0:
54 line = ' '*leading_space + line
55
56 html_doc.append('<BR>%s' % line)
57
58 return '\n'.join(html_doc)
59
60
Chris Sosa7c931362010-10-12 02:49:0161def _GetConfig(options):
62 """Returns the configuration for the devserver."""
63 base_config = { 'global':
64 { 'server.log_request_headers': True,
65 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 16:01:0866 'server.socket_host': '::',
Chris Sosa7c931362010-10-12 02:49:0167 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:5468 'server.socket_timeout': 6000,
69 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 02:59:1770 'tools.staticdir.root':
71 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-12 02:49:0172 },
Dale Curtisc9aaf3a2011-08-09 22:47:4073 '/api':
74 {
75 # Gets rid of cherrypy parsing post file for args.
76 'request.process_request_body': False,
77 },
Chris Sosaa1ef0102010-10-21 23:22:3578 '/build':
79 {
80 'response.timeout': 100000,
81 },
Chris Sosa7c931362010-10-12 02:49:0182 '/update':
83 {
84 # Gets rid of cherrypy parsing post file for args.
85 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:5186 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:0187 },
88 # Sets up the static dir for file hosting.
89 '/static':
90 { 'tools.staticdir.dir': 'static',
91 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:5192 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:0193 },
94 }
Chris Sosa417e55d2011-01-26 00:40:4895 if options.production:
96 base_config['global']['server.environment'] = 'production'
97
Chris Sosa7c931362010-10-12 02:49:0198 return base_config
[email protected]64244662009-11-12 00:52:0899
Darin Petkove17164a2010-08-11 20:24:41100
Zdenek Behan608f46c2011-02-18 23:47:16101def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 22:46:22102 """Sets up symlink to image_dir for serving purposes."""
103 assert os.path.exists(image_dir), '%s must exist.' % image_dir
104 # If we're serving out of an archived build dir (e.g. a
105 # buildbot), prepare this webserver's magic 'static/' dir with a
106 # link to the build archive.
Chris Sosa7c931362010-10-12 02:49:01107 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
108 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:16109 if os.path.lexists('%s/archive' % static_dir):
110 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-12 02:49:01111 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:16112 os.unlink('%s/archive' % static_dir)
113 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 22:46:22114 else:
Zdenek Behan608f46c2011-02-18 23:47:16115 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-12 02:49:01116 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
117 'DEVSERVER')
118
119
Dale Curtisc9aaf3a2011-08-09 22:47:40120class ApiRoot(object):
121 """RESTful API for Dev Server information."""
122 exposed = True
123
124 @cherrypy.expose
125 def hostinfo(self, ip):
126 """Returns a JSON dictionary containing information about the given ip.
127
128 Not all information may be known at the time the request is made. The
129 possible keys are:
130
131 last_event_type: int
132 Last update event type received.
133
134 last_event_status: int
135 Last update event status received.
136
137 last_known_version: string
138 Last known version recieved for update ping.
139
140 forced_update_label: string
141 Update label to force next update ping to use. Set by setnextupdate.
142
143 See the OmahaEvent class in update_engine/omaha_request_action.h for status
144 code definitions. If the ip does not exist an empty string is returned."""
145 return updater.HandleHostInfoPing(ip)
146
147 @cherrypy.expose
Gilad Arnold286a0062012-01-12 21:47:02148 def hostlog(self, ip):
149 """Returns a JSON object containing a log of events pertaining to a
150 particular host, or all hosts. Log events contain a timestamp and any
151 subset of the attributes listed for the hostinfo method."""
152 return updater.HandleHostLogPing(ip)
153
154 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 22:47:40155 def setnextupdate(self, ip):
156 """Allows the response to the next update ping from a host to be set.
157
158 Takes the IP of the host and an update label as normally provided to the
159 /update command."""
160 body_length = int(cherrypy.request.headers['Content-Length'])
161 label = cherrypy.request.rfile.read(body_length)
162
163 if label:
164 label = label.strip()
165 if label:
166 return updater.HandleSetUpdatePing(ip, label)
167 raise cherrypy.HTTPError(400, 'No label provided.')
168
169
David Rochberg7c79a812011-01-19 19:24:45170class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:01171 """The Root Class for the Dev Server.
172
173 CherryPy works as follows:
174 For each method in this class, cherrpy interprets root/path
175 as a call to an instance of DevServerRoot->method_name. For example,
176 a call to http://myhost/build will call build. CherryPy automatically
177 parses http args and places them as keyword arguments in each method.
178 For paths http://myhost/update/dir1/dir2, you can use *args so that
179 cherrypy uses the update method and puts the extra paths in args.
180 """
Dale Curtisc9aaf3a2011-08-09 22:47:40181 api = ApiRoot()
Chris Sosa7c931362010-10-12 02:49:01182
David Rochberg7c79a812011-01-19 19:24:45183 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 22:20:41184 self._builder = None
Frank Farzan40160872011-12-13 02:39:18185 self._downloader = None
David Rochberg7c79a812011-01-19 19:24:45186
Dale Curtisc9aaf3a2011-08-09 22:47:40187 @cherrypy.expose
David Rochberg7c79a812011-01-19 19:24:45188 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:01189 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 22:20:41190 import builder
191 if self._builder is None:
192 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 19:24:45193 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:01194
Dale Curtisc9aaf3a2011-08-09 22:47:40195 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 19:48:17196 def download(self, **kwargs):
197 """Downloads and archives full/delta payloads from Google Storage.
198
199 Args:
200 archive_url: Google Storage URL for the build.
201
202 Example URL:
203 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
204 'x86-generic/R17-1208.0.0-a1-b338'
205 """
Frank Farzan40160872011-12-13 02:39:18206 import downloader
Frank Farzan40160872011-12-13 02:39:18207 if self._downloader is None:
208 self._downloader = downloader.Downloader(updater.static_dir)
Frank Farzanbcb571e2012-01-03 19:48:17209 return self._downloader.Download(kwargs['archive_url'])
Frank Farzan40160872011-12-13 02:39:18210
211 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 20:12:42212 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 22:17:28213 """Return a control file or a list of all known control files.
214
215 Example URL:
216 To List all control files:
Scott Zawalski84a39c92012-01-13 20:12:42217 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 22:17:28218 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 20:12:42219 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 22:17:28220
221 Args:
Scott Zawalski84a39c92012-01-13 20:12:42222 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 22:17:28223 control_path: If you want the contents of a control file set this
224 to the path. E.g. client/site_tests/sleeptest/control
225 Optional, if not provided return a list of control files is returned.
226 Returns:
227 Contents of a control file if control_path is provided.
228 A list of control files if no control_path is provided.
229 """
Frank Farzan40160872011-12-13 02:39:18230 import devserver_util
Scott Zawalski4647ce62012-01-03 22:17:28231 if not params:
232 return _PrintDocStringAsHTML(self.controlfiles)
233
Scott Zawalski84a39c92012-01-13 20:12:42234 if 'build' not in params:
235 errmsg = 'Error: build is required!'
Scott Zawalski4647ce62012-01-03 22:17:28236 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 20:12:42237 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 22:17:28238
239 if 'control_path' not in params:
240 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 20:12:42241 params['build'])
Scott Zawalski4647ce62012-01-03 22:17:28242 else:
Scott Zawalski84a39c92012-01-13 20:12:42243 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 22:17:28244 params['control_path'])
Frank Farzan40160872011-12-13 02:39:18245
246 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01247 def index(self):
248 return 'Welcome to the Dev Server!'
249
Dale Curtisc9aaf3a2011-08-09 22:47:40250 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01251 def update(self, *args):
252 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 21:47:02253 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-12 02:49:01254 data = cherrypy.request.rfile.read(body_length)
255 return updater.HandleUpdatePing(data, label)
256
Chris Sosa0356d3b2010-09-16 22:46:22257
Sean O'Connor14b6a0a2010-03-21 06:23:48258if __name__ == '__main__':
259 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 21:47:02260 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 20:50:40261 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-21 06:23:48262 help='serve archived builds only.')
Chris Sosae67b78f12010-11-05 00:33:16263 parser.add_option('--board', dest='board',
264 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-18 02:13:37265 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-17 01:36:14266 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 21:15:23267 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
268 help='No longer used. It is still here so we don\'t break '
269 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 17:36:32270 parser.add_option('--critical_update', dest='critical_update',
271 action='store_true', default=False,
272 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 01:06:01273 parser.add_option('--data_dir', dest='data_dir',
274 help='Writable directory where static lives',
275 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-18 02:13:37276 parser.add_option('--exit', action='store_true', default=False,
277 help='Don\'t start the server (still pregenerate or clear'
278 'cache).')
Andrew de los Reyes52620802010-04-12 20:40:07279 parser.add_option('--factory_config', dest='factory_config',
280 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-29 06:42:37281 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
282 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 22:46:22283 parser.add_option('--image', dest='image',
284 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 23:05:27285 parser.add_option('-p', '--pregenerate_update', action='store_true',
286 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-18 02:13:37287 parser.add_option('--payload', dest='payload',
288 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-12 02:49:01289 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 21:47:02290 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-15 00:33:22291 parser.add_option('--private_key', default=None,
292 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-26 00:40:48293 parser.add_option('--production', action='store_true', default=False,
294 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-07 00:20:30295 parser.add_option('--proxy_port', default=None,
296 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-27 04:39:48297 parser.add_option('--src_image', default='',
298 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 23:34:52299 parser.add_option('-t', action='store_true', dest='test_image')
300 parser.add_option('-u', '--urlbase', dest='urlbase',
301 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 20:40:07302 parser.add_option('--validate_factory_config', action="store_true",
303 dest='validate_factory_config',
304 help='Validate factory config file, then exit.')
Gilad Arnold286a0062012-01-12 21:47:02305 parser.add_option('-l', '--logging', action="store_true", default=False,
306 help='Enable logging and reporting of update processes.')
Chris Sosa7c931362010-10-12 02:49:01307 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:23308
Chris Sosa7c931362010-10-12 02:49:01309 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
310 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:22311 serve_only = False
312
Zdenek Behan608f46c2011-02-18 23:47:16313 static_dir = os.path.realpath('%s/static' % options.data_dir)
314 os.system('mkdir -p %s' % static_dir)
315
Sean O'Connor14b6a0a2010-03-21 06:23:48316 if options.archive_dir:
Zdenek Behan608f46c2011-02-18 23:47:16317 # TODO(zbehan) Remove legacy support:
318 # archive_dir is the directory where static/archive will point.
319 # If this is an absolute path, all is fine. If someone calls this
320 # using a relative path, that is relative to src/platform/dev/.
321 # That use case is unmaintainable, but since applications use it
322 # with =./static, instead of a boolean flag, we'll make this relative
323 # to devserver_dir to keep these unbroken. For now.
324 archive_dir = options.archive_dir
325 if not os.path.isabs(archive_dir):
326 archive_dir = os.path.realpath(os.path.join(devserver_dir,archive_dir))
327 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 21:35:49328 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 22:46:22329 serve_only = True
Chris Sosa0356d3b2010-09-16 22:46:22330
Don Garrettf90edf02010-11-17 01:36:14331 cache_dir = os.path.join(static_dir, 'cache')
332 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
333
Don Garrettf90edf02010-11-17 01:36:14334 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 20:12:17335 if options.clear_cache:
336 # Clear the cache and exit on error.
337 if os.system('rm -rf %s/*' % cache_dir) != 0:
338 cherrypy.log('Failed to clear the cache with %s' % cmd,
339 'DEVSERVER')
340 sys.exit(1)
341
342 else:
343 # Clear all but the last N cached updates
344 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
345 (cache_dir, CACHED_ENTRIES))
346 if os.system(cmd) != 0:
347 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
348 'DEVSERVER')
349 sys.exit(1)
350 else:
351 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14352
Greg Spencerc8b59b22011-03-15 21:15:23353 if options.client_prefix_deprecated:
354 cherrypy.log('The --client_prefix argument is DEPRECATED, '
355 'and is no longer needed.', 'DEVSERVER')
356
Zdenek Behan5d21a2a2011-02-12 01:06:01357 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-12 02:49:01358 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
359 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
[email protected]21a5ca32009-11-04 18:23:23360
Andrew de los Reyes52620802010-04-12 20:40:07361 updater = autoupdate.Autoupdate(
362 root_dir=root_dir,
363 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 22:46:22364 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 20:40:07365 urlbase=options.urlbase,
366 test_image=options.test_image,
367 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 23:54:41368 forced_image=options.image,
Don Garrett0c880e22010-11-18 02:13:37369 forced_payload=options.payload,
Chris Sosa62f720b2010-10-27 04:39:48370 port=options.port,
Don Garrett0ad09372010-12-07 00:20:30371 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:37372 src_image=options.src_image,
Chris Sosae67b78f12010-11-05 00:33:16373 vm=options.vm,
Chris Sosa08d55a22011-01-20 00:08:02374 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:22375 copy_to_static_root=not options.exit,
376 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 17:36:32377 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-15 00:33:22378 )
Chris Sosa7c931362010-10-12 02:49:01379
380 # Sanity-check for use of validate_factory_config.
381 if not options.factory_config and options.validate_factory_config:
382 parser.error('You need a factory_config to validate.')
[email protected]64244662009-11-12 00:52:08383
Chris Sosa0356d3b2010-09-16 22:46:22384 if options.factory_config:
Chris Sosa7c931362010-10-12 02:49:01385 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 22:46:22386 options.validate_factory_config)
Chris Sosa7c931362010-10-12 02:49:01387 # We don't run the dev server with this option.
388 if options.validate_factory_config:
389 sys.exit(0)
Chris Sosa2c048f12010-10-27 23:05:27390 elif options.pregenerate_update:
Chris Sosae67b78f12010-11-05 00:33:16391 if not updater.PreGenerateUpdate():
392 sys.exit(1)
Chris Sosa0356d3b2010-09-16 22:46:22393
Don Garrett0c880e22010-11-18 02:13:37394 # If the command line requested after setup, it's time to do it.
395 if not options.exit:
396 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))