blob: 6a855e8a507522aedf5e01ae4a88063ed1397cf1 [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
Gilad Arnold55a2a372012-10-02 09:46:32 -07009import json
Chris Sosa781ba6d2012-04-11 12:44:43 -070010import logging
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070011import optparse
rtc@google.comded22402009-10-26 22:36:21 +000012import os
Scott Zawalski4647ce62012-01-03 17:17:28 -050013import re
Mandeep Singh Baines38dcdda2012-12-07 17:55:33 -080014import socket
chocobo@google.com4dc25812009-10-27 23:46:26 +000015import sys
Chris Masone816e38c2012-05-02 12:22:36 -070016import subprocess
17import tempfile
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070018import threading
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -070019import types
rtc@google.comded22402009-10-26 22:36:21 +000020
Gilad Arnoldabb352e2012-09-23 01:24:27 -070021import cherrypy
22
Chris Sosa0356d3b2010-09-16 15:46:22 -070023import autoupdate
Gilad Arnoldc65330c2012-09-20 15:17:48 -070024import common_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070025import downloader
Gilad Arnoldc65330c2012-09-20 15:17:48 -070026import log_util
27
28
29# Module-local log function.
30def _Log(message, *args, **kwargs):
31 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 15:46:22 -070032
Frank Farzan40160872011-12-12 18:39:18 -080033
Chris Sosa417e55d2011-01-25 16:40:48 -080034CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080035
Chris Sosa0356d3b2010-09-16 15:46:22 -070036# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000037global updater
38updater = None
rtc@google.comded22402009-10-26 22:36:21 +000039
Frank Farzan40160872011-12-12 18:39:18 -080040
Chris Sosa9164ca32012-03-28 11:04:50 -070041class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070042 """Exception class used by this module."""
43 pass
44
45
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070046class LockDict(object):
47 """A dictionary of locks.
48
49 This class provides a thread-safe store of threading.Lock objects, which can
50 be used to regulate access to any set of hashable resources. Usage:
51
52 foo_lock_dict = LockDict()
53 ...
54 with foo_lock_dict.lock('bar'):
55 # Critical section for 'bar'
56 """
57 def __init__(self):
58 self._lock = self._new_lock()
59 self._dict = {}
60
61 def _new_lock(self):
62 return threading.Lock()
63
64 def lock(self, key):
65 with self._lock:
66 lock = self._dict.get(key)
67 if not lock:
68 lock = self._new_lock()
69 self._dict[key] = lock
70 return lock
71
72
Scott Zawalski4647ce62012-01-03 17:17:28 -050073def _LeadingWhiteSpaceCount(string):
74 """Count the amount of leading whitespace in a string.
75
76 Args:
77 string: The string to count leading whitespace in.
78 Returns:
79 number of white space chars before characters start.
80 """
81 matched = re.match('^\s+', string)
82 if matched:
83 return len(matched.group())
84
85 return 0
86
87
88def _PrintDocStringAsHTML(func):
89 """Make a functions docstring somewhat HTML style.
90
91 Args:
92 func: The function to return the docstring from.
93 Returns:
94 A string that is somewhat formated for a web browser.
95 """
96 # TODO(scottz): Make this parse Args/Returns in a prettier way.
97 # Arguments could be bolded and indented etc.
98 html_doc = []
99 for line in func.__doc__.splitlines():
100 leading_space = _LeadingWhiteSpaceCount(line)
101 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700102 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -0500103
104 html_doc.append('<BR>%s' % line)
105
106 return '\n'.join(html_doc)
107
108
Chris Sosa7c931362010-10-11 19:49:01 -0700109def _GetConfig(options):
110 """Returns the configuration for the devserver."""
Mandeep Singh Baines38dcdda2012-12-07 17:55:33 -0800111
112 # On a system with IPv6 not compiled into the kernel,
113 # AF_INET6 sockets will return a socket.error exception.
114 # On such systems, fall-back to IPv4.
115 socket_host = '::'
116 try:
117 socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
118 except socket.error:
119 socket_host = '0.0.0.0'
120
Chris Sosa7c931362010-10-11 19:49:01 -0700121 base_config = { 'global':
122 { 'server.log_request_headers': True,
123 'server.protocol_version': 'HTTP/1.1',
Mandeep Singh Baines38dcdda2012-12-07 17:55:33 -0800124 'server.socket_host': socket_host,
Chris Sosa7c931362010-10-11 19:49:01 -0700125 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -0700126 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 15:44:46 -0700127 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -0700128 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +0100129 'tools.staticdir.root':
130 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -0700131 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700132 '/api':
133 {
134 # Gets rid of cherrypy parsing post file for args.
135 'request.process_request_body': False,
136 },
Chris Sosaa1ef0102010-10-21 16:22:35 -0700137 '/build':
138 {
139 'response.timeout': 100000,
140 },
Chris Sosa7c931362010-10-11 19:49:01 -0700141 '/update':
142 {
143 # Gets rid of cherrypy parsing post file for args.
144 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700145 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700146 },
147 # Sets up the static dir for file hosting.
148 '/static':
149 { 'tools.staticdir.dir': 'static',
150 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700151 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700152 },
153 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700154 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700155 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500156
Chris Sosa7c931362010-10-11 19:49:01 -0700157 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000158
Darin Petkove17164a2010-08-11 13:24:41 -0700159
Zdenek Behan608f46c2011-02-19 00:47:16 +0100160def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700161 """Sets up symlink to image_dir for serving purposes."""
162 assert os.path.exists(image_dir), '%s must exist.' % image_dir
163 # If we're serving out of an archived build dir (e.g. a
164 # buildbot), prepare this webserver's magic 'static/' dir with a
165 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700166 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100167 if os.path.lexists('%s/archive' % static_dir):
168 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700169 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-19 00:47:16 +0100170 os.unlink('%s/archive' % static_dir)
171 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700172
Chris Sosa0356d3b2010-09-16 15:46:22 -0700173 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100174 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700175
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700176 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700177
178
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700179def _GetRecursiveMemberObject(root, member_list):
180 """Returns an object corresponding to a nested member list.
181
182 Args:
183 root: the root object to search
184 member_list: list of nested members to search
185 Returns:
186 An object corresponding to the member name list; None otherwise.
187 """
188 for member in member_list:
189 next_root = root.__class__.__dict__.get(member)
190 if not next_root:
191 return None
192 root = next_root
193 return root
194
195
196def _IsExposed(name):
197 """Returns True iff |name| has an `exposed' attribute and it is set."""
198 return hasattr(name, 'exposed') and name.exposed
199
200
Gilad Arnold748c8322012-10-12 09:51:35 -0700201def _GetExposedMethod(root, nested_member, ignored=None):
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700202 """Returns a CherryPy-exposed method, if such exists.
203
204 Args:
205 root: the root object for searching
206 nested_member: a slash-joined path to the nested member
207 ignored: method paths to be ignored
208 Returns:
209 A function object corresponding to the path defined by |member_list| from
210 the |root| object, if the function is exposed and not ignored; None
211 otherwise.
212 """
Gilad Arnold748c8322012-10-12 09:51:35 -0700213 method = (not (ignored and nested_member in ignored) and
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700214 _GetRecursiveMemberObject(root, nested_member.split('/')))
215 if (method and type(method) == types.FunctionType and _IsExposed(method)):
216 return method
217
218
Gilad Arnold748c8322012-10-12 09:51:35 -0700219def _FindExposedMethods(root, prefix, unlisted=None):
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700220 """Finds exposed CherryPy methods.
221
222 Args:
223 root: the root object for searching
224 prefix: slash-joined chain of members leading to current object
225 unlisted: URLs to be excluded regardless of their exposed status
226 Returns:
227 List of exposed URLs that are not unlisted.
228 """
229 method_list = []
230 for member in sorted(root.__class__.__dict__.keys()):
231 prefixed_member = prefix + '/' + member if prefix else member
Gilad Arnold748c8322012-10-12 09:51:35 -0700232 if unlisted and prefixed_member in unlisted:
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700233 continue
234 member_obj = root.__class__.__dict__[member]
235 if _IsExposed(member_obj):
236 if type(member_obj) == types.FunctionType:
237 method_list.append(prefixed_member)
238 else:
239 method_list += _FindExposedMethods(
240 member_obj, prefixed_member, unlisted)
241 return method_list
242
243
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700244class ApiRoot(object):
245 """RESTful API for Dev Server information."""
246 exposed = True
247
248 @cherrypy.expose
249 def hostinfo(self, ip):
250 """Returns a JSON dictionary containing information about the given ip.
251
Gilad Arnold1b908392012-10-05 11:36:27 -0700252 Args:
253 ip: address of host whose info is requested
254 Returns:
255 A JSON dictionary containing all or some of the following fields:
256 last_event_type (int): last update event type received
257 last_event_status (int): last update event status received
258 last_known_version (string): last known version reported in update ping
259 forced_update_label (string): update label to force next update ping to
260 use, set by setnextupdate
261 See the OmahaEvent class in update_engine/omaha_request_action.h for
262 event type and status code definitions. If the ip does not exist an empty
263 string is returned.
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700264
Gilad Arnold1b908392012-10-05 11:36:27 -0700265 Example URL:
266 http://myhost/api/hostinfo?ip=192.168.1.5
267 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700268 return updater.HandleHostInfoPing(ip)
269
270 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800271 def hostlog(self, ip):
Gilad Arnold1b908392012-10-05 11:36:27 -0700272 """Returns a JSON object containing a log of host event.
273
274 Args:
275 ip: address of host whose event log is requested, or `all'
276 Returns:
277 A JSON encoded list (log) of dictionaries (events), each of which
278 containing a `timestamp' and other event fields, as described under
279 /api/hostinfo.
280
281 Example URL:
282 http://myhost/api/hostlog?ip=192.168.1.5
283 """
Gilad Arnold286a0062012-01-12 13:47:02 -0800284 return updater.HandleHostLogPing(ip)
285
286 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700287 def setnextupdate(self, ip):
288 """Allows the response to the next update ping from a host to be set.
289
290 Takes the IP of the host and an update label as normally provided to the
Gilad Arnold1b908392012-10-05 11:36:27 -0700291 /update command.
292 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700293 body_length = int(cherrypy.request.headers['Content-Length'])
294 label = cherrypy.request.rfile.read(body_length)
295
296 if label:
297 label = label.strip()
298 if label:
299 return updater.HandleSetUpdatePing(ip, label)
300 raise cherrypy.HTTPError(400, 'No label provided.')
301
302
Gilad Arnold55a2a372012-10-02 09:46:32 -0700303 @cherrypy.expose
304 def fileinfo(self, *path_args):
305 """Returns information about a given staged file.
306
307 Args:
308 path_args: path to the file inside the server's static staging directory
309 Returns:
310 A JSON encoded dictionary with information about the said file, which may
311 contain the following keys/values:
Gilad Arnold1b908392012-10-05 11:36:27 -0700312 size (int): the file size in bytes
313 sha1 (string): a base64 encoded SHA1 hash
314 sha256 (string): a base64 encoded SHA256 hash
315
316 Example URL:
317 http://myhost/api/fileinfo/some/path/to/file
Gilad Arnold55a2a372012-10-02 09:46:32 -0700318 """
319 file_path = os.path.join(updater.static_dir, *path_args)
320 if not os.path.exists(file_path):
321 raise DevServerError('file not found: %s' % file_path)
322 try:
323 file_size = os.path.getsize(file_path)
324 file_sha1 = common_util.GetFileSha1(file_path)
325 file_sha256 = common_util.GetFileSha256(file_path)
326 except os.error, e:
327 raise DevServerError('failed to get info for file %s: %s' %
328 (file_path, str(e)))
329 return json.dumps(
330 {'size': file_size, 'sha1': file_sha1, 'sha256': file_sha256})
331
David Rochberg7c79a812011-01-19 14:24:45 -0500332class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700333 """The Root Class for the Dev Server.
334
335 CherryPy works as follows:
336 For each method in this class, cherrpy interprets root/path
337 as a call to an instance of DevServerRoot->method_name. For example,
338 a call to http://myhost/build will call build. CherryPy automatically
339 parses http args and places them as keyword arguments in each method.
340 For paths http://myhost/update/dir1/dir2, you can use *args so that
341 cherrypy uses the update method and puts the extra paths in args.
342 """
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700343 # Method names that should not be listed on the index page.
344 _UNLISTED_METHODS = ['index', 'doc']
345
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700346 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700347
David Rochberg7c79a812011-01-19 14:24:45 -0500348 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700349 self._builder = None
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700350 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700351 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500352
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700353 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500354 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700355 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700356 import builder
357 if self._builder is None:
358 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500359 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700360
Chris Sosacde6bf42012-05-31 18:36:39 -0700361 @staticmethod
362 def _canonicalize_archive_url(archive_url):
363 """Canonicalizes archive_url strings.
364
365 Raises:
366 DevserverError: if archive_url is not set.
367 """
368 if archive_url:
369 return archive_url.rstrip('/')
370 else:
371 raise DevServerError("Must specify an archive_url in the request")
372
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700373 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800374 def download(self, **kwargs):
375 """Downloads and archives full/delta payloads from Google Storage.
376
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700377 This methods downloads artifacts. It may download artifacts in the
378 background in which case a caller should call wait_for_status to get
379 the status of the background artifact downloads. They should use the same
380 args passed to download.
381
Frank Farzanbcb571e2012-01-03 11:48:17 -0800382 Args:
383 archive_url: Google Storage URL for the build.
384
385 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700386 http://myhost/download?archive_url=gs://chromeos-image-archive/
387 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 11:48:17 -0800388 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700389 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700390
Chris Sosacde6bf42012-05-31 18:36:39 -0700391 # Guarantees that no two downloads for the same url can run this code
392 # at the same time.
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700393 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-05-31 18:36:39 -0700394 try:
395 # If we are currently downloading, return. Note, due to the above lock
396 # we know that the foreground artifacts must have finished downloading
397 # and returned Success if this downloader instance exists.
398 if (self._downloader_dict.get(archive_url) or
399 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700400 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-05-31 18:36:39 -0700401 return 'Success'
402
403 downloader_instance = downloader.Downloader(updater.static_dir)
404 self._downloader_dict[archive_url] = downloader_instance
405 return downloader_instance.Download(archive_url, background=True)
406
407 except:
408 # On any exception, reset the state of the downloader_dict.
409 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700410 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700411
412 @cherrypy.expose
413 def wait_for_status(self, **kwargs):
414 """Waits for background artifacts to be downloaded from Google Storage.
415
416 Args:
417 archive_url: Google Storage URL for the build.
418
419 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700420 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
421 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-05-31 18:36:39 -0700422 """
423 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
424 downloader_instance = self._downloader_dict.get(archive_url)
425 if downloader_instance:
426 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700427 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700428 return status
429 else:
430 # We may have previously downloaded but removed the downloader instance
431 # from the cache.
432 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
433 logging.info('%s not found in downloader cache but previously staged.',
434 archive_url)
435 return 'Success'
436 else:
437 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700438
439 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700440 def stage_debug(self, **kwargs):
441 """Downloads and stages debug symbol payloads from Google Storage.
442
443 This methods downloads the debug symbol build artifact synchronously,
444 and then stages it for use by symbolicate_dump/.
445
446 Args:
447 archive_url: Google Storage URL for the build.
448
449 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700450 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
451 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 12:22:36 -0700452 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700453 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700454 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
455
456 @cherrypy.expose
457 def symbolicate_dump(self, minidump):
458 """Symbolicates a minidump using pre-downloaded symbols, returns it.
459
460 Callers will need to POST to this URL with a body of MIME-type
461 "multipart/form-data".
462 The body should include a single argument, 'minidump', containing the
463 binary-formatted minidump to symbolicate.
464
465 It is up to the caller to ensure that the symbols they want are currently
466 staged.
467
468 Args:
469 minidump: The binary minidump file to symbolicate.
470 """
471 to_return = ''
472 with tempfile.NamedTemporaryFile() as local:
473 while True:
474 data = minidump.file.read(8192)
475 if not data:
476 break
477 local.write(data)
478 local.flush()
479 stackwalk = subprocess.Popen(['minidump_stackwalk',
480 local.name,
481 updater.static_dir + '/debug/breakpad'],
482 stdout=subprocess.PIPE,
483 stderr=subprocess.PIPE)
484 to_return, error_text = stackwalk.communicate()
485 if stackwalk.returncode != 0:
486 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
487 error_text, stackwalk.returncode))
488
489 return to_return
490
491 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400492 def latestbuild(self, **params):
493 """Return a string representing the latest build for a given target.
494
495 Args:
496 target: The build target, typically a combination of the board and the
497 type of build e.g. x86-mario-release.
498 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
499 provided the latest RXX build will be returned.
500 Returns:
501 A string representation of the latest build if one exists, i.e.
502 R19-1993.0.0-a1-b1480.
503 An empty string if no latest could be found.
504 """
505 if not params:
506 return _PrintDocStringAsHTML(self.latestbuild)
507
508 if 'target' not in params:
509 raise cherrypy.HTTPError('500 Internal Server Error',
510 'Error: target= is required!')
511 try:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700512 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 15:31:36 -0400513 updater.static_dir, params['target'],
514 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 10:05:01 -0700515 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 15:31:36 -0400516 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
517
518 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500519 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500520 """Return a control file or a list of all known control files.
521
522 Example URL:
523 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500524 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500525 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500526 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 -0500527
528 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500529 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500530 control_path: If you want the contents of a control file set this
531 to the path. E.g. client/site_tests/sleeptest/control
532 Optional, if not provided return a list of control files is returned.
533 Returns:
534 Contents of a control file if control_path is provided.
535 A list of control files if no control_path is provided.
536 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500537 if not params:
538 return _PrintDocStringAsHTML(self.controlfiles)
539
Scott Zawalski84a39c92012-01-13 15:12:42 -0500540 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500541 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500542 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500543
544 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700545 return common_util.GetControlFileList(
546 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500547 else:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700548 return common_util.GetControlFile(
549 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800550
551 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 10:49:40 -0700552 def stage_images(self, **kwargs):
553 """Downloads and stages a Chrome OS image from Google Storage.
554
555 This method downloads a zipped archive from a specified GS location, then
556 extracts and stages the specified list of images and stages them under
557 static/images/BOARD/BUILD/. Download is synchronous.
558
559 Args:
560 archive_url: Google Storage URL for the build.
561 image_types: comma-separated list of images to download, may include
562 'test', 'recovery', and 'base'
563
564 Example URL:
565 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
566 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
567 """
568 # TODO(garnold) This needs to turn into an async operation, to avoid
569 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
570 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
571 image_types = kwargs.get('image_types').split(',')
572 return (downloader.ImagesDownloader(
573 updater.static_dir).Download(archive_url, image_types))
574
575 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700576 def index(self):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700577 """Presents a welcome message and documentation links."""
578 method_dict = DevServerRoot.__dict__
579 return ('Welcome to the Dev Server!<br>\n'
580 '<br>\n'
581 'Here are the available methods, click for documentation:<br>\n'
582 '<br>\n'
583 '%s' %
584 '<br>\n'.join(
585 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700586 for name in _FindExposedMethods(
587 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700588
589 @cherrypy.expose
590 def doc(self, *args):
591 """Shows the documentation for available methods / URLs.
592
593 Example:
594 http://myhost/doc/update
595 """
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700596 name = '/'.join(args)
597 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700598 if not method:
599 raise DevServerError("No exposed method named `%s'" % name)
600 if not method.__doc__:
601 raise DevServerError("No documentation for exposed method `%s'" % name)
602 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-11 19:49:01 -0700603
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700604 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700605 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700606 """Handles an update check from a Chrome OS client.
607
608 The HTTP request should contain the standard Omaha-style XML blob. The URL
609 line may contain an additional intermediate path to the update payload.
610
611 Example:
612 http://myhost/update/optional/path/to/payload
613 """
Chris Sosa7c931362010-10-11 19:49:01 -0700614 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800615 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700616 data = cherrypy.request.rfile.read(body_length)
617 return updater.HandleUpdatePing(data, label)
618
Chris Sosa0356d3b2010-09-16 15:46:22 -0700619
Chris Sosacde6bf42012-05-31 18:36:39 -0700620def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700621 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800622 parser = optparse.OptionParser(usage=usage)
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700623 parser.add_option('--archive_dir',
624 metavar='PATH',
625 help='serve archived builds only')
626 parser.add_option('--board',
627 help='when pre-generating update, board for latest image')
628 parser.add_option('--clear_cache',
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800629 action='store_true', default=False,
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700630 help='clear out all cached updates and exit')
631 parser.add_option('--critical_update',
632 action='store_true', default=False,
633 help='present update payload as critical')
634 parser.add_option('--data_dir',
635 metavar='PATH',
636 default=os.path.dirname(os.path.abspath(sys.argv[0])),
637 help='writable directory where static lives')
638 parser.add_option('--exit',
639 action='store_true',
640 help='do not start server (yet pregenerate/clear cache)')
641 parser.add_option('--factory_config',
642 metavar='PATH',
643 help='config file for serving images from factory floor')
644 parser.add_option('--for_vm',
645 dest='vm', action='store_true',
646 help='update is for a vm image')
Gilad Arnold8318eac2012-10-04 12:52:23 -0700647 parser.add_option('--host_log',
648 action='store_true', default=False,
649 help='record history of host update events (/api/hostlog)')
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700650 parser.add_option('--image',
651 metavar='FILE',
652 help='force update using this image')
653 parser.add_option('--logfile',
654 metavar='PATH',
655 help='log output to this file instead of stdout')
Gilad Arnolda564b4b2012-10-04 10:32:44 -0700656 parser.add_option('--max_updates',
657 metavar='NUM', default=-1, type='int',
658 help='maximum number of update checks handled positively '
659 '(default: unlimited)')
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700660 parser.add_option('-p', '--pregenerate_update',
661 action='store_true', default=False,
662 help='pre-generate update payload')
663 parser.add_option('--payload',
664 metavar='PATH',
665 help='use update payload from specified directory')
666 parser.add_option('--port',
667 default=8080, type='int',
668 help='port for the dev server to use (default: 8080)')
669 parser.add_option('--private_key',
670 metavar='PATH', default=None,
671 help='path to the private key in pem format')
672 parser.add_option('--production',
673 action='store_true', default=False,
674 help='have the devserver use production values')
675 parser.add_option('--proxy_port',
676 metavar='PORT', default=None, type='int',
677 help='port to have the client connect to (testing support)')
678 parser.add_option('--remote_payload',
679 action='store_true', default=False,
680 help='Payload is being served from a remote machine')
681 parser.add_option('--src_image',
682 metavar='PATH', default='',
683 help='source image for generating delta updates from')
684 parser.add_option('-t', '--test_image',
685 action='store_true',
686 help='whether or not to use test images')
687 parser.add_option('-u', '--urlbase',
688 metavar='URL',
689 help='base URL for update images, other than the devserver')
690 parser.add_option('--validate_factory_config',
691 action="store_true",
692 help='validate factory config file, then exit')
Chris Sosa7c931362010-10-11 19:49:01 -0700693 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000694
Chris Sosa7c931362010-10-11 19:49:01 -0700695 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
696 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700697 serve_only = False
698
Zdenek Behan608f46c2011-02-19 00:47:16 +0100699 static_dir = os.path.realpath('%s/static' % options.data_dir)
700 os.system('mkdir -p %s' % static_dir)
701
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700702 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100703 # TODO(zbehan) Remove legacy support:
704 # archive_dir is the directory where static/archive will point.
705 # If this is an absolute path, all is fine. If someone calls this
706 # using a relative path, that is relative to src/platform/dev/.
707 # That use case is unmaintainable, but since applications use it
708 # with =./static, instead of a boolean flag, we'll make this relative
709 # to devserver_dir to keep these unbroken. For now.
710 archive_dir = options.archive_dir
711 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700712 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100713 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100714 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700715 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700716
Don Garrettf90edf02010-11-16 17:36:14 -0800717 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700718 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800719
Don Garrettf90edf02010-11-16 17:36:14 -0800720 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800721 if options.clear_cache:
722 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700723 cmd = 'rm -rf %s/*' % cache_dir
724 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700725 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800726 sys.exit(1)
727
728 else:
729 # Clear all but the last N cached updates
730 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
731 (cache_dir, CACHED_ENTRIES))
732 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700733 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800734 sys.exit(1)
735 else:
736 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800737
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700738 _Log('Data dir is %s' % options.data_dir)
739 _Log('Source root is %s' % root_dir)
740 _Log('Serving from %s' % static_dir)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000741
Chris Sosacde6bf42012-05-31 18:36:39 -0700742 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700743 updater = autoupdate.Autoupdate(
744 root_dir=root_dir,
745 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700746 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700747 urlbase=options.urlbase,
748 test_image=options.test_image,
749 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700750 forced_image=options.image,
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700751 payload_path=options.payload,
Don Garrett0ad09372010-12-06 16:20:30 -0800752 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700753 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700754 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800755 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800756 copy_to_static_root=not options.exit,
757 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800758 critical_update=options.critical_update,
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700759 remote_payload=options.remote_payload,
Gilad Arnolda564b4b2012-10-04 10:32:44 -0700760 max_updates=options.max_updates,
Gilad Arnold8318eac2012-10-04 12:52:23 -0700761 host_log=options.host_log,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800762 )
Chris Sosa7c931362010-10-11 19:49:01 -0700763
764 # Sanity-check for use of validate_factory_config.
765 if not options.factory_config and options.validate_factory_config:
766 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000767
Chris Sosa0356d3b2010-09-16 15:46:22 -0700768 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700769 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700770 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700771 # We don't run the dev server with this option.
772 if options.validate_factory_config:
773 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700774 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700775 if not updater.PreGenerateUpdate():
776 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700777
Don Garrett0c880e22010-11-17 18:13:37 -0800778 # If the command line requested after setup, it's time to do it.
779 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700780 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700781 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700782 cherrypy.config.update({'environment': 'production'})
783 if not options.logfile:
784 cherrypy.config.update({'log.screen': True})
785 else:
786 cherrypy.config.update({'log.error_file': options.logfile,
787 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700788
Don Garrett0c880e22010-11-17 18:13:37 -0800789 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700790
791
792if __name__ == '__main__':
793 main()