blob: 9590d6ee34046d6c96e9129037ab3e067d1fcb35 [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
Chris Sosacde6bf42012-05-31 18:36:39 -070011import multiprocessing
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,
Chris Sosa6fe23942012-07-02 15:44:46 -070080 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -070081 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +010082 'tools.staticdir.root':
83 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070084 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070085 '/api':
86 {
87 # Gets rid of cherrypy parsing post file for args.
88 'request.process_request_body': False,
89 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070090 '/build':
91 {
92 'response.timeout': 100000,
93 },
Chris Sosa7c931362010-10-11 19:49:01 -070094 '/update':
95 {
96 # Gets rid of cherrypy parsing post file for args.
97 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070098 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070099 },
100 # Sets up the static dir for file hosting.
101 '/static':
102 { 'tools.staticdir.dir': 'static',
103 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700104 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700105 },
106 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700107 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700108 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500109
Chris Sosa7c931362010-10-11 19:49:01 -0700110 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000111
Darin Petkove17164a2010-08-11 13:24:41 -0700112
Zdenek Behan608f46c2011-02-19 00:47:16 +0100113def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700114 """Sets up symlink to image_dir for serving purposes."""
115 assert os.path.exists(image_dir), '%s must exist.' % image_dir
116 # If we're serving out of an archived build dir (e.g. a
117 # buildbot), prepare this webserver's magic 'static/' dir with a
118 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -0700119 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
120 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100121 if os.path.lexists('%s/archive' % static_dir):
122 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700123 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100124 os.unlink('%s/archive' % static_dir)
125 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700126
Chris Sosa0356d3b2010-09-16 15:46:22 -0700127 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100128 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700129
Chris Sosa7c931362010-10-11 19:49:01 -0700130 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
131 'DEVSERVER')
132
133
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700134class ApiRoot(object):
135 """RESTful API for Dev Server information."""
136 exposed = True
137
138 @cherrypy.expose
139 def hostinfo(self, ip):
140 """Returns a JSON dictionary containing information about the given ip.
141
142 Not all information may be known at the time the request is made. The
143 possible keys are:
144
145 last_event_type: int
146 Last update event type received.
147
148 last_event_status: int
149 Last update event status received.
150
151 last_known_version: string
152 Last known version recieved for update ping.
153
154 forced_update_label: string
155 Update label to force next update ping to use. Set by setnextupdate.
156
157 See the OmahaEvent class in update_engine/omaha_request_action.h for status
158 code definitions. If the ip does not exist an empty string is returned."""
159 return updater.HandleHostInfoPing(ip)
160
161 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800162 def hostlog(self, ip):
163 """Returns a JSON object containing a log of events pertaining to a
164 particular host, or all hosts. Log events contain a timestamp and any
165 subset of the attributes listed for the hostinfo method."""
166 return updater.HandleHostLogPing(ip)
167
168 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700169 def setnextupdate(self, ip):
170 """Allows the response to the next update ping from a host to be set.
171
172 Takes the IP of the host and an update label as normally provided to the
173 /update command."""
174 body_length = int(cherrypy.request.headers['Content-Length'])
175 label = cherrypy.request.rfile.read(body_length)
176
177 if label:
178 label = label.strip()
179 if label:
180 return updater.HandleSetUpdatePing(ip, label)
181 raise cherrypy.HTTPError(400, 'No label provided.')
182
183
David Rochberg7c79a812011-01-19 14:24:45 -0500184class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700185 """The Root Class for the Dev Server.
186
187 CherryPy works as follows:
188 For each method in this class, cherrpy interprets root/path
189 as a call to an instance of DevServerRoot->method_name. For example,
190 a call to http://myhost/build will call build. CherryPy automatically
191 parses http args and places them as keyword arguments in each method.
192 For paths http://myhost/update/dir1/dir2, you can use *args so that
193 cherrypy uses the update method and puts the extra paths in args.
194 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700195 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700196
David Rochberg7c79a812011-01-19 14:24:45 -0500197 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700198 self._builder = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700199 self._lock_dict_lock = multiprocessing.Lock()
200 self._lock_dict = {}
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700201 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500202
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700203 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500204 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700205 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700206 import builder
207 if self._builder is None:
208 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500209 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700210
Chris Sosacde6bf42012-05-31 18:36:39 -0700211 def _get_lock_for_archive_url(self, archive_url):
212 """Return a multiprocessing lock to use per archive_url.
213
214 Use this lock to protect critical zones per archive_url.
215
216 Usage:
217 with DevserverInstance._get_lock_for_archive_url(archive_url):
218 # CRITICAL AREA FOR ARCHIVE_URL.
219
220 Returns:
221 A multiprocessing lock that is archive_url specific.
222 """
223 with self._lock_dict_lock:
224 lock = self._lock_dict.get(archive_url)
225 if lock:
226 return lock
227 else:
228 lock = multiprocessing.Lock()
229 self._lock_dict[archive_url] = lock
230 return lock
231
232 @staticmethod
233 def _canonicalize_archive_url(archive_url):
234 """Canonicalizes archive_url strings.
235
236 Raises:
237 DevserverError: if archive_url is not set.
238 """
239 if archive_url:
240 return archive_url.rstrip('/')
241 else:
242 raise DevServerError("Must specify an archive_url in the request")
243
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700244 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800245 def download(self, **kwargs):
246 """Downloads and archives full/delta payloads from Google Storage.
247
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700248 This methods downloads artifacts. It may download artifacts in the
249 background in which case a caller should call wait_for_status to get
250 the status of the background artifact downloads. They should use the same
251 args passed to download.
252
Frank Farzanbcb571e2012-01-03 11:48:17 -0800253 Args:
254 archive_url: Google Storage URL for the build.
255
256 Example URL:
257 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
258 'x86-generic/R17-1208.0.0-a1-b338'
259 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700260 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700261
Chris Sosacde6bf42012-05-31 18:36:39 -0700262 # Guarantees that no two downloads for the same url can run this code
263 # at the same time.
264 with self._get_lock_for_archive_url(archive_url):
265 try:
266 # If we are currently downloading, return. Note, due to the above lock
267 # we know that the foreground artifacts must have finished downloading
268 # and returned Success if this downloader instance exists.
269 if (self._downloader_dict.get(archive_url) or
270 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
271 cherrypy.log('Build %s has already been processed.' % archive_url,
272 'DEVSERVER')
273 return 'Success'
274
275 downloader_instance = downloader.Downloader(updater.static_dir)
276 self._downloader_dict[archive_url] = downloader_instance
277 return downloader_instance.Download(archive_url, background=True)
278
279 except:
280 # On any exception, reset the state of the downloader_dict.
281 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700282 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700283
284 @cherrypy.expose
285 def wait_for_status(self, **kwargs):
286 """Waits for background artifacts to be downloaded from Google Storage.
287
288 Args:
289 archive_url: Google Storage URL for the build.
290
291 Example URL:
292 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
293 'x86-generic/R17-1208.0.0-a1-b338'
294 """
295 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
296 downloader_instance = self._downloader_dict.get(archive_url)
297 if downloader_instance:
298 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700299 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700300 return status
301 else:
302 # We may have previously downloaded but removed the downloader instance
303 # from the cache.
304 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
305 logging.info('%s not found in downloader cache but previously staged.',
306 archive_url)
307 return 'Success'
308 else:
309 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700310
311 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700312 def stage_debug(self, **kwargs):
313 """Downloads and stages debug symbol payloads from Google Storage.
314
315 This methods downloads the debug symbol build artifact synchronously,
316 and then stages it for use by symbolicate_dump/.
317
318 Args:
319 archive_url: Google Storage URL for the build.
320
321 Example URL:
322 'http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/'
323 'x86-generic/R17-1208.0.0-a1-b338'
324 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700325 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700326 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
327
328 @cherrypy.expose
329 def symbolicate_dump(self, minidump):
330 """Symbolicates a minidump using pre-downloaded symbols, returns it.
331
332 Callers will need to POST to this URL with a body of MIME-type
333 "multipart/form-data".
334 The body should include a single argument, 'minidump', containing the
335 binary-formatted minidump to symbolicate.
336
337 It is up to the caller to ensure that the symbols they want are currently
338 staged.
339
340 Args:
341 minidump: The binary minidump file to symbolicate.
342 """
343 to_return = ''
344 with tempfile.NamedTemporaryFile() as local:
345 while True:
346 data = minidump.file.read(8192)
347 if not data:
348 break
349 local.write(data)
350 local.flush()
351 stackwalk = subprocess.Popen(['minidump_stackwalk',
352 local.name,
353 updater.static_dir + '/debug/breakpad'],
354 stdout=subprocess.PIPE,
355 stderr=subprocess.PIPE)
356 to_return, error_text = stackwalk.communicate()
357 if stackwalk.returncode != 0:
358 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
359 error_text, stackwalk.returncode))
360
361 return to_return
362
363 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400364 def latestbuild(self, **params):
365 """Return a string representing the latest build for a given target.
366
367 Args:
368 target: The build target, typically a combination of the board and the
369 type of build e.g. x86-mario-release.
370 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
371 provided the latest RXX build will be returned.
372 Returns:
373 A string representation of the latest build if one exists, i.e.
374 R19-1993.0.0-a1-b1480.
375 An empty string if no latest could be found.
376 """
377 if not params:
378 return _PrintDocStringAsHTML(self.latestbuild)
379
380 if 'target' not in params:
381 raise cherrypy.HTTPError('500 Internal Server Error',
382 'Error: target= is required!')
383 try:
384 return devserver_util.GetLatestBuildVersion(
385 updater.static_dir, params['target'],
386 milestone=params.get('milestone'))
387 except devserver_util.DevServerUtilError as errmsg:
388 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
389
390 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500391 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500392 """Return a control file or a list of all known control files.
393
394 Example URL:
395 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500396 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500397 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500398 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 -0500399
400 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500401 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500402 control_path: If you want the contents of a control file set this
403 to the path. E.g. client/site_tests/sleeptest/control
404 Optional, if not provided return a list of control files is returned.
405 Returns:
406 Contents of a control file if control_path is provided.
407 A list of control files if no control_path is provided.
408 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500409 if not params:
410 return _PrintDocStringAsHTML(self.controlfiles)
411
Scott Zawalski84a39c92012-01-13 15:12:42 -0500412 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500413 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500414 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500415
416 if 'control_path' not in params:
417 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 15:12:42 -0500418 params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500419 else:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500420 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 17:17:28 -0500421 params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800422
423 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700424 def index(self):
425 return 'Welcome to the Dev Server!'
426
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700427 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700428 def update(self, *args):
429 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800430 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700431 data = cherrypy.request.rfile.read(body_length)
432 return updater.HandleUpdatePing(data, label)
433
Chris Sosa0356d3b2010-09-16 15:46:22 -0700434
Chris Sosacde6bf42012-05-31 18:36:39 -0700435def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700436 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800437 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700438 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700439 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700440 parser.add_option('--board', dest='board',
441 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800442 parser.add_option('--clear_cache', action='store_true', default=False,
Chris Sosa6ab79622012-08-21 13:11:35 -0700443 help='Clear out all cached updates and exit')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800444 parser.add_option('--critical_update', dest='critical_update',
445 action='store_true', default=False,
446 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100447 parser.add_option('--data_dir', dest='data_dir',
448 help='Writable directory where static lives',
449 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800450 parser.add_option('--exit', action='store_true', default=False,
451 help='Don\'t start the server (still pregenerate or clear'
452 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700453 parser.add_option('--factory_config', dest='factory_config',
454 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700455 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
456 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700457 parser.add_option('--image', dest='image',
458 help='Force update using this image.')
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700459 parser.add_option('--logfile', dest='logfile',
460 help='Log output to this file instead of stdout.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700461 parser.add_option('-p', '--pregenerate_update', action='store_true',
462 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800463 parser.add_option('--payload', dest='payload',
464 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700465 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800466 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800467 parser.add_option('--private_key', default=None,
468 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800469 parser.add_option('--production', action='store_true', default=False,
470 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800471 parser.add_option('--proxy_port', default=None,
472 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700473 parser.add_option('--src_image', default='',
474 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700475 parser.add_option('-t', action='store_true', dest='test_image')
476 parser.add_option('-u', '--urlbase', dest='urlbase',
477 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700478 parser.add_option('--validate_factory_config', action="store_true",
479 dest='validate_factory_config',
480 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700481 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000482
Chris Sosa7c931362010-10-11 19:49:01 -0700483 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
484 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700485 serve_only = False
486
Zdenek Behan608f46c2011-02-19 00:47:16 +0100487 static_dir = os.path.realpath('%s/static' % options.data_dir)
488 os.system('mkdir -p %s' % static_dir)
489
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700490 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100491 # TODO(zbehan) Remove legacy support:
492 # archive_dir is the directory where static/archive will point.
493 # If this is an absolute path, all is fine. If someone calls this
494 # using a relative path, that is relative to src/platform/dev/.
495 # That use case is unmaintainable, but since applications use it
496 # with =./static, instead of a boolean flag, we'll make this relative
497 # to devserver_dir to keep these unbroken. For now.
498 archive_dir = options.archive_dir
499 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700500 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100501 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100502 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700503 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700504
Don Garrettf90edf02010-11-16 17:36:14 -0800505 cache_dir = os.path.join(static_dir, 'cache')
506 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
507
Don Garrettf90edf02010-11-16 17:36:14 -0800508 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800509 if options.clear_cache:
510 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700511 cmd = 'rm -rf %s/*' % cache_dir
512 if os.system(cmd) != 0:
Chris Sosa6b8c3742011-01-31 12:12:17 -0800513 cherrypy.log('Failed to clear the cache with %s' % cmd,
514 'DEVSERVER')
515 sys.exit(1)
516
517 else:
518 # Clear all but the last N cached updates
519 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
520 (cache_dir, CACHED_ENTRIES))
521 if os.system(cmd) != 0:
522 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
523 'DEVSERVER')
524 sys.exit(1)
525 else:
526 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800527
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100528 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-11 19:49:01 -0700529 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
530 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000531
Chris Sosacde6bf42012-05-31 18:36:39 -0700532 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700533 updater = autoupdate.Autoupdate(
534 root_dir=root_dir,
535 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700536 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700537 urlbase=options.urlbase,
538 test_image=options.test_image,
539 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700540 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800541 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700542 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800543 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700544 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700545 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800546 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800547 copy_to_static_root=not options.exit,
548 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800549 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800550 )
Chris Sosa7c931362010-10-11 19:49:01 -0700551
552 # Sanity-check for use of validate_factory_config.
553 if not options.factory_config and options.validate_factory_config:
554 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000555
Chris Sosa0356d3b2010-09-16 15:46:22 -0700556 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700557 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700558 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700559 # We don't run the dev server with this option.
560 if options.validate_factory_config:
561 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700562 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700563 if not updater.PreGenerateUpdate():
564 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700565
Don Garrett0c880e22010-11-17 18:13:37 -0800566 # If the command line requested after setup, it's time to do it.
567 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700568 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700569 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700570 cherrypy.config.update({'environment': 'production'})
571 if not options.logfile:
572 cherrypy.config.update({'log.screen': True})
573 else:
574 cherrypy.config.update({'log.error_file': options.logfile,
575 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700576
Don Garrett0c880e22010-11-17 18:13:37 -0800577 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700578
579
580if __name__ == '__main__':
581 main()