blob: bb22e22305cc6e909c846bae49504d108ef0da36 [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
rtc@google.comded22402009-10-26 22:36:21 +000015
Chris Sosa0356d3b2010-09-16 15:46:22 -070016import autoupdate
Scott Zawalski16954532012-03-20 15:31:36 -040017import devserver_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070018import downloader
Chris Sosa0356d3b2010-09-16 15:46:22 -070019
Frank Farzan40160872011-12-12 18:39:18 -080020
Chris Sosa417e55d2011-01-25 16:40:48 -080021CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080022
Chris Sosa0356d3b2010-09-16 15:46:22 -070023# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000024global updater
25updater = None
rtc@google.comded22402009-10-26 22:36:21 +000026
Frank Farzan40160872011-12-12 18:39:18 -080027
Chris Sosa9164ca32012-03-28 11:04:50 -070028class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070029 """Exception class used by this module."""
30 pass
31
32
Scott Zawalski4647ce62012-01-03 17:17:28 -050033def _LeadingWhiteSpaceCount(string):
34 """Count the amount of leading whitespace in a string.
35
36 Args:
37 string: The string to count leading whitespace in.
38 Returns:
39 number of white space chars before characters start.
40 """
41 matched = re.match('^\s+', string)
42 if matched:
43 return len(matched.group())
44
45 return 0
46
47
48def _PrintDocStringAsHTML(func):
49 """Make a functions docstring somewhat HTML style.
50
51 Args:
52 func: The function to return the docstring from.
53 Returns:
54 A string that is somewhat formated for a web browser.
55 """
56 # TODO(scottz): Make this parse Args/Returns in a prettier way.
57 # Arguments could be bolded and indented etc.
58 html_doc = []
59 for line in func.__doc__.splitlines():
60 leading_space = _LeadingWhiteSpaceCount(line)
61 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -070062 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -050063
64 html_doc.append('<BR>%s' % line)
65
66 return '\n'.join(html_doc)
67
68
Chris Sosa7c931362010-10-11 19:49:01 -070069def _GetConfig(options):
70 """Returns the configuration for the devserver."""
71 base_config = { 'global':
72 { 'server.log_request_headers': True,
73 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -070074 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -070075 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -070076 'server.socket_timeout': 6000,
77 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 03:59:17 +010078 'tools.staticdir.root':
79 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070080 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070081 '/api':
82 {
83 # Gets rid of cherrypy parsing post file for args.
84 'request.process_request_body': False,
85 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070086 '/build':
87 {
88 'response.timeout': 100000,
89 },
Chris Sosa7c931362010-10-11 19:49:01 -070090 '/update':
91 {
92 # Gets rid of cherrypy parsing post file for args.
93 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070094 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070095 },
96 # Sets up the static dir for file hosting.
97 '/static':
98 { 'tools.staticdir.dir': 'static',
99 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700100 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700101 },
102 }
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500103
104 if options.log_dir:
105 base_config['global']['log.access_file'] = os.path.join(
106 options.log_dir, 'devserver_access.log')
107 base_config['global']['log.error_file'] = os.path.join(
108 options.log_dir, 'devserver_error.log')
109
Chris Sosa417e55d2011-01-25 16:40:48 -0800110 if options.production:
111 base_config['global']['server.environment'] = 'production'
112
Chris Sosa7c931362010-10-11 19:49:01 -0700113 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000114
Darin Petkove17164a2010-08-11 13:24:41 -0700115
Zdenek Behan608f46c2011-02-19 00:47:16 +0100116def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700117 """Sets up symlink to image_dir for serving purposes."""
118 assert os.path.exists(image_dir), '%s must exist.' % image_dir
119 # If we're serving out of an archived build dir (e.g. a
120 # buildbot), prepare this webserver's magic 'static/' dir with a
121 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -0700122 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
123 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100124 if os.path.lexists('%s/archive' % static_dir):
125 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700126 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100127 os.unlink('%s/archive' % static_dir)
128 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700129 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100130 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700131 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
132 'DEVSERVER')
133
134
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700135class ApiRoot(object):
136 """RESTful API for Dev Server information."""
137 exposed = True
138
139 @cherrypy.expose
140 def hostinfo(self, ip):
141 """Returns a JSON dictionary containing information about the given ip.
142
143 Not all information may be known at the time the request is made. The
144 possible keys are:
145
146 last_event_type: int
147 Last update event type received.
148
149 last_event_status: int
150 Last update event status received.
151
152 last_known_version: string
153 Last known version recieved for update ping.
154
155 forced_update_label: string
156 Update label to force next update ping to use. Set by setnextupdate.
157
158 See the OmahaEvent class in update_engine/omaha_request_action.h for status
159 code definitions. If the ip does not exist an empty string is returned."""
160 return updater.HandleHostInfoPing(ip)
161
162 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800163 def hostlog(self, ip):
164 """Returns a JSON object containing a log of events pertaining to a
165 particular host, or all hosts. Log events contain a timestamp and any
166 subset of the attributes listed for the hostinfo method."""
167 return updater.HandleHostLogPing(ip)
168
169 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700170 def setnextupdate(self, ip):
171 """Allows the response to the next update ping from a host to be set.
172
173 Takes the IP of the host and an update label as normally provided to the
174 /update command."""
175 body_length = int(cherrypy.request.headers['Content-Length'])
176 label = cherrypy.request.rfile.read(body_length)
177
178 if label:
179 label = label.strip()
180 if label:
181 return updater.HandleSetUpdatePing(ip, label)
182 raise cherrypy.HTTPError(400, 'No label provided.')
183
184
David Rochberg7c79a812011-01-19 14:24:45 -0500185class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700186 """The Root Class for the Dev Server.
187
188 CherryPy works as follows:
189 For each method in this class, cherrpy interprets root/path
190 as a call to an instance of DevServerRoot->method_name. For example,
191 a call to http://myhost/build will call build. CherryPy automatically
192 parses http args and places them as keyword arguments in each method.
193 For paths http://myhost/update/dir1/dir2, you can use *args so that
194 cherrypy uses the update method and puts the extra paths in args.
195 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700196 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700197
David Rochberg7c79a812011-01-19 14:24:45 -0500198 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700199 self._builder = None
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700200 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500201
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700202 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500203 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700204 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700205 import builder
206 if self._builder is None:
207 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500208 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700209
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700210 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800211 def download(self, **kwargs):
212 """Downloads and archives full/delta payloads from Google Storage.
213
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700214 This methods downloads artifacts. It may download artifacts in the
215 background in which case a caller should call wait_for_status to get
216 the status of the background artifact downloads. They should use the same
217 args passed to download.
218
Frank Farzanbcb571e2012-01-03 11:48:17 -0800219 Args:
220 archive_url: Google Storage URL for the build.
221
222 Example URL:
223 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
224 'x86-generic/R17-1208.0.0-a1-b338'
225 """
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700226 downloader_instance = downloader.Downloader(updater.static_dir)
227 archive_url = kwargs.get('archive_url')
228 if not archive_url:
229 raise DevServerError("Didn't specify the archive_url in request")
230
Chris Sosa781ba6d2012-04-11 12:44:43 -0700231 # Do this before we start such that other calls to the downloader or
232 # wait_for_status are blocked until this completed/failed.
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700233 self._downloader_dict[archive_url] = downloader_instance
Chris Sosa781ba6d2012-04-11 12:44:43 -0700234 try:
235 return_obj = downloader_instance.Download(archive_url, background=True)
236 except:
237 self._downloader_dict[archive_url] = None
238 raise
239
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700240 return return_obj
241
242 @cherrypy.expose
243 def wait_for_status(self, **kwargs):
244 """Waits for background artifacts to be downloaded from Google Storage.
245
246 Args:
247 archive_url: Google Storage URL for the build.
248
249 Example URL:
250 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
251 'x86-generic/R17-1208.0.0-a1-b338'
252 """
253 archive_url = kwargs.get('archive_url')
254 if not archive_url:
255 raise DevServerError("Didn't specify the archive_url in request")
256
257 downloader_instance = self._downloader_dict.get(archive_url)
258 if downloader_instance:
Chris Sosa781ba6d2012-04-11 12:44:43 -0700259 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700260 self._downloader_dict[archive_url] = None
Chris Sosa781ba6d2012-04-11 12:44:43 -0700261 return status
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700262 else:
Chris Sosa9164ca32012-03-28 11:04:50 -0700263 # We may have previously downloaded but removed the downloader instance
264 # from the cache.
265 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
Chris Sosa781ba6d2012-04-11 12:44:43 -0700266 logging.info('%s not found in downloader cache but previously staged.',
267 archive_url)
Chris Sosa9164ca32012-03-28 11:04:50 -0700268 return 'Success'
269 else:
270 raise DevServerError('No download for the given archive_url found.')
Frank Farzan40160872011-12-12 18:39:18 -0800271
272 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400273 def latestbuild(self, **params):
274 """Return a string representing the latest build for a given target.
275
276 Args:
277 target: The build target, typically a combination of the board and the
278 type of build e.g. x86-mario-release.
279 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
280 provided the latest RXX build will be returned.
281 Returns:
282 A string representation of the latest build if one exists, i.e.
283 R19-1993.0.0-a1-b1480.
284 An empty string if no latest could be found.
285 """
286 if not params:
287 return _PrintDocStringAsHTML(self.latestbuild)
288
289 if 'target' not in params:
290 raise cherrypy.HTTPError('500 Internal Server Error',
291 'Error: target= is required!')
292 try:
293 return devserver_util.GetLatestBuildVersion(
294 updater.static_dir, params['target'],
295 milestone=params.get('milestone'))
296 except devserver_util.DevServerUtilError as errmsg:
297 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
298
299 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500300 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500301 """Return a control file or a list of all known control files.
302
303 Example URL:
304 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500305 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500306 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500307 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 -0500308
309 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500310 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500311 control_path: If you want the contents of a control file set this
312 to the path. E.g. client/site_tests/sleeptest/control
313 Optional, if not provided return a list of control files is returned.
314 Returns:
315 Contents of a control file if control_path is provided.
316 A list of control files if no control_path is provided.
317 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500318 if not params:
319 return _PrintDocStringAsHTML(self.controlfiles)
320
Scott Zawalski84a39c92012-01-13 15:12:42 -0500321 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500322 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500323 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500324
325 if 'control_path' not in params:
326 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 15:12:42 -0500327 params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500328 else:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500329 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 17:17:28 -0500330 params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800331
332 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700333 def index(self):
334 return 'Welcome to the Dev Server!'
335
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700336 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700337 def update(self, *args):
338 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800339 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700340 data = cherrypy.request.rfile.read(body_length)
341 return updater.HandleUpdatePing(data, label)
342
Chris Sosa0356d3b2010-09-16 15:46:22 -0700343
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700344if __name__ == '__main__':
345 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800346 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700347 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700348 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700349 parser.add_option('--board', dest='board',
350 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800351 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800352 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 14:15:23 -0700353 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
354 help='No longer used. It is still here so we don\'t break '
355 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800356 parser.add_option('--critical_update', dest='critical_update',
357 action='store_true', default=False,
358 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100359 parser.add_option('--data_dir', dest='data_dir',
360 help='Writable directory where static lives',
361 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800362 parser.add_option('--exit', action='store_true', default=False,
363 help='Don\'t start the server (still pregenerate or clear'
364 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700365 parser.add_option('--factory_config', dest='factory_config',
366 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700367 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
368 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700369 parser.add_option('--image', dest='image',
370 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700371 parser.add_option('-p', '--pregenerate_update', action='store_true',
372 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800373 parser.add_option('--payload', dest='payload',
374 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700375 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800376 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800377 parser.add_option('--private_key', default=None,
378 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800379 parser.add_option('--production', action='store_true', default=False,
380 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800381 parser.add_option('--proxy_port', default=None,
382 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700383 parser.add_option('--src_image', default='',
384 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700385 parser.add_option('-t', action='store_true', dest='test_image')
386 parser.add_option('-u', '--urlbase', dest='urlbase',
387 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700388 parser.add_option('--validate_factory_config', action="store_true",
389 dest='validate_factory_config',
390 help='Validate factory config file, then exit.')
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500391 parser.add_option('-l', '--log-dir', default=None,
Chris Sosab65973e2012-03-29 18:31:02 -0700392 help=('Specify a directory for error and access logs. '
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500393 'Default None, i.e. no logging.'))
Chris Sosa7c931362010-10-11 19:49:01 -0700394 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000395
Chris Sosa7c931362010-10-11 19:49:01 -0700396 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
397 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700398 serve_only = False
399
Zdenek Behan608f46c2011-02-19 00:47:16 +0100400 static_dir = os.path.realpath('%s/static' % options.data_dir)
401 os.system('mkdir -p %s' % static_dir)
402
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500403 if options.log_dir and not os.path.isdir(options.log_dir):
404 parser.error('%s is not a valid dir, provide a valid dir to --log-dir' %
405 options.log_dir)
406
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700407 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100408 # TODO(zbehan) Remove legacy support:
409 # archive_dir is the directory where static/archive will point.
410 # If this is an absolute path, all is fine. If someone calls this
411 # using a relative path, that is relative to src/platform/dev/.
412 # That use case is unmaintainable, but since applications use it
413 # with =./static, instead of a boolean flag, we'll make this relative
414 # to devserver_dir to keep these unbroken. For now.
415 archive_dir = options.archive_dir
416 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700417 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100418 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100419 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700420 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700421
Don Garrettf90edf02010-11-16 17:36:14 -0800422 cache_dir = os.path.join(static_dir, 'cache')
423 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
424
Don Garrettf90edf02010-11-16 17:36:14 -0800425 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800426 if options.clear_cache:
427 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700428 cmd = 'rm -rf %s/*' % cache_dir
429 if os.system(cmd) != 0:
Chris Sosa6b8c3742011-01-31 12:12:17 -0800430 cherrypy.log('Failed to clear the cache with %s' % cmd,
431 'DEVSERVER')
432 sys.exit(1)
433
434 else:
435 # Clear all but the last N cached updates
436 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
437 (cache_dir, CACHED_ENTRIES))
438 if os.system(cmd) != 0:
439 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
440 'DEVSERVER')
441 sys.exit(1)
442 else:
443 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800444
Greg Spencerc8b59b22011-03-15 14:15:23 -0700445 if options.client_prefix_deprecated:
446 cherrypy.log('The --client_prefix argument is DEPRECATED, '
447 'and is no longer needed.', 'DEVSERVER')
448
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100449 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-11 19:49:01 -0700450 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
451 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000452
Andrew de los Reyes52620802010-04-12 13:40:07 -0700453 updater = autoupdate.Autoupdate(
454 root_dir=root_dir,
455 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700456 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700457 urlbase=options.urlbase,
458 test_image=options.test_image,
459 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700460 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800461 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700462 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800463 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700464 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700465 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800466 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800467 copy_to_static_root=not options.exit,
468 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800469 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800470 )
Chris Sosa7c931362010-10-11 19:49:01 -0700471
472 # Sanity-check for use of validate_factory_config.
473 if not options.factory_config and options.validate_factory_config:
474 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000475
Chris Sosa0356d3b2010-09-16 15:46:22 -0700476 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700477 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700478 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700479 # We don't run the dev server with this option.
480 if options.validate_factory_config:
481 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700482 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700483 if not updater.PreGenerateUpdate():
484 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700485
Don Garrett0c880e22010-11-17 18:13:37 -0800486 # If the command line requested after setup, it's time to do it.
487 if not options.exit:
488 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))