~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to wsgitest.py

  • Committer: Michael Hudson
  • Date: 2008-06-16 11:25:25 UTC
  • mfrom: (160 trunk)
  • mto: This revision was merged to the branch mainline in revision 164.
  • Revision ID: michael.hudson@canonical.com-20080616112525-t1vsjh4s3knwpou3
merge trunk, rather brutally resolving conflicts

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009 Canonical Ltd.
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
#
17
 
"""Serve branches at urls that mimic a transport's file system layout."""
18
 
 
19
 
import threading
20
 
 
21
 
from bzrlib import branch, errors, lru_cache, urlutils
22
 
from bzrlib.config import LocationConfig
23
 
from bzrlib.transport import get_transport
24
 
from bzrlib.transport.http import wsgi
25
 
 
 
1
import cgi, os, tempfile
 
2
from bzrlib import branch, errors
 
3
from loggerhead.history import History
 
4
from loggerhead.wsgiapp import BranchWSGIApp, static_app
26
5
from paste.request import path_info_pop
 
6
from paste.wsgiwrappers import WSGIRequest, WSGIResponse
27
7
from paste import httpexceptions
28
 
from paste import urlparser
29
 
 
30
 
from loggerhead.apps.branch import BranchWSGIApp
31
 
from loggerhead.apps import favicon_app, static_app
32
 
from loggerhead.controllers.directory_ui import DirectoryUI
33
 
 
34
 
_bools = {
35
 
    'yes': True, 'no': False,
36
 
    'on': True, 'off': False,
37
 
    '1': True, '0': False,
38
 
    'true': True, 'false': False,
39
 
    }
40
 
 
41
 
class BranchesFromTransportServer(object):
42
 
 
43
 
    def __init__(self, transport, root, name=None):
44
 
        self.transport = transport
 
8
from paste import httpserver
 
9
from paste.httpexceptions import make_middleware
 
10
from paste.translogger import make_filter
 
11
from loggerhead.changecache import FileChangeCache
 
12
 
 
13
 
 
14
sql_dir = tempfile.mkdtemp()
 
15
 
 
16
class BranchesFromFileSystemServer(object):
 
17
    def __init__(self, folder, root):
 
18
        self.folder = folder
45
19
        self.root = root
46
 
        self.name = name
47
 
        self._config = root._config
48
 
 
49
 
    def app_for_branch(self, branch):
50
 
        if not self.name:
51
 
            name = branch._get_nick(local=True)
52
 
            is_root = True
53
 
        else:
54
 
            name = self.name
55
 
            is_root = False
56
 
        branch_app = BranchWSGIApp(
57
 
            branch, name,
58
 
            {'cachepath': self._config.SQL_DIR},
59
 
            self.root.graph_cache, is_root=is_root,
60
 
            use_cdn=self._config.get_option('use_cdn'))
61
 
        return branch_app.app
62
 
 
63
 
    def app_for_non_branch(self, environ):
 
20
 
 
21
    def __call__(self, environ, start_response):
64
22
        segment = path_info_pop(environ)
65
23
        if segment is None:
66
 
            raise httpexceptions.HTTPMovedPermanently(
67
 
                environ['SCRIPT_NAME'] + '/')
68
 
        elif segment == '':
69
 
            if self.name:
70
 
                name = self.name
71
 
            else:
72
 
                name = '/'
73
 
            return DirectoryUI(
74
 
                environ['loggerhead.static.url'], self.transport, name)
75
 
        else:
76
 
            new_transport = self.transport.clone(segment)
77
 
            if self.name:
78
 
                new_name = urlutils.join(self.name, segment)
79
 
            else:
80
 
                new_name = '/' + segment
81
 
            return BranchesFromTransportServer(new_transport, self.root, new_name)
82
 
 
83
 
    def app_for_bazaar_data(self, relpath):
84
 
        if relpath == '/.bzr/smart':
85
 
            wsgi_app = wsgi.SmartWSGIApp(self.transport)
86
 
            return wsgi.RelpathSetter(wsgi_app, '', 'PATH_INFO')
87
 
        else:
88
 
            # TODO: Use something here that uses the transport API
89
 
            # rather than relying on the local filesystem API.
90
 
            base = self.transport.base
91
 
            readonly_prefix = 'readonly+'
92
 
            if base.startswith(readonly_prefix):
93
 
                base = base[len(readonly_prefix):]
94
 
            try:
95
 
                path = urlutils.local_path_from_url(base)
96
 
            except errors.InvalidURL:
97
 
                raise httpexceptions.HTTPNotFound()
98
 
            else:
99
 
                return urlparser.make_static(None, path)
100
 
 
101
 
    def check_serveable(self, config):
102
 
        value = config.get_user_option('http_serve')
103
 
        if value is None:
104
 
            return
105
 
        elif not _bools.get(value.lower(), True):
 
24
            f = os.path.join(self.root.folder, self.folder)
 
25
            request = WSGIRequest(environ)
 
26
            response = WSGIResponse()
 
27
            listing = [d for d in os.listdir(f) if not d.startswith('.')]
 
28
            response.headers['Content-Type'] = 'text/html'
 
29
            print >> response, '<html><body>'
 
30
            for d in sorted(listing):
 
31
                d = cgi.escape(d)
 
32
                print >> response, '<li><a href="%s/">%s</a></li>' % (d, d)
 
