~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/apps/transport.py

Merge my old pep8 branch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import cgi
2
 
import os
3
 
import tempfile
4
 
 
5
 
from bzrlib import branch, errors
 
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
6
25
 
7
26
from paste.request import path_info_pop
8
 
from paste.wsgiwrappers import WSGIRequest, WSGIResponse
9
27
from paste import httpexceptions
 
28
from paste import urlparser
10
29
 
11
30
from loggerhead.apps.branch import BranchWSGIApp
12
31
from loggerhead.apps import favicon_app, static_app
13
 
 
14
 
 
15
 
sql_dir = tempfile.mkdtemp()
16
 
 
17
 
class BranchesFromFileSystemServer(object):
18
 
    def __init__(self, folder, root):
19
 
        self.folder = folder
 
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
20
45
        self.root = root
21
 
 
22
 
    def directory_listing(self, path, environ, start_response):
23
 
        request = WSGIRequest(environ)
24
 
        response = WSGIResponse()
25
 
        listing = [d for d in os.listdir(path) if not d.startswith('.')]
26
 
        response.headers['Content-Type'] = 'text/html'
27
 
        print >> response, '<html><body>'
28
 
        for d in sorted(listing):
29
 
            if os.path.isdir(os.path.join(path, d)):
30
 
                d = cgi.escape(d)
31
 
                print >> response, '<li><a href="%s/">%s</a></li>' % (d, d)
32
 
        print >> response, '</body></html>'
33
 
        return response(environ, start_response)
34
 
 
35
 
    def app_for_branch(self, b, path):
36
 
        if not self.folder:
37
 
            name = os.path.basename(os.path.abspath(path))
38
 
        else:
39
 
            name = self.folder
40
 
        h = BranchWSGIApp(path, name, {'cachepath': sql_dir})
41
 
        self.root.cache[path] = h
42
 
        return h.app
43
 
 
44
 
    def __call__(self, environ, start_response):
45
 
        path = os.path.join(self.root.folder, self.folder)
46
 
        if not os.path.isdir(path):
 
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,
 
58
            name,
 
59
            {'cachepath': self._config.SQL_DIR},
 
60
            self.root.graph_cache,
 
61
            is_root=is_root,
 
62
            use_cdn=self._config.get_option('use_cdn'),
 
63
            )
 
64
        return branch_app.app
 
65
 
 
66
    def app_for_non_branch(self, environ):
 
67
        segment = path_info_pop(environ)
 
68
        if segment is None:
 
69
            raise httpexceptions.HTTPMovedPermanently(
 
70
                environ['SCRIPT_NAME'] + '/')
 
71
        elif segment == '':
 
72
            if self.name:
 
73
                name = self.name
 
74
            else:
 
75
                name = '/'
 
76
            return DirectoryUI(
 
77
                environ['loggerhead.static.url'], self.transport, name)
 
78
        else:
 
79
            new_transport = self.transport.clone(segment)
 
80
            if self.name:
 
81
                new_name = urlutils.join(self.name, segment)
 
82
            else:
 
83
                new_name = '/' + segment
 
84
            return BranchesFromTransportServer(new_transport, self.root, new_name)
 
85
 
 
86
    def app_for_bazaar_data(self, relpath):
 
87
        if relpath == '/.bzr/smart':
 
88
            wsgi_app = wsgi.SmartWSGIApp(self.transport)
 
89
            return wsgi.RelpathSetter(wsgi_app, '', 'PATH_INFO')
 
90
        else:
 
91
            # TODO: Use something here that uses the transport API
 
92
            # rather than relying on the local filesystem API.
 
93
            base = self.transport.base
 
94
            readonly_prefix = 'readonly+'
 
95
            if base.startswith(readonly_prefix):
 
96
                base = base[len(readonly_prefix):]
 
97
            try:
 
98
                path = urlutils.local_path_from_url(base)
 
99
            except errors.InvalidURL:
 
100
                raise httpexceptions.HTTPNotFound()
 
101
            else:
 
102
                return urlparser.make_static(None, path)
 
103
 
 
104
    def check_serveable(self, config):
 
105
        value = config.get_user_option('http_serve')
 
106
        if value is None:
 
107
            return
 
108
        elif not _bools.get(value.lower(), True):
47
109
            raise httpexceptions.HTTPNotFound()
48
 
        cached = self.root.cache.get(path)
