blob: 7d744c59f3aeb6d44201ccd6d1b777ee152e426d [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
chocobo@google.com4dc25812009-10-27 23:46:26 +000012import sys
rtc@google.comded22402009-10-26 22:36:21 +000013
Chris Sosa0356d3b2010-09-16 15:46:22 -070014import autoupdate
Chris Sosa0356d3b2010-09-16 15:46:22 -070015
Don Garrettf90edf02010-11-16 17:36:14 -080016CACHED_ENTRIES=12
17
Chris Sosa0356d3b2010-09-16 15:46:22 -070018# Sets up global to share between classes.
rtc@google.com21a5ca32009-11-04 18:23:23 +000019global updater
20updater = None
rtc@google.comded22402009-10-26 22:36:21 +000021
Chris Sosa7c931362010-10-11 19:49:01 -070022def _GetConfig(options):
23 """Returns the configuration for the devserver."""
24 base_config = { 'global':
25 { 'server.log_request_headers': True,
26 'server.protocol_version': 'HTTP/1.1',
27 'server.socket_host': '0.0.0.0',
28 'server.socket_port': int(options.port),
Chris Sosa374c62d2010-10-14 09:13:54 -070029 'server.socket_timeout': 6000,
30 'response.timeout': 6000,
Chris Sosa7c931362010-10-11 19:49:01 -070031 'tools.staticdir.root': os.getcwd(),
32 },
Chris Sosaa1ef0102010-10-21 16:22:35 -070033 '/build':
34 {
35 'response.timeout': 100000,
36 },
Chris Sosa7c931362010-10-11 19:49:01 -070037 '/update':
38 {
39 # Gets rid of cherrypy parsing post file for args.
40 'request.process_request_body': False,
Chris Sosaf65f4b92010-10-21 15:57:51 -070041 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070042 },
43 # Sets up the static dir for file hosting.
44 '/static':
45 { 'tools.staticdir.dir': 'static',
46 'tools.staticdir.on': True,
Chris Sosaf65f4b92010-10-21 15:57:51 -070047 'response.timeout': 10000,
Chris Sosa7c931362010-10-11 19:49:01 -070048 },
49 }
50 return base_config
rtc@google.com64244662009-11-12 00:52:08 +000051
Darin Petkove17164a2010-08-11 13:24:41 -070052
Chris Sosa0356d3b2010-09-16 15:46:22 -070053def _PrepareToServeUpdatesOnly(image_dir):
54 """Sets up symlink to image_dir for serving purposes."""
55 assert os.path.exists(image_dir), '%s must exist.' % image_dir
56 # If we're serving out of an archived build dir (e.g. a
57 # buildbot), prepare this webserver's magic 'static/' dir with a
58 # link to the build archive.
Chris Sosa7c931362010-10-11 19:49:01 -070059 cherrypy.log('Preparing autoupdate for "serve updates only" mode.',
60 'DEVSERVER')
Chris Sosa0356d3b2010-09-16 15:46:22 -070061 if os.path.exists('static/archive'):
62 if image_dir != os.readlink('static/archive'):
Chris Sosa7c931362010-10-11 19:49:01 -070063 cherrypy.log('removing stale symlink to %s' % image_dir, 'DEVSERVER')
Chris Sosa0356d3b2010-09-16 15:46:22 -070064 os.unlink('static/archive')
65 os.symlink(image_dir, 'static/archive')
66 else:
67 os.symlink(image_dir, 'static/archive')
Chris Sosa7c931362010-10-11 19:49:01 -070068 cherrypy.log('archive dir: %s ready to be used to serve images.' % image_dir,
69 'DEVSERVER')
70
71
72class DevServerRoot:
73 """The Root Class for the Dev Server.
74
75 CherryPy works as follows:
76 For each method in this class, cherrpy interprets root/path
77 as a call to an instance of DevServerRoot->method_name. For example,
78 a call to http://myhost/build will call build. CherryPy automatically
79 parses http args and places them as keyword arguments in each method.
80 For paths http://myhost/update/dir1/dir2, you can use *args so that
81 cherrypy uses the update method and puts the extra paths in args.
82 """
83
84 def build(self, board, pkg):
85 """Builds the package specified."""
86 cherrypy.log('emerging %s' % pkg, 'BUILD')
87 emerge_command = 'emerge-%s %s' % (board, pkg)
88 err = os.system(emerge_command)
89 if err != 0:
90 raise Exception('failed to execute %s' % emerge_command)
91 eclean_command = 'eclean-%s -d packages' % board
92 err = os.system(eclean_command)
93 if err != 0:
94 raise Exception('failed to execute %s' % emerge_command)
95
96 def index(self):
97 return 'Welcome to the Dev Server!'
98
99 def update(self, *args):
100 label = '/'.join(args)
101 body_length = int(cherrypy.request.headers['Content-Length'])
102 data = cherrypy.request.rfile.read(body_length)
103 return updater.HandleUpdatePing(data, label)
104
105 # Expose actual methods. Necessary to actually have these callable.
106 build.exposed = True
107 update.exposed = True
108 index.exposed = True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700109
110
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700111if __name__ == '__main__':
112 usage = 'usage: %prog [options]'
113 parser = optparse.OptionParser(usage)
Sean O'Connore38ea152010-04-16 13:50:40 -0700114 parser.add_option('--archive_dir', dest='archive_dir',
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700115 help='serve archived builds only.')
Chris Sosae67b78f2010-11-04 17:33:16 -0700116 parser.add_option('--board', dest='board',
117 help='When pre-generating update, board for latest image.')
Don Garrett0c880e22010-11-17 18:13:37 -0800118 parser.add_option('--clear_cache', action='store_true', default=False,
Don Garrettf90edf02010-11-16 17:36:14 -0800119 help='Clear out all cached udpates and exit')
Andrew de los Reyes9223f132010-05-07 17:08:17 -0700120 parser.add_option('--client_prefix', dest='client_prefix',
121 help='Required prefix for client software version.',
122 default='MementoSoftwareUpdate')
Don Garrett0c880e22010-11-17 18:13:37 -0800123 parser.add_option('--exit', action='store_true', default=False,
124 help='Don\'t start the server (still pregenerate or clear'
125 'cache).')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700126 parser.add_option('--factory_config', dest='factory_config',
127 help='Config file for serving images from factory floor.')
Chris Sosa4136e692010-10-28 23:42:37 -0700128 parser.add_option('--for_vm', dest='vm', default=False, action='store_true',
129 help='Update is for a vm image.')
Chris Sosa0356d3b2010-09-16 15:46:22 -0700130 parser.add_option('--image', dest='image',
131 help='Force update using this image.')
Chris Sosa2c048f12010-10-27 16:05:27 -0700132 parser.add_option('-p', '--pregenerate_update', action='store_true',
133 default=False, help='Pre-generate update payload.')
Don Garrett0c880e22010-11-17 18:13:37 -0800134 parser.add_option('--payload', dest='payload',
135 help='Use update payload from specified directory.')
Chris Sosa7c931362010-10-11 19:49:01 -0700136 parser.add_option('--port', default=8080,
137 help='Port for the dev server to use.')
Don Garrett0ad09372010-12-06 16:20:30 -0800138 parser.add_option('--proxy_port', default=None,
139 help='Port to have the client connect to (testing support)')
Chris Sosa62f720b2010-10-26 21:39:48 -0700140 parser.add_option('--src_image', default='',
141 help='Image on remote machine for generating delta update.')
Sean O'Connor1f7fd362010-04-07 16:34:52 -0700142 parser.add_option('-t', action='store_true', dest='test_image')
143 parser.add_option('-u', '--urlbase', dest='urlbase',
144 help='base URL, other than devserver, for update images.')
Andrew de los Reyes52620802010-04-12 13:40:07 -0700145 parser.add_option('--validate_factory_config', action="store_true",
146 dest='validate_factory_config',
147 help='Validate factory config file, then exit.')
Chris Sosa7c931362010-10-11 19:49:01 -0700148 parser.set_usage(parser.format_help())
149 (options, _) = parser.parse_args()
rtc@google.com21a5ca32009-11-04 18:23:23 +0000150
Chris Sosa7c931362010-10-11 19:49:01 -0700151 devserver_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
152 root_dir = os.path.realpath('%s/../..' % devserver_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700153 serve_only = False
154
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700155 if options.archive_dir:
156 static_dir = os.path.realpath(options.archive_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700157 _PrepareToServeUpdatesOnly(static_dir)
158 serve_only = True
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700159 else:
Chris Sosa7c931362010-10-11 19:49:01 -0700160 static_dir = os.path.realpath('%s/static' % devserver_dir)
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700161 os.system('mkdir -p %s' % static_dir)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700162
Don Garrettf90edf02010-11-16 17:36:14 -0800163 cache_dir = os.path.join(static_dir, 'cache')
164 cherrypy.log('Using cache directory %s' % cache_dir, 'DEVSERVER')
165
166 if options.clear_cache:
Don Garrett0c880e22010-11-17 18:13:37 -0800167 # Clear the cache and exit on error
168 if os.system('sudo rm -rf %s' % cache_dir) != 0:
169 cherrypy.log('Failed to clear the cache with %s' % cmd,
170 'DEVSERVER')
171 sys.exit(1)
Don Garrettf90edf02010-11-16 17:36:14 -0800172
173 if os.path.exists(cache_dir):
174 # Clear all but the last N cached updates
Don Garrett0ad09372010-12-06 16:20:30 -0800175 cmd = ('cd %s; ls -tr | head --lines=-%d | xargs rm -rf' %
Don Garrettf90edf02010-11-16 17:36:14 -0800176 (cache_dir, CACHED_ENTRIES))
177 if os.system(cmd) != 0:
178 cherrypy.log('Failed to clean up old delta cache files with %s' % cmd,
179 'DEVSERVER')
180 sys.exit(1)
181
Chris Sosa7c931362010-10-11 19:49:01 -0700182 cherrypy.log('Source root is %s' % root_dir, 'DEVSERVER')
183 cherrypy.log('Serving from %s' % static_dir, 'DEVSERVER')
rtc@google.com21a5ca32009-11-04 18:23:23 +0000184
Andrew de los Reyes52620802010-04-12 13:40:07 -0700185 updater = autoupdate.Autoupdate(
186 root_dir=root_dir,
187 static_dir=static_dir,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700188 serve_only=serve_only,
Andrew de los Reyes52620802010-04-12 13:40:07 -0700189 urlbase=options.urlbase,
190 test_image=options.test_image,
191 factory_config_path=options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700192 client_prefix=options.client_prefix,
Chris Sosa5d342a22010-09-28 16:54:41 -0700193 forced_image=options.image,
Don Garrett0c880e22010-11-17 18:13:37 -0800194 forced_payload=options.payload,
Chris Sosa62f720b2010-10-26 21:39:48 -0700195 port=options.port,
Don Garrett0ad09372010-12-06 16:20:30 -0800196 proxy_port=options.proxy_port,
Chris Sosa4136e692010-10-28 23:42:37 -0700197 src_image=options.src_image,
Chris Sosae67b78f2010-11-04 17:33:16 -0700198 vm=options.vm,
199 board=options.board)
Chris Sosa7c931362010-10-11 19:49:01 -0700200
201 # Sanity-check for use of validate_factory_config.
202 if not options.factory_config and options.validate_factory_config:
203 parser.error('You need a factory_config to validate.')
rtc@google.com64244662009-11-12 00:52:08 +0000204
Chris Sosa0356d3b2010-09-16 15:46:22 -0700205 if options.factory_config:
Chris Sosa7c931362010-10-11 19:49:01 -0700206 updater.ImportFactoryConfigFile(options.factory_config,
Chris Sosa0356d3b2010-09-16 15:46:22 -0700207 options.validate_factory_config)
Chris Sosa7c931362010-10-11 19:49:01 -0700208 # We don't run the dev server with this option.
209 if options.validate_factory_config:
210 sys.exit(0)
Chris Sosa2c048f12010-10-27 16:05:27 -0700211 elif options.pregenerate_update:
Chris Sosae67b78f2010-11-04 17:33:16 -0700212 if not updater.PreGenerateUpdate():
213 sys.exit(1)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700214
Don Garrett0c880e22010-11-17 18:13:37 -0800215 # If the command line requested after setup, it's time to do it.
216 if not options.exit:
217 cherrypy.quickstart(DevServerRoot(), config=_GetConfig(options))