blob: 2f63f5df4d1b9d170894f948729274bad140ea56 [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
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -070017import types
rtc@google.comded22402009-10-26 22:36:21 +000018
Gilad Arnoldabb352e2012-09-23 01:24:27 -070019import cherrypy
20
Chris Sosa0356d3b2010-09-16 15:46:22 -070021import autoupdate
Gilad Arnoldc65330c2012-09-20 15:17:48 -070022import common_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070023import downloader
Gilad Arnoldc65330c2012-09-20 15:17:48 -070024import log_util
25
26
27# Module-local log function.
28def _Log(message, *args, **kwargs):
29 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 15:46:22 -070030
Frank Farzan40160872011-12-12 18:39:18 -080031
Chris Sosa417e55d2011-01-25 16:40:48 -080032CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080033
Chris Sosa0356d3b2010-09-16 15:46:22 -070034# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000035global updater
36updater = None
rtc@google.comded22402009-10-26 22:36:21 +000037
Frank Farzan40160872011-12-12 18:39:18 -080038
Chris Sosa9164ca32012-03-28 11:04:50 -070039class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070040 """Exception class used by this module."""
41 pass
42
43
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070044class LockDict(object):
45 """A dictionary of locks.
46
47 This class provides a thread-safe store of threading.Lock objects, which can
48 be used to regulate access to any set of hashable resources. Usage:
49
50 foo_lock_dict = LockDict()
51 ...
52 with foo_lock_dict.lock('bar'):
53 # Critical section for 'bar'
54 """
55 def __init__(self):
56 self._lock = self._new_lock()
57 self._dict = {}
58
59 def _new_lock(self):
60 return threading.Lock()
61
62 def lock(self, key):
63 with self._lock:
64 lock = self._dict.get(key)
65 if not lock:
66 lock = self._new_lock()
67 self._dict[key] = lock
68 return lock
69
70
Scott Zawalski4647ce62012-01-03 17:17:28 -050071def _LeadingWhiteSpaceCount(string):
72 """Count the amount of leading whitespace in a string.
73
74 Args:
75 string: The string to count leading whitespace in.
76 Returns:
77 number of white space chars before characters start.
78 """
79 matched = re.match('^\s+', string)
80 if matched:
81 return len(matched.group())
82
83 return 0
84
85
86def _PrintDocStringAsHTML(func):
87 """Make a functions docstring somewhat HTML style.
88
89 Args:
90 func: The function to return the docstring from.
91 Returns:
92 A string that is somewhat formated for a web browser.
93 """
94 # TODO(scottz): Make this parse Args/Returns in a prettier way.
95 # Arguments could be bolded and indented etc.
96 html_doc = []
97 for line in func.__doc__.splitlines():
98 leading_space = _LeadingWhiteSpaceCount(line)
99 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700100 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -0500101
102 html_doc.append('<BR>%s' % line)
103
104 return '\n'.join(html_doc)
105
106
Chris Sosa7c931362010-10-11 19:49:01 -0700107def _GetConfig(options):
108 """Returns the configuration for the devserver."""
109 base_config = { 'global':
110 { 'server.log_request_headers': True,
111 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -0700112 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -0700113 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -0700114 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 15:44:46 -0700115 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -0700116 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +0100117 'tools.staticdir.root':
118 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -0700119 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700120 '/api':
121 {
122 # Gets rid of cherrypy parsing post file for args.
123 'request.process_request_body': False,
124 },
Chris Sosaa1ef0102010-10-21 16:22:35 -0700125 '/build':
126 {
127 'response.timeout': 100000,
128 },
Chris Sosa7c931362010-10-11 19:49:01 -0700129 '/update':
130 {
131 # Gets rid of cherrypy parsing post file for args.
132 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700133 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700134 },
135 # Sets up the static dir for file hosting.
136 '/static':
137 { 'tools.staticdir.dir': 'static',
138 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700139 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700140 },
141 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700142 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700143 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500144
Chris Sosa7c931362010-10-11 19:49:01 -0700145 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000146
Darin Petkove17164a2010-08-11 13:24:41 -0700147
Zdenek Behan608f46c2011-02-19 00:47:16 +0100148def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700149 """Sets up symlink to image_dir for serving purposes."""
150 assert os.path.exists(image_dir), '%s must exist.' % image_dir
151 # If we're serving out of an archived build dir (e.g. a
152 # buildbot), prepare this webserver's magic 'static/' dir with a
153 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700154 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100155 if os.path.lexists('%s/archive' % static_dir):
156 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700157 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-19 00:47:16 +0100158 os.unlink('%s/archive' % static_dir)
159 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700160
Chris Sosa0356d3b2010-09-16 15:46:22 -0700161 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100162 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700163
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700164 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700165
166
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700167def _GetRecursiveMemberObject(root, member_list):
168 """Returns an object corresponding to a nested member list.
169
170 Args:
171 root: the root object to search
172 member_list: list of nested members to search
173 Returns:
174 An object corresponding to the member name list; None otherwise.
175 """
176 for member in member_list:
177 next_root = root.__class__.__dict__.get(member)
178 if not next_root:
179 return None
180 root = next_root
181 return root
182
183
184def _IsExposed(name):
185 """Returns True iff |name| has an `exposed' attribute and it is set."""
186 return hasattr(name, 'exposed') and name.exposed
187
188
189def _GetExposedMethod(root, nested_member, ignored=[]):
190 """Returns a CherryPy-exposed method, if such exists.
191
192 Args:
193 root: the root object for searching
194 nested_member: a slash-joined path to the nested member
195 ignored: method paths to be ignored
196 Returns:
197 A function object corresponding to the path defined by |member_list| from
198 the |root| object, if the function is exposed and not ignored; None
199 otherwise.
200 """
201 method = (nested_member not in ignored and
202 _GetRecursiveMemberObject(root, nested_member.split('/')))
203 if (method and type(method) == types.FunctionType and _IsExposed(method)):
204 return method
205
206
207def _FindExposedMethods(root, prefix, unlisted=[]):
208 """Finds exposed CherryPy methods.
209
210 Args:
211 root: the root object for searching
212 prefix: slash-joined chain of members leading to current object
213 unlisted: URLs to be excluded regardless of their exposed status
214 Returns:
215 List of exposed URLs that are not unlisted.
216 """
217 method_list = []
218 for member in sorted(root.__class__.__dict__.keys()):
219 prefixed_member = prefix + '/' + member if prefix else member
220 if prefixed_member in unlisted:
221 continue
222 member_obj = root.__class__.__dict__[member]
223 if _IsExposed(member_obj):
224 if type(member_obj) == types.FunctionType:
225 method_list.append(prefixed_member)
226 else:
227 method_list += _FindExposedMethods(
228 member_obj, prefixed_member, unlisted)
229 return method_list
230
231
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700232class ApiRoot(object):
233 """RESTful API for Dev Server information."""
234 exposed = True
235
236 @cherrypy.expose
237 def hostinfo(self, ip):
238 """Returns a JSON dictionary containing information about the given ip.
239
240 Not all information may be known at the time the request is made. The
241 possible keys are:
242
243 last_event_type: int
244 Last update event type received.
245
246 last_event_status: int
247 Last update event status received.
248
249 last_known_version: string
250 Last known version recieved for update ping.
251
252 forced_update_label: string
253 Update label to force next update ping to use. Set by setnextupdate.
254
255 See the OmahaEvent class in update_engine/omaha_request_action.h for status
256 code definitions. If the ip does not exist an empty string is returned."""
257 return updater.HandleHostInfoPing(ip)
258
259 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800260 def hostlog(self, ip):
261 """Returns a JSON object containing a log of events pertaining to a
262 particular host, or all hosts. Log events contain a timestamp and any
263 subset of the attributes listed for the hostinfo method."""
264 return updater.HandleHostLogPing(ip)
265
266 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700267 def setnextupdate(self, ip):
268 """Allows the response to the next update ping from a host to be set.
269
270 Takes the IP of the host and an update label as normally provided to the
271 /update command."""
272 body_length = int(cherrypy.request.headers['Content-Length'])
273 label = cherrypy.request.rfile.read(body_length)
274
275 if label:
276 label = label.strip()
277 if label:
278 return updater.HandleSetUpdatePing(ip, label)
279 raise cherrypy.HTTPError(400, 'No label provided.')
280
281
David Rochberg7c79a812011-01-19 14:24:45 -0500282class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700283 """The Root Class for the Dev Server.
284
285 CherryPy works as follows:
286 For each method in this class, cherrpy interprets root/path
287 as a call to an instance of DevServerRoot->method_name. For example,
288 a call to http://myhost/build will call build. CherryPy automatically
289 parses http args and places them as keyword arguments in each method.
290 For paths http://myhost/update/dir1/dir2, you can use *args so that
291 cherrypy uses the update method and puts the extra paths in args.
292 """
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700293 # Method names that should not be listed on the index page.
294 _UNLISTED_METHODS = ['index', 'doc']
295
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700296 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700297
David Rochberg7c79a812011-01-19 14:24:45 -0500298 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700299 self._builder = None
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700300 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700301 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500302
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700303 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500304 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700305 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700306 import builder
307 if self._builder is None:
308 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500309 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700310
Chris Sosacde6bf42012-05-31 18:36:39 -0700311 @staticmethod
312 def _canonicalize_archive_url(archive_url):
313 """Canonicalizes archive_url strings.
314
315 Raises:
316 DevserverError: if archive_url is not set.
317 """
318 if archive_url:
319 return archive_url.rstrip('/')
320 else:
321 raise DevServerError("Must specify an archive_url in the request")
322
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700323 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800324 def download(self, **kwargs):
325 """Downloads and archives full/delta payloads from Google Storage.
326
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700327 This methods downloads artifacts. It may download artifacts in the
328 background in which case a caller should call wait_for_status to get
329 the status of the background artifact downloads. They should use the same
330 args passed to download.
331
Frank Farzanbcb571e2012-01-03 11:48:17 -0800332 Args:
333 archive_url: Google Storage URL for the build.
334
335 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700336 http://myhost/download?archive_url=gs://chromeos-image-archive/
337 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 11:48:17 -0800338 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700339 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700340
Chris Sosacde6bf42012-05-31 18:36:39 -0700341 # Guarantees that no two downloads for the same url can run this code
342 # at the same time.
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700343 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-05-31 18:36:39 -0700344 try:
345 # If we are currently downloading, return. Note, due to the above lock
346 # we know that the foreground artifacts must have finished downloading
347 # and returned Success if this downloader instance exists.
348 if (self._downloader_dict.get(archive_url) or
349 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700350 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-05-31 18:36:39 -0700351 return 'Success'
352
353 downloader_instance = downloader.Downloader(updater.static_dir)
354 self._downloader_dict[archive_url] = downloader_instance
355 return downloader_instance.Download(archive_url, background=True)
356
357 except:
358 # On any exception, reset the state of the downloader_dict.
359 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700360 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700361
362 @cherrypy.expose
363 def wait_for_status(self, **kwargs):
364 """Waits for background artifacts to be downloaded from Google Storage.
365
366 Args:
367 archive_url: Google Storage URL for the build.
368
369 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700370 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
371 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-05-31 18:36:39 -0700372 """
373 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
374 downloader_instance = self._downloader_dict.get(archive_url)
375 if downloader_instance:
376 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700377 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700378 return status
379 else:
380 # We may have previously downloaded but removed the downloader instance
381 # from the cache.
382 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
383 logging.info('%s not found in downloader cache but previously staged.',
384 archive_url)
385 return 'Success'
386 else:
387 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700388
389 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700390 def stage_debug(self, **kwargs):
391 """Downloads and stages debug symbol payloads from Google Storage.
392
393 This methods downloads the debug symbol build artifact synchronously,
394 and then stages it for use by symbolicate_dump/.
395
396 Args:
397 archive_url: Google Storage URL for the build.
398
399 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700400 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
401 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 12:22:36 -0700402 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700403 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700404 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
405
406 @cherrypy.expose
407 def symbolicate_dump(self, minidump):
408 """Symbolicates a minidump using pre-downloaded symbols, returns it.
409
410 Callers will need to POST to this URL with a body of MIME-type
411 "multipart/form-data".
412 The body should include a single argument, 'minidump', containing the
413 binary-formatted minidump to symbolicate.
414
415 It is up to the caller to ensure that the symbols they want are currently
416 staged.
417
418 Args:
419 minidump: The binary minidump file to symbolicate.
420 """
421 to_return = ''
422 with tempfile.NamedTemporaryFile() as local:
423 while True:
424 data = minidump.file.read(8192)
425 if not data:
426 break
427 local.write(data)
428 local.flush()
429 stackwalk = subprocess.Popen(['minidump_stackwalk',
430 local.name,
431 updater.static_dir + '/debug/breakpad'],
432 stdout=subprocess.PIPE,
433 stderr=subprocess.PIPE)
434 to_return, error_text = stackwalk.communicate()
435 if stackwalk.returncode != 0:
436 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
437 error_text, stackwalk.returncode))
438
439 return to_return
440
441 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400442 def latestbuild(self, **params):
443 """Return a string representing the latest build for a given target.
444
445 Args:
446 target: The build target, typically a combination of the board and the
447 type of build e.g. x86-mario-release.
448 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
449 provided the latest RXX build will be returned.
450 Returns:
451 A string representation of the latest build if one exists, i.e.
452 R19-1993.0.0-a1-b1480.
453 An empty string if no latest could be found.
454 """
455 if not params:
456 return _PrintDocStringAsHTML(self.latestbuild)
457
458 if 'target' not in params:
459 raise cherrypy.HTTPError('500 Internal Server Error',
460 'Error: target= is required!')
461 try:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700462 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 15:31:36 -0400463 updater.static_dir, params['target'],
464 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 10:05:01 -0700465 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 15:31:36 -0400466 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
467
468 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500469 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500470 """Return a control file or a list of all known control files.
471
472 Example URL:
473 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500474 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500475 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500476 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 -0500477
478 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500479 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500480 control_path: If you want the contents of a control file set this
481 to the path. E.g. client/site_tests/sleeptest/control
482 Optional, if not provided return a list of control files is returned.
483 Returns:
484 Contents of a control file if control_path is provided.
485 A list of control files if no control_path is provided.
486 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500487 if not params:
488 return _PrintDocStringAsHTML(self.controlfiles)
489
Scott Zawalski84a39c92012-01-13 15:12:42 -0500490 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500491 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500492 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500493
494 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700495 return common_util.GetControlFileList(
496 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500497 else:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700498 return common_util.GetControlFile(
499 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800500
501 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 10:49:40 -0700502 def stage_images(self, **kwargs):
503 """Downloads and stages a Chrome OS image from Google Storage.
504
505 This method downloads a zipped archive from a specified GS location, then
506 extracts and stages the specified list of images and stages them under
507 static/images/BOARD/BUILD/. Download is synchronous.
508
509 Args:
510 archive_url: Google Storage URL for the build.
511 image_types: comma-separated list of images to download, may include
512 'test', 'recovery', and 'base'
513
514 Example URL:
515 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
516 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
517 """
518 # TODO(garnold) This needs to turn into an async operation, to avoid
519 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
520 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
521 image_types = kwargs.get('image_types').split(',')
522 return (downloader.ImagesDownloader(
523 updater.static_dir).Download(archive_url, image_types))
524
525 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700526 def index(self):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700527 """Presents a welcome message and documentation links."""
528 method_dict = DevServerRoot.__dict__
529 return ('Welcome to the Dev Server!<br>\n'
530 '<br>\n'
531 'Here are the available methods, click for documentation:<br>\n'
532 '<br>\n'
533 '%s' %
534 '<br>\n'.join(
535 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700536 for name in _FindExposedMethods(
537 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700538
539 @cherrypy.expose
540 def doc(self, *args):
541 """Shows the documentation for available methods / URLs.
542
543 Example:
544 http://myhost/doc/update
545 """
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700546 name = '/'.join(args)
547 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700548 if not method:
549 raise DevServerError("No exposed method named `%s'" % name)
550 if not method.__doc__:
551 raise DevServerError("No documentation for exposed method `%s'" % name)
552 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-11 19:49:01 -0700553
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700554 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700555 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700556 """Handles an update check from a Chrome OS client.
557
558 The HTTP request should contain the standard Omaha-style XML blob. The URL
559 line may contain an additional intermediate path to the update payload.
560
561 Example:
562 http://myhost/update/optional/path/to/payload
563 """
Chris Sosa7c931362010-10-11 19:49:01 -0700564 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800565 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700566 data = cherrypy.request.rfile.read(body_length)
567 return updater.HandleUpdatePing(data, label)
568
Chris Sosa0356d3b2010-09-16 15:46:22 -0700569
Chris Sosacde6bf42012-05-31 18:36:39 -0700570def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700571 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800572 parser = optparse.OptionParser(usage=usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700573 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700574 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700575 parser.add_option('--board', dest='board',
576 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800577 parser.add_option('--clear_cache', action='store_true', default=False,
Chris Sosa6ab79622012-08-21 13:11:35 -0700578 help='Clear out all cached updates and exit')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800579 parser.add_option('--critical_update', dest='critical_update',
580 action='store_true', default=False,
581 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100582 parser.add_option('--data_dir', dest='data_dir',
583 help='Writable directory where static lives',
584 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800585 parser.add_option('--exit', action='store_true', default=False,
586 help='Don\'t start the server (still pregenerate or clear'
587 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700588 parser.add_option('--factory_config', dest='factory_config',
589 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700590 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
591 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700592 parser.add_option('--image', dest='image',
593 help='Force update using this image.')
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700594 parser.add_option('--logfile', dest='logfile',
595 help='Log output to this file instead of stdout.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700596 parser.add_option('-p', '--pregenerate_update', action='store_true',
597 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800598 parser.add_option('--payload', dest='payload',
599 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700600 parser.add_option('--port', default=8080,
Gilad Arnold286a0062012-01-12 13:47:02 -0800601 help='Port for the dev server to use (default: 8080).')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800602 parser.add_option('--private_key', default=None,
603 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800604 parser.add_option('--production', action='store_true', default=False,
605 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800606 parser.add_option('--proxy_port', default=None,
607 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700608 parser.add_option('--src_image', default='',
609 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700610 parser.add_option('-t', action='store_true', dest='test_image')
611 parser.add_option('-u', '--urlbase', dest='urlbase',
612 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700613 parser.add_option('--validate_factory_config', action="store_true",
614 dest='validate_factory_config',
615 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700616 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000617
Chris Sosa7c931362010-10-11 19:49:01 -0700618 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
619 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700620 serve_only = False
621
Zdenek Behan608f46c2011-02-19 00:47:16 +0100622 static_dir = os.path.realpath('%s/static' % options.data_dir)
623 os.system('mkdir -p %s' % static_dir)
624
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700625 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100626 # TODO(zbehan) Remove legacy support:
627 # archive_dir is the directory where static/archive will point.
628 # If this is an absolute path, all is fine. If someone calls this
629 # using a relative path, that is relative to src/platform/dev/.
630 # That use case is unmaintainable, but since applications use it
631 # with =./static, instead of a boolean flag, we'll make this relative
632 # to devserver_dir to keep these unbroken. For now.
633 archive_dir = options.archive_dir
634 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700635 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100636 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100637 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700638 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700639
Don Garrettf90edf02010-11-16 17:36:14 -0800640 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700641 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800642
Don Garrettf90edf02010-11-16 17:36:14 -0800643 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800644 if options.clear_cache:
645 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700646 cmd = 'rm -rf %s/*' % cache_dir
647 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700648 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800649 sys.exit(1)
650
651 else:
652 # Clear all but the last N cached updates
653 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
654 (cache_dir, CACHED_ENTRIES))
655 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700656 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800657 sys.exit(1)
658 else:
659 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800660
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700661 _Log('Data dir is %s' % options.data_dir)
662 _Log('Source root is %s' % root_dir)
663 _Log('Serving from %s' % static_dir)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000664
Chris Sosacde6bf42012-05-31 18:36:39 -0700665 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700666 updater = autoupdate.Autoupdate(
667 root_dir=root_dir,
668 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700669 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700670 urlbase=options.urlbase,
671 test_image=options.test_image,
672 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700673 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800674 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700675 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800676 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700677 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700678 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800679 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800680 copy_to_static_root=not options.exit,
681 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800682 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800683 )
Chris Sosa7c931362010-10-11 19:49:01 -0700684
685 # Sanity-check for use of validate_factory_config.
686 if not options.factory_config and options.validate_factory_config:
687 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000688
Chris Sosa0356d3b2010-09-16 15:46:22 -0700689 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700690 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700691 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700692 # We don't run the dev server with this option.
693 if options.validate_factory_config:
694 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700695 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700696 if not updater.PreGenerateUpdate():
697 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700698
Don Garrett0c880e22010-11-17 18:13:37 -0800699 # If the command line requested after setup, it's time to do it.
700 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700701 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700702 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700703 cherrypy.config.update({'environment': 'production'})
704 if not options.logfile:
705 cherrypy.config.update({'log.screen': True})
706 else:
707 cherrypy.config.update({'log.error_file': options.logfile,
708 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700709
Don Garrett0c880e22010-11-17 18:13:37 -0800710 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700711
712
713if __name__ == '__main__':
714 main()