blob: f87d0dd184f5d1b7d5aa1bd446fb31e3a8035ec3 [file] [log] [blame]
Chris Sosa7c931362010-10-11 19:49:01 -07001#!/usr/bin/python
2
Chris Sosa0356d3b2010-09-16 15:46:22 -07003# Copyright (c) 2009-2010 The Chromium OS Authors. All rights reserved.
rtc@google.comded22402009-10-26 22:36:21 +00004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Chris Sosa7c931362010-10-11 19:49:01 -07007"""A CherryPy-based webserver to host images and build packages."""
8
9import cherrypy
Sean O'Connor14b6a0a2010-03-20 23:23:48 -070010import optparse
rtc@google.comded22402009-10-26 22:36:21 +000011import os
David Rochberg7c79a812011-01-19 14:24:45 -050012import subprocess
chocobo@google.com4dc25812009-10-27 23:46:26 +000013import sys
rtc@google.comded22402009-10-26 22:36:21 +000014
Chris Sosa0356d3b2010-09-16 15:46:22 -070015import autoupdate
Chris Sosa0356d3b2010-09-16 15:46:22 -070016
Chris Sosa417e55d2011-01-25 16:40:48 -080017CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080018
Chris Sosa0356d3b2010-09-16 15:46:22 -070019# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000020global updater
21updater = None
rtc@google.comded22402009-10-26 22:36:21 +000022
Chris Sosa7c931362010-10-11 19:49:01 -070023def _GetConfig(options):
24 """Returns the configuration for the devserver."""
25 base_config = { 'global':
26 { 'server.log_request_headers': True,
27 'server.protocol_version': 'HTTP/1.1',
Aaron Plattner2bfab982011-05-20 09:01:08 -070028 'server.socket_host': '::',
Chris Sosa7c931362010-10-11 19:49:01 -070029 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -070030 'server.socket_timeout': 6000,
31 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 03:59:17 +010032 'tools.staticdir.root':
33 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070034 },
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070035 '/api':
36 {
37 # Gets rid of cherrypy parsing post file for args.
38 'request.process_request_body': False,
39 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070040 '/build':
41 {
42 'response.timeout': 100000,
43 },
Chris Sosa7c931362010-10-11 19:49:01 -070044 '/update':
45 {
46 # Gets rid of cherrypy parsing post file for args.
47 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070048 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070049 },
50 # Sets up the static dir for file hosting.
51 '/static':
52 { 'tools.staticdir.dir': 'static',
53 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -070054 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070055 },
56 }
Chris Sosa417e55d2011-01-25 16:40:48 -080057 if options.production:
58 base_config['global']['server.environment'] = 'production'
59
Chris Sosa7c931362010-10-11 19:49:01 -070060 return base_config
rtc@google.com64244662009-11-12 00:52:08 +000061
Darin Petkove17164a2010-08-11 13:24:41 -070062
Zdenek Behan608f46c2011-02-19 00:47:16 +010063def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -070064 """Sets up symlink to image_dir for serving purposes."""
65 assert os.path.exists(image_dir), '%s must exist.' % image_dir
66 # If we're serving out of an archived build dir (e.g. a
67 # buildbot), prepare this webserver's magic 'static/' dir with a
68 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -070069 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
70 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +010071 if os.path.lexists('%s/archive' % static_dir):
72 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-11 19:49:01 -070073 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-19 00:47:16 +010074 os.unlink('%s/archive' % static_dir)
75 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -070076 else:
Zdenek Behan608f46c2011-02-19 00:47:16 +010077 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-11 19:49:01 -070078 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
79 'DEVSERVER')
80
81
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070082class ApiRoot(object):
83 """RESTful API for Dev Server information."""
84 exposed = True
85
86 @cherrypy.expose
87 def hostinfo(self, ip):
88 """Returns a JSON dictionary containing information about the given ip.
89
90 Not all information may be known at the time the request is made. The
91 possible keys are:
92
93 last_event_type: int
94 Last update event type received.
95
96 last_event_status: int
97 Last update event status received.
98
99 last_known_version: string
100 Last known version recieved for update ping.
101
102 forced_update_label: string
103 Update label to force next update ping to use. Set by setnextupdate.
104
105 See the OmahaEvent class in update_engine/omaha_request_action.h for status
106 code definitions. If the ip does not exist an empty string is returned."""
107 return updater.HandleHostInfoPing(ip)
108
109 @cherrypy.expose
110 def setnextupdate(self, ip):
111 """Allows the response to the next update ping from a host to be set.
112
113 Takes the IP of the host and an update label as normally provided to the
114 /update command."""
115 body_length = int(cherrypy.request.headers['Content-Length'])
116 label = cherrypy.request.rfile.read(body_length)
117
118 if label:
119 label = label.strip()
120 if label:
121 return updater.HandleSetUpdatePing(ip, label)
122 raise cherrypy.HTTPError(400, 'No label provided.')
123
124
David Rochberg7c79a812011-01-19 14:24:45 -0500125class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -0700126 """The Root Class for the Dev Server.
127
128 CherryPy works as follows:
129 For each method in this class, cherrpy interprets root/path
130 as a call to an instance of DevServerRoot->method_name. For example,
131 a call to http://myhost/build will call build. CherryPy automatically
132 parses http args and places them as keyword arguments in each method.
133 For paths http://myhost/update/dir1/dir2, you can use *args so that
134 cherrypy uses the update method and puts the extra paths in args.
135 """
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700136 api = ApiRoot()
Chris Sosa7c931362010-10-11 19:49:01 -0700137
David Rochberg7c79a812011-01-19 14:24:45 -0500138 def __init__(self):
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700139 self._builder = None
David Rochberg7c79a812011-01-19 14:24:45 -0500140
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700141 @cherrypy.expose
David Rochberg7c79a812011-01-19 14:24:45 -0500142 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -0700143 """Builds the package specified."""
Nick Sanders7dcaa2e2011-08-04 15:20:41 -0700144 import builder
145 if self._builder is None:
146 self._builder = builder.Builder()
David Rochberg7c79a812011-01-19 14:24:45 -0500147 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -0700148
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700149 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700150 def index(self):
151 return 'Welcome to the Dev Server!'
152
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700153 @cherrypy.expose
Chris Sosa7c931362010-10-11 19:49:01 -0700154 def update(self, *args):
155 label = '/'.join(args)
156 body_length = int(cherrypy.request.headers['Content-Length'])
157 data = cherrypy.request.rfile.read(body_length)
158 return updater.HandleUpdatePing(data, label)
159
Chris Sosa0356d3b2010-09-16 15:46:22 -0700160
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700161if __name__ == '__main__':
162 usage = 'usage: %prog [options]'
163 parser = optparse.OptionParser(usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700164 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700165 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700166 parser.add_option('--board', dest='board',
167 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800168 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800169 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 14:15:23 -0700170 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
171 help='No longer used. It is still here so we don\'t break '
172 'scripts that used it.', default='')
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800173 parser.add_option('--critical_update', dest='critical_update',
174 action='store_true', default=False,
175 help='Present update payload as critical')
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100176 parser.add_option('--data_dir', dest='data_dir',
177 help='Writable directory where static lives',
178 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-17 18:13:37 -0800179 parser.add_option('--exit', action='store_true', default=False,
180 help='Don\'t start the server (still pregenerate or clear'
181 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700182 parser.add_option('--factory_config', dest='factory_config',
183 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700184 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
185 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700186 parser.add_option('--image', dest='image',
187 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700188 parser.add_option('-p', '--pregenerate_update', action='store_true',
189 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800190 parser.add_option('--payload', dest='payload',
191 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700192 parser.add_option('--port', default=8080,
193 help='Port for the dev server to use.')
Chris Sosa0f1ec842011-02-14 16:33:22 -0800194 parser.add_option('--private_key', default=None,
195 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800196 parser.add_option('--production', action='store_true', default=False,
197 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800198 parser.add_option('--proxy_port', default=None,
199 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700200 parser.add_option('--src_image', default='',
201 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700202 parser.add_option('-t', action='store_true', dest='test_image')
203 parser.add_option('-u', '--urlbase', dest='urlbase',
204 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700205 parser.add_option('--validate_factory_config', action="store_true",
206 dest='validate_factory_config',
207 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700208 parser.set_usage(parser.format_help())
209 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000210
Chris Sosa7c931362010-10-11 19:49:01 -0700211 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
212 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700213 serve_only = False
214
Zdenek Behan608f46c2011-02-19 00:47:16 +0100215 static_dir = os.path.realpath('%s/static' % options.data_dir)
216 os.system('mkdir -p %s' % static_dir)
217
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700218 if options.archive_dir:
Zdenek Behan608f46c2011-02-19 00:47:16 +0100219 # TODO(zbehan) Remove legacy support:
220 # archive_dir is the directory where static/archive will point.
221 # If this is an absolute path, all is fine. If someone calls this
222 # using a relative path, that is relative to src/platform/dev/.
223 # That use case is unmaintainable, but since applications use it
224 # with =./static, instead of a boolean flag, we'll make this relative
225 # to devserver_dir to keep these unbroken. For now.
226 archive_dir = options.archive_dir
227 if not os.path.isabs(archive_dir):
228 archive_dir = os.path.realpath(os.path.join(devserver_dir,archive_dir))
229 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 22:35:49 +0100230 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700231 serve_only = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700232
Don Garrettf90edf02010-11-16 17:36:14 -0800233 cache_dir = os.path.join(static_dir, 'cache')
234 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
235
Don Garrettf90edf02010-11-16 17:36:14 -0800236 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800237 if options.clear_cache:
238 # Clear the cache and exit on error.
239 if os.system('rm -rf %s/*' % cache_dir) != 0:
240 cherrypy.log('Failed to clear the cache with %s' % cmd,
241 'DEVSERVER')
242 sys.exit(1)
243
244 else:
245 # Clear all but the last N cached updates
246 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
247 (cache_dir, CACHED_ENTRIES))
248 if os.system(cmd) != 0:
249 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
250 'DEVSERVER')
251 sys.exit(1)
252 else:
253 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800254
Greg Spencerc8b59b22011-03-15 14:15:23 -0700255 if options.client_prefix_deprecated:
256 cherrypy.log('The --client_prefix argument is DEPRECATED, '
257 'and is no longer needed.', 'DEVSERVER')
258
Zdenek Behan5d21a2a2011-02-12 02:06:01 +0100259 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-11 19:49:01 -0700260 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
261 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000262
Andrew de los Reyes52620802010-04-12 13:40:07 -0700263 updater = autoupdate.Autoupdate(
264 root_dir=root_dir,
265 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700266 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700267 urlbase=options.urlbase,
268 test_image=options.test_image,
269 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 16:54:41 -0700270 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800271 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700272 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800273 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700274 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700275 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800276 board=options.board,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800277 copy_to_static_root=not options.exit,
278 private_key=options.private_key,
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800279 critical_update=options.critical_update,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800280 )
Chris Sosa7c931362010-10-11 19:49:01 -0700281
282 # Sanity-check for use of validate_factory_config.
283 if not options.factory_config and options.validate_factory_config:
284 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000285
Chris Sosa0356d3b2010-09-16 15:46:22 -0700286 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700287 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700288 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700289 # We don't run the dev server with this option.
290 if options.validate_factory_config:
291 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700292 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700293 if not updater.PreGenerateUpdate():
294 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700295
Don Garrett0c880e22010-11-17 18:13:37 -0800296 # If the command line requested after setup, it's time to do it.
297 if not options.exit:
298 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))