blob: 9d4b87ef01f5cc0ba3165ca69af88cb90eecf61b [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
David Rochberg7c79a812011-01-19 14:24:45 -050016import builder
Chris Sosa0356d3b2010-09-16 15:46:22 -070017
Chris Sosa417e55d2011-01-25 16:40:48 -080018CACHED_ENTRIES = 12
Don Garrettf90edf02010-11-16 17:36:14 -080019
Chris Sosa0356d3b2010-09-16 15:46:22 -070020# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000021global updater
22updater = None
rtc@google.comded22402009-10-26 22:36:21 +000023
Chris Sosa7c931362010-10-11 19:49:01 -070024def _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 09:13:54 -070031 'server.socket_timeout': 6000,
32 'response.timeout': 6000,
Zdenek Behan1347a312011-02-10 03:59:17 +010033 'tools.staticdir.root':
34 os.path.dirname(os.path.abspath(sys.argv[0])),
Chris Sosa7c931362010-10-11 19:49:01 -070035 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070036 '/build':
37 {
38 'response.timeout': 100000,
39 },
Chris Sosa7c931362010-10-11 19:49:01 -070040 '/update':
41 {
42 # Gets rid of cherrypy parsing post file for args.
43 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070044 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070045 },
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 15:57:51 -070050 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070051 },
52 }
Chris Sosa417e55d2011-01-25 16:40:48 -080053 if options.production:
54 base_config['global']['server.environment'] = 'production'
55
Chris Sosa7c931362010-10-11 19:49:01 -070056 return base_config
rtc@google.com64244662009-11-12 00:52:08 +000057
Darin Petkove17164a2010-08-11 13:24:41 -070058
Chris Sosa0356d3b2010-09-16 15:46:22 -070059def _PrepareToServeUpdatesOnly(image_dir):
60 """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-11 19:49:01 -070065 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
66 'DEVSERVER')
Chris Sosa0356d3b2010-09-16 15:46:22 -070067 if os.path.exists('static/archive'):
68 if image_dir != os.readlink('static/archive'):
Chris Sosa7c931362010-10-11 19:49:01 -070069 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Chris Sosa0356d3b2010-09-16 15:46:22 -070070 os.unlink('static/archive')
71 os.symlink(image_dir, 'static/archive')
72 else:
73 os.symlink(image_dir, 'static/archive')
Chris Sosa7c931362010-10-11 19:49:01 -070074 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
75 'DEVSERVER')
76
77
David Rochberg7c79a812011-01-19 14:24:45 -050078class DevServerRoot(object):
Chris Sosa7c931362010-10-11 19:49:01 -070079 """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 14:24:45 -050090 def __init__(self):
91 self._builder = builder.Builder()
92
93 def build(self, board, pkg, **kwargs):
Chris Sosa7c931362010-10-11 19:49:01 -070094 """Builds the package specified."""
David Rochberg7c79a812011-01-19 14:24:45 -050095 return self._builder.Build(board, pkg, kwargs)
Chris Sosa7c931362010-10-11 19:49:01 -070096
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 15:46:22 -0700110
111
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700112if __name__ == '__main__':
113 usage = 'usage: %prog [options]'
114 parser = optparse.OptionParser(usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700115 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700116 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700117 parser.add_option('--board', dest='board',
118 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800119 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800120 help='Clear out all cached udpates and exit')
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700121 parser.add_option('--client_prefix', dest='client_prefix',
122 help='Required prefix for client software version.',
123 default='MementoSoftwareUpdate')
Don Garrett0c880e22010-11-17 18:13:37 -0800124 parser.add_option('--exit', action='store_true', default=False,
125 help='Don\'t start the server (still pregenerate or clear'
126 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700127 parser.add_option('--factory_config', dest='factory_config',
128 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700129 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
130 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700131 parser.add_option('--image', dest='image',
132 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700133 parser.add_option('-p', '--pregenerate_update', action='store_true',
134 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800135 parser.add_option('--payload', dest='payload',
136 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700137 parser.add_option('--port', default=8080,
138 help='Port for the dev server to use.')
Chris Sosa417e55d2011-01-25 16:40:48 -0800139 parser.add_option('--production', action='store_true', default=False,
140 help='Have the devserver use production values.')
Don Garrett0ad09372010-12-06 16:20:30 -0800141 parser.add_option('--proxy_port', default=None,
142 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700143 parser.add_option('--src_image', default='',
144 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700145 parser.add_option('-t', action='store_true', dest='test_image')
146 parser.add_option('-u', '--urlbase', dest='urlbase',
147 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700148 parser.add_option('--validate_factory_config', action="store_true",
149 dest='validate_factory_config',
150 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700151 parser.set_usage(parser.format_help())
152 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000153
Chris Sosa7c931362010-10-11 19:49:01 -0700154 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
155 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700156 serve_only = False
157
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700158 if options.archive_dir:
159 static_dir = os.path.realpath(options.archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700160 _PrepareToServeUpdatesOnly(static_dir)
161 serve_only = True
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700162 else:
Chris Sosa7c931362010-10-11 19:49:01 -0700163 static_dir = os.path.realpath('%s/static' % devserver_dir)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700164 os.system('mkdir -p %s' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700165
Don Garrettf90edf02010-11-16 17:36:14 -0800166 cache_dir = os.path.join(static_dir, 'cache')
167 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
168
Don Garrettf90edf02010-11-16 17:36:14 -0800169 if os.path.exists(cache_dir):
Chris Sosa6b8c3742011-01-31 12:12:17 -0800170 if options.clear_cache:
171 # Clear the cache and exit on error.
172 if os.system('rm -rf %s/*' % cache_dir) != 0:
173 cherrypy.log('Failed to clear the cache with %s' % cmd,
174 'DEVSERVER')
175 sys.exit(1)
176
177 else:
178 # Clear all but the last N cached updates
179 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
180 (cache_dir, CACHED_ENTRIES))
181 if os.system(cmd) != 0:
182 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
183 'DEVSERVER')
184 sys.exit(1)
185 else:
186 os.makedirs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800187
Chris Sosa7c931362010-10-11 19:49:01 -0700188 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
189 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000190
Andrew de los Reyes52620802010-04-12 13:40:07 -0700191 updater = autoupdate.Autoupdate(
192 root_dir=root_dir,
193 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700194 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700195 urlbase=options.urlbase,
196 test_image=options.test_image,
197 factory_config_path=options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700198 client_prefix=options.client_prefix,
Chris Sosa5d342a22010-09-28 16:54:41 -0700199 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800200 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700201 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800202 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700203 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700204 vm=options.vm,
Chris Sosa08d55a22011-01-19 16:08:02 -0800205 board=options.board,
206 copy_to_static_root=not options.exit)
Chris Sosa7c931362010-10-11 19:49:01 -0700207
208 # Sanity-check for use of validate_factory_config.
209 if not options.factory_config and options.validate_factory_config:
210 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000211
Chris Sosa0356d3b2010-09-16 15:46:22 -0700212 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700213 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700214 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700215 # We don't run the dev server with this option.
216 if options.validate_factory_config:
217 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700218 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700219 if not updater.PreGenerateUpdate():
220 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700221
Don Garrett0c880e22010-11-17 18:13:37 -0800222 # If the command line requested after setup, it's time to do it.
223 if not options.exit:
224 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))