blob: 78020ac2c19e46978f1785fb50d841d475e6dd36 [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 Sosa781ba6d2012-04-11 12:44:43 -070010import logging
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070011import optparse
rtc@google.comded22402009-10-26 22:36:21 +000012import os
Scott Zawalski4647ce62012-01-03 17:17:28 -050013import re
chocobo@google.com4dc25812009-10-27 23:46:26 +000014import sys
Chris Masone816e38c2012-05-02 12:22:36 -070015import subprocess
16import tempfile
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070017import threading
rtc@google.comded22402009-10-26 22:36:21 +000018
Chris Sosa0356d3b2010-09-16 15:46:22 -070019import autoupdate
Gilad Arnoldc65330c2012-09-20 15:17:48 -070020import common_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070021import downloader
Gilad Arnoldc65330c2012-09-20 15:17:48 -070022import log_util
23
24
25# Module-local log function.
26def _Log(message, *args, **kwargs):
27 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 15:46:22 -070028
Frank Farzan40160872011-12-12 18:39:18 -080029
Chris Sosa417e55d2011-01-25 16:40:48 -080030CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080031
Chris Sosa0356d3b2010-09-16 15:46:22 -070032# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000033global updater
34updater = None
rtc@google.comded22402009-10-26 22:36:21 +000035
Frank Farzan40160872011-12-12 18:39:18 -080036
Chris Sosa9164ca32012-03-28 11:04:50 -070037class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070038 """Exception class used by this module."""
39 pass
40
41
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070042class LockDict(object):
43 """A dictionary of locks.
44
45 This class provides a thread-safe store of threading.Lock objects, which can
46 be used to regulate access to any set of hashable resources. Usage:
47
48 foo_lock_dict = LockDict()
49 ...
50 with foo_lock_dict.lock('bar'):
51 # Critical section for 'bar'
52 """
53 def __init__(self):
54 self._lock = self._new_lock()
55 self._dict = {}
56
57 def _new_lock(self):
58 return threading.Lock()
59
60 def lock(self, key):
61 with self._lock:
62 lock = self._dict.get(key)
63 if not lock:
64 lock = self._new_lock()
65 self._dict[key] = lock
66 return lock
67
68
Scott Zawalski4647ce62012-01-03 17:17:28 -050069def _LeadingWhiteSpaceCount(string):
70 """Count the amount of leading whitespace in a string.
71
72 Args:
73 string: The string to count leading whitespace in.
74 Returns:
75 number of white space chars before characters start.
76 """
77 matched = re.match('^\s+', string)
78 if matched:
79 return len(matched.group())
80
81 return 0
82
83
84def _PrintDocStringAsHTML(func):
85 """Make a functions docstring somewhat HTML style.
86
87 Args:
88 func: The function to return the docstring from.
89 Returns:
90 A string that is somewhat formated for a web browser.
91 """
92 # TODO(scottz): Make this parse Args/Returns in a prettier way.
93 # Arguments could be bolded and indented etc.
94 html_doc = []
95 for line in func.__doc__.splitlines():
96 leading_space = _LeadingWhiteSpaceCount(line)
97 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -070098 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -050099
100 html_doc.append('<BR>%s' % line)
101
102 return '\n'.join(html_doc)
103
104
Chris Sosa7c931362010-10-11 19:49:01 -0700105def _GetConfig(options):
106 """Returns the configuration for the devserver."""
107 base_config = { 'global':
108 { 'server.log_request_headers': True,
109 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -0700110 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -0700111 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -0700112 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 15:44:46 -0700113 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -0700114 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +0100115 'tools.staticdir.root':
116 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -0700117 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700118 '/api':
119 {
120 # Gets rid of cherrypy parsing post file for args.
121 'request.process_request_body': False,
122 },
Chris Sosaa1ef0102010-10-21 16:22:35 -0700123 '/build':
124 {
125 'response.timeout': 100000,
126 },
Chris Sosa7c931362010-10-11 19:49:01 -0700127 '/update':
128 {
129 # Gets rid of cherrypy parsing post file for args.
130 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700131 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700132 },
133 # Sets up the static dir for file hosting.
134 '/static':
135 { 'tools.staticdir.dir': 'static',
136 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700137 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700138 },
139 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700140 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700141 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500142
Chris Sosa7c931362010-10-11 19:49:01 -0700143 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000144
Darin Petkove17164a2010-08-11 13:24:41 -0700145
Zdenek Behan608f46c2011-02-19 00:47:16 +0100146def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700147 """Sets up symlink to image_dir for serving purposes."""
148 assert os.path.exists(image_dir), '%s must exist.' % image_dir
149 # If we're serving out of an archived build dir (e.g. a
150 # buildbot), prepare this webserver's magic 'static/' dir with a
151 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700152 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100153 if os.path.lexists('%s/archive' % static_dir):
154 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700155 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-19 00:47:16 +0100156 os.unlink('%s/archive' % static_dir)
157 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700158
Chris Sosa0356d3b2010-09-16 15:46:22 -0700159 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100160 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700161
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700162 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700163
164
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700165class ApiRoot(object):
166 """RESTful API for Dev Server information."""
167 exposed = True
168
169 @cherrypy.expose
170 def hostinfo(self, ip):
171 """Returns a JSON dictionary containing information about the given ip.
172
173 Not all information may be known at the time the request is made. The
174 possible keys are:
175
176 last_event_type: int
177 Last update event type received.
178
179 last_event_status: int
180 Last update event status received.
181
182 last_known_version: string
183 Last known version recieved for update ping.
184
185 forced_update_label: string
186 Update label to force next update ping to use. Set by setnextupdate.
187
188 See the OmahaEvent class in update_engine/omaha_request_action.h for status
189 code definitions. If the ip does not exist an empty string is returned."""
190 return updater.HandleHostInfoPing(ip)
191
192 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800193 def hostlog(self, ip):
194 """Returns a JSON object containing a log of events pertaining to a
195 particular host, or all hosts. Log events contain a timestamp and any
196 subset of the attributes listed for the hostinfo method."""
197 return updater.HandleHostLogPing(ip)
198
199 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700200 def setnextupdate(self, ip):
201 """Allows the response to the next update ping from a host to be set.
202
203 Takes the IP of the host and an update label as normally provided to the
204 /update command."""
205 body_length = int(cherrypy.request.headers['Content-Length'])
206 label = cherrypy.request.rfile.read(body_length)
207
208 if label:
209 label = label.strip()
210 if label:
211 return updater.HandleSetUpdatePing(ip, label)
212 raise cherrypy.HTTPError(400, 'No label provided.')
213
214
David Rochberg7c79a812011-01-19 14:24:45 -0500215class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700216 """The Root Class for the Dev Server.
217
218 CherryPy works as follows:
219 For each method in this class, cherrpy interprets root/path
220 as a call to an instance of DevServerRoot->method_name. For example,
221 a call to http://myhost/build will call build. CherryPy automatically
222 parses http args and places them as keyword arguments in each method.
223 For paths http://myhost/update/dir1/dir2, you can use *args so that
224 cherrypy uses the update method and puts the extra paths in args.
225 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700226 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700227
David Rochberg7c79a812011-01-19 14:24:45 -0500228 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700229 self._builder = None
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700230 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700231 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500232
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700233 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500234 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700235 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700236 import builder
237 if self._builder is None:
238 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500239 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700240
Chris Sosacde6bf42012-05-31 18:36:39 -0700241 @staticmethod
242 def _canonicalize_archive_url(archive_url):
243 """Canonicalizes archive_url strings.
244
245 Raises:
246 DevserverError: if archive_url is not set.
247 """
248 if archive_url:
249 return archive_url.rstrip('/')
250 else:
251 raise DevServerError("Must specify an archive_url in the request")
252
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700253 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800254 def download(self, **kwargs):
255 """Downloads and archives full/delta payloads from Google Storage.
256
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700257 This methods downloads artifacts. It may download artifacts in the
258 background in which case a caller should call wait_for_status to get
259 the status of the background artifact downloads. They should use the same
260 args passed to download.
261
Frank Farzanbcb571e2012-01-03 11:48:17 -0800262 Args:
263 archive_url: Google Storage URL for the build.
264
265 Example URL:
266 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
267 'x86-generic/R17-1208.0.0-a1-b338'
268 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700269 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700270
Chris Sosacde6bf42012-05-31 18:36:39 -0700271 # Guarantees that no two downloads for the same url can run this code
272 # at the same time.
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700273 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-05-31 18:36:39 -0700274 try:
275 # If we are currently downloading, return. Note, due to the above lock
276 # we know that the foreground artifacts must have finished downloading
277 # and returned Success if this downloader instance exists.
278 if (self._downloader_dict.get(archive_url) or
279 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700280 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-05-31 18:36:39 -0700281 return 'Success'
282
283 downloader_instance = downloader.Downloader(updater.static_dir)
284 self._downloader_dict[archive_url] = downloader_instance
285 return downloader_instance.Download(archive_url, background=True)
286
287 except:
288 # On any exception, reset the state of the downloader_dict.
289 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700290 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700291
292 @cherrypy.expose
293 def wait_for_status(self, **kwargs):
294 """Waits for background artifacts to be downloaded from Google Storage.
295
296 Args:
297 archive_url: Google Storage URL for the build.
298
299 Example URL:
300 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
301 'x86-generic/R17-1208.0.0-a1-b338'
302 """
303 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
304 downloader_instance = self._downloader_dict.get(archive_url)
305 if downloader_instance:
306 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700307 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700308 return status
309 else:
310 # We may have previously downloaded but removed the downloader instance
311 # from the cache.
312 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
313 logging.info('%s not found in downloader cache but previously staged.',
314 archive_url)
315 return 'Success'
316 else:
317 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700318
319 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700320 def stage_debug(self, **kwargs):
321 """Downloads and stages debug symbol payloads from Google Storage.
322
323 This methods downloads the debug symbol build artifact synchronously,
324 and then stages it for use by symbolicate_dump/.
325
326 Args:
327 archive_url: Google Storage URL for the build.
328
329 Example URL:
330 'http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/'
331 'x86-generic/R17-1208.0.0-a1-b338'
332 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700333 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700334 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
335
336 @cherrypy.expose
337 def symbolicate_dump(self, minidump):
338 """Symbolicates a minidump using pre-downloaded symbols, returns it.
339
340 Callers will need to POST to this URL with a body of MIME-type
341 "multipart/form-data".
342 The body should include a single argument, 'minidump', containing the
343 binary-formatted minidump to symbolicate.
344
345 It is up to the caller to ensure that the symbols they want are currently
346 staged.
347
348 Args:
349 minidump: The binary minidump file to symbolicate.
350 """
351 to_return = ''
352 with tempfile.NamedTemporaryFile() as local:
353 while True:
354 data = minidump.file.read(8192)
355 if not data:
356 break
357 local.write(data)
358 local.flush()
359 stackwalk = subprocess.Popen(['minidump_stackwalk',
360 local.name,
361 updater.static_dir + '/debug/breakpad'],
362 stdout=subprocess.PIPE,
363 stderr=subprocess.PIPE)
364 to_return, error_text = stackwalk.communicate()
365 if stackwalk.returncode != 0:
366 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
367 error_text, stackwalk.returncode))
368
369 return to_return
370
371 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400372 def latestbuild(self, **params):
373 """Return a string representing the latest build for a given target.
374
375 Args:
376 target: The build target, typically a combination of the board and the
377 type of build e.g. x86-mario-release.
378 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
379 provided the latest RXX build will be returned.
380 Returns:
381 A string representation of the latest build if one exists, i.e.
382 R19-1993.0.0-a1-b1480.
383 An empty string if no latest could be found.
384 """
385 if not params:
386 return _PrintDocStringAsHTML(self.latestbuild)
387
388 if 'target' not in params:
389 raise cherrypy.HTTPError('500 Internal Server Error',
390 'Error: target= is required!')
391 try:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700392 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 15:31:36 -0400393 updater.static_dir, params['target'],
394 milestone=params.get('milestone'))
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700395 except common_util.DevServerUtilError as errmsg:
Scott Zawalski16954532012-03-20 15:31:36 -0400396 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
397
398 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500399 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500400 """Return a control file or a list of all known control files.
401
402 Example URL:
403 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500404 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500405 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500406 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 -0500407
408 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500409 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500410 control_path: If you want the contents of a control file set this
411 to the path. E.g. client/site_tests/sleeptest/control
412 Optional, if not provided return a list of control files is returned.
413 Returns:
414 Contents of a control file if control_path is provided.
415 A list of control files if no control_path is provided.
416 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500417 if not params:
418 return _PrintDocStringAsHTML(self.controlfiles)
419
Scott Zawalski84a39c92012-01-13 15:12:42 -0500420 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500421 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500422 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500423
424 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700425 return common_util.GetControlFileList(
426 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500427 else:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700428 return common_util.GetControlFile(
429 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800430
431 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 10:49:40 -0700432 def stage_images(self, **kwargs):
433 """Downloads and stages a Chrome OS image from Google Storage.
434
435 This method downloads a zipped archive from a specified GS location, then
436 extracts and stages the specified list of images and stages them under
437 static/images/BOARD/BUILD/. Download is synchronous.
438
439 Args:
440 archive_url: Google Storage URL for the build.
441 image_types: comma-separated list of images to download, may include
442 'test', 'recovery', and 'base'
443
444 Example URL:
445 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
446 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
447 """
448 # TODO(garnold) This needs to turn into an async operation, to avoid
449 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
450 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
451 image_types = kwargs.get('image_types').split(',')
452 return (downloader.ImagesDownloader(
453 updater.static_dir).Download(archive_url, image_types))
454
455 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700456 def index(self):
457 return 'Welcome to the Dev Server!'
458
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700459 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700460 def update(self, *args):
461 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800462 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700463 data = cherrypy.request.rfile.read(body_length)
464 return updater.HandleUpdatePing(data, label)
465
Chris Sosa0356d3b2010-09-16 15:46:22 -0700466
Chris Sosacde6bf42012-05-31 18:36:39 -0700467def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700468 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800469 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700470 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700471 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700472 parser.add_option('--board', dest='board',
473 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800474 parser.add_option('--clear_cache', action='store_true', default=False,
Chris Sosa6ab79622012-08-21 13:11:35 -0700475 help='Clear out all cached updates and exit')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800476 parser.add_option('--critical_update', dest='critical_update',
477 action='store_true', default=False,
478 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100479 parser.add_option('--data_dir', dest='data_dir',
480 help='Writable directory where static lives',
481 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800482 parser.add_option('--exit', action='store_true', default=False,
483 help='Don\'t start the server (still pregenerate or clear'
484 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700485 parser.add_option('--factory_config', dest='factory_config',
486 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700487 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
488 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700489 parser.add_option('--image', dest='image',
490 help='Force update using this image.')
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700491 parser.add_option('--logfile', dest='logfile',
492 help='Log output to this file instead of stdout.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700493 parser.add_option('-p', '--pregenerate_update', action='store_true',
494 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800495 parser.add_option('--payload', dest='payload',
496 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700497 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800498 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800499 parser.add_option('--private_key', default=None,
500 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800501 parser.add_option('--production', action='store_true', default=False,
502 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800503 parser.add_option('--proxy_port', default=None,
504 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700505 parser.add_option('--src_image', default='',
506 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700507 parser.add_option('-t', action='store_true', dest='test_image')
508 parser.add_option('-u', '--urlbase', dest='urlbase',
509 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700510 parser.add_option('--validate_factory_config', action="store_true",
511 dest='validate_factory_config',
512 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700513 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000514
Chris Sosa7c931362010-10-11 19:49:01 -0700515 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
516 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700517 serve_only = False
518
Zdenek Behan608f46c2011-02-19 00:47:16 +0100519 static_dir = os.path.realpath('%s/static' % options.data_dir)
520 os.system('mkdir -p %s' % static_dir)
521
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700522 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100523 # TODO(zbehan) Remove legacy support:
524 # archive_dir is the directory where static/archive will point.
525 # If this is an absolute path, all is fine. If someone calls this
526 # using a relative path, that is relative to src/platform/dev/.
527 # That use case is unmaintainable, but since applications use it
528 # with =./static, instead of a boolean flag, we'll make this relative
529 # to devserver_dir to keep these unbroken. For now.
530 archive_dir = options.archive_dir
531 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700532 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100533 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100534 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700535 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700536
Don Garrettf90edf02010-11-16 17:36:14 -0800537 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700538 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800539
Don Garrettf90edf02010-11-16 17:36:14 -0800540 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800541 if options.clear_cache:
542 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700543 cmd = 'rm -rf %s/*' % cache_dir
544 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700545 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800546 sys.exit(1)
547
548 else:
549 # Clear all but the last N cached updates
550 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
551 (cache_dir, CACHED_ENTRIES))
552 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700553 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800554 sys.exit(1)
555 else:
556 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800557
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700558 _Log('Data dir is %s' % options.data_dir)
559 _Log('Source root is %s' % root_dir)
560 _Log('Serving from %s' % static_dir)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000561
Chris Sosacde6bf42012-05-31 18:36:39 -0700562 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700563 updater = autoupdate.Autoupdate(
564 root_dir=root_dir,
565 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700566 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700567 urlbase=options.urlbase,
568 test_image=options.test_image,
569 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700570 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800571 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700572 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800573 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700574 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700575 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800576 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800577 copy_to_static_root=not options.exit,
578 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800579 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800580 )
Chris Sosa7c931362010-10-11 19:49:01 -0700581
582 # Sanity-check for use of validate_factory_config.
583 if not options.factory_config and options.validate_factory_config:
584 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000585
Chris Sosa0356d3b2010-09-16 15:46:22 -0700586 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700587 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700588 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700589 # We don't run the dev server with this option.
590 if options.validate_factory_config:
591 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700592 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700593 if not updater.PreGenerateUpdate():
594 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700595
Don Garrett0c880e22010-11-17 18:13:37 -0800596 # If the command line requested after setup, it's time to do it.
597 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700598 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700599 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700600 cherrypy.config.update({'environment': 'production'})
601 if not options.logfile:
602 cherrypy.config.update({'log.screen': True})
603 else:
604 cherrypy.config.update({'log.error_file': options.logfile,
605 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700606
Don Garrett0c880e22010-11-17 18:13:37 -0800607 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700608
609
610if __name__ == '__main__':
611 main()