blob: 80cd97781bbf6162611df144f31041ba6e86d532 [file] [log] [blame]
Chris Sosa7c931362010-10-12 02:49:011#!/usr/bin/python
2
Chris Sosa781ba6d2012-04-11 19:44:433# Copyright (c) 2009-2012 The Chromium OS Authors. All rights reserved.
[email protected]ded22402009-10-26 22:36:214# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Chris Sosa7c931362010-10-12 02:49:017"""A CherryPy-based webserver to host images and build packages."""
8
9import cherrypy
Chris Sosa781ba6d2012-04-11 19:44:4310import logging
Chris Sosacde6bf42012-06-01 01:36:3911import multiprocessing
Sean O'Connor14b6a0a2010-03-21 06:23:4812import optparse
[email protected]ded22402009-10-26 22:36:2113import os
Scott Zawalski4647ce62012-01-03 22:17:2814import re
[email protected]4dc25812009-10-27 23:46:2615import sys
Chris Masone816e38c2012-05-02 19:22:3616import subprocess
17import tempfile
[email protected]ded22402009-10-26 22:36:2118
Chris Sosa0356d3b2010-09-16 22:46:2219import autoupdate
Scott Zawalski16954532012-03-20 19:31:3620import devserver_util
Chris Sosa47a7d4e2012-03-28 18:26:5521import downloader
Chris Sosa0356d3b2010-09-16 22:46:2222
Frank Farzan40160872011-12-13 02:39:1823
Chris Sosa417e55d2011-01-26 00:40:4824CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-17 01:36:1425
Chris Sosa0356d3b2010-09-16 22:46:2226# Sets up global to share between classes.
[email protected]21a5ca32009-11-04 18:23:2327global updater
28updater = None
[email protected]ded22402009-10-26 22:36:2129
Frank Farzan40160872011-12-13 02:39:1830
Chris Sosa9164ca32012-03-28 18:04:5031class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 18:26:5532 """Exception class used by this module."""
33 pass
34
35
Scott Zawalski4647ce62012-01-03 22:17:2836def _LeadingWhiteSpaceCount(string):
37 """Count the amount of leading whitespace in a string.
38
39 Args:
40 string: The string to count leading whitespace in.
41 Returns:
42 number of white space chars before characters start.
43 """
44 matched = re.match('^\s+', string)
45 if matched:
46 return len(matched.group())
47
48 return 0
49
50
51def _PrintDocStringAsHTML(func):
52 """Make a functions docstring somewhat HTML style.
53
54 Args:
55 func: The function to return the docstring from.
56 Returns:
57 A string that is somewhat formated for a web browser.
58 """
59 # TODO(scottz): Make this parse Args/Returns in a prettier way.
60 # Arguments could be bolded and indented etc.
61 html_doc = []
62 for line in func.__doc__.splitlines():
63 leading_space = _LeadingWhiteSpaceCount(line)
64 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 18:26:5565 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 22:17:2866
67 html_doc.append('<BR>%s' % line)
68
69 return '\n'.join(html_doc)
70
71
Chris Sosa7c931362010-10-12 02:49:0172def _GetConfig(options):
73 """Returns the configuration for the devserver."""
74 base_config = { 'global':
75 { 'server.log_request_headers': True,
76 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 16:01:0877 'server.socket_host': '::',
Chris Sosa7c931362010-10-12 02:49:0178 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:5479 'response.timeout': 6000,
Chris Sosa72333d12012-06-13 18:28:0580 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 02:59:1781 'tools.staticdir.root':
82 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-12 02:49:0183 },
Dale Curtisc9aaf3a2011-08-09 22:47:4084 '/api':
85 {
86 # Gets rid of cherrypy parsing post file for args.
87 'request.process_request_body': False,
88 },
Chris Sosaa1ef0102010-10-21 23:22:3589 '/build':
90 {
91 'response.timeout': 100000,
92 },
Chris Sosa7c931362010-10-12 02:49:0193 '/update':
94 {
95 # Gets rid of cherrypy parsing post file for args.
96 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:5197 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:0198 },
99 # Sets up the static dir for file hosting.
100 '/static':
101 { 'tools.staticdir.dir': 'static',
102 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:51103 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:01104 },
105 }
Scott Zawalski1c5e7cd2012-02-27 18:12:52106
107 if options.log_dir:
108 base_config['global']['log.access_file'] = os.path.join(
109 options.log_dir, 'devserver_access.log')
110 base_config['global']['log.error_file'] = os.path.join(
111 options.log_dir, 'devserver_error.log')
112
Chris Sosa417e55d2011-01-26 00:40:48113 if options.production:
114 base_config['global']['server.environment'] = 'production'
115
Chris Sosa7c931362010-10-12 02:49:01116 return base_config
[email protected]64244662009-11-12 00:52:08117
Darin Petkove17164a2010-08-11 20:24:41118
Zdenek Behan608f46c2011-02-18 23:47:16119def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 22:46:22120 """Sets up symlink to image_dir for serving purposes."""
121 assert os.path.exists(image_dir), '%s must exist.' % image_dir
122 # If we're serving out of an archived build dir (e.g. a
123 # buildbot), prepare this webserver's magic 'static/' dir with a
124 # link to the build archive.
Chris Sosa7c931362010-10-12 02:49:01125 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
126 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:16127 if os.path.lexists('%s/archive' % static_dir):
128 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-12 02:49:01129 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:16130 os.unlink('%s/archive' % static_dir)
131 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-06-01 01:36:39132
Chris Sosa0356d3b2010-09-16 22:46:22133 else:
Zdenek Behan608f46c2011-02-18 23:47:16134 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-06-01 01:36:39135
Chris Sosa7c931362010-10-12 02:49:01136 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
137 'DEVSERVER')
138
139
Dale Curtisc9aaf3a2011-08-09 22:47:40140class ApiRoot(object):
141 """RESTful API for Dev Server information."""
142 exposed = True
143
144 @cherrypy.expose
145 def hostinfo(self, ip):
146 """Returns a JSON dictionary containing information about the given ip.
147
148 Not all information may be known at the time the request is made. The
149 possible keys are:
150
151 last_event_type: int
152 Last update event type received.
153
154 last_event_status: int
155 Last update event status received.
156
157 last_known_version: string
158 Last known version recieved for update ping.
159
160 forced_update_label: string
161 Update label to force next update ping to use. Set by setnextupdate.
162
163 See the OmahaEvent class in update_engine/omaha_request_action.h for status
164 code definitions. If the ip does not exist an empty string is returned."""
165 return updater.HandleHostInfoPing(ip)
166
167 @cherrypy.expose
Gilad Arnold286a0062012-01-12 21:47:02168 def hostlog(self, ip):
169 """Returns a JSON object containing a log of events pertaining to a
170 particular host, or all hosts. Log events contain a timestamp and any
171 subset of the attributes listed for the hostinfo method."""
172 return updater.HandleHostLogPing(ip)
173
174 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 22:47:40175 def setnextupdate(self, ip):
176 """Allows the response to the next update ping from a host to be set.
177
178 Takes the IP of the host and an update label as normally provided to the
179 /update command."""
180 body_length = int(cherrypy.request.headers['Content-Length'])
181 label = cherrypy.request.rfile.read(body_length)
182
183 if label:
184 label = label.strip()
185 if label:
186 return updater.HandleSetUpdatePing(ip, label)
187 raise cherrypy.HTTPError(400, 'No label provided.')
188
189
David Rochberg7c79a812011-01-19 19:24:45190class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:01191 """The Root Class for the Dev Server.
192
193 CherryPy works as follows:
194 For each method in this class, cherrpy interprets root/path
195 as a call to an instance of DevServerRoot->method_name. For example,
196 a call to http://myhost/build will call build. CherryPy automatically
197 parses http args and places them as keyword arguments in each method.
198 For paths http://myhost/update/dir1/dir2, you can use *args so that
199 cherrypy uses the update method and puts the extra paths in args.
200 """
Dale Curtisc9aaf3a2011-08-09 22:47:40201 api = ApiRoot()
Chris Sosa7c931362010-10-12 02:49:01202
David Rochberg7c79a812011-01-19 19:24:45203 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 22:20:41204 self._builder = None
Chris Sosacde6bf42012-06-01 01:36:39205 self._lock_dict_lock = multiprocessing.Lock()
206 self._lock_dict = {}
Chris Sosa47a7d4e2012-03-28 18:26:55207 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 19:24:45208
Dale Curtisc9aaf3a2011-08-09 22:47:40209 @cherrypy.expose
David Rochberg7c79a812011-01-19 19:24:45210 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:01211 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 22:20:41212 import builder
213 if self._builder is None:
214 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 19:24:45215 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:01216
Chris Sosacde6bf42012-06-01 01:36:39217 def _get_lock_for_archive_url(self, archive_url):
218 """Return a multiprocessing lock to use per archive_url.
219
220 Use this lock to protect critical zones per archive_url.
221
222 Usage:
223 with DevserverInstance._get_lock_for_archive_url(archive_url):
224 # CRITICAL AREA FOR ARCHIVE_URL.
225
226 Returns:
227 A multiprocessing lock that is archive_url specific.
228 """
229 with self._lock_dict_lock:
230 lock = self._lock_dict.get(archive_url)
231 if lock:
232 return lock
233 else:
234 lock = multiprocessing.Lock()
235 self._lock_dict[archive_url] = lock
236 return lock
237
238 @staticmethod
239 def _canonicalize_archive_url(archive_url):
240 """Canonicalizes archive_url strings.
241
242 Raises:
243 DevserverError: if archive_url is not set.
244 """
245 if archive_url:
246 return archive_url.rstrip('/')
247 else:
248 raise DevServerError("Must specify an archive_url in the request")
249
Dale Curtisc9aaf3a2011-08-09 22:47:40250 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 19:48:17251 def download(self, **kwargs):
252 """Downloads and archives full/delta payloads from Google Storage.
253
Chris Sosa47a7d4e2012-03-28 18:26:55254 This methods downloads artifacts. It may download artifacts in the
255 background in which case a caller should call wait_for_status to get
256 the status of the background artifact downloads. They should use the same
257 args passed to download.
258
Frank Farzanbcb571e2012-01-03 19:48:17259 Args:
260 archive_url: Google Storage URL for the build.
261
262 Example URL:
263 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
264 'x86-generic/R17-1208.0.0-a1-b338'
265 """
Chris Sosacde6bf42012-06-01 01:36:39266 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 18:26:55267
Chris Sosacde6bf42012-06-01 01:36:39268 # Guarantees that no two downloads for the same url can run this code
269 # at the same time.
270 with self._get_lock_for_archive_url(archive_url):
271 try:
272 # If we are currently downloading, return. Note, due to the above lock
273 # we know that the foreground artifacts must have finished downloading
274 # and returned Success if this downloader instance exists.
275 if (self._downloader_dict.get(archive_url) or
276 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
277 cherrypy.log('Build %s has already been processed.' % archive_url,
278 'DEVSERVER')
279 return 'Success'
280
281 downloader_instance = downloader.Downloader(updater.static_dir)
282 self._downloader_dict[archive_url] = downloader_instance
283 return downloader_instance.Download(archive_url, background=True)
284
285 except:
286 # On any exception, reset the state of the downloader_dict.
287 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 22:23:23288 raise
Chris Sosacde6bf42012-06-01 01:36:39289
290 @cherrypy.expose
291 def wait_for_status(self, **kwargs):
292 """Waits for background artifacts to be downloaded from Google Storage.
293
294 Args:
295 archive_url: Google Storage URL for the build.
296
297 Example URL:
298 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
299 'x86-generic/R17-1208.0.0-a1-b338'
300 """
301 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
302 downloader_instance = self._downloader_dict.get(archive_url)
303 if downloader_instance:
304 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 19:44:43305 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-06-01 01:36:39306 return status
307 else:
308 # We may have previously downloaded but removed the downloader instance
309 # from the cache.
310 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
311 logging.info('%s not found in downloader cache but previously staged.',
312 archive_url)
313 return 'Success'
314 else:
315 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 18:26:55316
317 @cherrypy.expose
Chris Masone816e38c2012-05-02 19:22:36318 def stage_debug(self, **kwargs):
319 """Downloads and stages debug symbol payloads from Google Storage.
320
321 This methods downloads the debug symbol build artifact synchronously,
322 and then stages it for use by symbolicate_dump/.
323
324 Args:
325 archive_url: Google Storage URL for the build.
326
327 Example URL:
328 'http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/'
329 'x86-generic/R17-1208.0.0-a1-b338'
330 """
Chris Sosacde6bf42012-06-01 01:36:39331 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 19:22:36332 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
333
334 @cherrypy.expose
335 def symbolicate_dump(self, minidump):
336 """Symbolicates a minidump using pre-downloaded symbols, returns it.
337
338 Callers will need to POST to this URL with a body of MIME-type
339 "multipart/form-data".
340 The body should include a single argument, 'minidump', containing the
341 binary-formatted minidump to symbolicate.
342
343 It is up to the caller to ensure that the symbols they want are currently
344 staged.
345
346 Args:
347 minidump: The binary minidump file to symbolicate.
348 """
349 to_return = ''
350 with tempfile.NamedTemporaryFile() as local:
351 while True:
352 data = minidump.file.read(8192)
353 if not data:
354 break
355 local.write(data)
356 local.flush()
357 stackwalk = subprocess.Popen(['minidump_stackwalk',
358 local.name,
359 updater.static_dir + '/debug/breakpad'],
360 stdout=subprocess.PIPE,
361 stderr=subprocess.PIPE)
362 to_return, error_text = stackwalk.communicate()
363 if stackwalk.returncode != 0:
364 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
365 error_text, stackwalk.returncode))
366
367 return to_return
368
369 @cherrypy.expose
Scott Zawalski16954532012-03-20 19:31:36370 def latestbuild(self, **params):
371 """Return a string representing the latest build for a given target.
372
373 Args:
374 target: The build target, typically a combination of the board and the
375 type of build e.g. x86-mario-release.
376 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
377 provided the latest RXX build will be returned.
378 Returns:
379 A string representation of the latest build if one exists, i.e.
380 R19-1993.0.0-a1-b1480.
381 An empty string if no latest could be found.
382 """
383 if not params:
384 return _PrintDocStringAsHTML(self.latestbuild)
385
386 if 'target' not in params:
387 raise cherrypy.HTTPError('500 Internal Server Error',
388 'Error: target= is required!')
389 try:
390 return devserver_util.GetLatestBuildVersion(
391 updater.static_dir, params['target'],
392 milestone=params.get('milestone'))
393 except devserver_util.DevServerUtilError as errmsg:
394 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
395
396 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 20:12:42397 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 22:17:28398 """Return a control file or a list of all known control files.
399
400 Example URL:
401 To List all control files:
Scott Zawalski84a39c92012-01-13 20:12:42402 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 22:17:28403 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 20:12:42404 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 22:17:28405
406 Args:
Scott Zawalski84a39c92012-01-13 20:12:42407 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 22:17:28408 control_path: If you want the contents of a control file set this
409 to the path. E.g. client/site_tests/sleeptest/control
410 Optional, if not provided return a list of control files is returned.
411 Returns:
412 Contents of a control file if control_path is provided.
413 A list of control files if no control_path is provided.
414 """
Scott Zawalski4647ce62012-01-03 22:17:28415 if not params:
416 return _PrintDocStringAsHTML(self.controlfiles)
417
Scott Zawalski84a39c92012-01-13 20:12:42418 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 22:17:28419 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 20:12:42420 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 22:17:28421
422 if 'control_path' not in params:
423 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 20:12:42424 params['build'])
Scott Zawalski4647ce62012-01-03 22:17:28425 else:
Scott Zawalski84a39c92012-01-13 20:12:42426 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 22:17:28427 params['control_path'])
Frank Farzan40160872011-12-13 02:39:18428
429 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01430 def index(self):
431 return 'Welcome to the Dev Server!'
432
Dale Curtisc9aaf3a2011-08-09 22:47:40433 @cherrypy.expose
Chris Sosa7c931362010-10-12 02:49:01434 def update(self, *args):
435 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 21:47:02436 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-12 02:49:01437 data = cherrypy.request.rfile.read(body_length)
438 return updater.HandleUpdatePing(data, label)
439
Chris Sosa0356d3b2010-09-16 22:46:22440
Chris Sosacde6bf42012-06-01 01:36:39441def main():
Sean O'Connor14b6a0a2010-03-21 06:23:48442 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 21:47:02443 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 20:50:40444 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-21 06:23:48445 help='serve archived builds only.')
Chris Sosae67b78f12010-11-05 00:33:16446 parser.add_option('--board', dest='board',
447 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-18 02:13:37448 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-17 01:36:14449 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 21:15:23450 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
451 help='No longer used. It is still here so we don\'t break '
452 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 17:36:32453 parser.add_option('--critical_update', dest='critical_update',
454 action='store_true', default=False,
455 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 01:06:01456 parser.add_option('--data_dir', dest='data_dir',
457 help='Writable directory where static lives',
458 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-18 02:13:37459 parser.add_option('--exit', action='store_true', default=False,
460 help='Don\'t start the server (still pregenerate or clear'
461 'cache).')
Andrew de los Reyes52620802010-04-12 20:40:07462 parser.add_option('--factory_config', dest='factory_config',
463 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-29 06:42:37464 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
465 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 22:46:22466 parser.add_option('--image', dest='image',
467 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 23:05:27468 parser.add_option('-p', '--pregenerate_update', action='store_true',
469 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-18 02:13:37470 parser.add_option('--payload', dest='payload',
471 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-12 02:49:01472 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 21:47:02473 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-15 00:33:22474 parser.add_option('--private_key', default=None,
475 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-26 00:40:48476 parser.add_option('--production', action='store_true', default=False,
477 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-07 00:20:30478 parser.add_option('--proxy_port', default=None,
479 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-27 04:39:48480 parser.add_option('--src_image', default='',
481 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 23:34:52482 parser.add_option('-t', action='store_true', dest='test_image')
483 parser.add_option('-u', '--urlbase', dest='urlbase',
484 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 20:40:07485 parser.add_option('--validate_factory_config', action="store_true",
486 dest='validate_factory_config',
487 help='Validate factory config file, then exit.')
Scott Zawalski1c5e7cd2012-02-27 18:12:52488 parser.add_option('-l', '--log-dir', default=None,
Chris Sosab65973e2012-03-30 01:31:02489 help=('Specify a directory for error and access logs. '
Scott Zawalski1c5e7cd2012-02-27 18:12:52490 'Default None, i.e. no logging.'))
Chris Sosa7c931362010-10-12 02:49:01491 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:23492
Chris Sosa7c931362010-10-12 02:49:01493 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
494 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:22495 serve_only = False
496
Zdenek Behan608f46c2011-02-18 23:47:16497 static_dir = os.path.realpath('%s/static' % options.data_dir)
498 os.system('mkdir -p %s' % static_dir)
499
Scott Zawalski1c5e7cd2012-02-27 18:12:52500 if options.log_dir and not os.path.isdir(options.log_dir):
501 parser.error('%s is not a valid dir, provide a valid dir to --log-dir' %
502 options.log_dir)
503
Sean O'Connor14b6a0a2010-03-21 06:23:48504 if options.archive_dir:
Zdenek Behan608f46c2011-02-18 23:47:16505 # TODO(zbehan) Remove legacy support:
506 # archive_dir is the directory where static/archive will point.
507 # If this is an absolute path, all is fine. If someone calls this
508 # using a relative path, that is relative to src/platform/dev/.
509 # That use case is unmaintainable, but since applications use it
510 # with =./static, instead of a boolean flag, we'll make this relative
511 # to devserver_dir to keep these unbroken. For now.
512 archive_dir = options.archive_dir
513 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 18:26:55514 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-18 23:47:16515 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 21:35:49516 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 22:46:22517 serve_only = True
Chris Sosa0356d3b2010-09-16 22:46:22518
Don Garrettf90edf02010-11-17 01:36:14519 cache_dir = os.path.join(static_dir, 'cache')
520 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
521
Don Garrettf90edf02010-11-17 01:36:14522 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 20:12:17523 if options.clear_cache:
524 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 18:04:50525 cmd = 'rm -rf %s/*' % cache_dir
526 if os.system(cmd) != 0:
Chris Sosa6b8c3742011-01-31 20:12:17527 cherrypy.log('Failed to clear the cache with %s' % cmd,
528 'DEVSERVER')
529 sys.exit(1)
530
531 else:
532 # Clear all but the last N cached updates
533 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
534 (cache_dir, CACHED_ENTRIES))
535 if os.system(cmd) != 0:
536 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
537 'DEVSERVER')
538 sys.exit(1)
539 else:
540 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14541
Greg Spencerc8b59b22011-03-15 21:15:23542 if options.client_prefix_deprecated:
543 cherrypy.log('The --client_prefix argument is DEPRECATED, '
544 'and is no longer needed.', 'DEVSERVER')
545
Zdenek Behan5d21a2a2011-02-12 01:06:01546 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-12 02:49:01547 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
548 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
[email protected]21a5ca32009-11-04 18:23:23549
Chris Sosacde6bf42012-06-01 01:36:39550 global updater
Andrew de los Reyes52620802010-04-12 20:40:07551 updater = autoupdate.Autoupdate(
552 root_dir=root_dir,
553 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 22:46:22554 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 20:40:07555 urlbase=options.urlbase,
556 test_image=options.test_image,
557 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 23:54:41558 forced_image=options.image,
Don Garrett0c880e22010-11-18 02:13:37559 forced_payload=options.payload,
Chris Sosa62f720b2010-10-27 04:39:48560 port=options.port,
Don Garrett0ad09372010-12-07 00:20:30561 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:37562 src_image=options.src_image,
Chris Sosae67b78f12010-11-05 00:33:16563 vm=options.vm,
Chris Sosa08d55a22011-01-20 00:08:02564 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:22565 copy_to_static_root=not options.exit,
566 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 17:36:32567 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-15 00:33:22568 )
Chris Sosa7c931362010-10-12 02:49:01569
570 # Sanity-check for use of validate_factory_config.
571 if not options.factory_config and options.validate_factory_config:
572 parser.error('You need a factory_config to validate.')
[email protected]64244662009-11-12 00:52:08573
Chris Sosa0356d3b2010-09-16 22:46:22574 if options.factory_config:
Chris Sosa7c931362010-10-12 02:49:01575 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 22:46:22576 options.validate_factory_config)
Chris Sosa7c931362010-10-12 02:49:01577 # We don't run the dev server with this option.
578 if options.validate_factory_config:
579 sys.exit(0)
Chris Sosa2c048f12010-10-27 23:05:27580 elif options.pregenerate_update:
Chris Sosae67b78f12010-11-05 00:33:16581 if not updater.PreGenerateUpdate():
582 sys.exit(1)
Chris Sosa0356d3b2010-09-16 22:46:22583
Don Garrett0c880e22010-11-18 02:13:37584 # If the command line requested after setup, it's time to do it.
585 if not options.exit:
586 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-06-01 01:36:39587
588
589if __name__ == '__main__':
590 main()