blob: ae408175acea8e9626a07166e3b0c522ede7a9e9 [file] [log] [blame]
Chris Sosa7c931362010-10-12 02:49:011#!/usr/bin/python
2
Chris Sosa0356d3b2010-09-16 22:46:223# Copyright (c) 2009-2010 The Chromium OS Authors. All rights reserved.
[email protected]ded22402009-10-26 22:36:214# 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-12 02:49:017"""A CherryPy-based webserver to host images and build packages."""
8
9import cherrypy
Sean O'Connor14b6a0a2010-03-21 06:23:4810import optparse
[email protected]ded22402009-10-26 22:36:2111import os
David Rochberg7c79a812011-01-19 19:24:4512import subprocess
[email protected]4dc25812009-10-27 23:46:2613import sys
[email protected]ded22402009-10-26 22:36:2114
Chris Sosa0356d3b2010-09-16 22:46:2215import autoupdate
David Rochberg7c79a812011-01-19 19:24:4516import builder
Chris Sosa0356d3b2010-09-16 22:46:2217
Chris Sosa417e55d2011-01-26 00:40:4818CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-17 01:36:1419
Chris Sosa0356d3b2010-09-16 22:46:2220# Sets up global to share between classes.
[email protected]21a5ca32009-11-04 18:23:2321global updater
22updater = None
[email protected]ded22402009-10-26 22:36:2123
Chris Sosa7c931362010-10-12 02:49:0124def _GetConfig(options):
25 """Returns the configuration for the devserver."""
26 base_config = { 'global':
27 { 'server.log_request_headers': True,
28 'server.protocol_version': 'HTTP/1.1',
29 'server.socket_host': '0.0.0.0',
30 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 16:13:5431 'server.socket_timeout': 6000,
32 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 02:59:1733 'tools.staticdir.root':
34 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-12 02:49:0135 },
Chris Sosaa1ef0102010-10-21 23:22:3536 '/build':
37 {
38 'response.timeout': 100000,
39 },
Chris Sosa7c931362010-10-12 02:49:0140 '/update':
41 {
42 # Gets rid of cherrypy parsing post file for args.
43 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 22:57:5144 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:0145 },
46 # Sets up the static dir for file hosting.
47 '/static':
48 { 'tools.staticdir.dir': 'static',
49 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 22:57:5150 'response.timeout': 10000,
Chris Sosa7c931362010-10-12 02:49:0151 },
52 }
Chris Sosa417e55d2011-01-26 00:40:4853 if options.production:
54 base_config['global']['server.environment'] = 'production'
55
Chris Sosa7c931362010-10-12 02:49:0156 return base_config
[email protected]64244662009-11-12 00:52:0857
Darin Petkove17164a2010-08-11 20:24:4158
Zdenek Behan608f46c2011-02-18 23:47:1659def _PrepareToServeUpdatesOnly(image_dir, static_dir):
Chris Sosa0356d3b2010-09-16 22:46:2260 """Sets up symlink to image_dir for serving purposes."""
61 assert os.path.exists(image_dir), '%s must exist.' % image_dir
62 # If we're serving out of an archived build dir (e.g. a
63 # buildbot), prepare this webserver's magic 'static/' dir with a
64 # link to the build archive.
Chris Sosa7c931362010-10-12 02:49:0165 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
66 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:1667 if os.path.lexists('%s/archive' % static_dir):
68 if image_dir != os.readlink('%s/archive' % static_dir):
Chris Sosa7c931362010-10-12 02:49:0169 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Zdenek Behan608f46c2011-02-18 23:47:1670 os.unlink('%s/archive' % static_dir)
71 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa0356d3b2010-09-16 22:46:2272 else:
Zdenek Behan608f46c2011-02-18 23:47:1673 os.symlink(image_dir, '%s/archive' % static_dir)
Chris Sosa7c931362010-10-12 02:49:0174 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
75 'DEVSERVER')
76
77
David Rochberg7c79a812011-01-19 19:24:4578class DevServerRoot(object):
Chris Sosa7c931362010-10-12 02:49:0179 """The Root Class for the Dev Server.
80
81 CherryPy works as follows:
82 For each method in this class, cherrpy interprets root/path
83 as a call to an instance of DevServerRoot->method_name. For example,
84 a call to http://myhost/build will call build. CherryPy automatically
85 parses http args and places them as keyword arguments in each method.
86 For paths http://myhost/update/dir1/dir2, you can use *args so that
87 cherrypy uses the update method and puts the extra paths in args.
88 """
89
David Rochberg7c79a812011-01-19 19:24:4590 def __init__(self):
91 self._builder = builder.Builder()
92
93 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-12 02:49:0194 """Builds the package specified."""
David Rochberg7c79a812011-01-19 19:24:4595 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-12 02:49:0196
97 def index(self):
98 return 'Welcome to the Dev Server!'
99
100 def update(self, *args):
101 label = '/'.join(args)
102 body_length = int(cherrypy.request.headers['Content-Length'])
103 data = cherrypy.request.rfile.read(body_length)
104 return updater.HandleUpdatePing(data, label)
105
106 # Expose actual methods. Necessary to actually have these callable.
107 build.exposed = True
108 update.exposed = True
109 index.exposed = True
Chris Sosa0356d3b2010-09-16 22:46:22110
111
Sean O'Connor14b6a0a2010-03-21 06:23:48112if __name__ == '__main__':
113 usage = 'usage: %prog [options]'
114 parser = optparse.OptionParser(usage)
Sean O'Connore38ea152010-04-16 20:50:40115 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-21 06:23:48116 help='serve archived builds only.')
Chris Sosae67b78f12010-11-05 00:33:16117 parser.add_option('--board', dest='board',
118 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-18 02:13:37119 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-17 01:36:14120 help='Clear out all cached udpates and exit')
Greg Spencerc8b59b22011-03-15 21:15:23121 parser.add_option('--client_prefix', dest='client_prefix_deprecated',
122 help='No longer used. It is still here so we don\'t break '
123 'scripts that used it.', default='')
Zdenek Behan5d21a2a2011-02-12 01:06:01124 parser.add_option('--data_dir', dest='data_dir',
125 help='Writable directory where static lives',
126 default=os.path.dirname(os.path.abspath(sys.argv[0])))
Don Garrett0c880e22010-11-18 02:13:37127 parser.add_option('--exit', action='store_true', default=False,
128 help='Don\'t start the server (still pregenerate or clear'
129 'cache).')
Andrew de los Reyes52620802010-04-12 20:40:07130 parser.add_option('--factory_config', dest='factory_config',
131 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-29 06:42:37132 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
133 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 22:46:22134 parser.add_option('--image', dest='image',
135 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 23:05:27136 parser.add_option('-p', '--pregenerate_update', action='store_true',
137 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-18 02:13:37138 parser.add_option('--payload', dest='payload',
139 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-12 02:49:01140 parser.add_option('--port', default=8080,
141 help='Port for the dev server to use.')
Chris Sosa0f1ec842011-02-15 00:33:22142 parser.add_option('--private_key', default=None,
143 help='Path to the private key in pem format.')
Chris Sosa417e55d2011-01-26 00:40:48144 parser.add_option('--production', action='store_true', default=False,
145 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-07 00:20:30146 parser.add_option('--proxy_port', default=None,
147 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-27 04:39:48148 parser.add_option('--src_image', default='',
149 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 23:34:52150 parser.add_option('-t', action='store_true', dest='test_image')
151 parser.add_option('-u', '--urlbase', dest='urlbase',
152 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 20:40:07153 parser.add_option('--validate_factory_config', action="store_true",
154 dest='validate_factory_config',
155 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-12 02:49:01156 parser.set_usage(parser.format_help())
157 (options, _) = parser.parse_args()
[email protected]21a5ca32009-11-04 18:23:23158
Chris Sosa7c931362010-10-12 02:49:01159 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
160 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 22:46:22161 serve_only = False
162
Zdenek Behan608f46c2011-02-18 23:47:16163 static_dir = os.path.realpath('%s/static' % options.data_dir)
164 os.system('mkdir -p %s' % static_dir)
165
Sean O'Connor14b6a0a2010-03-21 06:23:48166 if options.archive_dir:
Zdenek Behan608f46c2011-02-18 23:47:16167 # TODO(zbehan) Remove legacy support:
168 # archive_dir is the directory where static/archive will point.
169 # If this is an absolute path, all is fine. If someone calls this
170 # using a relative path, that is relative to src/platform/dev/.
171 # That use case is unmaintainable, but since applications use it
172 # with =./static, instead of a boolean flag, we'll make this relative
173 # to devserver_dir to keep these unbroken. For now.
174 archive_dir = options.archive_dir
175 if not os.path.isabs(archive_dir):
176 archive_dir = os.path.realpath(os.path.join(devserver_dir,archive_dir))
177 _PrepareToServeUpdatesOnly(archive_dir, static_dir)
Zdenek Behan6d93e552011-03-02 21:35:49178 static_dir = os.path.realpath(archive_dir)
Chris Sosa0356d3b2010-09-16 22:46:22179 serve_only = True
Chris Sosa0356d3b2010-09-16 22:46:22180
Don Garrettf90edf02010-11-17 01:36:14181 cache_dir = os.path.join(static_dir, 'cache')
182 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
183
Don Garrettf90edf02010-11-17 01:36:14184 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 20:12:17185 if options.clear_cache:
186 # Clear the cache and exit on error.
187 if os.system('rm -rf %s/*' % cache_dir) != 0:
188 cherrypy.log('Failed to clear the cache with %s' % cmd,
189 'DEVSERVER')
190 sys.exit(1)
191
192 else:
193 # Clear all but the last N cached updates
194 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
195 (cache_dir, CACHED_ENTRIES))
196 if os.system(cmd) != 0:
197 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
198 'DEVSERVER')
199 sys.exit(1)
200 else:
201 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14202
Greg Spencerc8b59b22011-03-15 21:15:23203 if options.client_prefix_deprecated:
204 cherrypy.log('The --client_prefix argument is DEPRECATED, '
205 'and is no longer needed.', 'DEVSERVER')
206
Zdenek Behan5d21a2a2011-02-12 01:06:01207 cherrypy.log('Data dir is %s' % options.data_dir, 'DEVSERVER')
Chris Sosa7c931362010-10-12 02:49:01208 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
209 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
[email protected]21a5ca32009-11-04 18:23:23210
Andrew de los Reyes52620802010-04-12 20:40:07211 updater = autoupdate.Autoupdate(
212 root_dir=root_dir,
213 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 22:46:22214 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 20:40:07215 urlbase=options.urlbase,
216 test_image=options.test_image,
217 factory_config_path=options.factory_config,
Chris Sosa5d342a22010-09-28 23:54:41218 forced_image=options.image,
Don Garrett0c880e22010-11-18 02:13:37219 forced_payload=options.payload,
Chris Sosa62f720b2010-10-27 04:39:48220 port=options.port,
Don Garrett0ad09372010-12-07 00:20:30221 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-29 06:42:37222 src_image=options.src_image,
Chris Sosae67b78f12010-11-05 00:33:16223 vm=options.vm,
Chris Sosa08d55a22011-01-20 00:08:02224 board=options.board,
Chris Sosa0f1ec842011-02-15 00:33:22225 copy_to_static_root=not options.exit,
226 private_key=options.private_key,
227 )
Chris Sosa7c931362010-10-12 02:49:01228
229 # Sanity-check for use of validate_factory_config.
230 if not options.factory_config and options.validate_factory_config:
231 parser.error('You need a factory_config to validate.')
[email protected]64244662009-11-12 00:52:08232
Chris Sosa0356d3b2010-09-16 22:46:22233 if options.factory_config:
Chris Sosa7c931362010-10-12 02:49:01234 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 22:46:22235 options.validate_factory_config)
Chris Sosa7c931362010-10-12 02:49:01236 # We don't run the dev server with this option.
237 if options.validate_factory_config:
238 sys.exit(0)
Chris Sosa2c048f12010-10-27 23:05:27239 elif options.pregenerate_update:
Chris Sosae67b78f12010-11-05 00:33:16240 if not updater.PreGenerateUpdate():
241 sys.exit(1)
Chris Sosa0356d3b2010-09-16 22:46:22242
Don Garrett0c880e22010-11-18 02:13:37243 # If the command line requested after setup, it's time to do it.
244 if not options.exit:
245 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))