author | Aurelien Campeas <aurelien.campeas@logilab.fr> |
Tue, 06 Oct 2009 14:14:16 +0200 | |
branch | stable |
changeset 3562 | cff18f0d7c73 |
parent 3558 | 0e478957a9d4 |
child 3589 | a5432f99f2d9 |
child 3606 | 8326aceecb46 |
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 |
3493
3e4603678d4e
use default repo looping task so they are started in thread, else we get blocking task
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3198
diff
changeset
|
13 |
import hotshot |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
14 |
from time import mktime |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
15 |
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
|
16 |
from urlparse import urlsplit, urlunsplit |
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... |
3558
0e478957a9d4
smallest possible change to fix #472806
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3502
diff
changeset
|
38 |
os._exit(0) |
3181
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) |
|
3493
3e4603678d4e
use default repo looping task so they are started in thread, else we get blocking task
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3198
diff
changeset
|
58 |
# wait until interval has expired to actually start the task, else we have |
3e4603678d4e
use default repo looping task so they are started in thread, else we get blocking task
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3198
diff
changeset
|
59 |
# to wait all task to be finished for the server to be actually started |
3e4603678d4e
use default repo looping task so they are started in thread, else we get blocking task
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3198
diff
changeset
|
60 |
lc.start(interval, now=False) |
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
61 |
|
1543
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
62 |
def host_prefixed_baseurl(baseurl, host): |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
63 |
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
|
64 |
netloc_domain = '.' + '.'.join(netloc.split('.')[-2:]) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
65 |
if host.endswith(netloc_domain): |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
66 |
netloc = host |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
67 |
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
|
68 |
return baseurl |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
69 |
|
0 | 70 |
|
71 |
class LongTimeExpiringFile(static.File): |
|
72 |
"""overrides static.File and sets a far futre ``Expires`` date |
|
73 |
on the resouce. |
|
74 |
||
75 |
versions handling is done by serving static files by different |
|
76 |
URLs for each version. For instance:: |
|
77 |
||
78 |
http://localhost:8080/data-2.48.2/cubicweb.css |
|
79 |
http://localhost:8080/data-2.49.0/cubicweb.css |
|
80 |
etc. |
|
81 |
||
82 |
""" |
|
83 |
def renderHTTP(self, request): |
|
84 |
def setExpireHeader(response): |
|
85 |
response = iweb.IResponse(response) |
|
86 |
# Don't provide additional resource information to error responses |
|
87 |
if response.code < 400: |
|
88 |
# 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
|
89 |
expires = date.today() + timedelta(days=6*30) |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
90 |
response.headers.setHeader('Expires', mktime(expires.timetuple())) |
0 | 91 |
return response |
92 |
d = maybeDeferred(super(LongTimeExpiringFile, self).renderHTTP, request) |
|
93 |
return d.addCallback(setExpireHeader) |
|
94 |
||
95 |
||
96 |
class CubicWebRootResource(resource.PostableResource): |
|
97 |
addSlash = False |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
98 |
|
0 | 99 |
def __init__(self, config, debug=None): |
100 |
self.appli = CubicWebPublisher(config, debug=debug) |
|
101 |
self.debugmode = debug |
|
102 |
self.config = config |
|
103 |
self.base_url = config['base-url'] or config.default_base_url() |
|
104 |
self.versioned_datadir = 'data%s' % config.instance_md5_version() |
|
105 |
assert self.base_url[-1] == '/' |
|
106 |
self.https_url = config['https-url'] |
|
107 |
assert not self.https_url or self.https_url[-1] == '/' |
|
108 |
# when we have an in-memory repository, clean unused sessions every XX |
|
109 |
# seconds and properly shutdown the server |
|
110 |
if config.repo_method == 'inmemory': |
|
111 |
reactor.addSystemEventTrigger('before', 'shutdown', |
|
112 |
self.shutdown_event) |
|
1115 | 113 |
# monkey patch start_looping_task to get proper reactor integration |
3493
3e4603678d4e
use default repo looping task so they are started in thread, else we get blocking task
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3198
diff
changeset
|
114 |
#self.appli.repo.__class__.start_looping_tasks = start_looping_tasks |
0 | 115 |
if config.pyro_enabled(): |
116 |
# if pyro is enabled, we have to register to the pyro name |
|
117 |
# server, create a pyro daemon, and create a task to handle pyro |
|
118 |
# requests |
|
119 |
self.pyro_daemon = self.appli.repo.pyro_register() |
|
120 |
self.pyro_listen_timeout = 0.02 |
|
3502 | 121 |
self.appli.repo.looping_task(1, self.pyro_loop_event) |
0 | 122 |
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
|
123 |
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
|
124 |
CW_EVENT_MANAGER.bind('after-registry-reload', self.set_url_rewriter) |
0 | 125 |
interval = min(config['cleanup-session-time'] or 120, |
126 |
config['cleanup-anonymous-session-time'] or 720) / 2. |
|
127 |
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
|
128 |
|
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
129 |
def set_url_rewriter(self): |
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
130 |
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
|
131 |
|
0 | 132 |
def shutdown_event(self): |
133 |
"""callback fired when the server is shutting down to properly |
|
134 |
clean opened sessions |
|
135 |
""" |
|
136 |
self.appli.repo.shutdown() |
|
137 |
||
138 |
def pyro_loop_event(self): |
|
139 |
"""listen for pyro events""" |
|
140 |
try: |
|
141 |
self.pyro_daemon.handleRequests(self.pyro_listen_timeout) |
|
142 |
except select.error: |
|
143 |
return |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
144 |
|
0 | 145 |
def locateChild(self, request, segments): |
146 |
"""Indicate which resource to use to process down the URL's path""" |
|
147 |
if segments: |
|
148 |
if segments[0] == 'https': |
|
149 |
segments = segments[1:] |
|
150 |
if len(segments) >= 2: |
|
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
151 |
if segments[0] in (self.versioned_datadir, 'data', 'static'): |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
152 |
# Anything in data/, static/ is treated as static files |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
153 |
if segments[0] == 'static': |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
154 |
# instance static directory |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
155 |
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
|
156 |
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
|
157 |
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
|
158 |
return static.File(fckeditordir), segments[2:] |
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
159 |
else: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
160 |
# cube static data file |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
161 |
datadir = self.config.locate_resource(segments[1]) |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
162 |
if datadir is None: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
163 |
return None, [] |
0 | 164 |
self.info('static file %s from %s', segments[-1], datadir) |
165 |
if segments[0] == 'data': |
|
166 |
return static.File(str(datadir)), segments[1:] |
|
167 |
else: |
|
168 |
return LongTimeExpiringFile(datadir), segments[1:] |
|
169 |
elif segments[0] == 'fckeditor': |
|
170 |
fckeditordir = self.config.ext_resources['FCKEDITOR_PATH'] |
|
171 |
return static.File(fckeditordir), segments[1:] |
|
172 |
# Otherwise we use this single resource |
|
173 |
return self, () |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
174 |
|
0 | 175 |
def render(self, request): |
176 |
"""Render a page from the root resource""" |
|
177 |
# reload modified files (only in development or debug mode) |
|
178 |
if self.config.mode == 'dev' or self.debugmode: |
|
179 |
self.appli.vreg.register_objects(self.config.vregistry_path()) |
|
180 |
if self.config['profile']: # default profiler don't trace threads |
|
181 |
return self.render_request(request) |
|
182 |
else: |
|
183 |
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
|
184 |
|
0 | 185 |
def render_request(self, request): |
186 |
origpath = request.path |
|
187 |
host = request.host |
|
188 |
# dual http/https access handling: expect a rewrite rule to prepend |
|
189 |
# 'https' to the path to detect https access |
|
190 |
if origpath.split('/', 2)[1] == 'https': |
|
191 |
origpath = origpath[6:] |
|
192 |
request.uri = request.uri[6:] |
|
193 |
https = True |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
194 |
baseurl = self.https_url or self.base_url |
0 | 195 |
else: |
196 |
https = False |
|
197 |
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
|
198 |
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
|
199 |
baseurl = host_prefixed_baseurl(baseurl, host) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
200 |
self.warning('used baseurl is %s for this request', baseurl) |
0 | 201 |
req = CubicWebTwistedRequestAdapter(request, self.appli.vreg, https, baseurl) |
202 |
if req.authmode == 'http': |
|
203 |
# activate realm-based auth |
|
204 |
realm = self.config['realm'] |
|
205 |
req.set_header('WWW-Authenticate', [('Basic', {'realm' : realm })], raw=False) |
|
206 |
try: |
|
207 |
self.appli.connect(req) |
|
208 |
except AuthenticationError: |
|
209 |
return self.request_auth(req) |
|
210 |
except Redirect, ex: |
|
211 |
return self.redirect(req, ex.location) |
|
212 |
if https and req.cnx.anonymous_connection: |
|
213 |
# 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
|
214 |
return self.request_auth(req) |
0 | 215 |
if self.url_rewriter is not None: |
1115 | 216 |
# XXX should occur before authentication? |
0 | 217 |
try: |
1936
c5af2fbda5b6
pass request to ApacheRewriter rewrite method
Florent <florent@secondweb.fr>
parents:
1543
diff
changeset
|
218 |
path = self.url_rewriter.rewrite(host, origpath, req) |
0 | 219 |
except Redirect, ex: |
220 |
return self.redirect(req, ex.location) |
|
221 |
request.uri.replace(origpath, path, 1) |
|
222 |
else: |
|
223 |
path = origpath |
|
224 |
if not path or path == "/": |
|
225 |
path = 'view' |
|
226 |
try: |
|
227 |
result = self.appli.publish(path, req) |
|
228 |
except DirectResponse, ex: |
|
229 |
return ex.response |
|
230 |
except StatusResponse, ex: |
|
231 |
return http.Response(stream=ex.content, code=ex.status, |
|
232 |
headers=req.headers_out or None) |
|
233 |
except RemoteCallFailed, ex: |
|
234 |
req.set_header('content-type', 'application/json') |
|
235 |
return http.Response(stream=ex.dumps(), |
|
236 |
code=responsecode.INTERNAL_SERVER_ERROR) |
|
237 |
except NotFound: |
|
238 |
result = self.appli.notfound_content(req) |
|
239 |
return http.Response(stream=result, code=responsecode.NOT_FOUND, |
|
240 |
headers=req.headers_out or None) |
|
241 |
except ExplicitLogin: # must be before AuthenticationError |
|
242 |
return self.request_auth(req) |
|
243 |
except AuthenticationError: |
|
244 |
if self.config['auth-mode'] == 'cookie': |
|
245 |
# in cookie mode redirecting to the index view is enough : |
|
246 |
# either anonymous connection is allowed and the page will |
|
247 |
# be displayed or we'll be redirected to the login form |
|
248 |
msg = req._('you have been logged out') |
|
249 |
if req.https: |
|
250 |
req._base_url = self.base_url |
|
251 |
req.https = False |
|
252 |
url = req.build_url('view', vid='index', __message=msg) |
|
253 |
return self.redirect(req, url) |
|
254 |
else: |
|
255 |
# in http we have to request auth to flush current http auth |
|
256 |
# information |
|
257 |
return self.request_auth(req, loggedout=True) |
|
258 |
except Redirect, ex: |
|
259 |
return self.redirect(req, ex.location) |
|
260 |
# request may be referenced by "onetime callback", so clear its entity |
|
261 |
# cache to avoid memory usage |
|
262 |
req.drop_entity_cache() |
|
263 |
return http.Response(stream=result, code=responsecode.OK, |
|
264 |
headers=req.headers_out or None) |
|
265 |
||
266 |
def redirect(self, req, location): |
|
267 |
req.headers_out.setHeader('location', str(location)) |
|
268 |
self.debug('redirecting to %s', location) |
|
269 |
# 303 See other |
|
270 |
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
|
271 |
|
0 | 272 |
def request_auth(self, req, loggedout=False): |
273 |
if self.https_url and req.base_url() != self.https_url: |
|
274 |
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
|
275 |
return http.Response(code=303, headers=req.headers_out) |
0 | 276 |
if self.config['auth-mode'] == 'http': |
277 |
code = responsecode.UNAUTHORIZED |
|
278 |
else: |
|
279 |
code = responsecode.FORBIDDEN |
|
280 |
if loggedout: |
|
281 |
if req.https: |
|
282 |
req._base_url = self.base_url |
|
283 |
req.https = False |
|
284 |
content = self.appli.loggedout_content(req) |
|
285 |
else: |
|
286 |
content = self.appli.need_login_content(req) |
|
287 |
return http.Response(code, req.headers_out, content) |
|
288 |
||
289 |
from twisted.python import failure |
|
290 |
from twisted.internet import defer |
|
291 |
from twisted.web2 import fileupload |
|
292 |
||
293 |
# XXX set max file size to 100Mo: put max upload size in the configuration |
|
294 |
# 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
|
295 |
resource.PostableResource.maxSize = 100*1024*1024 |
0 | 296 |
def parsePOSTData(request, maxMem=100*1024, maxFields=1024, |
297 |
maxSize=100*1024*1024): |
|
298 |
if request.stream.length == 0: |
|
299 |
return defer.succeed(None) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
300 |
|
0 | 301 |
ctype = request.headers.getHeader('content-type') |
302 |
||
303 |
if ctype is None: |
|
304 |
return defer.succeed(None) |
|
305 |
||
306 |
def updateArgs(data): |
|
307 |
args = data |
|
308 |
request.args.update(args) |
|
309 |
||
310 |
def updateArgsAndFiles(data): |
|
311 |
args, files = data |
|
312 |
request.args.update(args) |
|
313 |
request.files.update(files) |
|
314 |
||
315 |
def error(f): |
|
316 |
f.trap(fileupload.MimeFormatError) |
|
317 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
318 |
|
0 | 319 |
if ctype.mediaType == 'application' and ctype.mediaSubtype == 'x-www-form-urlencoded': |
320 |
d = fileupload.parse_urlencoded(request.stream, keep_blank_values=True) |
|
321 |
d.addCallbacks(updateArgs, error) |
|
322 |
return d |
|
323 |
elif ctype.mediaType == 'multipart' and ctype.mediaSubtype == 'form-data': |
|
324 |
boundary = ctype.params.get('boundary') |
|
325 |
if boundary is None: |
|
326 |
return defer.fail(http.HTTPError( |
|
327 |
http.StatusResponse(responsecode.BAD_REQUEST, |
|
328 |
"Boundary not specified in Content-Type."))) |
|
329 |
d = fileupload.parseMultipartFormData(request.stream, boundary, |
|
330 |
maxMem, maxFields, maxSize) |
|
331 |
d.addCallbacks(updateArgsAndFiles, error) |
|
332 |
return d |
|
333 |
else: |
|
334 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
335 |
||
336 |
server.parsePOSTData = parsePOSTData |
|
337 |
||
338 |
||
339 |
from logging import getLogger |
|
340 |
from cubicweb import set_log_methods |
|
341 |
set_log_methods(CubicWebRootResource, getLogger('cubicweb.twisted')) |
|
342 |
||
343 |
||
344 |
||
345 |
def _gc_debug(): |
|
346 |
import gc |
|
347 |
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
|
348 |
from cubicweb.appobject import AppObject |
0 | 349 |
gc.collect() |
350 |
count = 0 |
|
351 |
acount = 0 |
|
352 |
ocount = {} |
|
353 |
for obj in gc.get_objects(): |
|
354 |
if isinstance(obj, CubicWebTwistedRequestAdapter): |
|
355 |
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
|
356 |
elif isinstance(obj, AppObject): |
0 | 357 |
acount += 1 |
358 |
else: |
|
359 |
try: |
|
1132 | 360 |
ocount[obj.__class__] += 1 |
0 | 361 |
except KeyError: |
362 |
ocount[obj.__class__] = 1 |
|
363 |
except AttributeError: |
|
364 |
pass |
|
365 |
print 'IN MEM REQUESTS', count |
|
366 |
print 'IN MEM APPOBJECTS', acount |
|
367 |
ocount = sorted(ocount.items(), key=lambda x: x[1], reverse=True)[:20] |
|
368 |
pprint(ocount) |
|
369 |
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
|
370 |
|
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
|
371 |
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
|
372 |
# 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
|
373 |
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
|
374 |
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
|
375 |
# 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
|
376 |
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
|
377 |
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
|
378 |
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
|
379 |
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
|
380 |
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
|
381 |
if not debug: |
3558
0e478957a9d4
smallest possible change to fix #472806
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3502
diff
changeset
|
382 |
print 'instance starting in the background' |
0e478957a9d4
smallest possible change to fix #472806
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3502
diff
changeset
|
383 |
daemonize() |
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
|
384 |
if config['pid-file']: |
2711
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
385 |
# ensure the directory where the pid-file should be set exists (for |
3558
0e478957a9d4
smallest possible change to fix #472806
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3502
diff
changeset
|
386 |
# instance /var/run/cubicweb may be deleted on computer restart) |
2711
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
387 |
piddir = os.path.dirname(config['pid-file']) |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
388 |
if not os.path.exists(piddir): |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
389 |
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
|
390 |
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
|
391 |
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
|
392 |
try: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
393 |
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
|
394 |
except ValueError: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
395 |
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
|
396 |
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
|
397 |
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
|
398 |
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
|
399 |
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
|
400 |
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
|
401 |
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
|
402 |
reactor.run() |