49
 
        if cached is not None:
50
 
            return cached.app(environ, start_response)
 
110
 
 
111
    def __call__(self, environ, start_response):
 
112
        path = environ['PATH_INFO']
51
113
        try:
52
 
            b = branch.Branch.open(path)
 
114
            b = branch.Branch.open_from_transport(self.transport)
53
115
        except errors.NotBranchError:
54
 
            segment = path_info_pop(environ)
55
 
            if segment is None:
56
 
                raise httpexceptions.HTTPMovedPermanently(
57
 
                    environ['SCRIPT_NAME'] + '/')
58
 
            elif segment == '':
59
 
                return self.directory_listing(path, environ, start_response)
 
116
            if path.startswith('/.bzr'):
 
117
                self.check_serveable(LocationConfig(self.transport.base))
 
118
                return self.app_for_bazaar_data(path)(environ, start_response)
 
119
            if not self.transport.listable() or not self.transport.has('.'):
 
120
                raise httpexceptions.HTTPNotFound()
 
121
            return self.app_for_non_branch(environ)(environ, start_response)
 
122
        else:
 
123
            self.check_serveable(b.get_config())
 
124
            if path.startswith('/.bzr'):
 
125
                return self.app_for_bazaar_data(path)(environ, start_response)
60
126
            else:
61
 
                relpath = os.path.join(self.folder, segment)
62
 
                return BranchesFromFileSystemServer(relpath, self.root)(
63
 
                    environ, start_response)
64
 
        else:
65
 
            return self.app_for_branch(b, path)(environ, start_response)
66
 
 
67
 
 
68
 
class BranchesFromFileSystemRoot(object):
69
 
    def __init__(self, folder):
70
 
        self.cache = {}
71
 
        self.folder = folder
 
127
                return self.app_for_branch(b)(environ, start_response)
 
128
 
 
129
 
 
130
_transport_store = threading.local()
 
131
 
 
132
def get_transport_for_thread(base):
 
133
    """ """
 
134
    thread_transports = getattr(_transport_store, 'transports', None)
 
135
    if thread_transports is None:
 
136
        thread_transports = _transport_store.transports = {}
 
137
    if base in thread_transports:
 
138
        return thread_transports[base]
 
139
    transport = get_transport(base)
 
140
    return transport
 
141
 
 
142
 
 
143
class BranchesFromTransportRoot(object):
 
144
 
 
145
    def __init__(self, base, config):
 
146
        self.graph_cache = lru_cache.LRUCache(10)
 
147
        self.base = base
 
148
        self._config = config
 
149
 
72
150
    def __call__(self, environ, start_response):
73
151
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
74
152
        if environ['PATH_INFO'].startswith('/static/'):
78
156
        elif environ['PATH_INFO'] == '/favicon.ico':
79
157
            return favicon_app(environ, start_response)
80
158
        else:
81
 
            return BranchesFromFileSystemServer(
82
 
                '', self)(environ, start_response)
 
159
            transport = get_transport_for_thread(self.base)
 
160
            return BranchesFromTransportServer(
 
161
                transport, self)(environ, start_response)
 
162
 
 
163
 
 
164
class UserBranchesFromTransportRoot(object):
 
165
 
 
166
    def __init__(self, base, config):
 
167
        self.graph_cache = lru_cache.LRUCache(10)
 
168
        self.base = base
 
169
        self._config = config
 
170
        self.trunk_dir = config.get_option('trunk_dir')
 
171
 
 
172
    def __call__(self, environ, start_response):
 
173
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
 
174
        path_info = environ['PATH_INFO']
 
175
        if path_info.startswith('/static/'):
 
176
            segment = path_info_pop(environ)
 
177
            assert segment == 'static'
 
178
            return static_app(environ, start_response)
 
179
        elif path_info == '/favicon.ico':
 
180
            return favicon_app(environ, start_response)
 
181
        else:
 
182
            transport = get_transport_for_thread(self.base)
 
183
            # segments starting with ~ are user branches
 
184
            if path_info.startswith('/~'):
 
185
                segment = path_info_pop(environ)
 
186
                return BranchesFromTransportServer(
 
187
                    transport.clone(segment[1:]), self, segment)(
 
188
                    environ, start_response)
 
189
            else:
 
190
                return BranchesFromTransportServer(
 
191
                    transport.clone(self.trunk_dir), self)(
 
192
                    environ, start_response)