blob: 54b80e853a1763d9675db8f325ceb2c1cdc2d462 [file] [log] [blame]
Chris Sosa7c931362010-10-11 19:49:01 -07001#!/usr/bin/python
2
Chris Sosa781ba6d2012-04-11 12:44:43 -07003# Copyright (c) 2009-2012 The Chromium OS Authors. All rights reserved.
rtc@google.comded22402009-10-26 22:36:21 +00004# 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-11 19:49:01 -07007"""A CherryPy-based webserver to host images and build packages."""
8
9import cherrypy
Chris Masone816e38c2012-05-02 12:22:36 -070010import cStringIO
Chris Sosa781ba6d2012-04-11 12:44:43 -070011import logging
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070012import optparse
rtc@google.comded22402009-10-26 22:36:21 +000013import os
Scott Zawalski4647ce62012-01-03 17:17:28 -050014import re
chocobo@google.com4dc25812009-10-27 23:46:26 +000015import sys
Chris Masone816e38c2012-05-02 12:22:36 -070016import subprocess
17import tempfile
rtc@google.comded22402009-10-26 22:36:21 +000018
Chris Sosa0356d3b2010-09-16 15:46:22 -070019import autoupdate
Scott Zawalski16954532012-03-20 15:31:36 -040020import devserver_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070021import downloader
Chris Sosa0356d3b2010-09-16 15:46:22 -070022
Frank Farzan40160872011-12-12 18:39:18 -080023
Chris Sosa417e55d2011-01-25 16:40:48 -080024CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080025
Chris Sosa0356d3b2010-09-16 15:46:22 -070026# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000027global updater
28updater = None
rtc@google.comded22402009-10-26 22:36:21 +000029
Frank Farzan40160872011-12-12 18:39:18 -080030
Chris Sosa9164ca32012-03-28 11:04:50 -070031class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070032 """Exception class used by this module."""
33 pass
34
35
Scott Zawalski4647ce62012-01-03 17:17:28 -050036def _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 11:26:55 -070065 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -050066
67 html_doc.append('<BR>%s' % line)
68
69 return '\n'.join(html_doc)
70
71
Chris Sosa7c931362010-10-11 19:49:01 -070072def _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 09:01:08 -070077 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -070078 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -070079 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 03:59:17 +010080 'tools.staticdir.root':
81 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070082 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070083 '/api':
84 {
85 # Gets rid of cherrypy parsing post file for args.
86 'request.process_request_body': False,
87 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070088 '/build':
89 {
90 'response.timeout': 100000,
91 },
Chris Sosa7c931362010-10-11 19:49:01 -070092 '/update':
93 {
94 # Gets rid of cherrypy parsing post file for args.
95 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070096 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070097 },
98 # Sets up the static dir for file hosting.
99 '/static':
100 { 'tools.staticdir.dir': 'static',
101 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700102 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700103 },
104 }
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500105
106 if options.log_dir:
107 base_config['global']['log.access_file'] = os.path.join(
108 options.log_dir, 'devserver_access.log')
109 base_config['global']['log.error_file'] = os.path.join(
110 options.log_dir, 'devserver_error.log')
111
Chris Sosa417e55d2011-01-25 16:40:48 -0800112 if options.production:
113 base_config['global']['server.environment'] = 'production'
114
Chris Sosa7c931362010-10-11 19:49:01 -0700115 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000116
Darin Petkove17164a2010-08-11 13:24:41 -0700117
Zdenek Behan608f46c2011-02-19 00:47:16 +0100118def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700119 """Sets up symlink to image_dir for serving purposes."""
120 assert os.path.exists(image_dir), '%s must exist.' % image_dir
121 # If we're serving out of an archived build dir (e.g. a
122 # buildbot), prepare this webserver's magic 'static/' dir with a
123 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -0700124 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
125 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100126 if os.path.lexists('%s/archive' % static_dir):
127 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700128 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100129 os.unlink('%s/archive' % static_dir)
130 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700131 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100132 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700133 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
134 'DEVSERVER')
135
136
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700137class ApiRoot(object):
138 """RESTful API for Dev Server information."""
139 exposed = True
140
141 @cherrypy.expose
142 def hostinfo(self, ip):
143 """Returns a JSON dictionary containing information about the given ip.
144
145 Not all information may be known at the time the request is made. The
146 possible keys are:
147
148 last_event_type: int
149 Last update event type received.
150
151 last_event_status: int
152 Last update event status received.
153
154 last_known_version: string
155 Last known version recieved for update ping.
156
157 forced_update_label: string
158 Update label to force next update ping to use. Set by setnextupdate.
159
160 See the OmahaEvent class in update_engine/omaha_request_action.h for status
161 code definitions. If the ip does not exist an empty string is returned."""
162 return updater.HandleHostInfoPing(ip)
163
164 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800165 def hostlog(self, ip):
166 """Returns a JSON object containing a log of events pertaining to a
167 particular host, or all hosts. Log events contain a timestamp and any
168 subset of the attributes listed for the hostinfo method."""
169 return updater.HandleHostLogPing(ip)
170
171 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700172 def setnextupdate(self, ip):
173 """Allows the response to the next update ping from a host to be set.
174
175 Takes the IP of the host and an update label as normally provided to the
176 /update command."""
177 body_length = int(cherrypy.request.headers['Content-Length'])
178 label = cherrypy.request.rfile.read(body_length)
179
180 if label:
181 label = label.strip()
182 if label:
183 return updater.HandleSetUpdatePing(ip, label)
184 raise cherrypy.HTTPError(400, 'No label provided.')
185
186
David Rochberg7c79a812011-01-19 14:24:45 -0500187class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700188 """The Root Class for the Dev Server.
189
190 CherryPy works as follows:
191 For each method in this class, cherrpy interprets root/path
192 as a call to an instance of DevServerRoot->method_name. For example,
193 a call to http://myhost/build will call build. CherryPy automatically
194 parses http args and places them as keyword arguments in each method.
195 For paths http://myhost/update/dir1/dir2, you can use *args so that
196 cherrypy uses the update method and puts the extra paths in args.
197 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700198 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700199
David Rochberg7c79a812011-01-19 14:24:45 -0500200 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700201 self._builder = None
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700202 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500203
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700204 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500205 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700206 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700207 import builder
208 if self._builder is None:
209 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500210 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700211
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700212 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800213 def download(self, **kwargs):
214 """Downloads and archives full/delta payloads from Google Storage.
215
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700216 This methods downloads artifacts. It may download artifacts in the
217 background in which case a caller should call wait_for_status to get
218 the status of the background artifact downloads. They should use the same
219 args passed to download.
220
Frank Farzanbcb571e2012-01-03 11:48:17 -0800221 Args:
222 archive_url: Google Storage URL for the build.
223
224 Example URL:
225 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
226 'x86-generic/R17-1208.0.0-a1-b338'
227 """
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700228 downloader_instance = downloader.Downloader(updater.static_dir)
229 archive_url = kwargs.get('archive_url')
230 if not archive_url:
231 raise DevServerError("Didn't specify the archive_url in request")
232
Chris Sosa781ba6d2012-04-11 12:44:43 -0700233 # Do this before we start such that other calls to the downloader or
234 # wait_for_status are blocked until this completed/failed.
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700235 self._downloader_dict[archive_url] = downloader_instance
Chris Sosa781ba6d2012-04-11 12:44:43 -0700236 try:
237 return_obj = downloader_instance.Download(archive_url, background=True)
238 except:
239 self._downloader_dict[archive_url] = None
240 raise
241
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700242 return return_obj
243
244 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700245 def stage_debug(self, **kwargs):
246 """Downloads and stages debug symbol payloads from Google Storage.
247
248 This methods downloads the debug symbol build artifact synchronously,
249 and then stages it for use by symbolicate_dump/.
250
251 Args:
252 archive_url: Google Storage URL for the build.
253
254 Example URL:
255 'http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/'
256 'x86-generic/R17-1208.0.0-a1-b338'
257 """
258 archive_url = kwargs.get('archive_url')
259 if not archive_url:
260 raise DevServerError("Didn't specify the archive_url in request")
261
262 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
263
264 @cherrypy.expose
265 def symbolicate_dump(self, minidump):
266 """Symbolicates a minidump using pre-downloaded symbols, returns it.
267
268 Callers will need to POST to this URL with a body of MIME-type
269 "multipart/form-data".
270 The body should include a single argument, 'minidump', containing the
271 binary-formatted minidump to symbolicate.
272
273 It is up to the caller to ensure that the symbols they want are currently
274 staged.
275
276 Args:
277 minidump: The binary minidump file to symbolicate.
278 """
279 to_return = ''
280 with tempfile.NamedTemporaryFile() as local:
281 while True:
282 data = minidump.file.read(8192)
283 if not data:
284 break
285 local.write(data)
286 local.flush()
287 stackwalk = subprocess.Popen(['minidump_stackwalk',
288 local.name,
289 updater.static_dir + '/debug/breakpad'],
290 stdout=subprocess.PIPE,
291 stderr=subprocess.PIPE)
292 to_return, error_text = stackwalk.communicate()
293 if stackwalk.returncode != 0:
294 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
295 error_text, stackwalk.returncode))
296
297 return to_return
298
299 @cherrypy.expose
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700300 def wait_for_status(self, **kwargs):
301 """Waits for background artifacts to be downloaded from Google Storage.
302
303 Args:
304 archive_url: Google Storage URL for the build.
305
306 Example URL:
307 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
308 'x86-generic/R17-1208.0.0-a1-b338'
309 """
310 archive_url = kwargs.get('archive_url')
311 if not archive_url:
312 raise DevServerError("Didn't specify the archive_url in request")
313
314 downloader_instance = self._downloader_dict.get(archive_url)
315 if downloader_instance:
Chris Sosa781ba6d2012-04-11 12:44:43 -0700316 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700317 self._downloader_dict[archive_url] = None
Chris Sosa781ba6d2012-04-11 12:44:43 -0700318 return status
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700319 else:
Chris Sosa9164ca32012-03-28 11:04:50 -0700320 # We may have previously downloaded but removed the downloader instance
321 # from the cache.
322 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
Chris Sosa781ba6d2012-04-11 12:44:43 -0700323 logging.info('%s not found in downloader cache but previously staged.',
324 archive_url)
Chris Sosa9164ca32012-03-28 11:04:50 -0700325 return 'Success'
326 else:
327 raise DevServerError('No download for the given archive_url found.')
Frank Farzan40160872011-12-12 18:39:18 -0800328
329 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400330 def latestbuild(self, **params):
331 """Return a string representing the latest build for a given target.
332
333 Args:
334 target: The build target, typically a combination of the board and the
335 type of build e.g. x86-mario-release.
336 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
337 provided the latest RXX build will be returned.
338 Returns:
339 A string representation of the latest build if one exists, i.e.
340 R19-1993.0.0-a1-b1480.
341 An empty string if no latest could be found.
342 """
343 if not params:
344 return _PrintDocStringAsHTML(self.latestbuild)
345
346 if 'target' not in params:
347 raise cherrypy.HTTPError('500 Internal Server Error',
348 'Error: target= is required!')
349 try:
350 return devserver_util.GetLatestBuildVersion(
351 updater.static_dir, params['target'],
352 milestone=params.get('milestone'))
353 except devserver_util.DevServerUtilError as errmsg:
354 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
355
356 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500357 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500358 """Return a control file or a list of all known control files.
359
360 Example URL:
361 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500362 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500363 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500364 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0&control_path=client/sleeptest/control
Scott Zawalski4647ce62012-01-03 17:17:28 -0500365
366 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500367 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500368 control_path: If you want the contents of a control file set this
369 to the path. E.g. client/site_tests/sleeptest/control
370 Optional, if not provided return a list of control files is returned.
371 Returns:
372 Contents of a control file if control_path is provided.
373 A list of control files if no control_path is provided.
374 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500375 if not params:
376 return _PrintDocStringAsHTML(self.controlfiles)
377
Scott Zawalski84a39c92012-01-13 15:12:42 -0500378 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500379 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500380 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500381
382 if 'control_path' not in params:
383 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 15:12:42 -0500384 params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500385 else:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500386 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 17:17:28 -0500387 params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800388
389 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700390 def index(self):
391 return 'Welcome to the Dev Server!'
392
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700393 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700394 def update(self, *args):
395 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800396 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700397 data = cherrypy.request.rfile.read(body_length)
398 return updater.HandleUpdatePing(data, label)
399
Chris Sosa0356d3b2010-09-16 15:46:22 -0700400
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700401if __name__ == '__main__':
402 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800403 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700404 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700405 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700406 parser.add_option('--board', dest='board',
407 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800408 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800409 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 14:15:23 -0700410 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
411 help='No longer used. It is still here so we don\'t break '
412 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800413 parser.add_option('--critical_update', dest='critical_update',
414 action='store_true', default=False,
415 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100416 parser.add_option('--data_dir', dest='data_dir',
417 help='Writable directory where static lives',
418 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800419 parser.add_option('--exit', action='store_true', default=False,
420 help='Don\'t start the server (still pregenerate or clear'
421 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700422 parser.add_option('--factory_config', dest='factory_config',
423 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700424 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
425 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700426 parser.add_option('--image', dest='image',
427 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700428 parser.add_option('-p', '--pregenerate_update', action='store_true',
429 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800430 parser.add_option('--payload', dest='payload',
431 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700432 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800433 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800434 parser.add_option('--private_key', default=None,
435 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800436 parser.add_option('--production', action='store_true', default=False,
437 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800438 parser.add_option('--proxy_port', default=None,
439 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700440 parser.add_option('--src_image', default='',
441 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700442 parser.add_option('-t', action='store_true', dest='test_image')
443 parser.add_option('-u', '--urlbase', dest='urlbase',
444 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700445 parser.add_option('--validate_factory_config', action="store_true",
446 dest='validate_factory_config',
447 help='Validate factory config file, then exit.')
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500448 parser.add_option('-l', '--log-dir', default=None,
Chris Sosab65973e2012-03-29 18:31:02 -0700449 help=('Specify a directory for error and access logs. '
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500450 'Default None, i.e. no logging.'))
Chris Sosa7c931362010-10-11 19:49:01 -0700451 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000452
Chris Sosa7c931362010-10-11 19:49:01 -0700453 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
454 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700455 serve_only = False
456
Zdenek Behan608f46c2011-02-19 00:47:16 +0100457 static_dir = os.path.realpath('%s/static' % options.data_dir)
458 os.system('mkdir -p %s' % static_dir)
459
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500460 if options.log_dir and not os.path.isdir(options.log_dir):
461 parser.error('%s is not a valid dir, provide a valid dir to --log-dir' %
462 options.log_dir)
463
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700464 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100465 # TODO(zbehan) Remove legacy support:
466 # archive_dir is the directory where static/archive will point.
467 # If this is an absolute path, all is fine. If someone calls this
468 # using a relative path, that is relative to src/platform/dev/.
469 # That use case is unmaintainable, but since applications use it
470 # with =./static, instead of a boolean flag, we'll make this relative
471 # to devserver_dir to keep these unbroken. For now.
472 archive_dir = options.archive_dir
473 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700474 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100475 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100476 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700477 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700478
Don Garrettf90edf02010-11-16 17:36:14 -0800479 cache_dir = os.path.join(static_dir, 'cache')
480 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
481
Don Garrettf90edf02010-11-16 17:36:14 -0800482 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800483 if options.clear_cache:
484 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700485 cmd = 'rm -rf %s/*' % cache_dir
486 if os.system(cmd) != 0:
Chris Sosa6b8c3742011-01-31 12:12:17 -0800487 cherrypy.log('Failed to clear the cache with %s' % cmd,
488 'DEVSERVER')
489 sys.exit(1)
490
491 else:
492 # Clear all but the last N cached updates
493 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
494 (cache_dir, CACHED_ENTRIES))
495 if os.system(cmd) != 0:
496 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
497 'DEVSERVER')
498 sys.exit(1)
499 else:
500 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800501
Greg Spencerc8b59b22011-03-15 14:15:23 -0700502 if options.client_prefix_deprecated:
503 cherrypy.log('The --client_prefix argument is DEPRECATED, '
504 'and is no longer needed.', 'DEVSERVER')
505
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100506 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-11 19:49:01 -0700507 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
508 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000509
Andrew de los Reyes52620802010-04-12 13:40:07 -0700510 updater = autoupdate.Autoupdate(
511 root_dir=root_dir,
512 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700513 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700514 urlbase=options.urlbase,
515 test_image=options.test_image,
516 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700517 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800518 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700519 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800520 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700521 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700522 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800523 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800524 copy_to_static_root=not options.exit,
525 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800526 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800527 )
Chris Sosa7c931362010-10-11 19:49:01 -0700528
529 # Sanity-check for use of validate_factory_config.
530 if not options.factory_config and options.validate_factory_config:
531 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000532
Chris Sosa0356d3b2010-09-16 15:46:22 -0700533 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700534 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700535 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700536 # We don't run the dev server with this option.
537 if options.validate_factory_config:
538 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700539 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700540 if not updater.PreGenerateUpdate():
541 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700542
Don Garrett0c880e22010-11-17 18:13:37 -0800543 # If the command line requested after setup, it's time to do it.
544 if not options.exit:
545 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))