blob: b602145085b4dd229f154c1775e3719a77707687 [file] [log] [blame]
Chris Sosa7c931362010-10-12 02:49:011#!/usr/bin/python
2
Chris Sosa781ba6d2012-04-11 19:44:433# Copyright (c) 2009-2012 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
Gilad Arnold55a2a372012-10-02 16:46:329import json
Chris Sosa781ba6d2012-04-11 19:44:4310import logging
Sean O'Connor14b6a0a2010-03-21 06:23:4811import optparse
[email protected]ded22402009-10-26 22:36:2112import os
Scott Zawalski4647ce62012-01-03 22:17:2813import re
[email protected]4dc25812009-10-27 23:46:2614import sys
Chris Masone816e38c2012-05-02 19:22:3615import subprocess
16import tempfile
Gilad Arnold0b8c3f32012-09-19 21:35:4417import threading
Gilad Arnoldd5ebaaa2012-10-02 18:52:3818import types
[email protected]ded22402009-10-26 22:36:2119
Gilad Arnoldabb352e2012-09-23 08:24:2720import cherrypy
21
Chris Sosa0356d3b2010-09-16 22:46:2222import autoupdate
Gilad Arnoldc65330c2012-09-20 22:17:4823import common_util
Chris Sosa47a7d4e2012-03-28 18:26:5524import downloader
Gilad Arnoldc65330c2012-09-20 22:17:4825import log_util
26
27
28# Module-local log function.
29def _Log(message, *args, **kwargs):
30 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 22:46:2231
Frank Farzan40160872011-12-13 02:39:1832
Chris Sosa417e55d2011-01-26 00:40:4833CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-17 01:36:1434
Chris Sosa0356d3b2010-09-16 22:46:2235# Sets up global to share between classes.
[email protected]21a5ca32009-11-04 18:23:2336global updater
37updater = None
[email protected]ded22402009-10-26 22:36:2138
Frank Farzan40160872011-12-13 02:39:1839
Chris Sosa9164ca32012-03-28 18:04:5040class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 18:26:5541 """Exception class used by this module."""
42 pass
43
44
Gilad Arnold0b8c3f32012-09-19 21:35:4445class LockDict(object):
46 """A dictionary of locks.
47
48 This class provides a thread-safe store of threading.Lock objects, which can
49 be used to regulate access to any set of hashable resources. Usage:
50
51 foo_lock_dict = LockDict()
52 ...
53 with foo_lock_dict.lock('bar'):
54 # Critical section for 'bar'
55 """
56 def __init__(self):
57 self._lock = self._new_lock()
58 self._dict = {}
59
60 def _new_lock(self):
61 return threading.Lock()
62
63 def lock(self, key):
64 with self._lock:
65 lock = self._dict.get(key)
66 if not lock:
67 lock = self._new_lock()
68 self._dict[key] = lock
69 return lock
70
71
Scott Zawalski4647ce62012-01-03 22:17:2872def _LeadingWhiteSpaceCount(string):
73 """Count the amount of leading whitespace in a string.
74
75 Args:
76 string: The string to count leading whitespace in.
77 Returns:
78 number of white space chars before characters start.
79 """
80 matched = re.match('^\s+', string)
81 if matched:
82 return len(matched.group())
83
84 return 0
85
86
87def _PrintDocStringAsHTML(func):
88 """Make a functions docstring somewhat HTML style.
89
90 Args:
91 func: The function to return the docstring from.
92 Returns:
93 A string that is somewhat formated for a web browser.
94 """
95 # TODO(scottz): Make this parse Args/Returns in a prettier way.
96 # Arguments could be bolded and indented etc.
97 html_doc = []
98 for line in func.__doc__.splitlines():
99 leading_space = _LeadingWhiteSpaceCount(line)
100 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 18:26:55101 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 22:17:28102
103 html_doc.append('<BR>%s' % line)
104
105 return '\n'.join(html_doc)
106
107
Chris Sosa7c931362010-10-12 02:49:01108def _GetConfig(options):
109 """Returns the configuration for the devserver."""
110 base_config = { 'global':
111 { 'server.log_request_headers': True,
112 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 16:01:08113 'server.socket_host': '::',
Chris Sosa7c931362010-10-12 02:49:01114 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:54115 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 22:44:46116 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 18:28:05117 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 02:59:17118 'tools.staticdir.root':
119 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-12 02:49:01120 },
Dale Curtisc9aaf3a2011-08-09 22:47:40121 '/api':
122 {
123 # Gets rid of cherrypy parsing post file for args.
124 'request.process_request_body': False,
125 },
Chris Sosaa1ef0102010-10-21 23:22:35126 '/build':
127 {
128 'response.timeout': 100000,
129 },
Chris Sosa7c931362010-10-12 02:49:01130 '/update':
131 {
132 # Gets rid of cherrypy parsing post file for args.
133 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:51134 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01135 },
136 # Sets up the static dir for file hosting.
137 '/static':
138 { 'tools.staticdir.dir': 'static',
139 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:51140 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01141 },
142 }
Chris Sosa5f118ef2012-07-12 18:37:50143 if options.production:
Chris Sosad1ea86b2012-07-12 20:35:37144 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 18:12:52145
Chris Sosa7c931362010-10-12 02:49:01146 return base_config
[email protected]64244662009-11-12 00:52:08147
Darin Petkove17164a2010-08-11 20:24:41148
Zdenek Behan608f46c2011-02-18 23:47:16149def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 22:46:22150 """Sets up symlink to image_dir for serving purposes."""
151 assert os.path.exists(image_dir), '%s must exist.' % image_dir
152 # If we're serving out of an archived build dir (e.g. a
153 # buildbot), prepare this webserver's magic 'static/' dir with a
154 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 22:17:48155 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-18 23:47:16156 if os.path.lexists('%s/archive' % static_dir):
157 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 22:17:48158 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-18 23:47:16159 os.unlink('%s/archive' % static_dir)
160 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-06-01 01:36:39161
Chris Sosa0356d3b2010-09-16 22:46:22162 else:
Zdenek Behan608f46c2011-02-18 23:47:16163 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-06-01 01:36:39164
Gilad Arnoldc65330c2012-09-20 22:17:48165 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-12 02:49:01166
167
Gilad Arnoldd5ebaaa2012-10-02 18:52:38168def _GetRecursiveMemberObject(root, member_list):
169 """Returns an object corresponding to a nested member list.
170
171 Args:
172 root: the root object to search
173 member_list: list of nested members to search
174 Returns:
175 An object corresponding to the member name list; None otherwise.
176 """
177 for member in member_list:
178 next_root = root.__class__.__dict__.get(member)
179 if not next_root:
180 return None
181 root = next_root
182 return root
183
184
185def _IsExposed(name):
186 """Returns True iff |name| has an `exposed' attribute and it is set."""
187 return hasattr(name, 'exposed') and name.exposed
188
189
190def _GetExposedMethod(root, nested_member, ignored=[]):
191 """Returns a CherryPy-exposed method, if such exists.
192
193 Args:
194 root: the root object for searching
195 nested_member: a slash-joined path to the nested member
196 ignored: method paths to be ignored
197 Returns:
198 A function object corresponding to the path defined by |member_list| from
199 the |root| object, if the function is exposed and not ignored; None
200 otherwise.
201 """
202 method = (nested_member not in ignored and
203 _GetRecursiveMemberObject(root, nested_member.split('/')))
204 if (method and type(method) == types.FunctionType and _IsExposed(method)):
205 return method
206
207
208def _FindExposedMethods(root, prefix, unlisted=[]):
209 """Finds exposed CherryPy methods.
210
211 Args:
212 root: the root object for searching
213 prefix: slash-joined chain of members leading to current object
214 unlisted: URLs to be excluded regardless of their exposed status
215 Returns:
216 List of exposed URLs that are not unlisted.
217 """
218 method_list = []
219 for member in sorted(root.__class__.__dict__.keys()):
220 prefixed_member = prefix + '/' + member if prefix else member
221 if prefixed_member in unlisted:
222 continue
223 member_obj = root.__class__.__dict__[member]
224 if _IsExposed(member_obj):
225 if type(member_obj) == types.FunctionType:
226 method_list.append(prefixed_member)
227 else:
228 method_list += _FindExposedMethods(
229 member_obj, prefixed_member, unlisted)
230 return method_list
231
232
Dale Curtisc9aaf3a2011-08-09 22:47:40233class ApiRoot(object):
234 """RESTful API for Dev Server information."""
235 exposed = True
236
237 @cherrypy.expose
238 def hostinfo(self, ip):
239 """Returns a JSON dictionary containing information about the given ip.
240
241 Not all information may be known at the time the request is made. The
242 possible keys are:
243
244 last_event_type: int
245 Last update event type received.
246
247 last_event_status: int
248 Last update event status received.
249
250 last_known_version: string
251 Last known version recieved for update ping.
252
253 forced_update_label: string
254 Update label to force next update ping to use. Set by setnextupdate.
255
256 See the OmahaEvent class in update_engine/omaha_request_action.h for status
257 code definitions. If the ip does not exist an empty string is returned."""
258 return updater.HandleHostInfoPing(ip)
259
260 @cherrypy.expose
Gilad Arnold286a0062012-01-12 21:47:02261 def hostlog(self, ip):
262 """Returns a JSON object containing a log of events pertaining to a
263 particular host, or all hosts. Log events contain a timestamp and any
264 subset of the attributes listed for the hostinfo method."""
265 return updater.HandleHostLogPing(ip)
266
267 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 22:47:40268 def setnextupdate(self, ip):
269 """Allows the response to the next update ping from a host to be set.
270
271 Takes the IP of the host and an update label as normally provided to the
272 /update command."""
273 body_length = int(cherrypy.request.headers['Content-Length'])
274 label = cherrypy.request.rfile.read(body_length)
275
276 if label:
277 label = label.strip()
278 if label:
279 return updater.HandleSetUpdatePing(ip, label)
280 raise cherrypy.HTTPError(400, 'No label provided.')
281
282
Gilad Arnold55a2a372012-10-02 16:46:32283 @cherrypy.expose
284 def fileinfo(self, *path_args):
285 """Returns information about a given staged file.
286
287 Args:
288 path_args: path to the file inside the server's static staging directory
289 Returns:
290 A JSON encoded dictionary with information about the said file, which may
291 contain the following keys/values:
292 size: the file size in bytes (int)
293 sha1: a base64 encoded SHA1 hash (string)
294 sha256: a base64 encoded SHA256 hash (string)
295 """
296 file_path = os.path.join(updater.static_dir, *path_args)
297 if not os.path.exists(file_path):
298 raise DevServerError('file not found: %s' % file_path)
299 try:
300 file_size = os.path.getsize(file_path)
301 file_sha1 = common_util.GetFileSha1(file_path)
302 file_sha256 = common_util.GetFileSha256(file_path)
303 except os.error, e:
304 raise DevServerError('failed to get info for file %s: %s' %
305 (file_path, str(e)))
306 return json.dumps(
307 {'size': file_size, 'sha1': file_sha1, 'sha256': file_sha256})
308
David Rochberg7c79a812011-01-19 19:24:45309class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:01310 """The Root Class for the Dev Server.
311
312 CherryPy works as follows:
313 For each method in this class, cherrpy interprets root/path
314 as a call to an instance of DevServerRoot->method_name. For example,
315 a call to http://myhost/build will call build. CherryPy automatically
316 parses http args and places them as keyword arguments in each method.
317 For paths http://myhost/update/dir1/dir2, you can use *args so that
318 cherrypy uses the update method and puts the extra paths in args.
319 """
Gilad Arnoldf8f769f2012-09-24 15:43:01320 # Method names that should not be listed on the index page.
321 _UNLISTED_METHODS = ['index', 'doc']
322
Dale Curtisc9aaf3a2011-08-09 22:47:40323 api = ApiRoot()
Chris Sosa7c931362010-10-12 02:49:01324
David Rochberg7c79a812011-01-19 19:24:45325 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 22:20:41326 self._builder = None
Gilad Arnold0b8c3f32012-09-19 21:35:44327 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 18:26:55328 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 19:24:45329
Dale Curtisc9aaf3a2011-08-09 22:47:40330 @cherrypy.expose
David Rochberg7c79a812011-01-19 19:24:45331 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:01332 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 22:20:41333 import builder
334 if self._builder is None:
335 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 19:24:45336 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:01337
Chris Sosacde6bf42012-06-01 01:36:39338 @staticmethod
339 def _canonicalize_archive_url(archive_url):
340 """Canonicalizes archive_url strings.
341
342 Raises:
343 DevserverError: if archive_url is not set.
344 """
345 if archive_url:
346 return archive_url.rstrip('/')
347 else:
348 raise DevServerError("Must specify an archive_url in the request")
349
Dale Curtisc9aaf3a2011-08-09 22:47:40350 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 19:48:17351 def download(self, **kwargs):
352 """Downloads and archives full/delta payloads from Google Storage.
353
Chris Sosa47a7d4e2012-03-28 18:26:55354 This methods downloads artifacts. It may download artifacts in the
355 background in which case a caller should call wait_for_status to get
356 the status of the background artifact downloads. They should use the same
357 args passed to download.
358
Frank Farzanbcb571e2012-01-03 19:48:17359 Args:
360 archive_url: Google Storage URL for the build.
361
362 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01363 http://myhost/download?archive_url=gs://chromeos-image-archive/
364 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 19:48:17365 """
Chris Sosacde6bf42012-06-01 01:36:39366 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 18:26:55367
Chris Sosacde6bf42012-06-01 01:36:39368 # Guarantees that no two downloads for the same url can run this code
369 # at the same time.
Gilad Arnold0b8c3f32012-09-19 21:35:44370 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-06-01 01:36:39371 try:
372 # If we are currently downloading, return. Note, due to the above lock
373 # we know that the foreground artifacts must have finished downloading
374 # and returned Success if this downloader instance exists.
375 if (self._downloader_dict.get(archive_url) or
376 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 22:17:48377 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-06-01 01:36:39378 return 'Success'
379
380 downloader_instance = downloader.Downloader(updater.static_dir)
381 self._downloader_dict[archive_url] = downloader_instance
382 return downloader_instance.Download(archive_url, background=True)
383
384 except:
385 # On any exception, reset the state of the downloader_dict.
386 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 22:23:23387 raise
Chris Sosacde6bf42012-06-01 01:36:39388
389 @cherrypy.expose
390 def wait_for_status(self, **kwargs):
391 """Waits for background artifacts to be downloaded from Google Storage.
392
393 Args:
394 archive_url: Google Storage URL for the build.
395
396 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01397 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
398 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-06-01 01:36:39399 """
400 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
401 downloader_instance = self._downloader_dict.get(archive_url)
402 if downloader_instance:
403 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 19:44:43404 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-06-01 01:36:39405 return status
406 else:
407 # We may have previously downloaded but removed the downloader instance
408 # from the cache.
409 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
410 logging.info('%s not found in downloader cache but previously staged.',
411 archive_url)
412 return 'Success'
413 else:
414 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 18:26:55415
416 @cherrypy.expose
Chris Masone816e38c2012-05-02 19:22:36417 def stage_debug(self, **kwargs):
418 """Downloads and stages debug symbol payloads from Google Storage.
419
420 This methods downloads the debug symbol build artifact synchronously,
421 and then stages it for use by symbolicate_dump/.
422
423 Args:
424 archive_url: Google Storage URL for the build.
425
426 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01427 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
428 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 19:22:36429 """
Chris Sosacde6bf42012-06-01 01:36:39430 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 19:22:36431 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
432
433 @cherrypy.expose
434 def symbolicate_dump(self, minidump):
435 """Symbolicates a minidump using pre-downloaded symbols, returns it.
436
437 Callers will need to POST to this URL with a body of MIME-type
438 "multipart/form-data".
439 The body should include a single argument, 'minidump', containing the
440 binary-formatted minidump to symbolicate.
441
442 It is up to the caller to ensure that the symbols they want are currently
443 staged.
444
445 Args:
446 minidump: The binary minidump file to symbolicate.
447 """
448 to_return = ''
449 with tempfile.NamedTemporaryFile() as local:
450 while True:
451 data = minidump.file.read(8192)
452 if not data:
453 break
454 local.write(data)
455 local.flush()
456 stackwalk = subprocess.Popen(['minidump_stackwalk',
457 local.name,
458 updater.static_dir + '/debug/breakpad'],
459 stdout=subprocess.PIPE,
460 stderr=subprocess.PIPE)
461 to_return, error_text = stackwalk.communicate()
462 if stackwalk.returncode != 0:
463 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
464 error_text, stackwalk.returncode))
465
466 return to_return
467
468 @cherrypy.expose
Scott Zawalski16954532012-03-20 19:31:36469 def latestbuild(self, **params):
470 """Return a string representing the latest build for a given target.
471
472 Args:
473 target: The build target, typically a combination of the board and the
474 type of build e.g. x86-mario-release.
475 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
476 provided the latest RXX build will be returned.
477 Returns:
478 A string representation of the latest build if one exists, i.e.
479 R19-1993.0.0-a1-b1480.
480 An empty string if no latest could be found.
481 """
482 if not params:
483 return _PrintDocStringAsHTML(self.latestbuild)
484
485 if 'target' not in params:
486 raise cherrypy.HTTPError('500 Internal Server Error',
487 'Error: target= is required!')
488 try:
Gilad Arnoldc65330c2012-09-20 22:17:48489 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 19:31:36490 updater.static_dir, params['target'],
491 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 17:05:01492 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 19:31:36493 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
494
495 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 20:12:42496 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 22:17:28497 """Return a control file or a list of all known control files.
498
499 Example URL:
500 To List all control files:
Scott Zawalski84a39c92012-01-13 20:12:42501 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 22:17:28502 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 20:12:42503 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 22:17:28504
505 Args:
Scott Zawalski84a39c92012-01-13 20:12:42506 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 22:17:28507 control_path: If you want the contents of a control file set this
508 to the path. E.g. client/site_tests/sleeptest/control
509 Optional, if not provided return a list of control files is returned.
510 Returns:
511 Contents of a control file if control_path is provided.
512 A list of control files if no control_path is provided.
513 """
Scott Zawalski4647ce62012-01-03 22:17:28514 if not params:
515 return _PrintDocStringAsHTML(self.controlfiles)
516
Scott Zawalski84a39c92012-01-13 20:12:42517 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 22:17:28518 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 20:12:42519 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 22:17:28520
521 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 22:17:48522 return common_util.GetControlFileList(
523 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 22:17:28524 else:
Gilad Arnoldc65330c2012-09-20 22:17:48525 return common_util.GetControlFile(
526 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-13 02:39:18527
528 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 17:49:40529 def stage_images(self, **kwargs):
530 """Downloads and stages a Chrome OS image from Google Storage.
531
532 This method downloads a zipped archive from a specified GS location, then
533 extracts and stages the specified list of images and stages them under
534 static/images/BOARD/BUILD/. Download is synchronous.
535
536 Args:
537 archive_url: Google Storage URL for the build.
538 image_types: comma-separated list of images to download, may include
539 'test', 'recovery', and 'base'
540
541 Example URL:
542 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
543 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
544 """
545 # TODO(garnold) This needs to turn into an async operation, to avoid
546 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
547 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
548 image_types = kwargs.get('image_types').split(',')
549 return (downloader.ImagesDownloader(
550 updater.static_dir).Download(archive_url, image_types))
551
552 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01553 def index(self):
Gilad Arnoldf8f769f2012-09-24 15:43:01554 """Presents a welcome message and documentation links."""
555 method_dict = DevServerRoot.__dict__
556 return ('Welcome to the Dev Server!<br>\n'
557 '<br>\n'
558 'Here are the available methods, click for documentation:<br>\n'
559 '<br>\n'
560 '%s' %
561 '<br>\n'.join(
562 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 18:52:38563 for name in _FindExposedMethods(
564 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 15:43:01565
566 @cherrypy.expose
567 def doc(self, *args):
568 """Shows the documentation for available methods / URLs.
569
570 Example:
571 http://myhost/doc/update
572 """
Gilad Arnoldd5ebaaa2012-10-02 18:52:38573 name = '/'.join(args)
574 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 15:43:01575 if not method:
576 raise DevServerError("No exposed method named `%s'" % name)
577 if not method.__doc__:
578 raise DevServerError("No documentation for exposed method `%s'" % name)
579 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-12 02:49:01580
Dale Curtisc9aaf3a2011-08-09 22:47:40581 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01582 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 15:43:01583 """Handles an update check from a Chrome OS client.
584
585 The HTTP request should contain the standard Omaha-style XML blob. The URL
586 line may contain an additional intermediate path to the update payload.
587
588 Example:
589 http://myhost/update/optional/path/to/payload
590 """
Chris Sosa7c931362010-10-12 02:49:01591 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 21:47:02592 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-12 02:49:01593 data = cherrypy.request.rfile.read(body_length)
594 return updater.HandleUpdatePing(data, label)
595
Chris Sosa0356d3b2010-09-16 22:46:22596
Chris Sosacde6bf42012-06-01 01:36:39597def main():
Sean O'Connor14b6a0a2010-03-21 06:23:48598 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 21:47:02599 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 20:50:40600 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-21 06:23:48601 help='serve archived builds only.')
Chris Sosae67b78f12010-11-05 00:33:16602 parser.add_option('--board', dest='board',
603 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-18 02:13:37604 parser.add_option('--clear_cache', action='store_true', default=False,
Chris Sosa6ab79622012-08-21 20:11:35605 help='Clear out all cached updates and exit')
Satoru Takabayashid733cbe2011-11-15 17:36:32606 parser.add_option('--critical_update', dest='critical_update',
607 action='store_true', default=False,
608 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 01:06:01609 parser.add_option('--data_dir', dest='data_dir',
610 help='Writable directory where static lives',
611 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-18 02:13:37612 parser.add_option('--exit', action='store_true', default=False,
613 help='Don\'t start the server (still pregenerate or clear'
614 'cache).')
Andrew de los Reyes52620802010-04-12 20:40:07615 parser.add_option('--factory_config', dest='factory_config',
616 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-29 06:42:37617 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
618 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 22:46:22619 parser.add_option('--image', dest='image',
620 help='Force update using this image.')
Chris Sosa66e2d9c2012-07-11 21:14:14621 parser.add_option('--logfile', dest='logfile',
622 help='Log output to this file instead of stdout.')
Chris Sosa2c048f12010-10-27 23:05:27623 parser.add_option('-p', '--pregenerate_update', action='store_true',
624 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-18 02:13:37625 parser.add_option('--payload', dest='payload',
626 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-12 02:49:01627 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 21:47:02628 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-15 00:33:22629 parser.add_option('--private_key', default=None,
630 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-26 00:40:48631 parser.add_option('--production', action='store_true', default=False,
632 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-07 00:20:30633 parser.add_option('--proxy_port', default=None,
634 help='Port to have the client connect to (testing support)')
Gilad Arnold0c9c8602012-10-03 06:58:58635 parser.add_option('--remote_payload', action='store_true', default=False,
636 help='Payload is being served from a remote machine.')
Chris Sosa62f720b2010-10-27 04:39:48637 parser.add_option('--src_image', default='',
638 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 23:34:52639 parser.add_option('-t', action='store_true', dest='test_image')
640 parser.add_option('-u', '--urlbase', dest='urlbase',
641 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 20:40:07642 parser.add_option('--validate_factory_config', action="store_true",
643 dest='validate_factory_config',
644 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-12 02:49:01645 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:23646
Chris Sosa7c931362010-10-12 02:49:01647 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
648 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:22649 serve_only = False
650
Zdenek Behan608f46c2011-02-18 23:47:16651 static_dir = os.path.realpath('%s/static' % options.data_dir)
652 os.system('mkdir -p %s' % static_dir)
653
Sean O'Connor14b6a0a2010-03-21 06:23:48654 if options.archive_dir:
Zdenek Behan608f46c2011-02-18 23:47:16655 # TODO(zbehan) Remove legacy support:
656 # archive_dir is the directory where static/archive will point.
657 # If this is an absolute path, all is fine. If someone calls this
658 # using a relative path, that is relative to src/platform/dev/.
659 # That use case is unmaintainable, but since applications use it
660 # with =./static, instead of a boolean flag, we'll make this relative
661 # to devserver_dir to keep these unbroken. For now.
662 archive_dir = options.archive_dir
663 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 18:26:55664 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-18 23:47:16665 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 21:35:49666 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 22:46:22667 serve_only = True
Chris Sosa0356d3b2010-09-16 22:46:22668
Don Garrettf90edf02010-11-17 01:36:14669 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 22:17:48670 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-17 01:36:14671
Don Garrettf90edf02010-11-17 01:36:14672 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 20:12:17673 if options.clear_cache:
674 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 18:04:50675 cmd = 'rm -rf %s/*' % cache_dir
676 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 22:17:48677 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 20:12:17678 sys.exit(1)
679
680 else:
681 # Clear all but the last N cached updates
682 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
683 (cache_dir, CACHED_ENTRIES))
684 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 22:17:48685 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 20:12:17686 sys.exit(1)
687 else:
688 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14689
Gilad Arnoldc65330c2012-09-20 22:17:48690 _Log('Data dir is %s' % options.data_dir)
691 _Log('Source root is %s' % root_dir)
692 _Log('Serving from %s' % static_dir)
[email protected]21a5ca32009-11-04 18:23:23693
Chris Sosacde6bf42012-06-01 01:36:39694 global updater
Andrew de los Reyes52620802010-04-12 20:40:07695 updater = autoupdate.Autoupdate(
696 root_dir=root_dir,
697 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 22:46:22698 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 20:40:07699 urlbase=options.urlbase,
700 test_image=options.test_image,
701 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 23:54:41702 forced_image=options.image,
Gilad Arnold0c9c8602012-10-03 06:58:58703 payload_path=options.payload,
Don Garrett0ad09372010-12-07 00:20:30704 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:37705 src_image=options.src_image,
Chris Sosae67b78f12010-11-05 00:33:16706 vm=options.vm,
Chris Sosa08d55a22011-01-20 00:08:02707 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:22708 copy_to_static_root=not options.exit,
709 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 17:36:32710 critical_update=options.critical_update,
Gilad Arnold0c9c8602012-10-03 06:58:58711 remote_payload=options.remote_payload,
Chris Sosa0f1ec842011-02-15 00:33:22712 )
Chris Sosa7c931362010-10-12 02:49:01713
714 # Sanity-check for use of validate_factory_config.
715 if not options.factory_config and options.validate_factory_config:
716 parser.error('You need a factory_config to validate.')
[email protected]64244662009-11-12 00:52:08717
Chris Sosa0356d3b2010-09-16 22:46:22718 if options.factory_config:
Chris Sosa7c931362010-10-12 02:49:01719 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 22:46:22720 options.validate_factory_config)
Chris Sosa7c931362010-10-12 02:49:01721 # We don't run the dev server with this option.
722 if options.validate_factory_config:
723 sys.exit(0)
Chris Sosa2c048f12010-10-27 23:05:27724 elif options.pregenerate_update:
Chris Sosae67b78f12010-11-05 00:33:16725 if not updater.PreGenerateUpdate():
726 sys.exit(1)
Chris Sosa0356d3b2010-09-16 22:46:22727
Don Garrett0c880e22010-11-18 02:13:37728 # If the command line requested after setup, it's time to do it.
729 if not options.exit:
Chris Sosa66e2d9c2012-07-11 21:14:14730 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 21:32:33731 if options.production:
Chris Sosa66e2d9c2012-07-11 21:14:14732 cherrypy.config.update({'environment': 'production'})
733 if not options.logfile:
734 cherrypy.config.update({'log.screen': True})
735 else:
736 cherrypy.config.update({'log.error_file': options.logfile,
737 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 21:32:33738
Don Garrett0c880e22010-11-18 02:13:37739 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-06-01 01:36:39740
741
742if __name__ == '__main__':
743 main()