blob: 5b8260840b49e1ce019fbf264b19111e69525502 [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 Sosa3ae4dc12013-03-29 18:47:007"""Chromium OS development server that can be used for all forms of update.
8
9This devserver can be used to perform system-wide autoupdate and update
10of specific portage packages on devices running Chromium OS derived operating
11systems. It mainly operates in two modes:
12
131) archive mode: In this mode, the devserver is configured to stage and
14serve artifacts from Google Storage using the credentials provided to it before
15it is run. The easiest way to understand this is that the devserver is
16functioning as a local cache for artifacts produced and uploaded by build
17servers. Users of this form of devserver can either download the artifacts
18from the devservers static directory OR use the update RPC to perform a
19system-wide autoupdate. Archive mode is always active.
20
212) artifact-generation mode: in this mode, the devserver will attempt to
22generate update payloads and build artifacts when requested. This mode only
23works in the Chromium OS chroot as it uses build tools only present in the
24chroot (emerge, cros_generate_update_payload, etc.). By default, when a device
25requests an update from this form of devserver, the devserver will attempt to
26discover if a more recent build of the board has been built by the developer
27and generate a payload that the requested system can autoupdate to. In addition,
28it accepts gmerge requests from devices that will stage the newest version of
29a particular package from a developer's chroot onto a requesting device. Note
30if archive_dir is specified, this mode is disabled.
31
32For example:
33gmerge gmerge -d <devserver_url>
34
35devserver will see if a newer package of gmerge is available. If gmerge is
36cros_work'd on, it will re-build gmerge. After this, gmerge will install that
37version of gmerge that the devserver just created/found.
38
39For autoupdates, there are many more advanced options that can help specify
40how to update and which payload to give to a requester.
41"""
42
Chris Sosa7c931362010-10-12 02:49:0143
Gilad Arnold55a2a372012-10-02 16:46:3244import json
Sean O'Connor14b6a0a2010-03-21 06:23:4845import optparse
[email protected]ded22402009-10-26 22:36:2146import os
Scott Zawalski4647ce62012-01-03 22:17:2847import re
Simran Basi4baad082013-02-14 21:39:1848import shutil
Mandeep Singh Baines38dcdda2012-12-08 01:55:3349import socket
Chris Masone816e38c2012-05-02 19:22:3650import subprocess
J. Richard Barnette3d977b82013-04-23 18:05:1951import sys
Chris Masone816e38c2012-05-02 19:22:3652import tempfile
Dan Shi59ae7092013-06-04 21:37:2753import threading
Gilad Arnoldd5ebaaa2012-10-02 18:52:3854import types
J. Richard Barnette3d977b82013-04-23 18:05:1955from logging import handlers
56
57import cherrypy
58import cherrypy._cplogging
[email protected]ded22402009-10-26 22:36:2159
Chris Sosa0356d3b2010-09-16 22:46:2260import autoupdate
Gilad Arnoldc65330c2012-09-20 22:17:4861import common_util
Chris Sosa47a7d4e2012-03-28 18:26:5562import downloader
Gilad Arnoldc65330c2012-09-20 22:17:4863import log_util
joychen3cb228e2013-06-12 19:13:1364import xbuddy
Gilad Arnoldc65330c2012-09-20 22:17:4865
Gilad Arnoldc65330c2012-09-20 22:17:4866# Module-local log function.
Chris Sosa6a3697f2013-01-30 00:44:4367def _Log(message, *args):
68 return log_util.LogWithTag('DEVSERVER', message, *args)
Chris Sosa0356d3b2010-09-16 22:46:2269
Frank Farzan40160872011-12-13 02:39:1870
Chris Sosa417e55d2011-01-26 00:40:4871CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-17 01:36:1472
Simran Basi4baad082013-02-14 21:39:1873TELEMETRY_FOLDER = 'telemetry_src'
74TELEMETRY_DEPS = ['dep-telemetry_dep.tar.bz2',
75 'dep-page_cycler_dep.tar.bz2',
Simran Basi0d078682013-03-22 23:40:0476 'dep-chrome_test.tar.bz2',
77 'dep-perf_data_dep.tar.bz2']
Simran Basi4baad082013-02-14 21:39:1878
Chris Sosa0356d3b2010-09-16 22:46:2279# Sets up global to share between classes.
[email protected]21a5ca32009-11-04 18:23:2380updater = None
[email protected]ded22402009-10-26 22:36:2181
J. Richard Barnette3d977b82013-04-23 18:05:1982# Log rotation parameters. These settings correspond to once a week
J. Richard Barnette6dfa5342013-06-04 18:48:5683# at midnight between Friday and Saturday, with about three months
84# of old logs kept for backup.
J. Richard Barnette3d977b82013-04-23 18:05:1985#
86# For more, see the documentation for
87# logging.handlers.TimedRotatingFileHandler
J. Richard Barnette6dfa5342013-06-04 18:48:5688_LOG_ROTATION_TIME = 'W4'
J. Richard Barnette3d977b82013-04-23 18:05:1989_LOG_ROTATION_BACKUP = 13
90
Frank Farzan40160872011-12-13 02:39:1891
Chris Sosa9164ca32012-03-28 18:04:5092class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 18:26:5593 """Exception class used by this module."""
94 pass
95
96
Scott Zawalski4647ce62012-01-03 22:17:2897def _LeadingWhiteSpaceCount(string):
98 """Count the amount of leading whitespace in a string.
99
100 Args:
101 string: The string to count leading whitespace in.
102 Returns:
103 number of white space chars before characters start.
104 """
beepsbd337242013-07-10 05:44:06105 # pylint: disable=W1401
Scott Zawalski4647ce62012-01-03 22:17:28106 matched = re.match('^\s+', string)
107 if matched:
108 return len(matched.group())
109
110 return 0
111
112
113def _PrintDocStringAsHTML(func):
114 """Make a functions docstring somewhat HTML style.
115
116 Args:
117 func: The function to return the docstring from.
118 Returns:
119 A string that is somewhat formated for a web browser.
120 """
121 # TODO(scottz): Make this parse Args/Returns in a prettier way.
122 # Arguments could be bolded and indented etc.
123 html_doc = []
124 for line in func.__doc__.splitlines():
125 leading_space = _LeadingWhiteSpaceCount(line)
126 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 18:26:55127 line = '&nbsp;' * leading_space + line
Scott Zawalski4647ce62012-01-03 22:17:28128
129 html_doc.append('<BR>%s' % line)
130
131 return '\n'.join(html_doc)
132
133
Chris Sosa7c931362010-10-12 02:49:01134def _GetConfig(options):
135 """Returns the configuration for the devserver."""
Mandeep Singh Baines38dcdda2012-12-08 01:55:33136
137 # On a system with IPv6 not compiled into the kernel,
138 # AF_INET6 sockets will return a socket.error exception.
139 # On such systems, fall-back to IPv4.
140 socket_host = '::'
141 try:
142 socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
143 except socket.error:
144 socket_host = '0.0.0.0'
145
Chris Sosa7c931362010-10-12 02:49:01146 base_config = { 'global':
147 { 'server.log_request_headers': True,
148 'server.protocol_version': 'HTTP/1.1',
Mandeep Singh Baines38dcdda2012-12-08 01:55:33149 'server.socket_host': socket_host,
Chris Sosa7c931362010-10-12 02:49:01150 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:54151 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 22:44:46152 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 18:28:05153 'server.socket_timeout': 60,
joychenecc02aa2013-07-18 01:27:35154 'server.thread_pool': 2,
Chris Sosa7c931362010-10-12 02:49:01155 },
Dale Curtisc9aaf3a2011-08-09 22:47:40156 '/api':
157 {
158 # Gets rid of cherrypy parsing post file for args.
159 'request.process_request_body': False,
160 },
Chris Sosaa1ef0102010-10-21 23:22:35161 '/build':
162 {
163 'response.timeout': 100000,
164 },
Chris Sosa7c931362010-10-12 02:49:01165 '/update':
166 {
167 # Gets rid of cherrypy parsing post file for args.
168 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:51169 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01170 },
171 # Sets up the static dir for file hosting.
172 '/static':
joychened64b222013-06-21 23:39:34173 { 'tools.staticdir.dir': options.static_dir,
Chris Sosa7c931362010-10-12 02:49:01174 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:51175 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01176 },
177 }
Chris Sosa5f118ef2012-07-12 18:37:50178 if options.production:
Chris Sosad1ea86b2012-07-12 20:35:37179 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 18:12:52180
Chris Sosa7c931362010-10-12 02:49:01181 return base_config
[email protected]64244662009-11-12 00:52:08182
Darin Petkove17164a2010-08-11 20:24:41183
Gilad Arnoldd5ebaaa2012-10-02 18:52:38184def _GetRecursiveMemberObject(root, member_list):
185 """Returns an object corresponding to a nested member list.
186
187 Args:
188 root: the root object to search
189 member_list: list of nested members to search
190 Returns:
191 An object corresponding to the member name list; None otherwise.
192 """
193 for member in member_list:
194 next_root = root.__class__.__dict__.get(member)
195 if not next_root:
196 return None
197 root = next_root
198 return root
199
200
201def _IsExposed(name):
202 """Returns True iff |name| has an `exposed' attribute and it is set."""
203 return hasattr(name, 'exposed') and name.exposed
204
205
Gilad Arnold748c8322012-10-12 16:51:35206def _GetExposedMethod(root, nested_member, ignored=None):
Gilad Arnoldd5ebaaa2012-10-02 18:52:38207 """Returns a CherryPy-exposed method, if such exists.
208
209 Args:
210 root: the root object for searching
211 nested_member: a slash-joined path to the nested member
212 ignored: method paths to be ignored
213 Returns:
214 A function object corresponding to the path defined by |member_list| from
215 the |root| object, if the function is exposed and not ignored; None
216 otherwise.
217 """
Gilad Arnold748c8322012-10-12 16:51:35218 method = (not (ignored and nested_member in ignored) and
Gilad Arnoldd5ebaaa2012-10-02 18:52:38219 _GetRecursiveMemberObject(root, nested_member.split('/')))
220 if (method and type(method) == types.FunctionType and _IsExposed(method)):
221 return method
222
223
Gilad Arnold748c8322012-10-12 16:51:35224def _FindExposedMethods(root, prefix, unlisted=None):
Gilad Arnoldd5ebaaa2012-10-02 18:52:38225 """Finds exposed CherryPy methods.
226
227 Args:
228 root: the root object for searching
229 prefix: slash-joined chain of members leading to current object
230 unlisted: URLs to be excluded regardless of their exposed status
231 Returns:
232 List of exposed URLs that are not unlisted.
233 """
234 method_list = []
235 for member in sorted(root.__class__.__dict__.keys()):
236 prefixed_member = prefix + '/' + member if prefix else member
Gilad Arnold748c8322012-10-12 16:51:35237 if unlisted and prefixed_member in unlisted:
Gilad Arnoldd5ebaaa2012-10-02 18:52:38238 continue
239 member_obj = root.__class__.__dict__[member]
240 if _IsExposed(member_obj):
241 if type(member_obj) == types.FunctionType:
242 method_list.append(prefixed_member)
243 else:
244 method_list += _FindExposedMethods(
245 member_obj, prefixed_member, unlisted)
246 return method_list
247
248
Dale Curtisc9aaf3a2011-08-09 22:47:40249class ApiRoot(object):
250 """RESTful API for Dev Server information."""
251 exposed = True
252
253 @cherrypy.expose
254 def hostinfo(self, ip):
255 """Returns a JSON dictionary containing information about the given ip.
256
Gilad Arnold1b908392012-10-05 18:36:27257 Args:
258 ip: address of host whose info is requested
259 Returns:
260 A JSON dictionary containing all or some of the following fields:
261 last_event_type (int): last update event type received
262 last_event_status (int): last update event status received
263 last_known_version (string): last known version reported in update ping
264 forced_update_label (string): update label to force next update ping to
265 use, set by setnextupdate
266 See the OmahaEvent class in update_engine/omaha_request_action.h for
267 event type and status code definitions. If the ip does not exist an empty
268 string is returned.
Dale Curtisc9aaf3a2011-08-09 22:47:40269
Gilad Arnold1b908392012-10-05 18:36:27270 Example URL:
271 http://myhost/api/hostinfo?ip=192.168.1.5
272 """
Dale Curtisc9aaf3a2011-08-09 22:47:40273 return updater.HandleHostInfoPing(ip)
274
275 @cherrypy.expose
Gilad Arnold286a0062012-01-12 21:47:02276 def hostlog(self, ip):
Gilad Arnold1b908392012-10-05 18:36:27277 """Returns a JSON object containing a log of host event.
278
279 Args:
280 ip: address of host whose event log is requested, or `all'
281 Returns:
282 A JSON encoded list (log) of dictionaries (events), each of which
283 containing a `timestamp' and other event fields, as described under
284 /api/hostinfo.
285
286 Example URL:
287 http://myhost/api/hostlog?ip=192.168.1.5
288 """
Gilad Arnold286a0062012-01-12 21:47:02289 return updater.HandleHostLogPing(ip)
290
291 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 22:47:40292 def setnextupdate(self, ip):
293 """Allows the response to the next update ping from a host to be set.
294
295 Takes the IP of the host and an update label as normally provided to the
Gilad Arnold1b908392012-10-05 18:36:27296 /update command.
297 """
Dale Curtisc9aaf3a2011-08-09 22:47:40298 body_length = int(cherrypy.request.headers['Content-Length'])
299 label = cherrypy.request.rfile.read(body_length)
300
301 if label:
302 label = label.strip()
303 if label:
304 return updater.HandleSetUpdatePing(ip, label)
305 raise cherrypy.HTTPError(400, 'No label provided.')
306
307
Gilad Arnold55a2a372012-10-02 16:46:32308 @cherrypy.expose
309 def fileinfo(self, *path_args):
310 """Returns information about a given staged file.
311
312 Args:
313 path_args: path to the file inside the server's static staging directory
314 Returns:
315 A JSON encoded dictionary with information about the said file, which may
316 contain the following keys/values:
Gilad Arnold1b908392012-10-05 18:36:27317 size (int): the file size in bytes
318 sha1 (string): a base64 encoded SHA1 hash
319 sha256 (string): a base64 encoded SHA256 hash
320
321 Example URL:
322 http://myhost/api/fileinfo/some/path/to/file
Gilad Arnold55a2a372012-10-02 16:46:32323 """
324 file_path = os.path.join(updater.static_dir, *path_args)
325 if not os.path.exists(file_path):
326 raise DevServerError('file not found: %s' % file_path)
327 try:
328 file_size = os.path.getsize(file_path)
329 file_sha1 = common_util.GetFileSha1(file_path)
330 file_sha256 = common_util.GetFileSha256(file_path)
331 except os.error, e:
332 raise DevServerError('failed to get info for file %s: %s' %
Gilad Arnolde74b3812013-04-22 18:27:38333 (file_path, e))
334
335 is_delta = autoupdate.Autoupdate.IsDeltaFormatFile(file_path)
336
337 return json.dumps({
338 autoupdate.Autoupdate.SIZE_ATTR: file_size,
339 autoupdate.Autoupdate.SHA1_ATTR: file_sha1,
340 autoupdate.Autoupdate.SHA256_ATTR: file_sha256,
341 autoupdate.Autoupdate.ISDELTA_ATTR: is_delta
342 })
Gilad Arnold55a2a372012-10-02 16:46:32343
Chris Sosa76e44b92013-01-31 20:11:38344
David Rochberg7c79a812011-01-19 19:24:45345class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:01346 """The Root Class for the Dev Server.
347
348 CherryPy works as follows:
349 For each method in this class, cherrpy interprets root/path
350 as a call to an instance of DevServerRoot->method_name. For example,
351 a call to http://myhost/build will call build. CherryPy automatically
352 parses http args and places them as keyword arguments in each method.
353 For paths http://myhost/update/dir1/dir2, you can use *args so that
354 cherrypy uses the update method and puts the extra paths in args.
355 """
Gilad Arnoldf8f769f2012-09-24 15:43:01356 # Method names that should not be listed on the index page.
357 _UNLISTED_METHODS = ['index', 'doc']
358
Dale Curtisc9aaf3a2011-08-09 22:47:40359 api = ApiRoot()
Chris Sosa7c931362010-10-12 02:49:01360
Dan Shi59ae7092013-06-04 21:37:27361 # Number of threads that devserver is staging images.
362 _staging_thread_count = 0
363 # Lock used to lock increasing/decreasing count.
364 _staging_thread_count_lock = threading.Lock()
365
joychen3cb228e2013-06-12 19:13:13366 def __init__(self, _xbuddy):
Nick Sanders7dcaa2e2011-08-04 22:20:41367 self._builder = None
Simran Basi4baad082013-02-14 21:39:18368 self._telemetry_lock_dict = common_util.LockDict()
joychen3cb228e2013-06-12 19:13:13369 self._xbuddy = _xbuddy
David Rochberg7c79a812011-01-19 19:24:45370
Dale Curtisc9aaf3a2011-08-09 22:47:40371 @cherrypy.expose
David Rochberg7c79a812011-01-19 19:24:45372 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:01373 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 22:20:41374 import builder
375 if self._builder is None:
376 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 19:24:45377 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:01378
Chris Sosacde6bf42012-06-01 01:36:39379 @staticmethod
380 def _canonicalize_archive_url(archive_url):
381 """Canonicalizes archive_url strings.
382
383 Raises:
384 DevserverError: if archive_url is not set.
385 """
386 if archive_url:
Chris Sosa76e44b92013-01-31 20:11:38387 if not archive_url.startswith('gs://'):
388 raise DevServerError("Archive URL isn't from Google Storage.")
389
Chris Sosacde6bf42012-06-01 01:36:39390 return archive_url.rstrip('/')
391 else:
392 raise DevServerError("Must specify an archive_url in the request")
393
Dale Curtisc9aaf3a2011-08-09 22:47:40394 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 19:48:17395 def download(self, **kwargs):
396 """Downloads and archives full/delta payloads from Google Storage.
397
Chris Sosa76e44b92013-01-31 20:11:38398 THIS METHOD IS DEPRECATED: use stage(..., artifacts=...) instead.
Chris Sosa47a7d4e2012-03-28 18:26:55399 This methods downloads artifacts. It may download artifacts in the
400 background in which case a caller should call wait_for_status to get
401 the status of the background artifact downloads. They should use the same
402 args passed to download.
403
Frank Farzanbcb571e2012-01-03 19:48:17404 Args:
405 archive_url: Google Storage URL for the build.
406
407 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01408 http://myhost/download?archive_url=gs://chromeos-image-archive/
409 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 19:48:17410 """
Chris Sosa76e44b92013-01-31 20:11:38411 return self.stage(archive_url=kwargs.get('archive_url'),
412 artifacts='full_payload,test_suites,stateful')
413
Dan Shi59ae7092013-06-04 21:37:27414
Chris Sosa76e44b92013-01-31 20:11:38415 @cherrypy.expose
416 def stage(self, **kwargs):
417 """Downloads and caches the artifacts from Google Storage URL.
418
419 Downloads and caches the artifacts Google Storage URL. Returns once these
420 have been downloaded on the devserver. A call to this will attempt to cache
421 non-specified artifacts in the background for the given from the given URL
422 following the principle of spatial locality. Spatial locality of different
423 artifacts is explicitly defined in the build_artifact module.
424
425 These artifacts will then be available from the static/ sub-directory of
426 the devserver.
427
428 Args:
429 archive_url: Google Storage URL for the build.
430 artifacts: Comma separated list of artifacts to download.
431
432 Example:
433 To download the autotest and test suites tarballs:
434 http://devserver_url:<port>/stage?archive_url=gs://your_url/path&
435 artifacts=autotest,test_suites
436 To download the full update payload:
437 http://devserver_url:<port>/stage?archive_url=gs://your_url/path&
438 artifacts=full_payload
439
440 For both these examples, one could find these artifacts at:
joychened64b222013-06-21 23:39:34441 http://devserver_url:<port>/static/<relative_path>*
Chris Sosa76e44b92013-01-31 20:11:38442
443 Note for this example, relative path is the archive_url stripped of its
444 basename i.e. path/ in the examples above. Specific example:
445
446 gs://chromeos-image-archive/x86-mario-release/R26-3920.0.0
447
448 Will get staged to:
449
joychened64b222013-06-21 23:39:34450 http://devserver_url:<port>/static/x86-mario-release/R26-3920.0.0
Chris Sosa76e44b92013-01-31 20:11:38451 """
Chris Sosacde6bf42012-06-01 01:36:39452 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa76e44b92013-01-31 20:11:38453 artifacts = kwargs.get('artifacts', '')
454 if not artifacts:
455 raise DevServerError('No artifacts specified.')
Chris Sosa47a7d4e2012-03-28 18:26:55456
Dan Shi59ae7092013-06-04 21:37:27457 with DevServerRoot._staging_thread_count_lock:
458 DevServerRoot._staging_thread_count += 1
459 try:
460 downloader.Downloader(updater.static_dir, archive_url).Download(
461 artifacts.split(','))
462 finally:
463 with DevServerRoot._staging_thread_count_lock:
464 DevServerRoot._staging_thread_count -= 1
Chris Sosa76e44b92013-01-31 20:11:38465 return 'Success'
Chris Sosacde6bf42012-06-01 01:36:39466
Dan Shi59ae7092013-06-04 21:37:27467
Chris Sosacde6bf42012-06-01 01:36:39468 @cherrypy.expose
Simran Basi4baad082013-02-14 21:39:18469 def setup_telemetry(self, **kwargs):
470 """Extracts and sets up telemetry
471
472 This method goes through the telemetry deps packages, and stages them on
473 the devserver to be used by the drones and the telemetry tests.
474
475 Args:
476 archive_url: Google Storage URL for the build.
477
478 Returns:
479 Path to the source folder for the telemetry codebase once it is staged.
480 """
481 archive_url = kwargs.get('archive_url')
482 self.stage(archive_url=archive_url, artifacts='autotest')
483
484 build = '/'.join(downloader.Downloader.ParseUrl(archive_url))
485 build_path = os.path.join(updater.static_dir, build)
486 deps_path = os.path.join(build_path, 'autotest/packages')
487 telemetry_path = os.path.join(build_path, TELEMETRY_FOLDER)
488 src_folder = os.path.join(telemetry_path, 'src')
489
490 with self._telemetry_lock_dict.lock(telemetry_path):
491 if os.path.exists(src_folder):
492 # Telemetry is already fully stage return
493 return src_folder
494
495 common_util.MkDirP(telemetry_path)
496
497 # Copy over the required deps tar balls to the telemetry directory.
498 for dep in TELEMETRY_DEPS:
499 dep_path = os.path.join(deps_path, dep)
Simran Basi0d078682013-03-22 23:40:04500 if not os.path.exists(dep_path):
501 # This dep does not exist (could be new), do not extract it.
502 continue
Simran Basi4baad082013-02-14 21:39:18503 try:
504 common_util.ExtractTarball(dep_path, telemetry_path)
505 except common_util.CommonUtilError as e:
506 shutil.rmtree(telemetry_path)
507 raise DevServerError(str(e))
508
509 # By default all the tarballs extract to test_src but some parts of
510 # the telemetry code specifically hardcoded to exist inside of 'src'.
511 test_src = os.path.join(telemetry_path, 'test_src')
512 try:
513 shutil.move(test_src, src_folder)
514 except shutil.Error:
515 # This can occur if src_folder already exists. Remove and retry move.
516 shutil.rmtree(src_folder)
517 raise DevServerError('Failure in telemetry setup for build %s. Appears'
518 ' that the test_src to src move failed.' % build)
519
520 return src_folder
521
522 @cherrypy.expose
Chris Sosacde6bf42012-06-01 01:36:39523 def wait_for_status(self, **kwargs):
524 """Waits for background artifacts to be downloaded from Google Storage.
525
Chris Sosa76e44b92013-01-31 20:11:38526 THIS METHOD IS DEPRECATED: use stage(..., artifacts=...) instead.
Chris Sosacde6bf42012-06-01 01:36:39527 Args:
528 archive_url: Google Storage URL for the build.
529
530 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01531 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
532 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-06-01 01:36:39533 """
Chris Sosa76e44b92013-01-31 20:11:38534 return self.stage(archive_url=kwargs.get('archive_url'),
535 artifacts='full_payload,test_suites,autotest,stateful')
Chris Sosa47a7d4e2012-03-28 18:26:55536
537 @cherrypy.expose
Chris Masone816e38c2012-05-02 19:22:36538 def stage_debug(self, **kwargs):
539 """Downloads and stages debug symbol payloads from Google Storage.
540
Chris Sosa76e44b92013-01-31 20:11:38541 THIS METHOD IS DEPRECATED: use stage(..., artifacts=...) instead.
542 This methods downloads the debug symbol build artifact
543 synchronously, and then stages it for use by symbolicate_dump.
Chris Masone816e38c2012-05-02 19:22:36544
545 Args:
546 archive_url: Google Storage URL for the build.
547
548 Example URL:
Gilad Arnoldf8f769f2012-09-24 15:43:01549 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
550 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 19:22:36551 """
Chris Sosa76e44b92013-01-31 20:11:38552 return self.stage(archive_url=kwargs.get('archive_url'),
553 artifacts='symbols')
Chris Masone816e38c2012-05-02 19:22:36554
555 @cherrypy.expose
Chris Sosa76e44b92013-01-31 20:11:38556 def symbolicate_dump(self, minidump, **kwargs):
Chris Masone816e38c2012-05-02 19:22:36557 """Symbolicates a minidump using pre-downloaded symbols, returns it.
558
559 Callers will need to POST to this URL with a body of MIME-type
560 "multipart/form-data".
561 The body should include a single argument, 'minidump', containing the
562 binary-formatted minidump to symbolicate.
563
Chris Masone816e38c2012-05-02 19:22:36564 Args:
Chris Sosa76e44b92013-01-31 20:11:38565 archive_url: Google Storage URL for the build.
Chris Masone816e38c2012-05-02 19:22:36566 minidump: The binary minidump file to symbolicate.
567 """
Chris Sosa76e44b92013-01-31 20:11:38568 # Ensure the symbols have been staged.
569 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
570 if self.stage(archive_url=archive_url, artifacts='symbols') != 'Success':
571 raise DevServerError('Failed to stage symbols for %s' % archive_url)
572
Chris Masone816e38c2012-05-02 19:22:36573 to_return = ''
574 with tempfile.NamedTemporaryFile() as local:
575 while True:
576 data = minidump.file.read(8192)
577 if not data:
578 break
579 local.write(data)
Chris Sosa76e44b92013-01-31 20:11:38580
Chris Masone816e38c2012-05-02 19:22:36581 local.flush()
Chris Sosa76e44b92013-01-31 20:11:38582
583 symbols_directory = os.path.join(downloader.Downloader.GetBuildDir(
584 updater.static_dir, archive_url), 'debug', 'breakpad')
585
586 stackwalk = subprocess.Popen(
587 ['minidump_stackwalk', local.name, symbols_directory],
588 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
589
Chris Masone816e38c2012-05-02 19:22:36590 to_return, error_text = stackwalk.communicate()
591 if stackwalk.returncode != 0:
592 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
593 error_text, stackwalk.returncode))
594
595 return to_return
596
597 @cherrypy.expose
Scott Zawalski16954532012-03-20 19:31:36598 def latestbuild(self, **params):
599 """Return a string representing the latest build for a given target.
600
601 Args:
602 target: The build target, typically a combination of the board and the
603 type of build e.g. x86-mario-release.
604 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
605 provided the latest RXX build will be returned.
606 Returns:
607 A string representation of the latest build if one exists, i.e.
608 R19-1993.0.0-a1-b1480.
609 An empty string if no latest could be found.
610 """
611 if not params:
612 return _PrintDocStringAsHTML(self.latestbuild)
613
614 if 'target' not in params:
615 raise cherrypy.HTTPError('500 Internal Server Error',
616 'Error: target= is required!')
617 try:
Gilad Arnoldc65330c2012-09-20 22:17:48618 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 19:31:36619 updater.static_dir, params['target'],
620 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 17:05:01621 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 19:31:36622 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
623
624 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 20:12:42625 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 22:17:28626 """Return a control file or a list of all known control files.
627
628 Example URL:
629 To List all control files:
beepsbd337242013-07-10 05:44:06630 http://dev-server/controlfiles?suite_name=&build=daisy_spring-release/R29-4279.0.0
631 To List all control files for, say, the bvt suite:
632 http://dev-server/controlfiles?suite_name=bvt&build=daisy_spring-release/R29-4279.0.0
Scott Zawalski4647ce62012-01-03 22:17:28633 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 20:12:42634 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 22:17:28635
636 Args:
Scott Zawalski84a39c92012-01-13 20:12:42637 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 22:17:28638 control_path: If you want the contents of a control file set this
639 to the path. E.g. client/site_tests/sleeptest/control
640 Optional, if not provided return a list of control files is returned.
beepsbd337242013-07-10 05:44:06641 suite_name: If control_path is not specified but a suite_name is
642 specified, list the control files belonging to that suite instead of
643 all control files. The empty string for suite_name will list all control
644 files for the build.
Scott Zawalski4647ce62012-01-03 22:17:28645 Returns:
646 Contents of a control file if control_path is provided.
647 A list of control files if no control_path is provided.
648 """
Scott Zawalski4647ce62012-01-03 22:17:28649 if not params:
650 return _PrintDocStringAsHTML(self.controlfiles)
651
Scott Zawalski84a39c92012-01-13 20:12:42652 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 22:17:28653 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 20:12:42654 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 22:17:28655
656 if 'control_path' not in params:
beepsbd337242013-07-10 05:44:06657 if 'suite_name' in params and params['suite_name']:
658 return common_util.GetControlFileListForSuite(
659 updater.static_dir, params['build'], params['suite_name'])
660 else:
661 return common_util.GetControlFileList(
662 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 22:17:28663 else:
Gilad Arnoldc65330c2012-09-20 22:17:48664 return common_util.GetControlFile(
665 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-13 02:39:18666
667 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 17:49:40668 def stage_images(self, **kwargs):
669 """Downloads and stages a Chrome OS image from Google Storage.
670
Chris Sosa76e44b92013-01-31 20:11:38671 THIS METHOD IS DEPRECATED: use stage(..., artifacts=...) instead.
Gilad Arnold6f99b982012-09-12 17:49:40672 This method downloads a zipped archive from a specified GS location, then
673 extracts and stages the specified list of images and stages them under
Chris Sosa76e44b92013-01-31 20:11:38674 static/BOARD/BUILD/. Download is synchronous.
Gilad Arnold6f99b982012-09-12 17:49:40675
676 Args:
677 archive_url: Google Storage URL for the build.
678 image_types: comma-separated list of images to download, may include
679 'test', 'recovery', and 'base'
680
681 Example URL:
682 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
683 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
684 """
Gilad Arnold6f99b982012-09-12 17:49:40685 image_types = kwargs.get('image_types').split(',')
Chris Sosa76e44b92013-01-31 20:11:38686 image_types_list = [image + '_image' for image in image_types]
687 self.stage(archive_url=kwargs.get('archive_url'), artifacts=','.join(
688 image_types_list))
Gilad Arnold6f99b982012-09-12 17:49:40689
690 @cherrypy.expose
joycheneaf4cfc2013-07-02 15:38:57691 def xbuddy(self, *args, **kwargs):
692 """The full xBuddy call, returns resource specified by path_parts.
joychen3cb228e2013-06-12 19:13:13693
694 Args:
joycheneaf4cfc2013-07-02 15:38:57695 path_parts: the path following xbuddy/ in the call url is split into the
696 components of the path.
697 The path can be understood as a build_id/artifact, build_id is
698 composed of "board/version"
699
700 path_parts[0], the board, is the familiar board name, optionally
701 suffixed.
702 path_parts[1], the version, can be the google storage version
703 number, and may also be any of a number of xBuddy defined version
704 aliases that will be translated into the latest built image that
705 fits the description. defaults to latest.
706 path_parts[2], the artifact, is one of a number of image or artifact
707 aliases used by xbuddy, defined in xbuddy:ALIASES. Defaults to test
708
709 Kwargs:
joychen3cb228e2013-06-12 19:13:13710 return_dir: {true|false}
711 if set to true, returns the url to the update.gz
712 instead.
713
714 Example URL:
joycheneaf4cfc2013-07-02 15:38:57715 http://host:port/xbuddy/x86-generic/R26-4000.0.0/test
joychen3cb228e2013-06-12 19:13:13716 or
joycheneaf4cfc2013-07-02 15:38:57717 http://host:port/xbuddy/x86-generic/R26-4000.0.0/test?return_dir=true
joychen3cb228e2013-06-12 19:13:13718
719 Returns:
720 A redirect to the image or update file on the devserver.
721 e.g. http://host:port/static/archive/x86-generic-release/
722 R26-4000.0.0/chromium-test-image.bin
723 or if return_dir is True, return path to the folder where
724 image or update file is
725 http://host:port/static/x86-generic-release/R26-4000.0.0/
726 """
727 boolean_string = kwargs.get('return_dir')
728 return_dir = xbuddy.XBuddy.ParseBoolean(boolean_string)
joycheneaf4cfc2013-07-02 15:38:57729 return_url = self._xbuddy.Get(args,
joychen3cb228e2013-06-12 19:13:13730 return_dir)
731 if return_dir:
joycheneaf4cfc2013-07-02 15:38:57732 directory = os.path.join(cherrypy.request.base, return_url)
733 _Log("Directory requested, returning: %s", directory)
734 return directory
joychen3cb228e2013-06-12 19:13:13735 else:
joycheneaf4cfc2013-07-02 15:38:57736 return_url = '/' + return_url
737 _Log("Payload requested, returning: %s", return_url)
joychen3cb228e2013-06-12 19:13:13738 raise cherrypy.HTTPRedirect(return_url, 302)
739
740 @cherrypy.expose
741 def xbuddy_list(self):
742 """Lists the currently available images & time since last access.
743
744 @return: A string representation of a list of tuples
745 [(build_id, time since last access),...]
746 """
747 return self._xbuddy.List()
748
749 @cherrypy.expose
750 def xbuddy_capacity(self):
751 """Returns the number of images cached by xBuddy.
752
753 @return: Capacity of this devserver.
754 """
755 return self._xbuddy.Capacity()
756
757 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01758 def index(self):
Gilad Arnoldf8f769f2012-09-24 15:43:01759 """Presents a welcome message and documentation links."""
Gilad Arnoldf8f769f2012-09-24 15:43:01760 return ('Welcome to the Dev Server!<br>\n'
761 '<br>\n'
762 'Here are the available methods, click for documentation:<br>\n'
763 '<br>\n'
764 '%s' %
765 '<br>\n'.join(
766 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 18:52:38767 for name in _FindExposedMethods(
768 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 15:43:01769
770 @cherrypy.expose
771 def doc(self, *args):
772 """Shows the documentation for available methods / URLs.
773
774 Example:
775 http://myhost/doc/update
776 """
Gilad Arnoldd5ebaaa2012-10-02 18:52:38777 name = '/'.join(args)
778 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 15:43:01779 if not method:
780 raise DevServerError("No exposed method named `%s'" % name)
781 if not method.__doc__:
782 raise DevServerError("No documentation for exposed method `%s'" % name)
783 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-12 02:49:01784
Dale Curtisc9aaf3a2011-08-09 22:47:40785 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01786 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 15:43:01787 """Handles an update check from a Chrome OS client.
788
789 The HTTP request should contain the standard Omaha-style XML blob. The URL
790 line may contain an additional intermediate path to the update payload.
791
792 Example:
793 http://myhost/update/optional/path/to/payload
794 """
joychen346531c2013-07-24 23:55:56795 if len(args) > 0 and args[0] == 'xbuddy':
796 # Interpret the rest of the path as an xbuddy path
797 label, found = self._xbuddy.Translate(args[1:] + ('full_payload',))
798 if not found:
799 _Log("Update payload not found for %s, xBuddy looking it up.", label)
800 else:
801 label = '/'.join(args)
802
803 _Log('Update label: %s', label)
Gilad Arnold286a0062012-01-12 21:47:02804 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-12 02:49:01805 data = cherrypy.request.rfile.read(body_length)
806 return updater.HandleUpdatePing(data, label)
807
Chris Sosa0356d3b2010-09-16 22:46:22808
Dan Shif5ce2de2013-04-25 23:06:32809 @cherrypy.expose
810 def check_health(self):
811 """Collect the health status of devserver to see if it's ready for staging.
812
813 @return: A JSON dictionary containing all or some of the following fields:
Dan Shi59ae7092013-06-04 21:37:27814 free_disk (int): free disk space in GB
815 staging_thread_count (int): number of devserver threads currently
816 staging an image
Dan Shif5ce2de2013-04-25 23:06:32817 """
818 # Get free disk space.
819 stat = os.statvfs(updater.static_dir)
820 free_disk = stat.f_bsize * stat.f_bavail / 1000000000
821
822 return json.dumps({
823 'free_disk': free_disk,
Dan Shi59ae7092013-06-04 21:37:27824 'staging_thread_count': DevServerRoot._staging_thread_count,
Dan Shif5ce2de2013-04-25 23:06:32825 })
826
827
Chris Sosadbc20082012-12-10 21:39:11828def _CleanCache(cache_dir, wipe):
829 """Wipes any excess cached items in the cache_dir.
830
831 Args:
832 cache_dir: the directory we are wiping from.
833 wipe: If True, wipe all the contents -- not just the excess.
834 """
835 if wipe:
836 # Clear the cache and exit on error.
837 cmd = 'rm -rf %s/*' % cache_dir
838 if os.system(cmd) != 0:
839 _Log('Failed to clear the cache with %s' % cmd)
840 sys.exit(1)
841 else:
842 # Clear all but the last N cached updates
843 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
844 (cache_dir, CACHED_ENTRIES))
845 if os.system(cmd) != 0:
846 _Log('Failed to clean up old delta cache files with %s' % cmd)
847 sys.exit(1)
848
849
Chris Sosa3ae4dc12013-03-29 18:47:00850def _AddTestingOptions(parser):
851 group = optparse.OptionGroup(
852 parser, 'Advanced Testing Options', 'These are used by test scripts and '
853 'developers writing integration tests utilizing the devserver. They are '
854 'not intended to be really used outside the scope of someone '
855 'knowledgable about the test.')
856 group.add_option('--exit',
857 action='store_true',
858 help='do not start the server (yet pregenerate/clear cache)')
859 group.add_option('--host_log',
860 action='store_true', default=False,
861 help='record history of host update events (/api/hostlog)')
862 group.add_option('--max_updates',
863 metavar='NUM', default= -1, type='int',
864 help='maximum number of update checks handled positively '
865 '(default: unlimited)')
866 group.add_option('--private_key',
867 metavar='PATH', default=None,
868 help='path to the private key in pem format. If this is set '
869 'the devserver will generate update payloads that are '
870 'signed with this key.')
871 group.add_option('--proxy_port',
872 metavar='PORT', default=None, type='int',
873 help='port to have the client connect to -- basically the '
874 'devserver lies to the update to tell it to get the payload '
875 'from a different port that will proxy the request back to '
876 'the devserver. The proxy must be managed outside the '
877 'devserver.')
878 group.add_option('--remote_payload',
879 action='store_true', default=False,
880 help='Payload is being served from a remote machine')
881 group.add_option('-u', '--urlbase',
882 metavar='URL',
883 help='base URL for update images, other than the '
884 'devserver. Use in conjunction with remote_payload.')
885 parser.add_option_group(group)
886
887
888def _AddUpdateOptions(parser):
889 group = optparse.OptionGroup(
890 parser, 'Autoupdate Options', 'These options can be used to change '
891 'how the devserver either generates or serve update payloads. Please '
892 'note that all of these option affect how a payload is generated and so '
893 'do not work in archive-only mode.')
894 group.add_option('--board',
895 help='By default the devserver will create an update '
896 'payload from the latest image built for the board '
897 'a device that is requesting an update has. When we '
898 'pre-generate an update (see below) and we do not specify '
899 'another update_type option like image or payload, the '
900 'devserver needs to know the board to generate the latest '
901 'image for. This is that board.')
902 group.add_option('--critical_update',
903 action='store_true', default=False,
904 help='Present update payload as critical')
905 group.add_option('--for_vm',
906 dest='vm', action='store_true',
907 help='DEPRECATED: see no_patch_kernel.')
908 group.add_option('--image',
909 metavar='FILE',
910 help='Generate and serve an update using this image to any '
911 'device that requests an update.')
912 group.add_option('--no_patch_kernel',
913 dest='patch_kernel', action='store_false', default=True,
914 help='When generating an update payload, do not patch the '
915 'kernel with kernel verification blob from the stateful '
916 'partition.')
917 group.add_option('--payload',
918 metavar='PATH',
919 help='use the update payload from specified directory '
920 '(update.gz).')
921 group.add_option('-p', '--pregenerate_update',
922 action='store_true', default=False,
923 help='pre-generate the update payload before accepting '
924 'update requests. Useful to help debug payload generation '
925 'issues quickly. Also if an update payload will take a '
926 'long time to generate, a client may timeout if you do not'
927 'pregenerate the update.')
928 group.add_option('--src_image',
929 metavar='PATH', default='',
930 help='If specified, delta updates will be generated using '
931 'this image as the source image. Delta updates are when '
932 'you are updating from a "source image" to a another '
933 'image.')
934 parser.add_option_group(group)
935
936
937def _AddProductionOptions(parser):
938 group = optparse.OptionGroup(
939 parser, 'Advanced Server Options', 'These options can be used to changed '
940 'for advanced server behavior.')
Chris Sosa3ae4dc12013-03-29 18:47:00941 group.add_option('--archive_dir',
942 metavar='PATH',
joychened64b222013-06-21 23:39:34943 help='To be deprecated.')
Chris Sosa3ae4dc12013-03-29 18:47:00944 group.add_option('--clear_cache',
945 action='store_true', default=False,
946 help='At startup, removes all cached entries from the'
947 'devserver\'s cache.')
948 group.add_option('--logfile',
949 metavar='PATH',
950 help='log output to this file instead of stdout')
951 group.add_option('--production',
952 action='store_true', default=False,
953 help='have the devserver use production values when '
954 'starting up. This includes using more threads and '
955 'performing less logging.')
956 parser.add_option_group(group)
957
958
J. Richard Barnette3d977b82013-04-23 18:05:19959def _MakeLogHandler(logfile):
960 """Create a LogHandler instance used to log all messages."""
961 hdlr_cls = handlers.TimedRotatingFileHandler
962 hdlr = hdlr_cls(logfile, when=_LOG_ROTATION_TIME,
963 backupCount=_LOG_ROTATION_BACKUP)
964 # The cherrypy documentation says to use the _cplogging module for
965 # this, even though it's named as a private module.
966 # pylint: disable=W0212
967 hdlr.setFormatter(cherrypy._cplogging.logfmt)
968 return hdlr
969
970
Chris Sosacde6bf42012-06-01 01:36:39971def main():
Chris Sosa3ae4dc12013-03-29 18:47:00972 usage = '\n\n'.join(['usage: %prog [options]', __doc__])
Gilad Arnold286a0062012-01-12 21:47:02973 parser = optparse.OptionParser(usage=usage)
joychened64b222013-06-21 23:39:34974
975 # get directory that the devserver is run from
976 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
977 default_archive_dir = '%s/static' % devserver_dir
978 parser.add_option('--static_dir',
Gilad Arnold9714d9b2012-10-04 17:09:42979 metavar='PATH',
joychened64b222013-06-21 23:39:34980 default=default_archive_dir,
981 help='writable static directory')
Gilad Arnold9714d9b2012-10-04 17:09:42982 parser.add_option('--port',
983 default=8080, type='int',
984 help='port for the dev server to use (default: 8080)')
Gilad Arnold9714d9b2012-10-04 17:09:42985 parser.add_option('-t', '--test_image',
986 action='store_true',
Chris Sosa3ae4dc12013-03-29 18:47:00987 help='If set, look for the chromiumos_test_image.bin file '
988 'when generating update payloads rather than the '
989 'chromiumos_image.bin which is the default.')
joychen5260b9a2013-07-16 21:48:01990 parser.add_option('-x', '--xbuddy_manage_builds',
991 action='store_true',
992 default=False,
993 help='If set, allow xbuddy to manage images in'
994 'build/images.')
Chris Sosa3ae4dc12013-03-29 18:47:00995 _AddProductionOptions(parser)
996 _AddUpdateOptions(parser)
997 _AddTestingOptions(parser)
Chris Sosa7c931362010-10-12 02:49:01998 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:23999
J. Richard Barnette3d977b82013-04-23 18:05:191000 # Handle options that must be set globally in cherrypy. Do this
1001 # work up front, because calls to _Log() below depend on this
1002 # initialization.
1003 if options.production:
1004 cherrypy.config.update({'environment': 'production'})
1005 if not options.logfile:
1006 cherrypy.config.update({'log.screen': True})
1007 else:
1008 cherrypy.config.update({'log.error_file': '',
1009 'log.access_file': ''})
1010 hdlr = _MakeLogHandler(options.logfile)
1011 # Pylint can't seem to process these two calls properly
1012 # pylint: disable=E1101
1013 cherrypy.log.access_log.addHandler(hdlr)
1014 cherrypy.log.error_log.addHandler(hdlr)
1015 # pylint: enable=E1101
1016
Chris Sosa7c931362010-10-12 02:49:011017 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:221018 serve_only = False
1019
J. Richard Barnette3d977b82013-04-23 18:05:191020 # TODO(sosa): Remove after deprecation.
Chris Sosa3ae4dc12013-03-29 18:47:001021 if options.vm:
1022 options.patch_kernel = False
1023
joychened64b222013-06-21 23:39:341024 # set static_dir, from which everything will be served
Sean O'Connor14b6a0a2010-03-21 06:23:481025 if options.archive_dir:
joychened64b222013-06-21 23:39:341026 # TODO(joyc) To be deprecated
Zdenek Behan608f46c2011-02-18 23:47:161027 archive_dir = options.archive_dir
1028 if not os.path.isabs(archive_dir):
joychened64b222013-06-21 23:39:341029 archive_dir = os.path.join(devserver_dir, archive_dir)
1030 options.static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 22:46:221031 serve_only = True
joychened64b222013-06-21 23:39:341032 else:
1033 options.static_dir = os.path.realpath(options.static_dir)
Chris Sosa0356d3b2010-09-16 22:46:221034
joychened64b222013-06-21 23:39:341035 cache_dir = os.path.join(options.static_dir, 'cache')
J. Richard Barnette3d977b82013-04-23 18:05:191036 # If our devserver is only supposed to serve payloads, we shouldn't be
1037 # mucking with the cache at all. If the devserver hadn't previously
1038 # generated a cache and is expected, the caller is using it wrong.
Chris Sosadbc20082012-12-10 21:39:111039 if serve_only:
1040 # Extra check to make sure we're not being called incorrectly.
1041 if (options.clear_cache or options.exit or options.pregenerate_update or
1042 options.board or options.image):
1043 parser.error('Incompatible flags detected for serve_only mode.')
Chris Sosadbc20082012-12-10 21:39:111044 elif os.path.exists(cache_dir):
1045 _CleanCache(cache_dir, options.clear_cache)
Chris Sosa6b8c3742011-01-31 20:12:171046 else:
1047 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:141048
Chris Sosadbc20082012-12-10 21:39:111049 _Log('Using cache directory %s' % cache_dir)
Gilad Arnoldc65330c2012-09-20 22:17:481050 _Log('Source root is %s' % root_dir)
joychened64b222013-06-21 23:39:341051 _Log('Serving from %s' % options.static_dir)
[email protected]21a5ca32009-11-04 18:23:231052
Chris Sosa6a3697f2013-01-30 00:44:431053 # We allow global use here to share with cherrypy classes.
1054 # pylint: disable=W0603
Chris Sosacde6bf42012-06-01 01:36:391055 global updater
Andrew de los Reyes52620802010-04-12 20:40:071056 updater = autoupdate.Autoupdate(
1057 root_dir=root_dir,
joychened64b222013-06-21 23:39:341058 static_dir=options.static_dir,
Chris Sosa0356d3b2010-09-16 22:46:221059 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 20:40:071060 urlbase=options.urlbase,
1061 test_image=options.test_image,
Chris Sosa5d342a22010-09-28 23:54:411062 forced_image=options.image,
Gilad Arnold0c9c8602012-10-03 06:58:581063 payload_path=options.payload,
Don Garrett0ad09372010-12-07 00:20:301064 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:371065 src_image=options.src_image,
Chris Sosa3ae4dc12013-03-29 18:47:001066 patch_kernel=options.patch_kernel,
Chris Sosa08d55a22011-01-20 00:08:021067 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:221068 copy_to_static_root=not options.exit,
1069 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 17:36:321070 critical_update=options.critical_update,
Gilad Arnold0c9c8602012-10-03 06:58:581071 remote_payload=options.remote_payload,
Gilad Arnolda564b4b2012-10-04 17:32:441072 max_updates=options.max_updates,
Gilad Arnold8318eac2012-10-04 19:52:231073 host_log=options.host_log,
Chris Sosa0f1ec842011-02-15 00:33:221074 )
Chris Sosa7c931362010-10-12 02:49:011075
Chris Sosa6a3697f2013-01-30 00:44:431076 if options.pregenerate_update:
1077 updater.PreGenerateUpdate()
Chris Sosa0356d3b2010-09-16 22:46:221078
J. Richard Barnette3d977b82013-04-23 18:05:191079 if options.exit:
1080 return
Chris Sosa2f1c41e2012-07-10 21:32:331081
joychen5260b9a2013-07-16 21:48:011082 _xbuddy = xbuddy.XBuddy(options.xbuddy_manage_builds,
1083 root_dir=root_dir,
1084 static_dir=options.static_dir)
joychen3cb228e2013-06-12 19:13:131085 dev_server = DevServerRoot(_xbuddy)
1086
1087 cherrypy.quickstart(dev_server, config=_GetConfig(options))
Chris Sosacde6bf42012-06-01 01:36:391088
1089
1090if __name__ == '__main__':
1091 main()