blob: 07c85ee7349bcd49dfd16375f37ce633edbacb58 [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 Masonea32c3112012-05-01 09:35:44 -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 Masonea32c3112012-05-01 09:35:44 -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 'server.socket_timeout': 6000,
80 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 03:59:17 +010081 'tools.staticdir.root':
82 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070083 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070084 '/api':
85 {
86 # Gets rid of cherrypy parsing post file for args.
87 'request.process_request_body': False,
88 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070089 '/build':
90 {
91 'response.timeout': 100000,
92 },
Chris Sosa7c931362010-10-11 19:49:01 -070093 '/update':
94 {
95 # Gets rid of cherrypy parsing post file for args.
96 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070097 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070098 },
99 # Sets up the static dir for file hosting.
100 '/static':
101 { 'tools.staticdir.dir': 'static',
102 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700103 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700104 },
105 }
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500106
107 if options.log_dir:
108 base_config['global']['log.access_file'] = os.path.join(
109 options.log_dir, 'devserver_access.log')
110 base_config['global']['log.error_file'] = os.path.join(
111 options.log_dir, 'devserver_error.log')
112
Chris Sosa417e55d2011-01-25 16:40:48 -0800113 if options.production:
114 base_config['global']['server.environment'] = 'production'
115
Chris Sosa7c931362010-10-11 19:49:01 -0700116 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000117
Darin Petkove17164a2010-08-11 13:24:41 -0700118
Zdenek Behan608f46c2011-02-19 00:47:16 +0100119def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700120 """Sets up symlink to image_dir for serving purposes."""
121 assert os.path.exists(image_dir), '%s must exist.' % image_dir
122 # If we're serving out of an archived build dir (e.g. a
123 # buildbot), prepare this webserver's magic 'static/' dir with a
124 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -0700125 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
126 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100127 if os.path.lexists('%s/archive' % static_dir):
128 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-11 19:49:01 -0700129 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100130 os.unlink('%s/archive' % static_dir)
131 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700132 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100133 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700134 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
135 'DEVSERVER')
136
137
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700138class ApiRoot(object):
139 """RESTful API for Dev Server information."""
140 exposed = True
141
142 @cherrypy.expose
143 def hostinfo(self, ip):
144 """Returns a JSON dictionary containing information about the given ip.
145
146 Not all information may be known at the time the request is made. The
147 possible keys are:
148
149 last_event_type: int
150 Last update event type received.
151
152 last_event_status: int
153 Last update event status received.
154
155 last_known_version: string
156 Last known version recieved for update ping.
157
158 forced_update_label: string
159 Update label to force next update ping to use. Set by setnextupdate.
160
161 See the OmahaEvent class in update_engine/omaha_request_action.h for status
162 code definitions. If the ip does not exist an empty string is returned."""
163 return updater.HandleHostInfoPing(ip)
164
165 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800166 def hostlog(self, ip):
167 """Returns a JSON object containing a log of events pertaining to a
168 particular host, or all hosts. Log events contain a timestamp and any
169 subset of the attributes listed for the hostinfo method."""
170 return updater.HandleHostLogPing(ip)
171
172 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700173 def setnextupdate(self, ip):
174 """Allows the response to the next update ping from a host to be set.
175
176 Takes the IP of the host and an update label as normally provided to the
177 /update command."""
178 body_length = int(cherrypy.request.headers['Content-Length'])
179 label = cherrypy.request.rfile.read(body_length)
180
181 if label:
182 label = label.strip()
183 if label:
184 return updater.HandleSetUpdatePing(ip, label)
185 raise cherrypy.HTTPError(400, 'No label provided.')
186
187
David Rochberg7c79a812011-01-19 14:24:45 -0500188class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700189 """The Root Class for the Dev Server.
190
191 CherryPy works as follows:
192 For each method in this class, cherrpy interprets root/path
193 as a call to an instance of DevServerRoot->method_name. For example,
194 a call to http://myhost/build will call build. CherryPy automatically
195 parses http args and places them as keyword arguments in each method.
196 For paths http://myhost/update/dir1/dir2, you can use *args so that
197 cherrypy uses the update method and puts the extra paths in args.
198 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700199 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700200
David Rochberg7c79a812011-01-19 14:24:45 -0500201 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700202 self._builder = None
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700203 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500204
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700205 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500206 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700207 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700208 import builder
209 if self._builder is None:
210 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500211 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700212
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700213 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800214 def download(self, **kwargs):
215 """Downloads and archives full/delta payloads from Google Storage.
216
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700217 This methods downloads artifacts. It may download artifacts in the
218 background in which case a caller should call wait_for_status to get
219 the status of the background artifact downloads. They should use the same
220 args passed to download.
221
Frank Farzanbcb571e2012-01-03 11:48:17 -0800222 Args:
223 archive_url: Google Storage URL for the build.
224
225 Example URL:
226 'http://myhost/download?archive_url=gs://chromeos-image-archive/'
227 'x86-generic/R17-1208.0.0-a1-b338'
228 """
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700229 downloader_instance = downloader.Downloader(updater.static_dir)
230 archive_url = kwargs.get('archive_url')
231 if not archive_url:
232 raise DevServerError("Didn't specify the archive_url in request")
233
Chris Sosa781ba6d2012-04-11 12:44:43 -0700234 # Do this before we start such that other calls to the downloader or
235 # wait_for_status are blocked until this completed/failed.
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700236 self._downloader_dict[archive_url] = downloader_instance
Chris Sosa781ba6d2012-04-11 12:44:43 -0700237 try:
238 return_obj = downloader_instance.Download(archive_url, background=True)
239 except:
240 self._downloader_dict[archive_url] = None
241 raise
242
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700243 return return_obj
244
245 @cherrypy.expose
Chris Masonea32c3112012-05-01 09:35:44 -0700246 def symbolicate_dump(self, minidump):
247 """Symbolicates a minidump using pre-downloaded symbols, returns it.
248
249 Callers will need to POST to this URL with a body of MIME-type
250 "multipart/form-data".
251 The body should include a single argument, 'minidump', containing the
252 binary-formatted minidump to symbolicate.
253
254 It is up to the caller to ensure that the symbols they want are currently
255 staged.
256
257 Args:
258 minidump: The binary minidump file to symbolicate.
259 """
260 to_return = ''
261 with tempfile.NamedTemporaryFile() as local:
262 while True:
263 data = minidump.file.read(8192)
264 if not data:
265 break
266 local.write(data)
267 local.flush()
268 stackwalk = subprocess.Popen(['minidump_stackwalk',
269 local.name,
270 updater.static_dir + '/debug/breakpad'],
271 stdout=subprocess.PIPE,
272 stderr=subprocess.PIPE)
273 to_return, error_text = stackwalk.communicate()
274 if stackwalk.returncode != 0:
275 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
276 error_text, stackwalk.returncode))
277
278 return to_return
279
280 @cherrypy.expose
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700281 def wait_for_status(self, **kwargs):
282 """Waits for background artifacts to be downloaded from Google Storage.
283
284 Args:
285 archive_url: Google Storage URL for the build.
286
287 Example URL:
288 'http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/'
289 'x86-generic/R17-1208.0.0-a1-b338'
290 """
291 archive_url = kwargs.get('archive_url')
292 if not archive_url:
293 raise DevServerError("Didn't specify the archive_url in request")
294
295 downloader_instance = self._downloader_dict.get(archive_url)
296 if downloader_instance:
Chris Sosa781ba6d2012-04-11 12:44:43 -0700297 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700298 self._downloader_dict[archive_url] = None
Chris Sosa781ba6d2012-04-11 12:44:43 -0700299 return status
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700300 else:
Chris Sosa9164ca32012-03-28 11:04:50 -0700301 # We may have previously downloaded but removed the downloader instance
302 # from the cache.
303 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
Chris Sosa781ba6d2012-04-11 12:44:43 -0700304 logging.info('%s not found in downloader cache but previously staged.',
305 archive_url)
Chris Sosa9164ca32012-03-28 11:04:50 -0700306 return 'Success'
307 else:
308 raise DevServerError('No download for the given archive_url found.')
Frank Farzan40160872011-12-12 18:39:18 -0800309
310 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400311 def latestbuild(self, **params):
312 """Return a string representing the latest build for a given target.
313
314 Args:
315 target: The build target, typically a combination of the board and the
316 type of build e.g. x86-mario-release.
317 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
318 provided the latest RXX build will be returned.
319 Returns:
320 A string representation of the latest build if one exists, i.e.
321 R19-1993.0.0-a1-b1480.
322 An empty string if no latest could be found.
323 """
324 if not params:
325 return _PrintDocStringAsHTML(self.latestbuild)
326
327 if 'target' not in params:
328 raise cherrypy.HTTPError('500 Internal Server Error',
329 'Error: target= is required!')
330 try:
331 return devserver_util.GetLatestBuildVersion(
332 updater.static_dir, params['target'],
333 milestone=params.get('milestone'))
334 except devserver_util.DevServerUtilError as errmsg:
335 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
336
337 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500338 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500339 """Return a control file or a list of all known control files.
340
341 Example URL:
342 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500343 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500344 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500345 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 -0500346
347 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500348 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500349 control_path: If you want the contents of a control file set this
350 to the path. E.g. client/site_tests/sleeptest/control
351 Optional, if not provided return a list of control files is returned.
352 Returns:
353 Contents of a control file if control_path is provided.
354 A list of control files if no control_path is provided.
355 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500356 if not params:
357 return _PrintDocStringAsHTML(self.controlfiles)
358
Scott Zawalski84a39c92012-01-13 15:12:42 -0500359 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500360 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500361 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500362
363 if 'control_path' not in params:
364 return devserver_util.GetControlFileList(updater.static_dir,
Scott Zawalski84a39c92012-01-13 15:12:42 -0500365 params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500366 else:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500367 return devserver_util.GetControlFile(updater.static_dir, params['build'],
Scott Zawalski4647ce62012-01-03 17:17:28 -0500368 params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800369
370 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700371 def index(self):
372 return 'Welcome to the Dev Server!'
373
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700374 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700375 def update(self, *args):
376 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800377 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700378 data = cherrypy.request.rfile.read(body_length)
379 return updater.HandleUpdatePing(data, label)
380
Chris Sosa0356d3b2010-09-16 15:46:22 -0700381
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700382if __name__ == '__main__':
383 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800384 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700385 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700386 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700387 parser.add_option('--board', dest='board',
388 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800389 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800390 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 14:15:23 -0700391 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
392 help='No longer used. It is still here so we don\'t break '
393 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800394 parser.add_option('--critical_update', dest='critical_update',
395 action='store_true', default=False,
396 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100397 parser.add_option('--data_dir', dest='data_dir',
398 help='Writable directory where static lives',
399 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800400 parser.add_option('--exit', action='store_true', default=False,
401 help='Don\'t start the server (still pregenerate or clear'
402 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700403 parser.add_option('--factory_config', dest='factory_config',
404 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700405 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
406 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700407 parser.add_option('--image', dest='image',
408 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700409 parser.add_option('-p', '--pregenerate_update', action='store_true',
410 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800411 parser.add_option('--payload', dest='payload',
412 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700413 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800414 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800415 parser.add_option('--private_key', default=None,
416 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800417 parser.add_option('--production', action='store_true', default=False,
418 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800419 parser.add_option('--proxy_port', default=None,
420 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700421 parser.add_option('--src_image', default='',
422 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700423 parser.add_option('-t', action='store_true', dest='test_image')
424 parser.add_option('-u', '--urlbase', dest='urlbase',
425 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700426 parser.add_option('--validate_factory_config', action="store_true",
427 dest='validate_factory_config',
428 help='Validate factory config file, then exit.')
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500429 parser.add_option('-l', '--log-dir', default=None,
Chris Sosab65973e2012-03-29 18:31:02 -0700430 help=('Specify a directory for error and access logs. '
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500431 'Default None, i.e. no logging.'))
Chris Sosa7c931362010-10-11 19:49:01 -0700432 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000433
Chris Sosa7c931362010-10-11 19:49:01 -0700434 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
435 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700436 serve_only = False
437
Zdenek Behan608f46c2011-02-19 00:47:16 +0100438 static_dir = os.path.realpath('%s/static' % options.data_dir)
439 os.system('mkdir -p %s' % static_dir)
440
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500441 if options.log_dir and not os.path.isdir(options.log_dir):
442 parser.error('%s is not a valid dir, provide a valid dir to --log-dir' %
443 options.log_dir)
444
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700445 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100446 # TODO(zbehan) Remove legacy support:
447 # archive_dir is the directory where static/archive will point.
448 # If this is an absolute path, all is fine. If someone calls this
449 # using a relative path, that is relative to src/platform/dev/.
450 # That use case is unmaintainable, but since applications use it
451 # with =./static, instead of a boolean flag, we'll make this relative
452 # to devserver_dir to keep these unbroken. For now.
453 archive_dir = options.archive_dir
454 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700455 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100456 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100457 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700458 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700459
Don Garrettf90edf02010-11-16 17:36:14 -0800460 cache_dir = os.path.join(static_dir, 'cache')
461 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
462
Don Garrettf90edf02010-11-16 17:36:14 -0800463 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800464 if options.clear_cache:
465 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700466 cmd = 'rm -rf %s/*' % cache_dir
467 if os.system(cmd) != 0:
Chris Sosa6b8c3742011-01-31 12:12:17 -0800468 cherrypy.log('Failed to clear the cache with %s' % cmd,
469 'DEVSERVER')
470 sys.exit(1)
471
472 else:
473 # Clear all but the last N cached updates
474 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
475 (cache_dir, CACHED_ENTRIES))
476 if os.system(cmd) != 0:
477 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
478 'DEVSERVER')
479 sys.exit(1)
480 else:
481 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800482
Greg Spencerc8b59b22011-03-15 14:15:23 -0700483 if options.client_prefix_deprecated:
484 cherrypy.log('The --client_prefix argument is DEPRECATED, '
485 'and is no longer needed.', 'DEVSERVER')
486
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100487 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-11 19:49:01 -0700488 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
489 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000490
Andrew de los Reyes52620802010-04-12 13:40:07 -0700491 updater = autoupdate.Autoupdate(
492 root_dir=root_dir,
493 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700494 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700495 urlbase=options.urlbase,
496 test_image=options.test_image,
497 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700498 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800499 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700500 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800501 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700502 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700503 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800504 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800505 copy_to_static_root=not options.exit,
506 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800507 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800508 )
Chris Sosa7c931362010-10-11 19:49:01 -0700509
510 # Sanity-check for use of validate_factory_config.
511 if not options.factory_config and options.validate_factory_config:
512 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000513
Chris Sosa0356d3b2010-09-16 15:46:22 -0700514 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700515 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700516 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700517 # We don't run the dev server with this option.
518 if options.validate_factory_config:
519 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700520 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700521 if not updater.PreGenerateUpdate():
522 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700523
Don Garrett0c880e22010-11-17 18:13:37 -0800524 # If the command line requested after setup, it's time to do it.
525 if not options.exit:
526 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))