blob: 95bcfb66b83ec711a20ded8467a21635f614a898 [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
Chris Sosa781ba6d2012-04-11 12:44:43 -07009import logging
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070010import optparse
rtc@google.comded22402009-10-26 22:36:21 +000011import os
Scott Zawalski4647ce62012-01-03 17:17:28 -050012import re
chocobo@google.com4dc25812009-10-27 23:46:26 +000013import sys
Chris Masone816e38c2012-05-02 12:22:36 -070014import subprocess
15import tempfile
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070016import threading
rtc@google.comded22402009-10-26 22:36:21 +000017
Gilad Arnoldabb352e2012-09-23 01:24:27 -070018import cherrypy
19
Chris Sosa0356d3b2010-09-16 15:46:22 -070020import autoupdate
Gilad Arnoldc65330c2012-09-20 15:17:48 -070021import common_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070022import downloader
Gilad Arnoldc65330c2012-09-20 15:17:48 -070023import log_util
24
25
26# Module-local log function.
27def _Log(message, *args, **kwargs):
28 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 15:46:22 -070029
Frank Farzan40160872011-12-12 18:39:18 -080030
Chris Sosa417e55d2011-01-25 16:40:48 -080031CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080032
Chris Sosa0356d3b2010-09-16 15:46:22 -070033# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000034global updater
35updater = None
rtc@google.comded22402009-10-26 22:36:21 +000036
Frank Farzan40160872011-12-12 18:39:18 -080037
Chris Sosa9164ca32012-03-28 11:04:50 -070038class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070039 """Exception class used by this module."""
40 pass
41
42
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070043class LockDict(object):
44 """A dictionary of locks.
45
46 This class provides a thread-safe store of threading.Lock objects, which can
47 be used to regulate access to any set of hashable resources. Usage:
48
49 foo_lock_dict = LockDict()
50 ...
51 with foo_lock_dict.lock('bar'):
52 # Critical section for 'bar'
53 """
54 def __init__(self):
55 self._lock = self._new_lock()
56 self._dict = {}
57
58 def _new_lock(self):
59 return threading.Lock()
60
61 def lock(self, key):
62 with self._lock:
63 lock = self._dict.get(key)
64 if not lock:
65 lock = self._new_lock()
66 self._dict[key] = lock
67 return lock
68
69
Scott Zawalski4647ce62012-01-03 17:17:28 -050070def _LeadingWhiteSpaceCount(string):
71 """Count the amount of leading whitespace in a string.
72
73 Args:
74 string: The string to count leading whitespace in.
75 Returns:
76 number of white space chars before characters start.
77 """
78 matched = re.match('^\s+', string)
79 if matched:
80 return len(matched.group())
81
82 return 0
83
84
85def _PrintDocStringAsHTML(func):
86 """Make a functions docstring somewhat HTML style.
87
88 Args:
89 func: The function to return the docstring from.
90 Returns:
91 A string that is somewhat formated for a web browser.
92 """
93 # TODO(scottz): Make this parse Args/Returns in a prettier way.
94 # Arguments could be bolded and indented etc.
95 html_doc = []
96 for line in func.__doc__.splitlines():
97 leading_space = _LeadingWhiteSpaceCount(line)
98 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -070099 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -0500100
101 html_doc.append('<BR>%s' % line)
102
103 return '\n'.join(html_doc)
104
105
Chris Sosa7c931362010-10-11 19:49:01 -0700106def _GetConfig(options):
107 """Returns the configuration for the devserver."""
108 base_config = { 'global':
109 { 'server.log_request_headers': True,
110 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -0700111 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -0700112 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -0700113 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 15:44:46 -0700114 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -0700115 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +0100116 'tools.staticdir.root':
117 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -0700118 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700119 '/api':
120 {
121 # Gets rid of cherrypy parsing post file for args.
122 'request.process_request_body': False,
123 },
Chris Sosaa1ef0102010-10-21 16:22:35 -0700124 '/build':
125 {
126 'response.timeout': 100000,
127 },
Chris Sosa7c931362010-10-11 19:49:01 -0700128 '/update':
129 {
130 # Gets rid of cherrypy parsing post file for args.
131 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700132 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700133 },
134 # Sets up the static dir for file hosting.
135 '/static':
136 { 'tools.staticdir.dir': 'static',
137 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700138 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700139 },
140 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700141 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700142 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500143
Chris Sosa7c931362010-10-11 19:49:01 -0700144 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000145
Darin Petkove17164a2010-08-11 13:24:41 -0700146
Zdenek Behan608f46c2011-02-19 00:47:16 +0100147def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700148 """Sets up symlink to image_dir for serving purposes."""
149 assert os.path.exists(image_dir), '%s must exist.' % image_dir
150 # If we're serving out of an archived build dir (e.g. a
151 # buildbot), prepare this webserver's magic 'static/' dir with a
152 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700153 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100154 if os.path.lexists('%s/archive' % static_dir):
155 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700156 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-19 00:47:16 +0100157 os.unlink('%s/archive' % static_dir)
158 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700159
Chris Sosa0356d3b2010-09-16 15:46:22 -0700160 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100161 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700162
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700163 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700164
165
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700166class ApiRoot(object):
167 """RESTful API for Dev Server information."""
168 exposed = True
169
170 @cherrypy.expose
171 def hostinfo(self, ip):
172 """Returns a JSON dictionary containing information about the given ip.
173
174 Not all information may be known at the time the request is made. The
175 possible keys are:
176
177 last_event_type: int
178 Last update event type received.
179
180 last_event_status: int
181 Last update event status received.
182
183 last_known_version: string
184 Last known version recieved for update ping.
185
186 forced_update_label: string
187 Update label to force next update ping to use. Set by setnextupdate.
188
189 See the OmahaEvent class in update_engine/omaha_request_action.h for status
190 code definitions. If the ip does not exist an empty string is returned."""
191 return updater.HandleHostInfoPing(ip)
192
193 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800194 def hostlog(self, ip):
195 """Returns a JSON object containing a log of events pertaining to a
196 particular host, or all hosts. Log events contain a timestamp and any
197 subset of the attributes listed for the hostinfo method."""
198 return updater.HandleHostLogPing(ip)
199
200 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700201 def setnextupdate(self, ip):
202 """Allows the response to the next update ping from a host to be set.
203
204 Takes the IP of the host and an update label as normally provided to the
205 /update command."""
206 body_length = int(cherrypy.request.headers['Content-Length'])
207 label = cherrypy.request.rfile.read(body_length)
208
209 if label:
210 label = label.strip()
211 if label:
212 return updater.HandleSetUpdatePing(ip, label)
213 raise cherrypy.HTTPError(400, 'No label provided.')
214
215
David Rochberg7c79a812011-01-19 14:24:45 -0500216class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700217 """The Root Class for the Dev Server.
218
219 CherryPy works as follows:
220 For each method in this class, cherrpy interprets root/path
221 as a call to an instance of DevServerRoot->method_name. For example,
222 a call to http://myhost/build will call build. CherryPy automatically
223 parses http args and places them as keyword arguments in each method.
224 For paths http://myhost/update/dir1/dir2, you can use *args so that
225 cherrypy uses the update method and puts the extra paths in args.
226 """
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700227 # Method names that should not be listed on the index page.
228 _UNLISTED_METHODS = ['index', 'doc']
229
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700230 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700231
David Rochberg7c79a812011-01-19 14:24:45 -0500232 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700233 self._builder = None
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700234 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700235 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500236
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700237 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500238 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700239 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700240 import builder
241 if self._builder is None:
242 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500243 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700244
Chris Sosacde6bf42012-05-31 18:36:39 -0700245 @staticmethod
246 def _canonicalize_archive_url(archive_url):
247 """Canonicalizes archive_url strings.
248
249 Raises:
250 DevserverError: if archive_url is not set.
251 """
252 if archive_url:
253 return archive_url.rstrip('/')
254 else:
255 raise DevServerError("Must specify an archive_url in the request")
256
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700257 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800258 def download(self, **kwargs):
259 """Downloads and archives full/delta payloads from Google Storage.
260
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700261 This methods downloads artifacts. It may download artifacts in the
262 background in which case a caller should call wait_for_status to get
263 the status of the background artifact downloads. They should use the same
264 args passed to download.
265
Frank Farzanbcb571e2012-01-03 11:48:17 -0800266 Args:
267 archive_url: Google Storage URL for the build.
268
269 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700270 http://myhost/download?archive_url=gs://chromeos-image-archive/
271 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 11:48:17 -0800272 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700273 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700274
Chris Sosacde6bf42012-05-31 18:36:39 -0700275 # Guarantees that no two downloads for the same url can run this code
276 # at the same time.
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700277 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-05-31 18:36:39 -0700278 try:
279 # If we are currently downloading, return. Note, due to the above lock
280 # we know that the foreground artifacts must have finished downloading
281 # and returned Success if this downloader instance exists.
282 if (self._downloader_dict.get(archive_url) or
283 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700284 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-05-31 18:36:39 -0700285 return 'Success'
286
287 downloader_instance = downloader.Downloader(updater.static_dir)
288 self._downloader_dict[archive_url] = downloader_instance
289 return downloader_instance.Download(archive_url, background=True)
290
291 except:
292 # On any exception, reset the state of the downloader_dict.
293 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700294 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700295
296 @cherrypy.expose
297 def wait_for_status(self, **kwargs):
298 """Waits for background artifacts to be downloaded from Google Storage.
299
300 Args:
301 archive_url: Google Storage URL for the build.
302
303 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700304 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
305 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-05-31 18:36:39 -0700306 """
307 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
308 downloader_instance = self._downloader_dict.get(archive_url)
309 if downloader_instance:
310 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700311 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700312 return status
313 else:
314 # We may have previously downloaded but removed the downloader instance
315 # from the cache.
316 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
317 logging.info('%s not found in downloader cache but previously staged.',
318 archive_url)
319 return 'Success'
320 else:
321 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700322
323 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700324 def stage_debug(self, **kwargs):
325 """Downloads and stages debug symbol payloads from Google Storage.
326
327 This methods downloads the debug symbol build artifact synchronously,
328 and then stages it for use by symbolicate_dump/.
329
330 Args:
331 archive_url: Google Storage URL for the build.
332
333 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700334 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
335 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 12:22:36 -0700336 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700337 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700338 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
339
340 @cherrypy.expose
341 def symbolicate_dump(self, minidump):
342 """Symbolicates a minidump using pre-downloaded symbols, returns it.
343
344 Callers will need to POST to this URL with a body of MIME-type
345 "multipart/form-data".
346 The body should include a single argument, 'minidump', containing the
347 binary-formatted minidump to symbolicate.
348
349 It is up to the caller to ensure that the symbols they want are currently
350 staged.
351
352 Args:
353 minidump: The binary minidump file to symbolicate.
354 """
355 to_return = ''
356 with tempfile.NamedTemporaryFile() as local:
357 while True:
358 data = minidump.file.read(8192)
359 if not data:
360 break
361 local.write(data)
362 local.flush()
363 stackwalk = subprocess.Popen(['minidump_stackwalk',
364 local.name,
365 updater.static_dir + '/debug/breakpad'],
366 stdout=subprocess.PIPE,
367 stderr=subprocess.PIPE)
368 to_return, error_text = stackwalk.communicate()
369 if stackwalk.returncode != 0:
370 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
371 error_text, stackwalk.returncode))
372
373 return to_return
374
375 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400376 def latestbuild(self, **params):
377 """Return a string representing the latest build for a given target.
378
379 Args:
380 target: The build target, typically a combination of the board and the
381 type of build e.g. x86-mario-release.
382 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
383 provided the latest RXX build will be returned.
384 Returns:
385 A string representation of the latest build if one exists, i.e.
386 R19-1993.0.0-a1-b1480.
387 An empty string if no latest could be found.
388 """
389 if not params:
390 return _PrintDocStringAsHTML(self.latestbuild)
391
392 if 'target' not in params:
393 raise cherrypy.HTTPError('500 Internal Server Error',
394 'Error: target= is required!')
395 try:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700396 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 15:31:36 -0400397 updater.static_dir, params['target'],
398 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 10:05:01 -0700399 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 15:31:36 -0400400 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
401
402 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500403 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500404 """Return a control file or a list of all known control files.
405
406 Example URL:
407 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500408 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500409 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500410 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 -0500411
412 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500413 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500414 control_path: If you want the contents of a control file set this
415 to the path. E.g. client/site_tests/sleeptest/control
416 Optional, if not provided return a list of control files is returned.
417 Returns:
418 Contents of a control file if control_path is provided.
419 A list of control files if no control_path is provided.
420 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500421 if not params:
422 return _PrintDocStringAsHTML(self.controlfiles)
423
Scott Zawalski84a39c92012-01-13 15:12:42 -0500424 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500425 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500426 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500427
428 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700429 return common_util.GetControlFileList(
430 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500431 else:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700432 return common_util.GetControlFile(
433 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800434
435 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 10:49:40 -0700436 def stage_images(self, **kwargs):
437 """Downloads and stages a Chrome OS image from Google Storage.
438
439 This method downloads a zipped archive from a specified GS location, then
440 extracts and stages the specified list of images and stages them under
441 static/images/BOARD/BUILD/. Download is synchronous.
442
443 Args:
444 archive_url: Google Storage URL for the build.
445 image_types: comma-separated list of images to download, may include
446 'test', 'recovery', and 'base'
447
448 Example URL:
449 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
450 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
451 """
452 # TODO(garnold) This needs to turn into an async operation, to avoid
453 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
454 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
455 image_types = kwargs.get('image_types').split(',')
456 return (downloader.ImagesDownloader(
457 updater.static_dir).Download(archive_url, image_types))
458
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700459 def _get_exposed_method(self, name, unlisted=[]):
460 """Checks whether a method is exposed as CherryPy URL.
461
462 Args:
463 name: method name to check
464 unlisted: methods to be excluded regardless of their exposed status
465 Returns:
466 Function object if method is exposed and not unlisted, None otherwise.
467 """
468 method = name not in unlisted and self.__class__.__dict__.get(name)
469 if method and hasattr(method, 'exposed') and method.exposed:
470 return method
471 return None
472
473 def _find_exposed_methods(self, unlisted=[]):
474 """Finds exposed CherryPy methods.
475
476 Args:
477 unlisted: methods to be excluded regardless of their exposed status
478 Returns:
479 List of exposed methods that are not unlisted.
480 """
481 return [name for name in self.__class__.__dict__.keys()
482 if self._get_exposed_method(name, unlisted)]
483
Gilad Arnold6f99b982012-09-12 10:49:40 -0700484 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700485 def index(self):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700486 """Presents a welcome message and documentation links."""
487 method_dict = DevServerRoot.__dict__
488 return ('Welcome to the Dev Server!<br>\n'
489 '<br>\n'
490 'Here are the available methods, click for documentation:<br>\n'
491 '<br>\n'
492 '%s' %
493 '<br>\n'.join(
494 [('<a href=doc/%s>%s</a>' % (name, name))
495 for name in self._find_exposed_methods(
496 unlisted=self._UNLISTED_METHODS)]))
497
498 @cherrypy.expose
499 def doc(self, *args):
500 """Shows the documentation for available methods / URLs.
501
502 Example:
503 http://myhost/doc/update
504 """
505 name = args[0]
506 method = self._get_exposed_method(name)
507 if not method:
508 raise DevServerError("No exposed method named `%s'" % name)
509 if not method.__doc__:
510 raise DevServerError("No documentation for exposed method `%s'" % name)
511 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-11 19:49:01 -0700512
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700513 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700514 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700515 """Handles an update check from a Chrome OS client.
516
517 The HTTP request should contain the standard Omaha-style XML blob. The URL
518 line may contain an additional intermediate path to the update payload.
519
520 Example:
521 http://myhost/update/optional/path/to/payload
522 """
Chris Sosa7c931362010-10-11 19:49:01 -0700523 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800524 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700525 data = cherrypy.request.rfile.read(body_length)
526 return updater.HandleUpdatePing(data, label)
527
Chris Sosa0356d3b2010-09-16 15:46:22 -0700528
Chris Sosacde6bf42012-05-31 18:36:39 -0700529def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700530 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800531 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700532 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700533 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700534 parser.add_option('--board', dest='board',
535 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800536 parser.add_option('--clear_cache', action='store_true', default=False,
Chris Sosa6ab79622012-08-21 13:11:35 -0700537 help='Clear out all cached updates and exit')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800538 parser.add_option('--critical_update', dest='critical_update',
539 action='store_true', default=False,
540 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100541 parser.add_option('--data_dir', dest='data_dir',
542 help='Writable directory where static lives',
543 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800544 parser.add_option('--exit', action='store_true', default=False,
545 help='Don\'t start the server (still pregenerate or clear'
546 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700547 parser.add_option('--factory_config', dest='factory_config',
548 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700549 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
550 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700551 parser.add_option('--image', dest='image',
552 help='Force update using this image.')
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700553 parser.add_option('--logfile', dest='logfile',
554 help='Log output to this file instead of stdout.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700555 parser.add_option('-p', '--pregenerate_update', action='store_true',
556 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800557 parser.add_option('--payload', dest='payload',
558 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700559 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800560 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800561 parser.add_option('--private_key', default=None,
562 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800563 parser.add_option('--production', action='store_true', default=False,
564 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800565 parser.add_option('--proxy_port', default=None,
566 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700567 parser.add_option('--src_image', default='',
568 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700569 parser.add_option('-t', action='store_true', dest='test_image')
570 parser.add_option('-u', '--urlbase', dest='urlbase',
571 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700572 parser.add_option('--validate_factory_config', action="store_true",
573 dest='validate_factory_config',
574 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700575 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000576
Chris Sosa7c931362010-10-11 19:49:01 -0700577 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
578 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700579 serve_only = False
580
Zdenek Behan608f46c2011-02-19 00:47:16 +0100581 static_dir = os.path.realpath('%s/static' % options.data_dir)
582 os.system('mkdir -p %s' % static_dir)
583
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700584 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100585 # TODO(zbehan) Remove legacy support:
586 # archive_dir is the directory where static/archive will point.
587 # If this is an absolute path, all is fine. If someone calls this
588 # using a relative path, that is relative to src/platform/dev/.
589 # That use case is unmaintainable, but since applications use it
590 # with =./static, instead of a boolean flag, we'll make this relative
591 # to devserver_dir to keep these unbroken. For now.
592 archive_dir = options.archive_dir
593 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700594 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100595 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100596 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700597 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700598
Don Garrettf90edf02010-11-16 17:36:14 -0800599 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700600 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800601
Don Garrettf90edf02010-11-16 17:36:14 -0800602 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800603 if options.clear_cache:
604 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700605 cmd = 'rm -rf %s/*' % cache_dir
606 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700607 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800608 sys.exit(1)
609
610 else:
611 # Clear all but the last N cached updates
612 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
613 (cache_dir, CACHED_ENTRIES))
614 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700615 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800616 sys.exit(1)
617 else:
618 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800619
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700620 _Log('Data dir is %s' % options.data_dir)
621 _Log('Source root is %s' % root_dir)
622 _Log('Serving from %s' % static_dir)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000623
Chris Sosacde6bf42012-05-31 18:36:39 -0700624 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700625 updater = autoupdate.Autoupdate(
626 root_dir=root_dir,
627 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700628 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700629 urlbase=options.urlbase,
630 test_image=options.test_image,
631 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700632 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800633 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700634 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800635 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700636 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700637 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800638 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800639 copy_to_static_root=not options.exit,
640 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800641 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800642 )
Chris Sosa7c931362010-10-11 19:49:01 -0700643
644 # Sanity-check for use of validate_factory_config.
645 if not options.factory_config and options.validate_factory_config:
646 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000647
Chris Sosa0356d3b2010-09-16 15:46:22 -0700648 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700649 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700650 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700651 # We don't run the dev server with this option.
652 if options.validate_factory_config:
653 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700654 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700655 if not updater.PreGenerateUpdate():
656 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700657
Don Garrett0c880e22010-11-17 18:13:37 -0800658 # If the command line requested after setup, it's time to do it.
659 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700660 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700661 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700662 cherrypy.config.update({'environment': 'production'})
663 if not options.logfile:
664 cherrypy.config.update({'log.screen': True})
665 else:
666 cherrypy.config.update({'log.error_file': options.logfile,
667 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700668
Don Garrett0c880e22010-11-17 18:13:37 -0800669 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700670
671
672if __name__ == '__main__':
673 main()