author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Mon, 21 Sep 2009 19:49:47 +0200 | |
branch | stable |
changeset 3357 | 5aed5d6cd5d0 |
parent 3198 | d2f48d30e73e |
child 3199 | fc63b80ec979 |
child 3493 | 3e4603678d4e |
permissions | -rw-r--r-- |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2181
diff
changeset
|
1 |
"""twisted server for CubicWeb web instances |
0 | 2 |
|
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1936
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1936
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
10 |
import sys |
|
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
11 |
import os |
0 | 12 |
import select |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
13 |
from time import mktime |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
14 |
from datetime import date, timedelta |
1520
b097057e629d
provide an option to substitute the base-url (left-most part) subdomain by the one of the current http query to easy multiple subdomains website management
Florent <florent@secondweb.fr>
parents:
1420
diff
changeset
|
15 |
from urlparse import urlsplit, urlunsplit |
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
16 |
import hotshot |
0 | 17 |
|
3117
32686ae66c75
mostly adapt the i18n subsystem to limitation wrt redirection handinling in windows, using the -o argument of the utilities
Aurélien Campéas
parents:
3115
diff
changeset
|
18 |
from twisted.application import strports |
0 | 19 |
from twisted.internet import reactor, task, threads |
20 |
from twisted.internet.defer import maybeDeferred |
|
21 |
from twisted.web2 import channel, http, server, iweb |
|
22 |
from twisted.web2 import static, resource, responsecode |
|
23 |
||
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
24 |
from cubicweb import ObjectNotFound, CW_EVENT_MANAGER |
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
25 |
from cubicweb.web import (AuthenticationError, NotFound, Redirect, |
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
26 |
RemoteCallFailed, DirectResponse, StatusResponse, |
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
27 |
ExplicitLogin) |
0 | 28 |
from cubicweb.web.application import CubicWebPublisher |
29 |
||
30 |
from cubicweb.etwist.request import CubicWebTwistedRequestAdapter |
|
31 |
||
3193
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
32 |
def daemonize(): |
3181
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
33 |
# XXX unix specific |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
34 |
# XXX factorize w/ code in cw.server.server and cw.server.serverctl |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
35 |
# (start-repository command) |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
36 |
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16 |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
37 |
if os.fork(): # launch child and... |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
38 |
return -1 |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
39 |
os.setsid() |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
40 |
if os.fork(): # launch child and... |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
41 |
os._exit(0) # kill off parent again. |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
42 |
# move to the root to avoit mount pb |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
43 |
os.chdir('/') |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
44 |
# set paranoid umask |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
45 |
os.umask(077) |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
46 |
null = os.open('/dev/null', os.O_RDWR) |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
47 |
for i in range(3): |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
48 |
try: |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
49 |
os.dup2(null, i) |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
50 |
except OSError, e: |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
51 |
if e.errno != errno.EBADF: |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
52 |
raise |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
53 |
os.close(null) |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
54 |
return None |
0 | 55 |
|
56 |
def start_task(interval, func): |
|
57 |
lc = task.LoopingCall(func) |
|
58 |
lc.start(interval) |
|
59 |
||
60 |
def start_looping_tasks(repo): |
|
2708
60d728bdcba5
allow to specify arbitrary argument when recording a looping task func
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2705
diff
changeset
|
61 |
for interval, func, args in repo._looping_tasks: |
0 | 62 |
repo.info('starting twisted task %s with interval %.2fs', |
63 |
func.__name__, interval) |
|
2708
60d728bdcba5
allow to specify arbitrary argument when recording a looping task func
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2705
diff
changeset
|
64 |
def catch_error_func(repo=repo, func=func, args=args): |
0 | 65 |
try: |
2708
60d728bdcba5
allow to specify arbitrary argument when recording a looping task func
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2705
diff
changeset
|
66 |
func(*args) |
0 | 67 |
except: |
68 |
repo.exception('error in looping task') |
|
69 |
start_task(interval, catch_error_func) |
|
70 |
# ensure no tasks will be further added |
|
71 |
repo._looping_tasks = () |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
72 |
|
1543
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
73 |
def host_prefixed_baseurl(baseurl, host): |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
74 |
scheme, netloc, url, query, fragment = urlsplit(baseurl) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
75 |
netloc_domain = '.' + '.'.join(netloc.split('.')[-2:]) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
76 |
if host.endswith(netloc_domain): |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
77 |
netloc = host |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
78 |
baseurl = urlunsplit((scheme, netloc, url, query, fragment)) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
79 |
return baseurl |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
80 |
|
0 | 81 |
|
82 |
class LongTimeExpiringFile(static.File): |
|
83 |
"""overrides static.File and sets a far futre ``Expires`` date |
|
84 |
on the resouce. |
|
85 |
||
86 |
versions handling is done by serving static files by different |
|
87 |
URLs for each version. For instance:: |
|
88 |
||
89 |
http://localhost:8080/data-2.48.2/cubicweb.css |
|
90 |
http://localhost:8080/data-2.49.0/cubicweb.css |
|
91 |
etc. |
|
92 |
||
93 |
""" |
|
94 |
def renderHTTP(self, request): |
|
95 |
def setExpireHeader(response): |
|
96 |
response = iweb.IResponse(response) |
|
97 |
# Don't provide additional resource information to error responses |
|
98 |
if response.code < 400: |
|
99 |
# the HTTP RFC recommands not going further than 1 year ahead |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
100 |
expires = date.today() + timedelta(days=6*30) |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
101 |
response.headers.setHeader('Expires', mktime(expires.timetuple())) |
0 | 102 |
return response |
103 |
d = maybeDeferred(super(LongTimeExpiringFile, self).renderHTTP, request) |
|
104 |
return d.addCallback(setExpireHeader) |
|
105 |
||
106 |
||
107 |
class CubicWebRootResource(resource.PostableResource): |
|
108 |
addSlash = False |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
109 |
|
0 | 110 |
def __init__(self, config, debug=None): |
111 |
self.appli = CubicWebPublisher(config, debug=debug) |
|
112 |
self.debugmode = debug |
|
113 |
self.config = config |
|
114 |
self.base_url = config['base-url'] or config.default_base_url() |
|
115 |
self.versioned_datadir = 'data%s' % config.instance_md5_version() |
|
116 |
assert self.base_url[-1] == '/' |
|
117 |
self.https_url = config['https-url'] |
|
118 |
assert not self.https_url or self.https_url[-1] == '/' |
|
119 |
# when we have an in-memory repository, clean unused sessions every XX |
|
120 |
# seconds and properly shutdown the server |
|
121 |
if config.repo_method == 'inmemory': |
|
122 |
reactor.addSystemEventTrigger('before', 'shutdown', |
|
123 |
self.shutdown_event) |
|
1115 | 124 |
# monkey patch start_looping_task to get proper reactor integration |
0 | 125 |
self.appli.repo.__class__.start_looping_tasks = start_looping_tasks |
126 |
if config.pyro_enabled(): |
|
127 |
# if pyro is enabled, we have to register to the pyro name |
|
128 |
# server, create a pyro daemon, and create a task to handle pyro |
|
129 |
# requests |
|
130 |
self.pyro_daemon = self.appli.repo.pyro_register() |
|
131 |
self.pyro_listen_timeout = 0.02 |
|
132 |
start_task(1, self.pyro_loop_event) |
|
133 |
self.appli.repo.start_looping_tasks() |
|
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
134 |
self.set_url_rewriter() |
2705
30bcdbd92820
[events] renamed source-reload into registry-reload to avoid potential confusions with datasources
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2694
diff
changeset
|
135 |
CW_EVENT_MANAGER.bind('after-registry-reload', self.set_url_rewriter) |
0 | 136 |
interval = min(config['cleanup-session-time'] or 120, |
137 |
config['cleanup-anonymous-session-time'] or 720) / 2. |
|
138 |
start_task(interval, self.appli.session_handler.clean_sessions) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
139 |
|
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
140 |
def set_url_rewriter(self): |
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
141 |
self.url_rewriter = self.appli.vreg['components'].select_object('urlrewriter') |
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
142 |
|
0 | 143 |
def shutdown_event(self): |
144 |
"""callback fired when the server is shutting down to properly |
|
145 |
clean opened sessions |
|
146 |
""" |
|
147 |
self.appli.repo.shutdown() |
|
148 |
||
149 |
def pyro_loop_event(self): |
|
150 |
"""listen for pyro events""" |
|
151 |
try: |
|
152 |
self.pyro_daemon.handleRequests(self.pyro_listen_timeout) |
|
153 |
except select.error: |
|
154 |
return |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
155 |
|
0 | 156 |
def locateChild(self, request, segments): |
157 |
"""Indicate which resource to use to process down the URL's path""" |
|
158 |
if segments: |
|
159 |
if segments[0] == 'https': |
|
160 |
segments = segments[1:] |
|
161 |
if len(segments) >= 2: |
|
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
162 |
if segments[0] in (self.versioned_datadir, 'data', 'static'): |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
163 |
# Anything in data/, static/ is treated as static files |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
164 |
if segments[0] == 'static': |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
165 |
# instance static directory |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
166 |
datadir = self.config.static_directory |
2169
124fb0b9fa4b
fckeditor may be a subdirectory of the data directory
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
167 |
elif segments[1] == 'fckeditor': |
124fb0b9fa4b
fckeditor may be a subdirectory of the data directory
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
168 |
fckeditordir = self.config.ext_resources['FCKEDITOR_PATH'] |
124fb0b9fa4b
fckeditor may be a subdirectory of the data directory
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
169 |
return static.File(fckeditordir), segments[2:] |
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
170 |
else: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
171 |
# cube static data file |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
172 |
datadir = self.config.locate_resource(segments[1]) |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
173 |
if datadir is None: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
174 |
return None, [] |
0 | 175 |
self.info('static file %s from %s', segments[-1], datadir) |
176 |
if segments[0] == 'data': |
|
177 |
return static.File(str(datadir)), segments[1:] |
|
178 |
else: |
|
179 |
return LongTimeExpiringFile(datadir), segments[1:] |
|
180 |
elif segments[0] == 'fckeditor': |
|
181 |
fckeditordir = self.config.ext_resources['FCKEDITOR_PATH'] |
|
182 |
return static.File(fckeditordir), segments[1:] |
|
183 |
# Otherwise we use this single resource |
|
184 |
return self, () |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
185 |
|
0 | 186 |
def render(self, request): |
187 |
"""Render a page from the root resource""" |
|
188 |
# reload modified files (only in development or debug mode) |
|
189 |
if self.config.mode == 'dev' or self.debugmode: |
|
190 |
self.appli.vreg.register_objects(self.config.vregistry_path()) |
|
191 |
if self.config['profile']: # default profiler don't trace threads |
|
192 |
return self.render_request(request) |
|
193 |
else: |
|
194 |
return threads.deferToThread(self.render_request, request) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
195 |
|
0 | 196 |
def render_request(self, request): |
197 |
origpath = request.path |
|
198 |
host = request.host |
|
199 |
# dual http/https access handling: expect a rewrite rule to prepend |
|
200 |
# 'https' to the path to detect https access |
|
201 |
if origpath.split('/', 2)[1] == 'https': |
|
202 |
origpath = origpath[6:] |
|
203 |
request.uri = request.uri[6:] |
|
204 |
https = True |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
205 |
baseurl = self.https_url or self.base_url |
0 | 206 |
else: |
207 |
https = False |
|
208 |
baseurl = self.base_url |
|
1520
b097057e629d
provide an option to substitute the base-url (left-most part) subdomain by the one of the current http query to easy multiple subdomains website management
Florent <florent@secondweb.fr>
parents:
1420
diff
changeset
|
209 |
if self.config['use-request-subdomain']: |
1543
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
210 |
baseurl = host_prefixed_baseurl(baseurl, host) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
211 |
self.warning('used baseurl is %s for this request', baseurl) |
0 | 212 |
req = CubicWebTwistedRequestAdapter(request, self.appli.vreg, https, baseurl) |
213 |
if req.authmode == 'http': |
|
214 |
# activate realm-based auth |
|
215 |
realm = self.config['realm'] |
|
216 |
req.set_header('WWW-Authenticate', [('Basic', {'realm' : realm })], raw=False) |
|
217 |
try: |
|
218 |
self.appli.connect(req) |
|
219 |
except AuthenticationError: |
|
220 |
return self.request_auth(req) |
|
221 |
except Redirect, ex: |
|
222 |
return self.redirect(req, ex.location) |
|
223 |
if https and req.cnx.anonymous_connection: |
|
224 |
# don't allow anonymous on https connection |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
225 |
return self.request_auth(req) |
0 | 226 |
if self.url_rewriter is not None: |
1115 | 227 |
# XXX should occur before authentication? |
0 | 228 |
try: |
1936
c5af2fbda5b6
pass request to ApacheRewriter rewrite method
Florent <florent@secondweb.fr>
parents:
1543
diff
changeset
|
229 |
path = self.url_rewriter.rewrite(host, origpath, req) |
0 | 230 |
except Redirect, ex: |
231 |
return self.redirect(req, ex.location) |
|
232 |
request.uri.replace(origpath, path, 1) |
|
233 |
else: |
|
234 |
path = origpath |
|
235 |
if not path or path == "/": |
|
236 |
path = 'view' |
|
237 |
try: |
|
238 |
result = self.appli.publish(path, req) |
|
239 |
except DirectResponse, ex: |
|
240 |
return ex.response |
|
241 |
except StatusResponse, ex: |
|
242 |
return http.Response(stream=ex.content, code=ex.status, |
|
243 |
headers=req.headers_out or None) |
|
244 |
except RemoteCallFailed, ex: |
|
245 |
req.set_header('content-type', 'application/json') |
|
246 |
return http.Response(stream=ex.dumps(), |
|
247 |
code=responsecode.INTERNAL_SERVER_ERROR) |
|
248 |
except NotFound: |
|
249 |
result = self.appli.notfound_content(req) |
|
250 |
return http.Response(stream=result, code=responsecode.NOT_FOUND, |
|
251 |
headers=req.headers_out or None) |
|
252 |
except ExplicitLogin: # must be before AuthenticationError |
|
253 |
return self.request_auth(req) |
|
254 |
except AuthenticationError: |
|
255 |
if self.config['auth-mode'] == 'cookie': |
|
256 |
# in cookie mode redirecting to the index view is enough : |
|
257 |
# either anonymous connection is allowed and the page will |
|
258 |
# be displayed or we'll be redirected to the login form |
|
259 |
msg = req._('you have been logged out') |
|
260 |
if req.https: |
|
261 |
req._base_url = self.base_url |
|
262 |
req.https = False |
|
263 |
url = req.build_url('view', vid='index', __message=msg) |
|
264 |
return self.redirect(req, url) |
|
265 |
else: |
|
266 |
# in http we have to request auth to flush current http auth |
|
267 |
# information |
|
268 |
return self.request_auth(req, loggedout=True) |
|
269 |
except Redirect, ex: |
|
270 |
return self.redirect(req, ex.location) |
|
271 |
# request may be referenced by "onetime callback", so clear its entity |
|
272 |
# cache to avoid memory usage |
|
273 |
req.drop_entity_cache() |
|
274 |
return http.Response(stream=result, code=responsecode.OK, |
|
275 |
headers=req.headers_out or None) |
|
276 |
||
277 |
def redirect(self, req, location): |
|
278 |
req.headers_out.setHeader('location', str(location)) |
|
279 |
self.debug('redirecting to %s', location) |
|
280 |
# 303 See other |
|
281 |
return http.Response(code=303, headers=req.headers_out) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
282 |
|
0 | 283 |
def request_auth(self, req, loggedout=False): |
284 |
if self.https_url and req.base_url() != self.https_url: |
|
285 |
req.headers_out.setHeader('location', self.https_url + 'login') |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
286 |
return http.Response(code=303, headers=req.headers_out) |
0 | 287 |
if self.config['auth-mode'] == 'http': |
288 |
code = responsecode.UNAUTHORIZED |
|
289 |
else: |
|
290 |
code = responsecode.FORBIDDEN |
|
291 |
if loggedout: |
|
292 |
if req.https: |
|
293 |
req._base_url = self.base_url |
|
294 |
req.https = False |
|
295 |
content = self.appli.loggedout_content(req) |
|
296 |
else: |
|
297 |
content = self.appli.need_login_content(req) |
|
298 |
return http.Response(code, req.headers_out, content) |
|
299 |
||
300 |
from twisted.python import failure |
|
301 |
from twisted.internet import defer |
|
302 |
from twisted.web2 import fileupload |
|
303 |
||
304 |
# XXX set max file size to 100Mo: put max upload size in the configuration |
|
305 |
# line below for twisted >= 8.0, default param value for earlier version |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
306 |
resource.PostableResource.maxSize = 100*1024*1024 |
0 | 307 |
def parsePOSTData(request, maxMem=100*1024, maxFields=1024, |
308 |
maxSize=100*1024*1024): |
|
309 |
if request.stream.length == 0: |
|
310 |
return defer.succeed(None) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
311 |
|
0 | 312 |
ctype = request.headers.getHeader('content-type') |
313 |
||
314 |
if ctype is None: |
|
315 |
return defer.succeed(None) |
|
316 |
||
317 |
def updateArgs(data): |
|
318 |
args = data |
|
319 |
request.args.update(args) |
|
320 |
||
321 |
def updateArgsAndFiles(data): |
|
322 |
args, files = data |
|
323 |
request.args.update(args) |
|
324 |
request.files.update(files) |
|
325 |
||
326 |
def error(f): |
|
327 |
f.trap(fileupload.MimeFormatError) |
|
328 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
329 |
|
0 | 330 |
if ctype.mediaType == 'application' and ctype.mediaSubtype == 'x-www-form-urlencoded': |
331 |
d = fileupload.parse_urlencoded(request.stream, keep_blank_values=True) |
|
332 |
d.addCallbacks(updateArgs, error) |
|
333 |
return d |
|
334 |
elif ctype.mediaType == 'multipart' and ctype.mediaSubtype == 'form-data': |
|
335 |
boundary = ctype.params.get('boundary') |
|
336 |
if boundary is None: |
|
337 |
return defer.fail(http.HTTPError( |
|
338 |
http.StatusResponse(responsecode.BAD_REQUEST, |
|
339 |
"Boundary not specified in Content-Type."))) |
|
340 |
d = fileupload.parseMultipartFormData(request.stream, boundary, |
|
341 |
maxMem, maxFields, maxSize) |
|
342 |
d.addCallbacks(updateArgsAndFiles, error) |
|
343 |
return d |
|
344 |
else: |
|
345 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
346 |
||
347 |
server.parsePOSTData = parsePOSTData |
|
348 |
||
349 |
||
350 |
from logging import getLogger |
|
351 |
from cubicweb import set_log_methods |
|
352 |
set_log_methods(CubicWebRootResource, getLogger('cubicweb.twisted')) |
|
353 |
||
354 |
||
355 |
||
356 |
def _gc_debug(): |
|
357 |
import gc |
|
358 |
from pprint import pprint |
|
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2654
diff
changeset
|
359 |
from cubicweb.appobject import AppObject |
0 | 360 |
gc.collect() |
361 |
count = 0 |
|
362 |
acount = 0 |
|
363 |
ocount = {} |
|
364 |
for obj in gc.get_objects(): |
|
365 |
if isinstance(obj, CubicWebTwistedRequestAdapter): |
|
366 |
count += 1 |
|
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2654
diff
changeset
|
367 |
elif isinstance(obj, AppObject): |
0 | 368 |
acount += 1 |
369 |
else: |
|
370 |
try: |
|
1132 | 371 |
ocount[obj.__class__] += 1 |
0 | 372 |
except KeyError: |
373 |
ocount[obj.__class__] = 1 |
|
374 |
except AttributeError: |
|
375 |
pass |
|
376 |
print 'IN MEM REQUESTS', count |
|
377 |
print 'IN MEM APPOBJECTS', acount |
|
378 |
ocount = sorted(ocount.items(), key=lambda x: x[1], reverse=True)[:20] |
|
379 |
pprint(ocount) |
|
380 |
print 'UNREACHABLE', gc.garbage |
|
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
381 |
|
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
382 |
def run(config, debug): |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
383 |
# create the site |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
384 |
root_resource = CubicWebRootResource(config, debug) |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
385 |
website = server.Site(root_resource) |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
386 |
# serve it via standard HTTP on port set in the configuration |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
387 |
port = config['port'] or 8080 |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
388 |
reactor.listenTCP(port, channel.HTTPFactory(website)) |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
389 |
baseurl = config['base-url'] or config.default_base_url() |
2694
4303ff921a9b
[twisted] use cubicweb.twisted.logger instead of print to notify when the instance is started
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2685
diff
changeset
|
390 |
logger = getLogger('cubicweb.twisted') |
4303ff921a9b
[twisted] use cubicweb.twisted.logger instead of print to notify when the instance is started
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2685
diff
changeset
|
391 |
logger.info('instance started on %s', baseurl) |
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
392 |
if not debug: |
3193
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
393 |
if daemonize(): |
3181
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
394 |
# child process |
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
395 |
return |
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
396 |
if config['pid-file']: |
2711
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
397 |
# ensure the directory where the pid-file should be set exists (for |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
398 |
# instance /var/run/cubicweb may be deleted on computer restart) |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
399 |
piddir = os.path.dirname(config['pid-file']) |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
400 |
if not os.path.exists(piddir): |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
401 |
os.makedirs(piddir) |
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
402 |
file(config['pid-file'], 'w').write(str(os.getpid())) |
3193
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
403 |
if config['uid'] is not None: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
404 |
try: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
405 |
uid = int(config['uid']) |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
406 |
except ValueError: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
407 |
from pwd import getpwnam |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
408 |
uid = getpwnam(config['uid']).pw_uid |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
409 |
os.setuid(uid) |
2654
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
410 |
if config['profile']: |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
411 |
prof = hotshot.Profile(config['profile']) |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
412 |
prof.runcall(reactor.run) |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
413 |
else: |
6512522860aa
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2476
diff
changeset
|
414 |
reactor.run() |