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