blob: 7d8fd55f0dad1aa598fc7e201b196711d64e8bb4 [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
joychen84d13772013-08-06 16:17:2329a particular package from a developer's chroot onto a requesting device.
Chris Sosa3ae4dc12013-03-29 18:47:0030
31For example:
32gmerge gmerge -d <devserver_url>
33
34devserver will see if a newer package of gmerge is available. If gmerge is
35cros_work'd on, it will re-build gmerge. After this, gmerge will install that
36version of gmerge that the devserver just created/found.
37
38For autoupdates, there are many more advanced options that can help specify
39how to update and which payload to give to a requester.
40"""
41
Chris Sosa7c931362010-10-12 02:49:0142
Gilad Arnold55a2a372012-10-02 16:46:3243import json
Sean O'Connor14b6a0a2010-03-21 06:23:4844import optparse
[email protected]ded22402009-10-26 22:36:2145import os
Scott Zawalski4647ce62012-01-03 22:17:2846import re
Simran Basi4baad082013-02-14 21:39:1847import shutil
Mandeep Singh Baines38dcdda2012-12-08 01:55:3348import socket
Chris Masone816e38c2012-05-02 19:22:3649import subprocess
J. Richard Barnette3d977b82013-04-23 18:05:1950import sys
Chris Masone816e38c2012-05-02 19:22:3651import tempfile
Dan Shi59ae7092013-06-04 21:37:2752import threading
Gilad Arnoldd5ebaaa2012-10-02 18:52:3853import types
J. Richard Barnette3d977b82013-04-23 18:05:1954from logging import handlers
55
56import cherrypy
Chris Sosa855b8932013-08-21 20:24:5557from cherrypy import _cplogging as cplogging
58from cherrypy.process import plugins
[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."""
Chris Sosa47a7d4e2012-03-28 18:26:5594
95
Don Garrett8ccab732013-08-30 16:13:5996class DevServerHTTPError(cherrypy.HTTPError):
beepsd76c6092013-08-29 05:23:3097 """Exception class to log the HTTPResponse before routing it to cherrypy."""
98 def __init__(self, status, message):
99 """
100 @param status: HTTPResponse status.
101 @param message: Message associated with the response.
102 """
Don Garrett8ccab732013-08-30 16:13:59103 cherrypy.HTTPError.__init__(self, status, message)
beepsd76c6092013-08-29 05:23:30104 _Log('HTTPError status: %s message: %s', status, message)
beepsd76c6092013-08-29 05:23:30105
106
Scott Zawalski4647ce62012-01-03 22:17:28107def _LeadingWhiteSpaceCount(string):
108 """Count the amount of leading whitespace in a string.
109
110 Args:
111 string: The string to count leading whitespace in.
112 Returns:
113 number of white space chars before characters start.
114 """
115 matched = re.match('^\s+', string)
116 if matched:
117 return len(matched.group())
118
119 return 0
120
121
122def _PrintDocStringAsHTML(func):
123 """Make a functions docstring somewhat HTML style.
124
125 Args:
126 func: The function to return the docstring from.
127 Returns:
128 A string that is somewhat formated for a web browser.
129 """
130 # TODO(scottz): Make this parse Args/Returns in a prettier way.
131 # Arguments could be bolded and indented etc.
132 html_doc = []
133 for line in func.__doc__.splitlines():
134 leading_space = _LeadingWhiteSpaceCount(line)
135 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 18:26:55136 line = '&nbsp;' * leading_space + line
Scott Zawalski4647ce62012-01-03 22:17:28137
138 html_doc.append('<BR>%s' % line)
139
140 return '\n'.join(html_doc)
141
142
Chris Sosa7c931362010-10-12 02:49:01143def _GetConfig(options):
144 """Returns the configuration for the devserver."""
Mandeep Singh Baines38dcdda2012-12-08 01:55:33145
146 # On a system with IPv6 not compiled into the kernel,
147 # AF_INET6 sockets will return a socket.error exception.
148 # On such systems, fall-back to IPv4.
149 socket_host = '::'
150 try:
151 socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
152 except socket.error:
153 socket_host = '0.0.0.0'
154
Chris Sosa7c931362010-10-12 02:49:01155 base_config = { 'global':
156 { 'server.log_request_headers': True,
157 'server.protocol_version': 'HTTP/1.1',
Mandeep Singh Baines38dcdda2012-12-08 01:55:33158 'server.socket_host': socket_host,
Chris Sosa7c931362010-10-12 02:49:01159 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:54160 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 22:44:46161 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 18:28:05162 'server.socket_timeout': 60,
joychenecc02aa2013-07-18 01:27:35163 'server.thread_pool': 2,
Chris Sosa7c931362010-10-12 02:49:01164 },
Dale Curtisc9aaf3a2011-08-09 22:47:40165 '/api':
166 {
167 # Gets rid of cherrypy parsing post file for args.
168 'request.process_request_body': False,
169 },
Chris Sosaa1ef0102010-10-21 23:22:35170 '/build':
171 {
172 'response.timeout': 100000,
173 },
Chris Sosa7c931362010-10-12 02:49:01174 '/update':
175 {
176 # Gets rid of cherrypy parsing post file for args.
177 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:51178 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01179 },
180 # Sets up the static dir for file hosting.
181 '/static':
joychened64b222013-06-21 23:39:34182 { 'tools.staticdir.dir': options.static_dir,
Chris Sosa7c931362010-10-12 02:49:01183 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:51184 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01185 },
186 }
Chris Sosa5f118ef2012-07-12 18:37:50187 if options.production:
Alex Miller93beca52013-07-31 02:25:09188 base_config['global'].update({'server.thread_pool': 150})
Scott Zawalski1c5e7cd2012-02-27 18:12:52189
Chris Sosa7c931362010-10-12 02:49:01190 return base_config
[email protected]64244662009-11-12 00:52:08191
Darin Petkove17164a2010-08-11 20:24:41192
Gilad Arnoldd5ebaaa2012-10-02 18:52:38193def _GetRecursiveMemberObject(root, member_list):
194 """Returns an object corresponding to a nested member list.
195
196 Args:
197 root: the root object to search
198 member_list: list of nested members to search
199 Returns:
200 An object corresponding to the member name list; None otherwise.
201 """
202 for member in member_list:
203 next_root = root.__class__.__dict__.get(member)
204 if not next_root:
205 return None
206 root = next_root
207 return root
208
209
210def _IsExposed(name):
211 """Returns True iff |name| has an `exposed' attribute and it is set."""
212 return hasattr(name, 'exposed') and name.exposed
213
214
Gilad Arnold748c8322012-10-12 16:51:35215def _GetExposedMethod(root, nested_member, ignored=None):
Gilad Arnoldd5ebaaa2012-10-02 18:52:38216 """Returns a CherryPy-exposed method, if such exists.
217
218 Args:
219 root: the root object for searching
220 nested_member: a slash-joined path to the nested member
221 ignored: method paths to be ignored
222 Returns:
223 A function object corresponding to the path defined by |member_list| from
224 the |root| object, if the function is exposed and not ignored; None
225 otherwise.
226 """
Gilad Arnold748c8322012-10-12 16:51:35227 method = (not (ignored and nested_member in ignored) and
Gilad Arnoldd5ebaaa2012-10-02 18:52:38228 _GetRecursiveMemberObject(root, nested_member.split('/')))
229 if (method and type(method) == types.FunctionType and _IsExposed(method)):
230 return method
231
232
Gilad Arnold748c8322012-10-12 16:51:35233def _FindExposedMethods(root, prefix, unlisted=None):
Gilad Arnoldd5ebaaa2012-10-02 18:52:38234 """Finds exposed CherryPy methods.
235
236 Args:
237 root: the root object for searching
238 prefix: slash-joined chain of members leading to current object
239 unlisted: URLs to be excluded regardless of their exposed status
240 Returns:
241 List of exposed URLs that are not unlisted.
242 """
243 method_list = []
244 for member in sorted(root.__class__.__dict__.keys()):
245 prefixed_member = prefix + '/' + member if prefix else member
Gilad Arnold748c8322012-10-12 16:51:35246 if unlisted and prefixed_member in unlisted:
Gilad Arnoldd5ebaaa2012-10-02 18:52:38247 continue
248 member_obj = root.__class__.__dict__[member]
249 if _IsExposed(member_obj):
250 if type(member_obj) == types.FunctionType:
251 method_list.append(prefixed_member)
252 else:
253 method_list += _FindExposedMethods(
254 member_obj, prefixed_member, unlisted)
255 return method_list
256
257
Dale Curtisc9aaf3a2011-08-09 22:47:40258class ApiRoot(object):
259 """RESTful API for Dev Server information."""
260 exposed = True
261
262 @cherrypy.expose
263 def hostinfo(self, ip):
264 """Returns a JSON dictionary containing information about the given ip.
265
Gilad Arnold1b908392012-10-05 18:36:27266 Args:
267 ip: address of host whose info is requested
268 Returns:
269 A JSON dictionary containing all or some of the following fields:
270 last_event_type (int): last update event type received
271 last_event_status (int): last update event status received
272 last_known_version (string): last known version reported in update ping
273 forced_update_label (string): update label to force next update ping to
274 use, set by setnextupdate
275 See the OmahaEvent class in update_engine/omaha_request_action.h for
276 event type and status code definitions. If the ip does not exist an empty
277 string is returned.
Dale Curtisc9aaf3a2011-08-09 22:47:40278
Gilad Arnold1b908392012-10-05 18:36:27279 Example URL:
280 http://myhost/api/hostinfo?ip=192.168.1.5
281 """
Dale Curtisc9aaf3a2011-08-09 22:47:40282 return updater.HandleHostInfoPing(ip)
283
284 @cherrypy.expose
Gilad Arnold286a0062012-01-12 21:47:02285 def hostlog(self, ip):
Gilad Arnold1b908392012-10-05 18:36:27286 """Returns a JSON object containing a log of host event.
287
288 Args:
289 ip: address of host whose event log is requested, or `all'
290 Returns:
291 A JSON encoded list (log) of dictionaries (events), each of which
292 containing a `timestamp' and other event fields, as described under
293 /api/hostinfo.
294
295 Example URL:
296 http://myhost/api/hostlog?ip=192.168.1.5
297 """
Gilad Arnold286a0062012-01-12 21:47:02298 return updater.HandleHostLogPing(ip)
299
300 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 22:47:40301 def setnextupdate(self, ip):
302 """Allows the response to the next update ping from a host to be set.
303
304 Takes the IP of the host and an update label as normally provided to the
Gilad Arnold1b908392012-10-05 18:36:27305 /update command.
306 """
Dale Curtisc9aaf3a2011-08-09 22:47:40307 body_length = int(cherrypy.request.headers['Content-Length'])
308 label = cherrypy.request.rfile.read(body_length)
309
310 if label:
311 label = label.strip()
312 if label:
313 return updater.HandleSetUpdatePing(ip, label)
beepsd76c6092013-08-29 05:23:30314 raise DevServerHTTPError(400, 'No label provided.')
Dale Curtisc9aaf3a2011-08-09 22:47:40315
316
Gilad Arnold55a2a372012-10-02 16:46:32317 @cherrypy.expose
318 def fileinfo(self, *path_args):
319 """Returns information about a given staged file.
320
321 Args:
322 path_args: path to the file inside the server's static staging directory
323 Returns:
324 A JSON encoded dictionary with information about the said file, which may
325 contain the following keys/values:
Gilad Arnold1b908392012-10-05 18:36:27326 size (int): the file size in bytes
327 sha1 (string): a base64 encoded SHA1 hash
328 sha256 (string): a base64 encoded SHA256 hash
329
330 Example URL:
331 http://myhost/api/fileinfo/some/path/to/file
Gilad Arnold55a2a372012-10-02 16:46:32332 """
333 file_path = os.path.join(updater.static_dir, *path_args)
334 if not os.path.exists(file_path):
335 raise DevServerError('file not found: %s' % file_path)
336 try:
337 file_size = os.path.getsize(file_path)
338 file_sha1 = common_util.GetFileSha1(file_path)
339 file_sha256 = common_util.GetFileSha256(file_path)
340 except os.error, e:
341 raise DevServerError('failed to get info for file %s: %s' %
Gilad Arnolde74b3812013-04-22 18:27:38342 (file_path, e))
343
344 is_delta = autoupdate.Autoupdate.IsDeltaFormatFile(file_path)
345
346 return json.dumps({
347 autoupdate.Autoupdate.SIZE_ATTR: file_size,
348 autoupdate.Autoupdate.SHA1_ATTR: file_sha1,
349 autoupdate.Autoupdate.SHA256_ATTR: file_sha256,
350 autoupdate.Autoupdate.ISDELTA_ATTR: is_delta
351 })
Gilad Arnold55a2a372012-10-02 16:46:32352
Chris Sosa76e44b92013-01-31 20:11:38353
David Rochberg7c79a812011-01-19 19:24:45354class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:01355 """The Root Class for the Dev Server.
356
357 CherryPy works as follows:
358 For each method in this class, cherrpy interprets root/path
359 as a call to an instance of DevServerRoot->method_name. For example,
360 a call to http://myhost/build will call build. CherryPy automatically
361 parses http args and places them as keyword arguments in each method.
362 For paths http://myhost/update/dir1/dir2, you can use *args so that
363 cherrypy uses the update method and puts the extra paths in args.
364 """
Gilad Arnoldf8f769f2012-09-24 15:43:01365 # Method names that should not be listed on the index page.
366 _UNLISTED_METHODS = ['index', 'doc']
367
Dale Curtisc9aaf3a2011-08-09 22:47:40368 api = ApiRoot()
Chris Sosa7c931362010-10-12 02:49:01369
Dan Shi59ae7092013-06-04 21:37:27370 # Number of threads that devserver is staging images.
371 _staging_thread_count = 0
372 # Lock used to lock increasing/decreasing count.
373 _staging_thread_count_lock = threading.Lock()
374
joychen3cb228e2013-06-12 19:13:13375 def __init__(self, _xbuddy):
Nick Sanders7dcaa2e2011-08-04 22:20:41376 self._builder = None
Simran Basi4baad082013-02-14 21:39:18377 self._telemetry_lock_dict = common_util.LockDict()
joychen3cb228e2013-06-12 19:13:13378 self._xbuddy = _xbuddy
David Rochberg7c79a812011-01-19 19:24:45379
Chris Sosa6b0c6172013-08-06 00:01:33380 @staticmethod
381 def _get_artifacts(kwargs):
382 """Returns a tuple of named and file artifacts given the stage rpc kwargs.
383
384 Raises: DevserverError if no artifacts would be returned.
385 """
386 artifacts = kwargs.get('artifacts')
387 files = kwargs.get('files')
388 if not artifacts and not files:
389 raise DevServerError('No artifacts specified.')
390
Chris Sosafa86b482013-09-04 18:30:36391 # Note we NEED to coerce files to a string as we get raw unicode from
392 # cherrypy and we treat files as strings elsewhere in the code.
393 return (str(artifacts).split(',') if artifacts else [],
394 str(files).split(',') if files else [])
Chris Sosa6b0c6172013-08-06 00:01:33395
Dale Curtisc9aaf3a2011-08-09 22:47:40396 @cherrypy.expose
David Rochberg7c79a812011-01-19 19:24:45397 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:01398 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 22:20:41399 import builder
400 if self._builder is None:
401 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 19:24:45402 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:01403
Chris Sosacde6bf42012-06-01 01:36:39404 @staticmethod
405 def _canonicalize_archive_url(archive_url):
406 """Canonicalizes archive_url strings.
407
408 Raises:
409 DevserverError: if archive_url is not set.
410 """
411 if archive_url:
Chris Sosa76e44b92013-01-31 20:11:38412 if not archive_url.startswith('gs://'):
Don Garrett8ccab732013-08-30 16:13:59413 raise DevServerError("Archive URL isn't from Google Storage (%s) ." %
414 archive_url)
Chris Sosa76e44b92013-01-31 20:11:38415
Chris Sosacde6bf42012-06-01 01:36:39416 return archive_url.rstrip('/')
417 else:
418 raise DevServerError("Must specify an archive_url in the request")
419
Dale Curtisc9aaf3a2011-08-09 22:47:40420 @cherrypy.expose
Dan Shif8eb0d12013-08-02 00:52:06421 def is_staged(self, **kwargs):
422 """Check if artifacts have been downloaded.
423
Chris Sosa6b0c6172013-08-06 00:01:33424 async: True to return without waiting for download to complete.
425 artifacts: Comma separated list of named artifacts to download.
426 These are defined in artifact_info and have their implementation
427 in build_artifact.py.
428 files: Comma separated list of file artifacts to stage. These
429 will be available as is in the corresponding static directory with no
430 custom post-processing.
431
432 returns: True of all artifacts are staged.
Dan Shif8eb0d12013-08-02 00:52:06433
434 Example:
435 To check if autotest and test_suites are staged:
436 http://devserver_url:<port>/is_staged?archive_url=gs://your_url/path&
437 artifacts=autotest,test_suites
438 """
439 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa6b0c6172013-08-06 00:01:33440 artifacts, files = self._get_artifacts(kwargs)
Dan Shif8eb0d12013-08-02 00:52:06441 return str(downloader.Downloader(updater.static_dir, archive_url).IsStaged(
Chris Sosa6b0c6172013-08-06 00:01:33442 artifacts, files))
Dan Shi59ae7092013-06-04 21:37:27443
Chris Sosa76e44b92013-01-31 20:11:38444 @cherrypy.expose
445 def stage(self, **kwargs):
446 """Downloads and caches the artifacts from Google Storage URL.
447
448 Downloads and caches the artifacts Google Storage URL. Returns once these
449 have been downloaded on the devserver. A call to this will attempt to cache
450 non-specified artifacts in the background for the given from the given URL
451 following the principle of spatial locality. Spatial locality of different
452 artifacts is explicitly defined in the build_artifact module.
453
454 These artifacts will then be available from the static/ sub-directory of
455 the devserver.
456
457 Args:
458 archive_url: Google Storage URL for the build.
Dan Shif8eb0d12013-08-02 00:52:06459 async: True to return without waiting for download to complete.
Chris Sosa6b0c6172013-08-06 00:01:33460 artifacts: Comma separated list of named artifacts to download.
461 These are defined in artifact_info and have their implementation
462 in build_artifact.py.
463 files: Comma separated list of files to stage. These
464 will be available as is in the corresponding static directory with no
465 custom post-processing.
Chris Sosa76e44b92013-01-31 20:11:38466
467 Example:
468 To download the autotest and test suites tarballs:
469 http://devserver_url:<port>/stage?archive_url=gs://your_url/path&
470 artifacts=autotest,test_suites
471 To download the full update payload:
472 http://devserver_url:<port>/stage?archive_url=gs://your_url/path&
473 artifacts=full_payload
Chris Sosa6b0c6172013-08-06 00:01:33474 To download just a file called blah.bin:
475 http://devserver_url:<port>/stage?archive_url=gs://your_url/path&
476 files=blah.bin
Chris Sosa76e44b92013-01-31 20:11:38477
478 For both these examples, one could find these artifacts at:
joychened64b222013-06-21 23:39:34479 http://devserver_url:<port>/static/<relative_path>*
Chris Sosa76e44b92013-01-31 20:11:38480
481 Note for this example, relative path is the archive_url stripped of its
482 basename i.e. path/ in the examples above. Specific example:
483
484 gs://chromeos-image-archive/x86-mario-release/R26-3920.0.0
485
486 Will get staged to:
487
joychened64b222013-06-21 23:39:34488 http://devserver_url:<port>/static/x86-mario-release/R26-3920.0.0
Chris Sosa76e44b92013-01-31 20:11:38489 """
Chris Sosacde6bf42012-06-01 01:36:39490 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Dan Shif8eb0d12013-08-02 00:52:06491 async = kwargs.get('async', False)
Chris Sosa6b0c6172013-08-06 00:01:33492 artifacts, files = self._get_artifacts(kwargs)
Dan Shi59ae7092013-06-04 21:37:27493 with DevServerRoot._staging_thread_count_lock:
494 DevServerRoot._staging_thread_count += 1
495 try:
Chris Sosa6b0c6172013-08-06 00:01:33496 downloader.Downloader(updater.static_dir, archive_url).Download(
497 artifacts, files, async=async)
Dan Shi59ae7092013-06-04 21:37:27498 finally:
499 with DevServerRoot._staging_thread_count_lock:
500 DevServerRoot._staging_thread_count -= 1
Chris Sosa76e44b92013-01-31 20:11:38501 return 'Success'
Chris Sosacde6bf42012-06-01 01:36:39502
503 @cherrypy.expose
Simran Basi4baad082013-02-14 21:39:18504 def setup_telemetry(self, **kwargs):
505 """Extracts and sets up telemetry
506
507 This method goes through the telemetry deps packages, and stages them on
508 the devserver to be used by the drones and the telemetry tests.
509
510 Args:
511 archive_url: Google Storage URL for the build.
512
513 Returns:
514 Path to the source folder for the telemetry codebase once it is staged.
515 """
516 archive_url = kwargs.get('archive_url')
517 self.stage(archive_url=archive_url, artifacts='autotest')
518
519 build = '/'.join(downloader.Downloader.ParseUrl(archive_url))
520 build_path = os.path.join(updater.static_dir, build)
521 deps_path = os.path.join(build_path, 'autotest/packages')
522 telemetry_path = os.path.join(build_path, TELEMETRY_FOLDER)
523 src_folder = os.path.join(telemetry_path, 'src')
524
525 with self._telemetry_lock_dict.lock(telemetry_path):
526 if os.path.exists(src_folder):
527 # Telemetry is already fully stage return
528 return src_folder
529
530 common_util.MkDirP(telemetry_path)
531
532 # Copy over the required deps tar balls to the telemetry directory.
533 for dep in TELEMETRY_DEPS:
534 dep_path = os.path.join(deps_path, dep)
Simran Basi0d078682013-03-22 23:40:04535 if not os.path.exists(dep_path):
536 # This dep does not exist (could be new), do not extract it.
537 continue
Simran Basi4baad082013-02-14 21:39:18538 try:
539 common_util.ExtractTarball(dep_path, telemetry_path)
540 except common_util.CommonUtilError as e:
541 shutil.rmtree(telemetry_path)
542 raise DevServerError(str(e))
543
544 # By default all the tarballs extract to test_src but some parts of
545 # the telemetry code specifically hardcoded to exist inside of 'src'.
546 test_src = os.path.join(telemetry_path, 'test_src')
547 try:
548 shutil.move(test_src, src_folder)
549 except shutil.Error:
550 # This can occur if src_folder already exists. Remove and retry move.
551 shutil.rmtree(src_folder)
552 raise DevServerError('Failure in telemetry setup for build %s. Appears'
553 ' that the test_src to src move failed.' % build)
554
555 return src_folder
556
557 @cherrypy.expose
Chris Sosa76e44b92013-01-31 20:11:38558 def symbolicate_dump(self, minidump, **kwargs):
Chris Masone816e38c2012-05-02 19:22:36559 """Symbolicates a minidump using pre-downloaded symbols, returns it.
560
561 Callers will need to POST to this URL with a body of MIME-type
562 "multipart/form-data".
563 The body should include a single argument, 'minidump', containing the
564 binary-formatted minidump to symbolicate.
565
Chris Masone816e38c2012-05-02 19:22:36566 Args:
Chris Sosa76e44b92013-01-31 20:11:38567 archive_url: Google Storage URL for the build.
Chris Masone816e38c2012-05-02 19:22:36568 minidump: The binary minidump file to symbolicate.
569 """
Chris Sosa76e44b92013-01-31 20:11:38570 # Ensure the symbols have been staged.
571 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
572 if self.stage(archive_url=archive_url, artifacts='symbols') != 'Success':
573 raise DevServerError('Failed to stage symbols for %s' % archive_url)
574
Chris Masone816e38c2012-05-02 19:22:36575 to_return = ''
576 with tempfile.NamedTemporaryFile() as local:
577 while True:
578 data = minidump.file.read(8192)
579 if not data:
580 break
581 local.write(data)
Chris Sosa76e44b92013-01-31 20:11:38582
Chris Masone816e38c2012-05-02 19:22:36583 local.flush()
Chris Sosa76e44b92013-01-31 20:11:38584
585 symbols_directory = os.path.join(downloader.Downloader.GetBuildDir(
586 updater.static_dir, archive_url), 'debug', 'breakpad')
587
588 stackwalk = subprocess.Popen(
589 ['minidump_stackwalk', local.name, symbols_directory],
590 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
591
Chris Masone816e38c2012-05-02 19:22:36592 to_return, error_text = stackwalk.communicate()
593 if stackwalk.returncode != 0:
594 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
595 error_text, stackwalk.returncode))
596
597 return to_return
598
599 @cherrypy.expose
Scott Zawalski16954532012-03-20 19:31:36600 def latestbuild(self, **params):
601 """Return a string representing the latest build for a given target.
602
603 Args:
604 target: The build target, typically a combination of the board and the
605 type of build e.g. x86-mario-release.
606 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
607 provided the latest RXX build will be returned.
608 Returns:
609 A string representation of the latest build if one exists, i.e.
610 R19-1993.0.0-a1-b1480.
611 An empty string if no latest could be found.
612 """
613 if not params:
614 return _PrintDocStringAsHTML(self.latestbuild)
615
616 if 'target' not in params:
beepsd76c6092013-08-29 05:23:30617 raise DevServerHTTPError(500, 'Error: target= is required!')
Scott Zawalski16954532012-03-20 19:31:36618 try:
Gilad Arnoldc65330c2012-09-20 22:17:48619 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 19:31:36620 updater.static_dir, params['target'],
621 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 17:05:01622 except common_util.CommonUtilError as errmsg:
beepsd76c6092013-08-29 05:23:30623 raise DevServerHTTPError(500, str(errmsg))
Scott Zawalski16954532012-03-20 19:31:36624
625 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 20:12:42626 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 22:17:28627 """Return a control file or a list of all known control files.
628
629 Example URL:
630 To List all control files:
beepsbd337242013-07-10 05:44:06631 http://dev-server/controlfiles?suite_name=&build=daisy_spring-release/R29-4279.0.0
632 To List all control files for, say, the bvt suite:
633 http://dev-server/controlfiles?suite_name=bvt&build=daisy_spring-release/R29-4279.0.0
Scott Zawalski4647ce62012-01-03 22:17:28634 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 20:12:42635 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 22:17:28636
637 Args:
Scott Zawalski84a39c92012-01-13 20:12:42638 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 22:17:28639 control_path: If you want the contents of a control file set this
640 to the path. E.g. client/site_tests/sleeptest/control
641 Optional, if not provided return a list of control files is returned.
beepsbd337242013-07-10 05:44:06642 suite_name: If control_path is not specified but a suite_name is
643 specified, list the control files belonging to that suite instead of
644 all control files. The empty string for suite_name will list all control
645 files for the build.
Scott Zawalski4647ce62012-01-03 22:17:28646 Returns:
647 Contents of a control file if control_path is provided.
648 A list of control files if no control_path is provided.
649 """
Scott Zawalski4647ce62012-01-03 22:17:28650 if not params:
651 return _PrintDocStringAsHTML(self.controlfiles)
652
Scott Zawalski84a39c92012-01-13 20:12:42653 if 'build' not in params:
beepsd76c6092013-08-29 05:23:30654 raise DevServerHTTPError(500, '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
joycheneaf4cfc2013-07-02 15:38:57668 def xbuddy(self, *args, **kwargs):
669 """The full xBuddy call, returns resource specified by path_parts.
joychen3cb228e2013-06-12 19:13:13670
671 Args:
joycheneaf4cfc2013-07-02 15:38:57672 path_parts: the path following xbuddy/ in the call url is split into the
joychen121fc9b2013-08-02 21:30:30673 components of the path. The path can be understood as
674 "{local|remote}/build_id/artifact" where build_id is composed of
675 "board/version."
joycheneaf4cfc2013-07-02 15:38:57676
joychen121fc9b2013-08-02 21:30:30677 The first path element is optional, and can be "remote" or "local"
678 If local (the default), devserver will not attempt to access Google
679 Storage, and will only search the static directory for the files.
680 If remote, devserver will try to obtain the artifact off GS if it's
681 not found locally.
682 The board is the familiar board name, optionally suffixed.
683 The version can be the google storage version number, and may also be
684 any of a number of xBuddy defined version aliases that will be
685 translated into the latest built image that fits the description.
686 Defaults to latest.
687 The artifact is one of a number of image or artifact aliases used by
688 xbuddy, defined in xbuddy:ALIASES. Defaults to test.
joycheneaf4cfc2013-07-02 15:38:57689
690 Kwargs:
joychen3cb228e2013-06-12 19:13:13691 return_dir: {true|false}
692 if set to true, returns the url to the update.gz
693 instead.
694
695 Example URL:
joycheneaf4cfc2013-07-02 15:38:57696 http://host:port/xbuddy/x86-generic/R26-4000.0.0/test
joychen3cb228e2013-06-12 19:13:13697 or
joycheneaf4cfc2013-07-02 15:38:57698 http://host:port/xbuddy/x86-generic/R26-4000.0.0/test?return_dir=true
joychen3cb228e2013-06-12 19:13:13699
700 Returns:
701 A redirect to the image or update file on the devserver.
702 e.g. http://host:port/static/archive/x86-generic-release/
703 R26-4000.0.0/chromium-test-image.bin
704 or if return_dir is True, return path to the folder where
joychen121fc9b2013-08-02 21:30:30705 the artifact is.
joychen3cb228e2013-06-12 19:13:13706 http://host:port/static/x86-generic-release/R26-4000.0.0/
707 """
708 boolean_string = kwargs.get('return_dir')
709 return_dir = xbuddy.XBuddy.ParseBoolean(boolean_string)
joychen121fc9b2013-08-02 21:30:30710
711 build_id, file_name = self._xbuddy.Get(args)
joychen3cb228e2013-06-12 19:13:13712 if return_dir:
Chris Sosa855b8932013-08-21 20:24:55713 directory = os.path.join(cherrypy.request.base, 'static', build_id)
joycheneaf4cfc2013-07-02 15:38:57714 _Log("Directory requested, returning: %s", directory)
715 return directory
joychen3cb228e2013-06-12 19:13:13716 else:
joychen121fc9b2013-08-02 21:30:30717 build_id = '/' + os.path.join('static', build_id, file_name)
718 _Log("Payload requested, returning: %s", build_id)
719 raise cherrypy.HTTPRedirect(build_id, 302)
joychen3cb228e2013-06-12 19:13:13720
721 @cherrypy.expose
722 def xbuddy_list(self):
723 """Lists the currently available images & time since last access.
724
725 @return: A string representation of a list of tuples
726 [(build_id, time since last access),...]
727 """
728 return self._xbuddy.List()
729
730 @cherrypy.expose
731 def xbuddy_capacity(self):
732 """Returns the number of images cached by xBuddy.
733
734 @return: Capacity of this devserver.
735 """
736 return self._xbuddy.Capacity()
737
738 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01739 def index(self):
Gilad Arnoldf8f769f2012-09-24 15:43:01740 """Presents a welcome message and documentation links."""
Gilad Arnoldf8f769f2012-09-24 15:43:01741 return ('Welcome to the Dev Server!<br>\n'
742 '<br>\n'
743 'Here are the available methods, click for documentation:<br>\n'
744 '<br>\n'
745 '%s' %
746 '<br>\n'.join(
747 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 18:52:38748 for name in _FindExposedMethods(
749 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 15:43:01750
751 @cherrypy.expose
752 def doc(self, *args):
753 """Shows the documentation for available methods / URLs.
754
755 Example:
756 http://myhost/doc/update
757 """
Gilad Arnoldd5ebaaa2012-10-02 18:52:38758 name = '/'.join(args)
759 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 15:43:01760 if not method:
761 raise DevServerError("No exposed method named `%s'" % name)
762 if not method.__doc__:
763 raise DevServerError("No documentation for exposed method `%s'" % name)
764 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-12 02:49:01765
Dale Curtisc9aaf3a2011-08-09 22:47:40766 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01767 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 15:43:01768 """Handles an update check from a Chrome OS client.
769
770 The HTTP request should contain the standard Omaha-style XML blob. The URL
771 line may contain an additional intermediate path to the update payload.
772
joychen121fc9b2013-08-02 21:30:30773 This request can be handled in one of 4 ways, depending on the devsever
774 settings and intermediate path.
joychenb0dfe552013-07-30 17:02:06775
joychen121fc9b2013-08-02 21:30:30776 1. No intermediate path
777 If no intermediate path is given, the default behavior is to generate an
778 update payload from the latest test image locally built for the board
779 specified in the xml. Devserver serves the generated payload.
780
781 2. Path explicitly invokes XBuddy
782 If there is a path given, it can explicitly invoke xbuddy by prefixing it
783 with 'xbuddy'. This path is then used to acquire an image binary for the
784 devserver to generate an update payload from. Devserver then serves this
785 payload.
786
787 3. Path is left for the devserver to interpret.
788 If the path given doesn't explicitly invoke xbuddy, devserver will attempt
789 to generate a payload from the test image in that directory and serve it.
790
791 4. The devserver is in a 'forced' mode. TO BE DEPRECATED
792 This comes from the usage of --forced_payload or --image when starting the
793 devserver. No matter what path (or no path) gets passed in, devserver will
794 serve the update payload (--forced_payload) or generate an update payload
795 from the image (--image).
796
797 Examples:
798 1. No intermediate path
799 update_engine_client --omaha_url=http://myhost/update
800 This generates an update payload from the latest test image locally built
801 for the board specified in the xml.
802
803 2. Explicitly invoke xbuddy
804 update_engine_client --omaha_url=
805 http://myhost/update/xbuddy/remote/board/version/dev
806 This would go to GS to download the dev image for the board, from which
807 the devserver would generate a payload to serve.
808
809 3. Give a path for devserver to interpret
810 update_engine_client --omaha_url=http://myhost/update/some/random/path
811 This would attempt, in order to:
812 a) Generate an update from a test image binary if found in
813 static_dir/some/random/path.
814 b) Serve an update payload found in static_dir/some/random/path.
815 c) Hope that some/random/path takes the form "board/version" and
816 and attempt to download an update payload for that board/version
817 from GS.
Gilad Arnoldf8f769f2012-09-24 15:43:01818 """
joychen121fc9b2013-08-02 21:30:30819 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 21:47:02820 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-12 02:49:01821 data = cherrypy.request.rfile.read(body_length)
Chris Sosa7c931362010-10-12 02:49:01822
joychen121fc9b2013-08-02 21:30:30823 return updater.HandleUpdatePing(data, label)
Chris Sosa0356d3b2010-09-16 22:46:22824
Dan Shif5ce2de2013-04-25 23:06:32825 @cherrypy.expose
826 def check_health(self):
827 """Collect the health status of devserver to see if it's ready for staging.
828
829 @return: A JSON dictionary containing all or some of the following fields:
Dan Shi59ae7092013-06-04 21:37:27830 free_disk (int): free disk space in GB
831 staging_thread_count (int): number of devserver threads currently
832 staging an image
Dan Shif5ce2de2013-04-25 23:06:32833 """
834 # Get free disk space.
835 stat = os.statvfs(updater.static_dir)
836 free_disk = stat.f_bsize * stat.f_bavail / 1000000000
837
838 return json.dumps({
839 'free_disk': free_disk,
Dan Shi59ae7092013-06-04 21:37:27840 'staging_thread_count': DevServerRoot._staging_thread_count,
Dan Shif5ce2de2013-04-25 23:06:32841 })
842
843
Chris Sosadbc20082012-12-10 21:39:11844def _CleanCache(cache_dir, wipe):
845 """Wipes any excess cached items in the cache_dir.
846
847 Args:
848 cache_dir: the directory we are wiping from.
849 wipe: If True, wipe all the contents -- not just the excess.
850 """
851 if wipe:
852 # Clear the cache and exit on error.
853 cmd = 'rm -rf %s/*' % cache_dir
854 if os.system(cmd) != 0:
855 _Log('Failed to clear the cache with %s' % cmd)
856 sys.exit(1)
857 else:
858 # Clear all but the last N cached updates
859 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
860 (cache_dir, CACHED_ENTRIES))
861 if os.system(cmd) != 0:
862 _Log('Failed to clean up old delta cache files with %s' % cmd)
863 sys.exit(1)
864
865
Chris Sosa3ae4dc12013-03-29 18:47:00866def _AddTestingOptions(parser):
867 group = optparse.OptionGroup(
868 parser, 'Advanced Testing Options', 'These are used by test scripts and '
869 'developers writing integration tests utilizing the devserver. They are '
870 'not intended to be really used outside the scope of someone '
871 'knowledgable about the test.')
872 group.add_option('--exit',
873 action='store_true',
874 help='do not start the server (yet pregenerate/clear cache)')
875 group.add_option('--host_log',
876 action='store_true', default=False,
877 help='record history of host update events (/api/hostlog)')
878 group.add_option('--max_updates',
879 metavar='NUM', default= -1, type='int',
880 help='maximum number of update checks handled positively '
881 '(default: unlimited)')
882 group.add_option('--private_key',
883 metavar='PATH', default=None,
884 help='path to the private key in pem format. If this is set '
885 'the devserver will generate update payloads that are '
886 'signed with this key.')
887 group.add_option('--proxy_port',
888 metavar='PORT', default=None, type='int',
889 help='port to have the client connect to -- basically the '
890 'devserver lies to the update to tell it to get the payload '
891 'from a different port that will proxy the request back to '
892 'the devserver. The proxy must be managed outside the '
893 'devserver.')
894 group.add_option('--remote_payload',
895 action='store_true', default=False,
896 help='Payload is being served from a remote machine')
897 group.add_option('-u', '--urlbase',
898 metavar='URL',
899 help='base URL for update images, other than the '
900 'devserver. Use in conjunction with remote_payload.')
901 parser.add_option_group(group)
902
903
904def _AddUpdateOptions(parser):
905 group = optparse.OptionGroup(
906 parser, 'Autoupdate Options', 'These options can be used to change '
907 'how the devserver either generates or serve update payloads. Please '
908 'note that all of these option affect how a payload is generated and so '
909 'do not work in archive-only mode.')
910 group.add_option('--board',
911 help='By default the devserver will create an update '
912 'payload from the latest image built for the board '
913 'a device that is requesting an update has. When we '
914 'pre-generate an update (see below) and we do not specify '
915 'another update_type option like image or payload, the '
916 'devserver needs to know the board to generate the latest '
917 'image for. This is that board.')
918 group.add_option('--critical_update',
919 action='store_true', default=False,
920 help='Present update payload as critical')
Chris Sosa3ae4dc12013-03-29 18:47:00921 group.add_option('--image',
922 metavar='FILE',
923 help='Generate and serve an update using this image to any '
924 'device that requests an update.')
925 group.add_option('--no_patch_kernel',
926 dest='patch_kernel', action='store_false', default=True,
927 help='When generating an update payload, do not patch the '
928 'kernel with kernel verification blob from the stateful '
929 'partition.')
930 group.add_option('--payload',
931 metavar='PATH',
932 help='use the update payload from specified directory '
933 '(update.gz).')
934 group.add_option('-p', '--pregenerate_update',
935 action='store_true', default=False,
936 help='pre-generate the update payload before accepting '
937 'update requests. Useful to help debug payload generation '
938 'issues quickly. Also if an update payload will take a '
939 'long time to generate, a client may timeout if you do not'
940 'pregenerate the update.')
941 group.add_option('--src_image',
942 metavar='PATH', default='',
943 help='If specified, delta updates will be generated using '
944 'this image as the source image. Delta updates are when '
945 'you are updating from a "source image" to a another '
946 'image.')
947 parser.add_option_group(group)
948
949
950def _AddProductionOptions(parser):
951 group = optparse.OptionGroup(
952 parser, 'Advanced Server Options', 'These options can be used to changed '
953 'for advanced server behavior.')
Chris Sosa3ae4dc12013-03-29 18:47:00954 group.add_option('--clear_cache',
955 action='store_true', default=False,
956 help='At startup, removes all cached entries from the'
957 'devserver\'s cache.')
958 group.add_option('--logfile',
959 metavar='PATH',
960 help='log output to this file instead of stdout')
Chris Sosa855b8932013-08-21 20:24:55961 group.add_option('--pidfile',
962 metavar='PATH',
963 help='path to output a pid file for the server.')
Chris Sosa3ae4dc12013-03-29 18:47:00964 group.add_option('--production',
965 action='store_true', default=False,
966 help='have the devserver use production values when '
967 'starting up. This includes using more threads and '
968 'performing less logging.')
969 parser.add_option_group(group)
970
971
J. Richard Barnette3d977b82013-04-23 18:05:19972def _MakeLogHandler(logfile):
973 """Create a LogHandler instance used to log all messages."""
974 hdlr_cls = handlers.TimedRotatingFileHandler
975 hdlr = hdlr_cls(logfile, when=_LOG_ROTATION_TIME,
976 backupCount=_LOG_ROTATION_BACKUP)
Chris Sosa855b8932013-08-21 20:24:55977 hdlr.setFormatter(cplogging.logfmt)
J. Richard Barnette3d977b82013-04-23 18:05:19978 return hdlr
979
980
Chris Sosacde6bf42012-06-01 01:36:39981def main():
Chris Sosa3ae4dc12013-03-29 18:47:00982 usage = '\n\n'.join(['usage: %prog [options]', __doc__])
Gilad Arnold286a0062012-01-12 21:47:02983 parser = optparse.OptionParser(usage=usage)
joychened64b222013-06-21 23:39:34984
985 # get directory that the devserver is run from
986 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
joychen84d13772013-08-06 16:17:23987 default_static_dir = '%s/static' % devserver_dir
joychened64b222013-06-21 23:39:34988 parser.add_option('--static_dir',
Gilad Arnold9714d9b2012-10-04 17:09:42989 metavar='PATH',
joychen84d13772013-08-06 16:17:23990 default=default_static_dir,
joychened64b222013-06-21 23:39:34991 help='writable static directory')
Gilad Arnold9714d9b2012-10-04 17:09:42992 parser.add_option('--port',
993 default=8080, type='int',
994 help='port for the dev server to use (default: 8080)')
Gilad Arnold9714d9b2012-10-04 17:09:42995 parser.add_option('-t', '--test_image',
996 action='store_true',
joychen121fc9b2013-08-02 21:30:30997 help='Deprecated.')
joychen5260b9a2013-07-16 21:48:01998 parser.add_option('-x', '--xbuddy_manage_builds',
999 action='store_true',
1000 default=False,
1001 help='If set, allow xbuddy to manage images in'
1002 'build/images.')
Chris Sosa3ae4dc12013-03-29 18:47:001003 _AddProductionOptions(parser)
1004 _AddUpdateOptions(parser)
1005 _AddTestingOptions(parser)
Chris Sosa7c931362010-10-12 02:49:011006 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:231007
J. Richard Barnette3d977b82013-04-23 18:05:191008 # Handle options that must be set globally in cherrypy. Do this
1009 # work up front, because calls to _Log() below depend on this
1010 # initialization.
1011 if options.production:
1012 cherrypy.config.update({'environment': 'production'})
1013 if not options.logfile:
1014 cherrypy.config.update({'log.screen': True})
1015 else:
1016 cherrypy.config.update({'log.error_file': '',
1017 'log.access_file': ''})
1018 hdlr = _MakeLogHandler(options.logfile)
1019 # Pylint can't seem to process these two calls properly
1020 # pylint: disable=E1101
1021 cherrypy.log.access_log.addHandler(hdlr)
1022 cherrypy.log.error_log.addHandler(hdlr)
1023 # pylint: enable=E1101
1024
Chris Sosa7c931362010-10-12 02:49:011025 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:221026
joychened64b222013-06-21 23:39:341027 # set static_dir, from which everything will be served
joychen84d13772013-08-06 16:17:231028 options.static_dir = os.path.realpath(options.static_dir)
Chris Sosa0356d3b2010-09-16 22:46:221029
joychened64b222013-06-21 23:39:341030 cache_dir = os.path.join(options.static_dir, 'cache')
J. Richard Barnette3d977b82013-04-23 18:05:191031 # If our devserver is only supposed to serve payloads, we shouldn't be
1032 # mucking with the cache at all. If the devserver hadn't previously
1033 # generated a cache and is expected, the caller is using it wrong.
joychen7c2054a2013-07-25 18:14:071034 if os.path.exists(cache_dir):
Chris Sosadbc20082012-12-10 21:39:111035 _CleanCache(cache_dir, options.clear_cache)
Chris Sosa6b8c3742011-01-31 20:12:171036 else:
1037 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:141038
Chris Sosadbc20082012-12-10 21:39:111039 _Log('Using cache directory %s' % cache_dir)
Gilad Arnoldc65330c2012-09-20 22:17:481040 _Log('Source root is %s' % root_dir)
joychened64b222013-06-21 23:39:341041 _Log('Serving from %s' % options.static_dir)
[email protected]21a5ca32009-11-04 18:23:231042
joychen121fc9b2013-08-02 21:30:301043 _xbuddy = xbuddy.XBuddy(options.xbuddy_manage_builds,
1044 options.board,
1045 root_dir=root_dir,
1046 static_dir=options.static_dir)
1047
Chris Sosa6a3697f2013-01-30 00:44:431048 # We allow global use here to share with cherrypy classes.
1049 # pylint: disable=W0603
Chris Sosacde6bf42012-06-01 01:36:391050 global updater
Andrew de los Reyes52620802010-04-12 20:40:071051 updater = autoupdate.Autoupdate(
joychen121fc9b2013-08-02 21:30:301052 _xbuddy,
Andrew de los Reyes52620802010-04-12 20:40:071053 root_dir=root_dir,
joychened64b222013-06-21 23:39:341054 static_dir=options.static_dir,
Andrew de los Reyes52620802010-04-12 20:40:071055 urlbase=options.urlbase,
Chris Sosa5d342a22010-09-28 23:54:411056 forced_image=options.image,
Gilad Arnold0c9c8602012-10-03 06:58:581057 payload_path=options.payload,
Don Garrett0ad09372010-12-07 00:20:301058 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:371059 src_image=options.src_image,
Chris Sosa3ae4dc12013-03-29 18:47:001060 patch_kernel=options.patch_kernel,
Chris Sosa08d55a22011-01-20 00:08:021061 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:221062 copy_to_static_root=not options.exit,
1063 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 17:36:321064 critical_update=options.critical_update,
Gilad Arnold0c9c8602012-10-03 06:58:581065 remote_payload=options.remote_payload,
Gilad Arnolda564b4b2012-10-04 17:32:441066 max_updates=options.max_updates,
Gilad Arnold8318eac2012-10-04 19:52:231067 host_log=options.host_log,
Chris Sosa0f1ec842011-02-15 00:33:221068 )
Chris Sosa7c931362010-10-12 02:49:011069
Chris Sosa6a3697f2013-01-30 00:44:431070 if options.pregenerate_update:
1071 updater.PreGenerateUpdate()
Chris Sosa0356d3b2010-09-16 22:46:221072
J. Richard Barnette3d977b82013-04-23 18:05:191073 if options.exit:
1074 return
Chris Sosa2f1c41e2012-07-10 21:32:331075
joychen3cb228e2013-06-12 19:13:131076 dev_server = DevServerRoot(_xbuddy)
1077
Chris Sosa855b8932013-08-21 20:24:551078 if options.pidfile:
1079 plugins.PIDFile(cherrypy.engine, options.pidfile).subscribe()
1080
joychen3cb228e2013-06-12 19:13:131081 cherrypy.quickstart(dev_server, config=_GetConfig(options))
Chris Sosacde6bf42012-06-01 01:36:391082
1083
1084if __name__ == '__main__':
1085 main()