author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Wed, 17 Mar 2010 09:21:58 +0100 | |
branch | stable |
changeset 4928 | cbca73dc9753 |
parent 4911 | 898c35be5873 |
child 4914 | dcb055f32d9b |
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 |
|
4212
ab6573088b4a
update copyright: welcome 2010
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
4194
diff
changeset
|
4 |
:copyright: 2001-2010 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 |
4398
4e7e74918631
add missing errno import in etwist/server.py
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
4221
diff
changeset
|
13 |
import errno |
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
|
14 |
import hotshot |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
15 |
from time import mktime |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
151
diff
changeset
|
16 |
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
|
17 |
from urlparse import urlsplit, urlunsplit |
0 | 18 |
|
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 |
||
4221
da84ca26896d
raising ConfigurationError is cleaner; remove some unused imports
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4219
diff
changeset
|
24 |
from cubicweb import ConfigurationError, 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... |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
38 |
return 1 |
3181
735c5f9fcded
fix daemonize: set umask, move to /, consider uid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2711
diff
changeset
|
39 |
os.setsid() |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
40 |
if os.fork(): # launch child again. |
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
41 |
return 1 |
3181
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.debugmode = debug |
|
101 |
self.config = config |
|
3828
335e40fdb5a5
when instance is started normally (eg not in debug mode), check versions before daemonization
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3791
diff
changeset
|
102 |
# instantiate publisher here and not in init_publisher to get some |
335e40fdb5a5
when instance is started normally (eg not in debug mode), check versions before daemonization
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3791
diff
changeset
|
103 |
# checks done before daemonization (eg versions consistency) |
335e40fdb5a5
when instance is started normally (eg not in debug mode), check versions before daemonization
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3791
diff
changeset
|
104 |
self.appli = CubicWebPublisher(config, debug=self.debugmode) |
4909
a13c1d1ecc5b
[web server]Â simplify base-url handling on startup. Ensure config['base-url'] is correctly set once started
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4436
diff
changeset
|
105 |
self.base_url = config['base-url'] |
a13c1d1ecc5b
[web server]Â simplify base-url handling on startup. Ensure config['base-url'] is correctly set once started
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4436
diff
changeset
|
106 |
self.https_url = config['https-url'] |
3828
335e40fdb5a5
when instance is started normally (eg not in debug mode), check versions before daemonization
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3791
diff
changeset
|
107 |
self.versioned_datadir = 'data%s' % config.instance_md5_version() |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
108 |
|
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
109 |
def init_publisher(self): |
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
110 |
config = self.config |
0 | 111 |
# when we have an in-memory repository, clean unused sessions every XX |
112 |
# seconds and properly shutdown the server |
|
113 |
if config.repo_method == 'inmemory': |
|
114 |
reactor.addSystemEventTrigger('before', 'shutdown', |
|
115 |
self.shutdown_event) |
|
1115 | 116 |
# 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
|
117 |
#self.appli.repo.__class__.start_looping_tasks = start_looping_tasks |
0 | 118 |
if config.pyro_enabled(): |
119 |
# if pyro is enabled, we have to register to the pyro name |
|
120 |
# server, create a pyro daemon, and create a task to handle pyro |
|
121 |
# requests |
|
122 |
self.pyro_daemon = self.appli.repo.pyro_register() |
|
123 |
self.pyro_listen_timeout = 0.02 |
|
3502 | 124 |
self.appli.repo.looping_task(1, self.pyro_loop_event) |
0 | 125 |
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
|
126 |
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
|
127 |
CW_EVENT_MANAGER.bind('after-registry-reload', self.set_url_rewriter) |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
128 |
|
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
129 |
def start_service(self): |
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
130 |
config = self.config |
0 | 131 |
interval = min(config['cleanup-session-time'] or 120, |
132 |
config['cleanup-anonymous-session-time'] or 720) / 2. |
|
133 |
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
|
134 |
|
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
135 |
def set_url_rewriter(self): |
2770
356e9d7c356d
R propagate registry API changes
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2711
diff
changeset
|
136 |
self.url_rewriter = self.appli.vreg['components'].select_or_none('urlrewriter') |
2685
0518ca8f63e3
[autoreload] recompute urlresolver / urlrewriter after autoreload
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2670
diff
changeset
|
137 |
|
0 | 138 |
def shutdown_event(self): |
139 |
"""callback fired when the server is shutting down to properly |
|
140 |
clean opened sessions |
|
141 |
""" |
|
142 |
self.appli.repo.shutdown() |
|
143 |
||
144 |
def pyro_loop_event(self): |
|
145 |
"""listen for pyro events""" |
|
146 |
try: |
|
147 |
self.pyro_daemon.handleRequests(self.pyro_listen_timeout) |
|
148 |
except select.error: |
|
149 |
return |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
150 |
|
0 | 151 |
def locateChild(self, request, segments): |
152 |
"""Indicate which resource to use to process down the URL's path""" |
|
153 |
if segments: |
|
154 |
if segments[0] == 'https': |
|
155 |
segments = segments[1:] |
|
156 |
if len(segments) >= 2: |
|
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
157 |
if segments[0] in (self.versioned_datadir, 'data', 'static'): |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
158 |
# Anything in data/, static/ is treated as static files |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
159 |
if segments[0] == 'static': |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
160 |
# instance static directory |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
161 |
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
|
162 |
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
|
163 |
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
|
164 |
return static.File(fckeditordir), segments[2:] |
151
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
165 |
else: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
166 |
# cube static data file |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
167 |
datadir = self.config.locate_resource(segments[1]) |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
168 |
if datadir is None: |
343e7a18675d
static files support
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
169 |
return None, [] |
3618 | 170 |
self.info('static file %s from %s', segments[-1], datadir) |
0 | 171 |
if segments[0] == 'data': |
172 |
return static.File(str(datadir)), segments[1:] |
|
173 |
else: |
|
174 |
return LongTimeExpiringFile(datadir), segments[1:] |
|
175 |
elif segments[0] == 'fckeditor': |
|
176 |
fckeditordir = self.config.ext_resources['FCKEDITOR_PATH'] |
|
177 |
return static.File(fckeditordir), segments[1:] |
|
178 |
# Otherwise we use this single resource |
|
179 |
return self, () |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
180 |
|
0 | 181 |
def render(self, request): |
182 |
"""Render a page from the root resource""" |
|
3638
648d6dbec630
system/user modes + CWDEV instead of installed/dev mixed modes. Fix behaviour when setting CW_MODE explicitly
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3618
diff
changeset
|
183 |
# reload modified files in debug mode |
3641
cf30e4498674
fix debug attribute conflict on configuration
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3638
diff
changeset
|
184 |
if self.debugmode: |
0 | 185 |
self.appli.vreg.register_objects(self.config.vregistry_path()) |
186 |
if self.config['profile']: # default profiler don't trace threads |
|
187 |
return self.render_request(request) |
|
188 |
else: |
|
189 |
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
|
190 |
|
0 | 191 |
def render_request(self, request): |
192 |
origpath = request.path |
|
193 |
host = request.host |
|
194 |
# dual http/https access handling: expect a rewrite rule to prepend |
|
195 |
# 'https' to the path to detect https access |
|
196 |
if origpath.split('/', 2)[1] == 'https': |
|
197 |
origpath = origpath[6:] |
|
198 |
request.uri = request.uri[6:] |
|
199 |
https = True |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
200 |
baseurl = self.https_url or self.base_url |
0 | 201 |
else: |
202 |
https = False |
|
203 |
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
|
204 |
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
|
205 |
baseurl = host_prefixed_baseurl(baseurl, host) |
dca9817bb337
fix use-request-subdomain option behaviour and add tests
Florent <florent@secondweb.fr>
parents:
1542
diff
changeset
|
206 |
self.warning('used baseurl is %s for this request', baseurl) |
0 | 207 |
req = CubicWebTwistedRequestAdapter(request, self.appli.vreg, https, baseurl) |
208 |
if req.authmode == 'http': |
|
209 |
# activate realm-based auth |
|
210 |
realm = self.config['realm'] |
|
211 |
req.set_header('WWW-Authenticate', [('Basic', {'realm' : realm })], raw=False) |
|
212 |
try: |
|
213 |
self.appli.connect(req) |
|
214 |
except AuthenticationError: |
|
215 |
return self.request_auth(req) |
|
216 |
except Redirect, ex: |
|
217 |
return self.redirect(req, ex.location) |
|
218 |
if https and req.cnx.anonymous_connection: |
|
219 |
# 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
|
220 |
return self.request_auth(req) |
0 | 221 |
if self.url_rewriter is not None: |
1115 | 222 |
# XXX should occur before authentication? |
0 | 223 |
try: |
1936
c5af2fbda5b6
pass request to ApacheRewriter rewrite method
Florent <florent@secondweb.fr>
parents:
1543
diff
changeset
|
224 |
path = self.url_rewriter.rewrite(host, origpath, req) |
0 | 225 |
except Redirect, ex: |
226 |
return self.redirect(req, ex.location) |
|
227 |
request.uri.replace(origpath, path, 1) |
|
228 |
else: |
|
229 |
path = origpath |
|
230 |
if not path or path == "/": |
|
231 |
path = 'view' |
|
232 |
try: |
|
233 |
result = self.appli.publish(path, req) |
|
234 |
except DirectResponse, ex: |
|
235 |
return ex.response |
|
236 |
except StatusResponse, ex: |
|
237 |
return http.Response(stream=ex.content, code=ex.status, |
|
238 |
headers=req.headers_out or None) |
|
239 |
except RemoteCallFailed, ex: |
|
240 |
req.set_header('content-type', 'application/json') |
|
241 |
return http.Response(stream=ex.dumps(), |
|
242 |
code=responsecode.INTERNAL_SERVER_ERROR) |
|
243 |
except NotFound: |
|
244 |
result = self.appli.notfound_content(req) |
|
245 |
return http.Response(stream=result, code=responsecode.NOT_FOUND, |
|
246 |
headers=req.headers_out or None) |
|
247 |
except ExplicitLogin: # must be before AuthenticationError |
|
248 |
return self.request_auth(req) |
|
4911
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
249 |
except AuthenticationError, ex: |
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
250 |
if self.config['auth-mode'] == 'cookie' and getattr(ex, 'url', None): |
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
251 |
return self.redirect(req, ex.url) |
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
252 |
# in http we have to request auth to flush current http auth |
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
253 |
# information |
898c35be5873
#750055: make it easier to change post logout url
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4909
diff
changeset
|
254 |
return self.request_auth(req, loggedout=True) |
0 | 255 |
except Redirect, ex: |
256 |
return self.redirect(req, ex.location) |
|
257 |
# request may be referenced by "onetime callback", so clear its entity |
|
258 |
# cache to avoid memory usage |
|
259 |
req.drop_entity_cache() |
|
260 |
return http.Response(stream=result, code=responsecode.OK, |
|
261 |
headers=req.headers_out or None) |
|
262 |
||
263 |
def redirect(self, req, location): |
|
264 |
req.headers_out.setHeader('location', str(location)) |
|
265 |
self.debug('redirecting to %s', location) |
|
266 |
# 303 See other |
|
267 |
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
|
268 |
|
0 | 269 |
def request_auth(self, req, loggedout=False): |
270 |
if self.https_url and req.base_url() != self.https_url: |
|
271 |
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
|
272 |
return http.Response(code=303, headers=req.headers_out) |
0 | 273 |
if self.config['auth-mode'] == 'http': |
274 |
code = responsecode.UNAUTHORIZED |
|
275 |
else: |
|
276 |
code = responsecode.FORBIDDEN |
|
277 |
if loggedout: |
|
278 |
if req.https: |
|
279 |
req._base_url = self.base_url |
|
280 |
req.https = False |
|
281 |
content = self.appli.loggedout_content(req) |
|
282 |
else: |
|
283 |
content = self.appli.need_login_content(req) |
|
284 |
return http.Response(code, req.headers_out, content) |
|
285 |
||
286 |
from twisted.internet import defer |
|
287 |
from twisted.web2 import fileupload |
|
288 |
||
289 |
# XXX set max file size to 100Mo: put max upload size in the configuration |
|
290 |
# 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
|
291 |
resource.PostableResource.maxSize = 100*1024*1024 |
0 | 292 |
def parsePOSTData(request, maxMem=100*1024, maxFields=1024, |
293 |
maxSize=100*1024*1024): |
|
294 |
if request.stream.length == 0: |
|
295 |
return defer.succeed(None) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
296 |
|
0 | 297 |
ctype = request.headers.getHeader('content-type') |
298 |
||
299 |
if ctype is None: |
|
300 |
return defer.succeed(None) |
|
301 |
||
302 |
def updateArgs(data): |
|
303 |
args = data |
|
304 |
request.args.update(args) |
|
305 |
||
306 |
def updateArgsAndFiles(data): |
|
307 |
args, files = data |
|
308 |
request.args.update(args) |
|
309 |
request.files.update(files) |
|
310 |
||
311 |
def error(f): |
|
312 |
f.trap(fileupload.MimeFormatError) |
|
313 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
1420
25c13e5b12bd
stop complaining about empty response, remove trailing spaces
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
314 |
|
0 | 315 |
if ctype.mediaType == 'application' and ctype.mediaSubtype == 'x-www-form-urlencoded': |
316 |
d = fileupload.parse_urlencoded(request.stream, keep_blank_values=True) |
|
317 |
d.addCallbacks(updateArgs, error) |
|
318 |
return d |
|
319 |
elif ctype.mediaType == 'multipart' and ctype.mediaSubtype == 'form-data': |
|
320 |
boundary = ctype.params.get('boundary') |
|
321 |
if boundary is None: |
|
322 |
return defer.fail(http.HTTPError( |
|
323 |
http.StatusResponse(responsecode.BAD_REQUEST, |
|
324 |
"Boundary not specified in Content-Type."))) |
|
325 |
d = fileupload.parseMultipartFormData(request.stream, boundary, |
|
326 |
maxMem, maxFields, maxSize) |
|
327 |
d.addCallbacks(updateArgsAndFiles, error) |
|
328 |
return d |
|
329 |
else: |
|
330 |
raise http.HTTPError(responsecode.BAD_REQUEST) |
|
331 |
||
332 |
server.parsePOSTData = parsePOSTData |
|
333 |
||
334 |
||
335 |
from logging import getLogger |
|
336 |
from cubicweb import set_log_methods |
|
337 |
set_log_methods(CubicWebRootResource, getLogger('cubicweb.twisted')) |
|
338 |
||
339 |
||
340 |
||
341 |
def _gc_debug(): |
|
342 |
import gc |
|
343 |
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
|
344 |
from cubicweb.appobject import AppObject |
0 | 345 |
gc.collect() |
346 |
count = 0 |
|
347 |
acount = 0 |
|
348 |
ocount = {} |
|
349 |
for obj in gc.get_objects(): |
|
350 |
if isinstance(obj, CubicWebTwistedRequestAdapter): |
|
351 |
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
|
352 |
elif isinstance(obj, AppObject): |
0 | 353 |
acount += 1 |
354 |
else: |
|
355 |
try: |
|
1132 | 356 |
ocount[obj.__class__] += 1 |
0 | 357 |
except KeyError: |
358 |
ocount[obj.__class__] = 1 |
|
359 |
except AttributeError: |
|
360 |
pass |
|
361 |
print 'IN MEM REQUESTS', count |
|
362 |
print 'IN MEM APPOBJECTS', acount |
|
363 |
ocount = sorted(ocount.items(), key=lambda x: x[1], reverse=True)[:20] |
|
364 |
pprint(ocount) |
|
365 |
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
|
366 |
|
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
|
367 |
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
|
368 |
# 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
|
369 |
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
|
370 |
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
|
371 |
# 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
|
372 |
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
|
373 |
reactor.listenTCP(port, channel.HTTPFactory(website)) |
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
|
374 |
logger = getLogger('cubicweb.twisted') |
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
|
375 |
if not debug: |
4219
87203a0a3a81
do not attempt to daemonize under windows
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4212
diff
changeset
|
376 |
if sys.platform == 'win32': |
4221
da84ca26896d
raising ConfigurationError is cleaner; remove some unused imports
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4219
diff
changeset
|
377 |
raise ConfigurationError("Under windows, you must use the service management " |
da84ca26896d
raising ConfigurationError is cleaner; remove some unused imports
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4219
diff
changeset
|
378 |
"commands (e.g : 'net start my_instance)'") |
3558
0e478957a9d4
smallest possible change to fix #472806
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3502
diff
changeset
|
379 |
print 'instance starting in the background' |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
380 |
if daemonize(): |
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
381 |
return # child process |
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
|
382 |
if config['pid-file']: |
2711
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
383 |
# ensure the directory where the pid-file should be set exists (for |
3791
62d6ab877694
put back url info started at the end of initialisations
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3641
diff
changeset
|
384 |
# 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
|
385 |
piddir = os.path.dirname(config['pid-file']) |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
386 |
if not os.path.exists(piddir): |
7aee3bd7a704
ensure runtime dir exists
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2708
diff
changeset
|
387 |
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
|
388 |
file(config['pid-file'], 'w').write(str(os.getpid())) |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
389 |
root_resource.init_publisher() # before changing uid |
3193
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
390 |
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
|
391 |
try: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
392 |
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
|
393 |
except ValueError: |
c1a8456cb5f9
should change process'user once pid file has been written
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3181
diff
changeset
|
394 |
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
|
395 |
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
|
396 |
os.setuid(uid) |
3606
8326aceecb46
fix startup as a daemon
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3558
diff
changeset
|
397 |
root_resource.start_service() |
3791
62d6ab877694
put back url info started at the end of initialisations
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3641
diff
changeset
|
398 |
logger.info('instance started on %s', root_resource.base_url) |
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
|
399 |
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
|
400 |
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
|
401 |
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
|
402 |
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
|
403 |
reactor.run() |