207e9d2cbab6c85db741eba7d01b0aa0504cf11c
[mediagoblin.git] / mediagoblin / app.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import os
18 import logging
19
20 from mediagoblin.routing import get_url_map, endpoint_to_controller
21
22 from werkzeug.wrappers import Request
23 from werkzeug.exceptions import HTTPException, NotFound
24
25 from mediagoblin import meddleware, __version__
26 from mediagoblin.tools import common, translate, template
27 from mediagoblin.tools.response import render_http_exception
28 from mediagoblin.tools.theme import register_themes
29 from mediagoblin.tools import request as mg_request
30 from mediagoblin.mg_globals import setup_globals
31 from mediagoblin.init.celery import setup_celery_from_config
32 from mediagoblin.init.plugins import setup_plugins
33 from mediagoblin.init import (get_jinja_loader, get_staticdirector,
34 setup_global_and_app_config, setup_locales, setup_workbench, setup_database,
35 setup_storage, setup_beaker_cache)
36 from mediagoblin.tools.pluginapi import PluginManager
37
38
39 _log = logging.getLogger(__name__)
40
41
42 class MediaGoblinApp(object):
43 """
44 WSGI application of MediaGoblin
45
46 ... this is the heart of the program!
47 """
48 def __init__(self, config_path, setup_celery=True):
49 """
50 Initialize the application based on a configuration file.
51
52 Arguments:
53 - config_path: path to the configuration file we're opening.
54 - setup_celery: whether or not to setup celery during init.
55 (Note: setting 'celery_setup_elsewhere' also disables
56 setting up celery.)
57 """
58 _log.info("GNU MediaGoblin %s main server starting", __version__)
59 _log.debug("Using config file %s", config_path)
60 ##############
61 # Setup config
62 ##############
63
64 # Open and setup the config
65 global_config, app_config = setup_global_and_app_config(config_path)
66
67 ##########################################
68 # Setup other connections / useful objects
69 ##########################################
70
71 # load all available locales
72 setup_locales()
73
74 # Set up plugins -- need to do this early so that plugins can
75 # affect startup.
76 _log.info("Setting up plugins.")
77 setup_plugins()
78
79 # Set up the database
80 self.connection, self.db = setup_database()
81
82 # Register themes
83 self.theme_registry, self.current_theme = register_themes(app_config)
84
85 # Get the template environment
86 self.template_loader = get_jinja_loader(
87 app_config.get('local_templates'),
88 self.current_theme,
89 PluginManager().get_template_paths()
90 )
91
92 # Set up storage systems
93 self.public_store, self.queue_store = setup_storage()
94
95 # set up routing
96 self.url_map = get_url_map()
97
98 # set up staticdirector tool
99 self.staticdirector = get_staticdirector(app_config)
100
101 # set up caching
102 self.cache = setup_beaker_cache()
103
104 # Setup celery, if appropriate
105 if setup_celery and not app_config.get('celery_setup_elsewhere'):
106 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
107 setup_celery_from_config(
108 app_config, global_config,
109 force_celery_always_eager=True)
110 else:
111 setup_celery_from_config(app_config, global_config)
112
113 #######################################################
114 # Insert appropriate things into mediagoblin.mg_globals
115 #
116 # certain properties need to be accessed globally eg from
117 # validators, etc, which might not access to the request
118 # object.
119 #######################################################
120
121 setup_globals(app=self)
122
123 # Workbench *currently* only used by celery, so this only
124 # matters in always eager mode :)
125 setup_workbench()
126
127 # instantiate application meddleware
128 self.meddleware = [common.import_component(m)(self)
129 for m in meddleware.ENABLED_MEDDLEWARE]
130
131 def call_backend(self, environ, start_response):
132 request = Request(environ)
133
134 # Compatibility with django, use request.args preferrably
135 request.GET = request.args
136
137 ## Routing / controller loading stuff
138 map_adapter = self.url_map.bind_to_environ(request.environ)
139
140 # By using fcgi, mediagoblin can run under a base path
141 # like /mediagoblin/. request.path_info contains the
142 # path inside mediagoblin. If the something needs the
143 # full path of the current page, that should include
144 # the basepath.
145 # Note: urlgen and routes are fine!
146 request.full_path = environ["SCRIPT_NAME"] + request.path
147 # python-routes uses SCRIPT_NAME. So let's use that too.
148 # The other option would be:
149 # request.full_path = environ["SCRIPT_URL"]
150
151 # Fix up environ for urlgen
152 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
153 if environ.get('HTTPS', '').lower() == 'off':
154 environ.pop('HTTPS')
155
156 ## Attach utilities to the request object
157 # Do we really want to load this via middleware? Maybe?
158 request.session = request.environ['beaker.session']
159 # Attach self as request.app
160 # Also attach a few utilities from request.app for convenience?
161 request.app = self
162
163 request.db = self.db
164 request.staticdirect = self.staticdirector
165
166 request.locale = translate.get_locale_from_request(request)
167 request.template_env = template.get_jinja_env(
168 self.template_loader, request.locale)
169
170 def build_proxy(endpoint, **kw):
171 try:
172 qualified = kw.pop('qualified')
173 except KeyError:
174 qualified = False
175
176 return map_adapter.build(
177 endpoint,
178 values=dict(**kw),
179 force_external=qualified)
180
181 request.urlgen = build_proxy
182
183 mg_request.setup_user_in_request(request)
184
185 try:
186 endpoint, url_values = map_adapter.match()
187 request.matchdict = url_values
188 except HTTPException as exc:
189 # Stop and render exception
190 return render_http_exception(
191 request, exc,
192 exc.get_description(environ))(environ, start_response)
193
194 controller = endpoint_to_controller(endpoint)
195
196 # pass the request through our meddleware classes
197 try:
198 for m in self.meddleware:
199 response = m.process_request(request, controller)
200 if response is not None:
201 return response(environ, start_response)
202 except HTTPException as e:
203 return render_http_exception(
204 request, e,
205 e.get_description(environ))(environ, start_response)
206
207 request.start_response = start_response
208
209 # get the Http response from the controller
210 try:
211 response = controller(request)
212 except HTTPException as e:
213 response = render_http_exception(
214 request, e, e.get_description(environ))
215
216 # pass the response through the meddlewares
217 try:
218 for m in self.meddleware[::-1]:
219 m.process_response(request, response)
220 except HTTPException as e:
221 response = render_http_exeption(
222 request, e, e.get_description(environ))
223
224 return response(environ, start_response)
225
226 def __call__(self, environ, start_response):
227 ## If more errors happen that look like unclean sessions:
228 # self.db.check_session_clean()
229
230 try:
231 return self.call_backend(environ, start_response)
232 finally:
233 # Reset the sql session, so that the next request
234 # gets a fresh session
235 self.db.reset_after_request()
236
237
238 def paste_app_factory(global_config, **app_config):
239 configs = app_config['config'].split()
240 mediagoblin_config = None
241 for config in configs:
242 if os.path.exists(config) and os.access(config, os.R_OK):
243 mediagoblin_config = config
244 break
245
246 if not mediagoblin_config:
247 raise IOError("Usable mediagoblin config not found.")
248
249 mgoblin_app = MediaGoblinApp(mediagoblin_config)
250
251 return mgoblin_app