blob: 5692d97a397b8b20e92abf231c49dc4f7d41b827 [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
chocobo@google.com4dc25812009-10-27 23:46:26 +000014import sys
Chris Masone816e38c2012-05-02 12:22:36 -070015import subprocess
16import tempfile
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070017import threading
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -070018import types
rtc@google.comded22402009-10-26 22:36:21 +000019
Gilad Arnoldabb352e2012-09-23 01:24:27 -070020import cherrypy
21
Chris Sosa0356d3b2010-09-16 15:46:22 -070022import autoupdate
Gilad Arnoldc65330c2012-09-20 15:17:48 -070023import common_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070024import downloader
Gilad Arnoldc65330c2012-09-20 15:17:48 -070025import log_util
26
27
28# Module-local log function.
29def _Log(message, *args, **kwargs):
30 return log_util.LogWithTag('DEVSERVER', message, *args, **kwargs)
Chris Sosa0356d3b2010-09-16 15:46:22 -070031
Frank Farzan40160872011-12-12 18:39:18 -080032
Chris Sosa417e55d2011-01-25 16:40:48 -080033CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080034
Chris Sosa0356d3b2010-09-16 15:46:22 -070035# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000036global updater
37updater = None
rtc@google.comded22402009-10-26 22:36:21 +000038
Frank Farzan40160872011-12-12 18:39:18 -080039
Chris Sosa9164ca32012-03-28 11:04:50 -070040class DevServerError(Exception):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070041 """Exception class used by this module."""
42 pass
43
44
Gilad Arnold0b8c3f32012-09-19 14:35:44 -070045class LockDict(object):
46 """A dictionary of locks.
47
48 This class provides a thread-safe store of threading.Lock objects, which can
49 be used to regulate access to any set of hashable resources. Usage:
50
51 foo_lock_dict = LockDict()
52 ...
53 with foo_lock_dict.lock('bar'):
54 # Critical section for 'bar'
55 """
56 def __init__(self):
57 self._lock = self._new_lock()
58 self._dict = {}
59
60 def _new_lock(self):
61 return threading.Lock()
62
63 def lock(self, key):
64 with self._lock:
65 lock = self._dict.get(key)
66 if not lock:
67 lock = self._new_lock()
68 self._dict[key] = lock
69 return lock
70
71
Scott Zawalski4647ce62012-01-03 17:17:28 -050072def _LeadingWhiteSpaceCount(string):
73 """Count the amount of leading whitespace in a string.
74
75 Args:
76 string: The string to count leading whitespace in.
77 Returns:
78 number of white space chars before characters start.
79 """
80 matched = re.match('^\s+', string)
81 if matched:
82 return len(matched.group())
83
84 return 0
85
86
87def _PrintDocStringAsHTML(func):
88 """Make a functions docstring somewhat HTML style.
89
90 Args:
91 func: The function to return the docstring from.
92 Returns:
93 A string that is somewhat formated for a web browser.
94 """
95 # TODO(scottz): Make this parse Args/Returns in a prettier way.
96 # Arguments could be bolded and indented etc.
97 html_doc = []
98 for line in func.__doc__.splitlines():
99 leading_space = _LeadingWhiteSpaceCount(line)
100 if leading_space > 0:
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700101 line = ' ' * leading_space + line
Scott Zawalski4647ce62012-01-03 17:17:28 -0500102
103 html_doc.append('<BR>%s' % line)
104
105 return '\n'.join(html_doc)
106
107
Chris Sosa7c931362010-10-11 19:49:01 -0700108def _GetConfig(options):
109 """Returns the configuration for the devserver."""
110 base_config = { 'global':
111 { 'server.log_request_headers': True,
112 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -0700113 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -0700114 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -0700115 'response.timeout': 6000,
Chris Sosa6fe23942012-07-02 15:44:46 -0700116 'request.show_tracebacks': True,
Chris Sosa72333d12012-06-13 11:28:05 -0700117 'server.socket_timeout': 60,
Zdenek Behan1347a312011-02-10 03:59:17 +0100118 'tools.staticdir.root':
119 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -0700120 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700121 '/api':
122 {
123 # Gets rid of cherrypy parsing post file for args.
124 'request.process_request_body': False,
125 },
Chris Sosaa1ef0102010-10-21 16:22:35 -0700126 '/build':
127 {
128 'response.timeout': 100000,
129 },
Chris Sosa7c931362010-10-11 19:49:01 -0700130 '/update':
131 {
132 # Gets rid of cherrypy parsing post file for args.
133 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700134 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700135 },
136 # Sets up the static dir for file hosting.
137 '/static':
138 { 'tools.staticdir.dir': 'static',
139 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -0700140 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -0700141 },
142 }
Chris Sosa5f118ef2012-07-12 11:37:50 -0700143 if options.production:
Chris Sosad1ea86b2012-07-12 13:35:37 -0700144 base_config['global'].update({'server.thread_pool': 75})
Scott Zawalski1c5e7cd2012-02-27 13:12:52 -0500145
Chris Sosa7c931362010-10-11 19:49:01 -0700146 return base_config
rtc@google.com64244662009-11-12 00:52:08 +0000147
Darin Petkove17164a2010-08-11 13:24:41 -0700148
Zdenek Behan608f46c2011-02-19 00:47:16 +0100149def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700150 """Sets up symlink to image_dir for serving purposes."""
151 assert os.path.exists(image_dir), '%s must exist.' % image_dir
152 # If we're serving out of an archived build dir (e.g. a
153 # buildbot), prepare this webserver's magic 'static/' dir with a
154 # link to the build archive.
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700155 _Log('Preparing autoupdate for "serve updates only" mode.')
Zdenek Behan608f46c2011-02-19 00:47:16 +0100156 if os.path.lexists('%s/archive' % static_dir):
157 if image_dir != os.readlink('%s/archive' % static_dir):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700158 _Log('removing stale symlink to %s' % image_dir)
Zdenek Behan608f46c2011-02-19 00:47:16 +0100159 os.unlink('%s/archive' % static_dir)
160 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700161
Chris Sosa0356d3b2010-09-16 15:46:22 -0700162 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100163 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosacde6bf42012-05-31 18:36:39 -0700164
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700165 _Log('archive dir: %s ready to be used to serve images.' % image_dir)
Chris Sosa7c931362010-10-11 19:49:01 -0700166
167
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700168def _GetRecursiveMemberObject(root, member_list):
169 """Returns an object corresponding to a nested member list.
170
171 Args:
172 root: the root object to search
173 member_list: list of nested members to search
174 Returns:
175 An object corresponding to the member name list; None otherwise.
176 """
177 for member in member_list:
178 next_root = root.__class__.__dict__.get(member)
179 if not next_root:
180 return None
181 root = next_root
182 return root
183
184
185def _IsExposed(name):
186 """Returns True iff |name| has an `exposed' attribute and it is set."""
187 return hasattr(name, 'exposed') and name.exposed
188
189
Gilad Arnold748c8322012-10-12 09:51:35 -0700190def _GetExposedMethod(root, nested_member, ignored=None):
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700191 """Returns a CherryPy-exposed method, if such exists.
192
193 Args:
194 root: the root object for searching
195 nested_member: a slash-joined path to the nested member
196 ignored: method paths to be ignored
197 Returns:
198 A function object corresponding to the path defined by |member_list| from
199 the |root| object, if the function is exposed and not ignored; None
200 otherwise.
201 """
Gilad Arnold748c8322012-10-12 09:51:35 -0700202 method = (not (ignored and nested_member in ignored) and
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700203 _GetRecursiveMemberObject(root, nested_member.split('/')))
204 if (method and type(method) == types.FunctionType and _IsExposed(method)):
205 return method
206
207
Gilad Arnold748c8322012-10-12 09:51:35 -0700208def _FindExposedMethods(root, prefix, unlisted=None):
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700209 """Finds exposed CherryPy methods.
210
211 Args:
212 root: the root object for searching
213 prefix: slash-joined chain of members leading to current object
214 unlisted: URLs to be excluded regardless of their exposed status
215 Returns:
216 List of exposed URLs that are not unlisted.
217 """
218 method_list = []
219 for member in sorted(root.__class__.__dict__.keys()):
220 prefixed_member = prefix + '/' + member if prefix else member
Gilad Arnold748c8322012-10-12 09:51:35 -0700221 if unlisted and prefixed_member in unlisted:
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700222 continue
223 member_obj = root.__class__.__dict__[member]
224 if _IsExposed(member_obj):
225 if type(member_obj) == types.FunctionType:
226 method_list.append(prefixed_member)
227 else:
228 method_list += _FindExposedMethods(
229 member_obj, prefixed_member, unlisted)
230 return method_list
231
232
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700233class ApiRoot(object):
234 """RESTful API for Dev Server information."""
235 exposed = True
236
237 @cherrypy.expose
238 def hostinfo(self, ip):
239 """Returns a JSON dictionary containing information about the given ip.
240
Gilad Arnold1b908392012-10-05 11:36:27 -0700241 Args:
242 ip: address of host whose info is requested
243 Returns:
244 A JSON dictionary containing all or some of the following fields:
245 last_event_type (int): last update event type received
246 last_event_status (int): last update event status received
247 last_known_version (string): last known version reported in update ping
248 forced_update_label (string): update label to force next update ping to
249 use, set by setnextupdate
250 See the OmahaEvent class in update_engine/omaha_request_action.h for
251 event type and status code definitions. If the ip does not exist an empty
252 string is returned.
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700253
Gilad Arnold1b908392012-10-05 11:36:27 -0700254 Example URL:
255 http://myhost/api/hostinfo?ip=192.168.1.5
256 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700257 return updater.HandleHostInfoPing(ip)
258
259 @cherrypy.expose
Gilad Arnold286a0062012-01-12 13:47:02 -0800260 def hostlog(self, ip):
Gilad Arnold1b908392012-10-05 11:36:27 -0700261 """Returns a JSON object containing a log of host event.
262
263 Args:
264 ip: address of host whose event log is requested, or `all'
265 Returns:
266 A JSON encoded list (log) of dictionaries (events), each of which
267 containing a `timestamp' and other event fields, as described under
268 /api/hostinfo.
269
270 Example URL:
271 http://myhost/api/hostlog?ip=192.168.1.5
272 """
Gilad Arnold286a0062012-01-12 13:47:02 -0800273 return updater.HandleHostLogPing(ip)
274
275 @cherrypy.expose
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700276 def setnextupdate(self, ip):
277 """Allows the response to the next update ping from a host to be set.
278
279 Takes the IP of the host and an update label as normally provided to the
Gilad Arnold1b908392012-10-05 11:36:27 -0700280 /update command.
281 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700282 body_length = int(cherrypy.request.headers['Content-Length'])
283 label = cherrypy.request.rfile.read(body_length)
284
285 if label:
286 label = label.strip()
287 if label:
288 return updater.HandleSetUpdatePing(ip, label)
289 raise cherrypy.HTTPError(400, 'No label provided.')
290
291
Gilad Arnold55a2a372012-10-02 09:46:32 -0700292 @cherrypy.expose
293 def fileinfo(self, *path_args):
294 """Returns information about a given staged file.
295
296 Args:
297 path_args: path to the file inside the server's static staging directory
298 Returns:
299 A JSON encoded dictionary with information about the said file, which may
300 contain the following keys/values:
Gilad Arnold1b908392012-10-05 11:36:27 -0700301 size (int): the file size in bytes
302 sha1 (string): a base64 encoded SHA1 hash
303 sha256 (string): a base64 encoded SHA256 hash
304
305 Example URL:
306 http://myhost/api/fileinfo/some/path/to/file
Gilad Arnold55a2a372012-10-02 09:46:32 -0700307 """
308 file_path = os.path.join(updater.static_dir, *path_args)
309 if not os.path.exists(file_path):
310 raise DevServerError('file not found: %s' % file_path)
311 try:
312 file_size = os.path.getsize(file_path)
313 file_sha1 = common_util.GetFileSha1(file_path)
314 file_sha256 = common_util.GetFileSha256(file_path)
315 except os.error, e:
316 raise DevServerError('failed to get info for file %s: %s' %
317 (file_path, str(e)))
318 return json.dumps(
319 {'size': file_size, 'sha1': file_sha1, 'sha256': file_sha256})
320
David Rochberg7c79a812011-01-19 14:24:45 -0500321class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700322 """The Root Class for the Dev Server.
323
324 CherryPy works as follows:
325 For each method in this class, cherrpy interprets root/path
326 as a call to an instance of DevServerRoot->method_name. For example,
327 a call to http://myhost/build will call build. CherryPy automatically
328 parses http args and places them as keyword arguments in each method.
329 For paths http://myhost/update/dir1/dir2, you can use *args so that
330 cherrypy uses the update method and puts the extra paths in args.
331 """
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700332 # Method names that should not be listed on the index page.
333 _UNLISTED_METHODS = ['index', 'doc']
334
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700335 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700336
David Rochberg7c79a812011-01-19 14:24:45 -0500337 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700338 self._builder = None
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700339 self._download_lock_dict = LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700340 self._downloader_dict = {}
David Rochberg7c79a812011-01-19 14:24:45 -0500341
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700342 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500343 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700344 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700345 import builder
346 if self._builder is None:
347 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500348 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700349
Chris Sosacde6bf42012-05-31 18:36:39 -0700350 @staticmethod
351 def _canonicalize_archive_url(archive_url):
352 """Canonicalizes archive_url strings.
353
354 Raises:
355 DevserverError: if archive_url is not set.
356 """
357 if archive_url:
358 return archive_url.rstrip('/')
359 else:
360 raise DevServerError("Must specify an archive_url in the request")
361
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700362 @cherrypy.expose
Frank Farzanbcb571e2012-01-03 11:48:17 -0800363 def download(self, **kwargs):
364 """Downloads and archives full/delta payloads from Google Storage.
365
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700366 This methods downloads artifacts. It may download artifacts in the
367 background in which case a caller should call wait_for_status to get
368 the status of the background artifact downloads. They should use the same
369 args passed to download.
370
Frank Farzanbcb571e2012-01-03 11:48:17 -0800371 Args:
372 archive_url: Google Storage URL for the build.
373
374 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700375 http://myhost/download?archive_url=gs://chromeos-image-archive/
376 x86-generic/R17-1208.0.0-a1-b338
Frank Farzanbcb571e2012-01-03 11:48:17 -0800377 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700378 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700379
Chris Sosacde6bf42012-05-31 18:36:39 -0700380 # Guarantees that no two downloads for the same url can run this code
381 # at the same time.
Gilad Arnold0b8c3f32012-09-19 14:35:44 -0700382 with self._download_lock_dict.lock(archive_url):
Chris Sosacde6bf42012-05-31 18:36:39 -0700383 try:
384 # If we are currently downloading, return. Note, due to the above lock
385 # we know that the foreground artifacts must have finished downloading
386 # and returned Success if this downloader instance exists.
387 if (self._downloader_dict.get(archive_url) or
388 downloader.Downloader.BuildStaged(archive_url, updater.static_dir)):
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700389 _Log('Build %s has already been processed.' % archive_url)
Chris Sosacde6bf42012-05-31 18:36:39 -0700390 return 'Success'
391
392 downloader_instance = downloader.Downloader(updater.static_dir)
393 self._downloader_dict[archive_url] = downloader_instance
394 return downloader_instance.Download(archive_url, background=True)
395
396 except:
397 # On any exception, reset the state of the downloader_dict.
398 self._downloader_dict[archive_url] = None
Chris Sosa4d9c4d42012-06-29 15:23:23 -0700399 raise
Chris Sosacde6bf42012-05-31 18:36:39 -0700400
401 @cherrypy.expose
402 def wait_for_status(self, **kwargs):
403 """Waits for background artifacts to be downloaded from Google Storage.
404
405 Args:
406 archive_url: Google Storage URL for the build.
407
408 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700409 http://myhost/wait_for_status?archive_url=gs://chromeos-image-archive/
410 x86-generic/R17-1208.0.0-a1-b338
Chris Sosacde6bf42012-05-31 18:36:39 -0700411 """
412 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
413 downloader_instance = self._downloader_dict.get(archive_url)
414 if downloader_instance:
415 status = downloader_instance.GetStatusOfBackgroundDownloads()
Chris Sosa781ba6d2012-04-11 12:44:43 -0700416 self._downloader_dict[archive_url] = None
Chris Sosacde6bf42012-05-31 18:36:39 -0700417 return status
418 else:
419 # We may have previously downloaded but removed the downloader instance
420 # from the cache.
421 if downloader.Downloader.BuildStaged(archive_url, updater.static_dir):
422 logging.info('%s not found in downloader cache but previously staged.',
423 archive_url)
424 return 'Success'
425 else:
426 raise DevServerError('No download for the given archive_url found.')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700427
428 @cherrypy.expose
Chris Masone816e38c2012-05-02 12:22:36 -0700429 def stage_debug(self, **kwargs):
430 """Downloads and stages debug symbol payloads from Google Storage.
431
432 This methods downloads the debug symbol build artifact synchronously,
433 and then stages it for use by symbolicate_dump/.
434
435 Args:
436 archive_url: Google Storage URL for the build.
437
438 Example URL:
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700439 http://myhost/stage_debug?archive_url=gs://chromeos-image-archive/
440 x86-generic/R17-1208.0.0-a1-b338
Chris Masone816e38c2012-05-02 12:22:36 -0700441 """
Chris Sosacde6bf42012-05-31 18:36:39 -0700442 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
Chris Masone816e38c2012-05-02 12:22:36 -0700443 return downloader.SymbolDownloader(updater.static_dir).Download(archive_url)
444
445 @cherrypy.expose
446 def symbolicate_dump(self, minidump):
447 """Symbolicates a minidump using pre-downloaded symbols, returns it.
448
449 Callers will need to POST to this URL with a body of MIME-type
450 "multipart/form-data".
451 The body should include a single argument, 'minidump', containing the
452 binary-formatted minidump to symbolicate.
453
454 It is up to the caller to ensure that the symbols they want are currently
455 staged.
456
457 Args:
458 minidump: The binary minidump file to symbolicate.
459 """
460 to_return = ''
461 with tempfile.NamedTemporaryFile() as local:
462 while True:
463 data = minidump.file.read(8192)
464 if not data:
465 break
466 local.write(data)
467 local.flush()
468 stackwalk = subprocess.Popen(['minidump_stackwalk',
469 local.name,
470 updater.static_dir + '/debug/breakpad'],
471 stdout=subprocess.PIPE,
472 stderr=subprocess.PIPE)
473 to_return, error_text = stackwalk.communicate()
474 if stackwalk.returncode != 0:
475 raise DevServerError("Can't generate stack trace: %s (rc=%d)" % (
476 error_text, stackwalk.returncode))
477
478 return to_return
479
480 @cherrypy.expose
Scott Zawalski16954532012-03-20 15:31:36 -0400481 def latestbuild(self, **params):
482 """Return a string representing the latest build for a given target.
483
484 Args:
485 target: The build target, typically a combination of the board and the
486 type of build e.g. x86-mario-release.
487 milestone: The milestone to filter builds on. E.g. R16. Optional, if not
488 provided the latest RXX build will be returned.
489 Returns:
490 A string representation of the latest build if one exists, i.e.
491 R19-1993.0.0-a1-b1480.
492 An empty string if no latest could be found.
493 """
494 if not params:
495 return _PrintDocStringAsHTML(self.latestbuild)
496
497 if 'target' not in params:
498 raise cherrypy.HTTPError('500 Internal Server Error',
499 'Error: target= is required!')
500 try:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700501 return common_util.GetLatestBuildVersion(
Scott Zawalski16954532012-03-20 15:31:36 -0400502 updater.static_dir, params['target'],
503 milestone=params.get('milestone'))
Gilad Arnold17fe03d2012-10-02 10:05:01 -0700504 except common_util.CommonUtilError as errmsg:
Scott Zawalski16954532012-03-20 15:31:36 -0400505 raise cherrypy.HTTPError('500 Internal Server Error', str(errmsg))
506
507 @cherrypy.expose
Scott Zawalski84a39c92012-01-13 15:12:42 -0500508 def controlfiles(self, **params):
Scott Zawalski4647ce62012-01-03 17:17:28 -0500509 """Return a control file or a list of all known control files.
510
511 Example URL:
512 To List all control files:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500513 http://dev-server/controlfiles?board=x86-alex-release&build=R18-1514.0.0
Scott Zawalski4647ce62012-01-03 17:17:28 -0500514 To return the contents of a path:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500515 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 -0500516
517 Args:
Scott Zawalski84a39c92012-01-13 15:12:42 -0500518 build: The build i.e. x86-alex-release/R18-1514.0.0-a1-b1450.
Scott Zawalski4647ce62012-01-03 17:17:28 -0500519 control_path: If you want the contents of a control file set this
520 to the path. E.g. client/site_tests/sleeptest/control
521 Optional, if not provided return a list of control files is returned.
522 Returns:
523 Contents of a control file if control_path is provided.
524 A list of control files if no control_path is provided.
525 """
Scott Zawalski4647ce62012-01-03 17:17:28 -0500526 if not params:
527 return _PrintDocStringAsHTML(self.controlfiles)
528
Scott Zawalski84a39c92012-01-13 15:12:42 -0500529 if 'build' not in params:
Scott Zawalski4647ce62012-01-03 17:17:28 -0500530 raise cherrypy.HTTPError('500 Internal Server Error',
Scott Zawalski84a39c92012-01-13 15:12:42 -0500531 'Error: build= is required!')
Scott Zawalski4647ce62012-01-03 17:17:28 -0500532
533 if 'control_path' not in params:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700534 return common_util.GetControlFileList(
535 updater.static_dir, params['build'])
Scott Zawalski4647ce62012-01-03 17:17:28 -0500536 else:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700537 return common_util.GetControlFile(
538 updater.static_dir, params['build'], params['control_path'])
Frank Farzan40160872011-12-12 18:39:18 -0800539
540 @cherrypy.expose
Gilad Arnold6f99b982012-09-12 10:49:40 -0700541 def stage_images(self, **kwargs):
542 """Downloads and stages a Chrome OS image from Google Storage.
543
544 This method downloads a zipped archive from a specified GS location, then
545 extracts and stages the specified list of images and stages them under
546 static/images/BOARD/BUILD/. Download is synchronous.
547
548 Args:
549 archive_url: Google Storage URL for the build.
550 image_types: comma-separated list of images to download, may include
551 'test', 'recovery', and 'base'
552
553 Example URL:
554 http://myhost/stage_images?archive_url=gs://chromeos-image-archive/
555 x86-generic/R17-1208.0.0-a1-b338&image_types=test,base
556 """
557 # TODO(garnold) This needs to turn into an async operation, to avoid
558 # unnecessary failure of concurrent secondary requests (chromium-os:34661).
559 archive_url = self._canonicalize_archive_url(kwargs.get('archive_url'))
560 image_types = kwargs.get('image_types').split(',')
561 return (downloader.ImagesDownloader(
562 updater.static_dir).Download(archive_url, image_types))
563
564 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700565 def index(self):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700566 """Presents a welcome message and documentation links."""
567 method_dict = DevServerRoot.__dict__
568 return ('Welcome to the Dev Server!<br>\n'
569 '<br>\n'
570 'Here are the available methods, click for documentation:<br>\n'
571 '<br>\n'
572 '%s' %
573 '<br>\n'.join(
574 [('<a href=doc/%s>%s</a>' % (name, name))
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700575 for name in _FindExposedMethods(
576 self, '', unlisted=self._UNLISTED_METHODS)]))
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700577
578 @cherrypy.expose
579 def doc(self, *args):
580 """Shows the documentation for available methods / URLs.
581
582 Example:
583 http://myhost/doc/update
584 """
Gilad Arnoldd5ebaaa2012-10-02 11:52:38 -0700585 name = '/'.join(args)
586 method = _GetExposedMethod(self, name)
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700587 if not method:
588 raise DevServerError("No exposed method named `%s'" % name)
589 if not method.__doc__:
590 raise DevServerError("No documentation for exposed method `%s'" % name)
591 return '<pre>\n%s</pre>' % method.__doc__
Chris Sosa7c931362010-10-11 19:49:01 -0700592
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700593 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700594 def update(self, *args):
Gilad Arnoldf8f769f2012-09-24 08:43:01 -0700595 """Handles an update check from a Chrome OS client.
596
597 The HTTP request should contain the standard Omaha-style XML blob. The URL
598 line may contain an additional intermediate path to the update payload.
599
600 Example:
601 http://myhost/update/optional/path/to/payload
602 """
Chris Sosa7c931362010-10-11 19:49:01 -0700603 label = '/'.join(args)
Gilad Arnold286a0062012-01-12 13:47:02 -0800604 body_length = int(cherrypy.request.headers.get('Content-Length', 0))
Chris Sosa7c931362010-10-11 19:49:01 -0700605 data = cherrypy.request.rfile.read(body_length)
606 return updater.HandleUpdatePing(data, label)
607
Chris Sosa0356d3b2010-09-16 15:46:22 -0700608
Chris Sosacde6bf42012-05-31 18:36:39 -0700609def main():
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700610 usage = 'usage: %prog [options]'
Gilad Arnold286a0062012-01-12 13:47:02 -0800611 parser = optparse.OptionParser(usage=usage)
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700612 parser.add_option('--archive_dir',
613 metavar='PATH',
614 help='serve archived builds only')
615 parser.add_option('--board',
616 help='when pre-generating update, board for latest image')
617 parser.add_option('--clear_cache',
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800618 action='store_true', default=False,
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700619 help='clear out all cached updates and exit')
620 parser.add_option('--critical_update',
621 action='store_true', default=False,
622 help='present update payload as critical')
623 parser.add_option('--data_dir',
624 metavar='PATH',
625 default=os.path.dirname(os.path.abspath(sys.argv[0])),
626 help='writable directory where static lives')
627 parser.add_option('--exit',
628 action='store_true',
629 help='do not start server (yet pregenerate/clear cache)')
630 parser.add_option('--factory_config',
631 metavar='PATH',
632 help='config file for serving images from factory floor')
633 parser.add_option('--for_vm',
634 dest='vm', action='store_true',
635 help='update is for a vm image')
Gilad Arnold8318eac2012-10-04 12:52:23 -0700636 parser.add_option('--host_log',
637 action='store_true', default=False,
638 help='record history of host update events (/api/hostlog)')
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700639 parser.add_option('--image',
640 metavar='FILE',
641 help='force update using this image')
642 parser.add_option('--logfile',
643 metavar='PATH',
644 help='log output to this file instead of stdout')
Gilad Arnolda564b4b2012-10-04 10:32:44 -0700645 parser.add_option('--max_updates',
646 metavar='NUM', default=-1, type='int',
647 help='maximum number of update checks handled positively '
648 '(default: unlimited)')
Gilad Arnold9714d9b2012-10-04 10:09:42 -0700649 parser.add_option('-p', '--pregenerate_update',
650 action='store_true', default=False,
651 help='pre-generate update payload')
652 parser.add_option('--payload',
653 metavar='PATH',
654 help='use update payload from specified directory')
655 parser.add_option('--port',
656 default=8080, type='int',
657 help='port for the dev server to use (default: 8080)')
658 parser.add_option('--private_key',
659 metavar='PATH', default=None,
660 help='path to the private key in pem format')
661 parser.add_option('--production',
662 action='store_true', default=False,
663 help='have the devserver use production values')
664 parser.add_option('--proxy_port',
665 metavar='PORT', default=None, type='int',
666 help='port to have the client connect to (testing support)')
667 parser.add_option('--remote_payload',
668 action='store_true', default=False,
669 help='Payload is being served from a remote machine')
670 parser.add_option('--src_image',
671 metavar='PATH', default='',
672 help='source image for generating delta updates from')
673 parser.add_option('-t', '--test_image',
674 action='store_true',
675 help='whether or not to use test images')
676 parser.add_option('-u', '--urlbase',
677 metavar='URL',
678 help='base URL for update images, other than the devserver')
679 parser.add_option('--validate_factory_config',
680 action="store_true",
681 help='validate factory config file, then exit')
Chris Sosa7c931362010-10-11 19:49:01 -0700682 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000683
Chris Sosa7c931362010-10-11 19:49:01 -0700684 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
685 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700686 serve_only = False
687
Zdenek Behan608f46c2011-02-19 00:47:16 +0100688 static_dir = os.path.realpath('%s/static' % options.data_dir)
689 os.system('mkdir -p %s' % static_dir)
690
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700691 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100692 # TODO(zbehan) Remove legacy support:
693 # archive_dir is the directory where static/archive will point.
694 # If this is an absolute path, all is fine. If someone calls this
695 # using a relative path, that is relative to src/platform/dev/.
696 # That use case is unmaintainable, but since applications use it
697 # with =./static, instead of a boolean flag, we'll make this relative
698 # to devserver_dir to keep these unbroken. For now.
699 archive_dir = options.archive_dir
700 if not os.path.isabs(archive_dir):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700701 archive_dir = os.path.realpath(os.path.join(devserver_dir, archive_dir))
Zdenek Behan608f46c2011-02-19 00:47:16 +0100702 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100703 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700704 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700705
Don Garrettf90edf02010-11-16 17:36:14 -0800706 cache_dir = os.path.join(static_dir, 'cache')
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700707 _Log('Using cache directory %s' % cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800708
Don Garrettf90edf02010-11-16 17:36:14 -0800709 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800710 if options.clear_cache:
711 # Clear the cache and exit on error.
Chris Sosa9164ca32012-03-28 11:04:50 -0700712 cmd = 'rm -rf %s/*' % cache_dir
713 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700714 _Log('Failed to clear the cache with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800715 sys.exit(1)
716
717 else:
718 # Clear all but the last N cached updates
719 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
720 (cache_dir, CACHED_ENTRIES))
721 if os.system(cmd) != 0:
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700722 _Log('Failed to clean up old delta cache files with %s' % cmd)
Chris Sosa6b8c3742011-01-31 12:12:17 -0800723 sys.exit(1)
724 else:
725 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800726
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700727 _Log('Data dir is %s' % options.data_dir)
728 _Log('Source root is %s' % root_dir)
729 _Log('Serving from %s' % static_dir)
rtc@google.com21a5ca32009-11-04 18:23:23 +0000730
Chris Sosacde6bf42012-05-31 18:36:39 -0700731 global updater
Andrew de los Reyes52620802010-04-12 13:40:07 -0700732 updater = autoupdate.Autoupdate(
733 root_dir=root_dir,
734 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700735 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700736 urlbase=options.urlbase,
737 test_image=options.test_image,
738 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700739 forced_image=options.image,
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700740 payload_path=options.payload,
Don Garrett0ad09372010-12-06 16:20:30 -0800741 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700742 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700743 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800744 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800745 copy_to_static_root=not options.exit,
746 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800747 critical_update=options.critical_update,
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700748 remote_payload=options.remote_payload,
Gilad Arnolda564b4b2012-10-04 10:32:44 -0700749 max_updates=options.max_updates,
Gilad Arnold8318eac2012-10-04 12:52:23 -0700750 host_log=options.host_log,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800751 )
Chris Sosa7c931362010-10-11 19:49:01 -0700752
753 # Sanity-check for use of validate_factory_config.
754 if not options.factory_config and options.validate_factory_config:
755 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000756
Chris Sosa0356d3b2010-09-16 15:46:22 -0700757 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700758 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700759 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700760 # We don't run the dev server with this option.
761 if options.validate_factory_config:
762 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700763 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700764 if not updater.PreGenerateUpdate():
765 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700766
Don Garrett0c880e22010-11-17 18:13:37 -0800767 # If the command line requested after setup, it's time to do it.
768 if not options.exit:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700769 # Handle options that must be set globally in cherrypy.
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700770 if options.production:
Chris Sosa66e2d9c2012-07-11 14:14:14 -0700771 cherrypy.config.update({'environment': 'production'})
772 if not options.logfile:
773 cherrypy.config.update({'log.screen': True})
774 else:
775 cherrypy.config.update({'log.error_file': options.logfile,
776 'log.access_file': options.logfile})
Chris Sosa2f1c41e2012-07-10 14:32:33 -0700777
Don Garrett0c880e22010-11-17 18:13:37 -0800778 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))
Chris Sosacde6bf42012-05-31 18:36:39 -0700779
780
781if __name__ == '__main__':
782 main()