33
            print >> response, '</body></html>'
 
34
            return response(environ, start_response)
 
35
        relpath = os.path.join(self.folder, segment)
 
36
        f = os.path.join(self.root.folder, relpath)
 
37
        if not os.path.isdir(f):
106
38
            raise httpexceptions.HTTPNotFound()
107
 
 
108
 
    def __call__(self, environ, start_response):
109
 
        path = environ['PATH_INFO']
 
39
        if f in self.root.cache:
 
40
            return self.root.cache[f](environ, start_response)
110
41
        try:
111
 
            b = branch.Branch.open_from_transport(self.transport)
 
42
            b = branch.Branch.open(f)
112
43
        except errors.NotBranchError:
113
 
            if path.startswith('/.bzr'):
114
 
                self.check_serveable(LocationConfig(self.transport.base))
115
 
                return self.app_for_bazaar_data(path)(environ, start_response)
116
 
            if not self.transport.listable() or not self.transport.has('.'):
117
 
                raise httpexceptions.HTTPNotFound()
118
 
            return self.app_for_non_branch(environ)(environ, start_response)
119
 
        else:
120
 
            self.check_serveable(b.get_config())
121
 
            if path.startswith('/.bzr'):
122
 
                return self.app_for_bazaar_data(path)(environ, start_response)
123
 
            else:
124
 
                return self.app_for_branch(b)(environ, start_response)
125
 
 
126
 
 
127
 
_transport_store = threading.local()
128
 
 
129
 
def get_transport_for_thread(base):
130
 
    """ """
131
 
    thread_transports = getattr(_transport_store, 'transports', None)
132
 
    if thread_transports is None:
133
 
        thread_transports = _transport_store.transports = {}
134
 
    if base in thread_transports:
135
 
        return thread_transports[base]
136
 
    transport = get_transport(base)
137
 
    return transport
138
 
 
139
 
 
140
 
class BranchesFromTransportRoot(object):
141
 
 
142
 
    def __init__(self, base, config):
143
 
        self.graph_cache = lru_cache.LRUCache(10)
144
 
        self.base = base
145
 
        self._config = config
146
 
 
147
 
    def __call__(self, environ, start_response):
148
 
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
149
 
        if environ['PATH_INFO'].startswith('/static/'):
150
 
            segment = path_info_pop(environ)
151
 
            assert segment == 'static'
152
 
            return static_app(environ, start_response)
153
 
        elif environ['PATH_INFO'] == '/favicon.ico':
154
 
            return favicon_app(environ, start_response)
155
 
        else:
156
 
            transport = get_transport_for_thread(self.base)
157
 
            return BranchesFromTransportServer(
158
 
                transport, self)(environ, start_response)
159
 
 
160
 
 
161
 
class UserBranchesFromTransportRoot(object):
162
 
 
163
 
    def __init__(self, base, config):
164
 
        self.graph_cache = lru_cache.LRUCache(10)
165
 
        self.base = base
166
 
        self._config = config
167
 
        self.trunk_dir = config.get_option('trunk_dir')
168
 
 
169
 
    def __call__(self, environ, start_response):
170
 
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
171
 
        path_info = environ['PATH_INFO']
172
 
        if path_info.startswith('/static/'):
173
 
            segment = path_info_pop(environ)
174
 
            assert segment == 'static'
175
 
            return static_app(environ, start_response)
176
 
        elif path_info == '/favicon.ico':
177
 
            return favicon_app(environ, start_response)
178
 
        else:
179
 
            transport = get_transport_for_thread(self.base)
180
 
            # segments starting with ~ are user branches
181
 
            if path_info.startswith('/~'):
182
 
                segment = path_info_pop(environ)
183
 
                return BranchesFromTransportServer(
184
 
                    transport.clone(segment[1:]), self, segment)(
185
 
                    environ, start_response)
186
 
            else:
187
 
                return BranchesFromTransportServer(
188
 
                    transport.clone(self.trunk_dir), self)(
189
 
                    environ, start_response)
 
44
            return BranchesFromFileSystemServer(relpath, self.root)(environ, start_response)
 
45
        else:
 
46
            b.lock_read()
 
47
            try:
 
48
                _history = History.from_branch(b)
 
49
                _history.use_file_cache(FileChangeCache(_history, sql_dir))
 
50
                h = BranchWSGIApp(_history, relpath).app
 
51
                self.root.cache[f] = h
 
52
                return h(environ, start_response)
 
53
            finally:
 
54
                b.unlock()
 
55
 
 
56
class BranchesFromFileSystemRoot(object):
 
57
    def __init__(self, folder):
 
58
        self.cache = {}
 
59
        self.folder = folder
 
60
    def __call__(self, environ, start_response):
 
61
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
 
62
        segment = path_info_pop(environ)
 
63
        if segment == 'static':
 
64
            return static_app(environ, start_response)
 
65
        else:
 
66
            return BranchesFromFileSystemServer(
 
67
                segment, self)(environ, start_response)
 
68
 
 
69
app = BranchesFromFileSystemRoot('.')
 
70
 
 
71
app = app
 
72
app = make_middleware(app)
 
73
app = make_filter(app, None)
 
74
 
 
75
 
 
76
httpserver.serve(app, host='127.0.0.1', port='9876')
 
77