~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/apps/transport.py

  • Committer: Michael Hudson-Doyle
  • Date: 2012-01-08 22:04:51 UTC
  • mto: This revision was merged to the branch mainline in revision 464.
  • Revision ID: michael.hudson@linaro.org-20120108220451-kepgk6pfh59cze8a
this should fix the bug, but i cannot reproduce it locally

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2011 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
#
1
17
"""Serve branches at urls that mimic a transport's file system layout."""
2
18
 
 
19
import threading
 
20
 
3
21
from bzrlib import branch, errors, lru_cache, urlutils
 
22
from bzrlib.config import LocationConfig
 
23
from bzrlib.smart import request
 
24
from bzrlib.transport import get_transport
 
25
from bzrlib.transport.http import wsgi
4
26
 
5
27
from paste.request import path_info_pop
6
28
from paste import httpexceptions
7
29
from paste import urlparser
8
30
 
 
31
from loggerhead import util
9
32
from loggerhead.apps.branch import BranchWSGIApp
10
 
from loggerhead.apps import favicon_app, static_app
11
 
from loggerhead.config import LoggerheadConfig
 
33
from loggerhead.apps import favicon_app, robots_app, static_app
12
34
from loggerhead.controllers.directory_ui import DirectoryUI
13
35
 
 
36
# TODO: Use bzrlib.ui.bool_from_string(), added in bzr 1.18
 
37
_bools = {
 
38
    'yes': True, 'no': False,
 
39
    'on': True, 'off': False,
 
40
    '1': True, '0': False,
 
41
    'true': True, 'false': False,
 
42
    }
14
43
 
15
44
class BranchesFromTransportServer(object):
16
45
 
28
57
            name = self.name
29
58
            is_root = False
30
59
        branch_app = BranchWSGIApp(
31
 
            branch, name,
 
60
            branch,
 
61
            name,
32
62
            {'cachepath': self._config.SQL_DIR},
33
 
            self.root.graph_cache, is_root=is_root,
34
 
            use_cdn=self._config.get_option('use_cdn'))
 
63
            self.root.graph_cache,
 
64
            is_root=is_root,
 
65
            use_cdn=self._config.get_option('use_cdn'),
 
66
            )
35
67
        return branch_app.app
36
68
 
37
69
    def app_for_non_branch(self, environ):
38
70
        segment = path_info_pop(environ)
39
71
        if segment is None:
40
 
            raise httpexceptions.HTTPMovedPermanently(
41
 
                environ['SCRIPT_NAME'] + '/')
 
72
            raise httpexceptions.HTTPMovedPermanently.relative_redirect(
 
73
                environ['SCRIPT_NAME'] + '/', environ)
42
74
        elif segment == '':
43
75
            if self.name:
44
76
                name = self.name
45
77
            else:
46
78
                name = '/'
47
 
            return DirectoryUI(environ['loggerhead.static.url'],
48
 
                               self.transport,
49
 
                               name)
 
79
            return DirectoryUI(
 
80
                environ['loggerhead.static.url'], self.transport, name)
50
81
        else:
51
82
            new_transport = self.transport.clone(segment)
52
83
            if self.name:
55
86
                new_name = '/' + segment
56
87
            return BranchesFromTransportServer(new_transport, self.root, new_name)
57
88
 
 
89
    def app_for_bazaar_data(self, relpath):
 
90
        if relpath == '/.bzr/smart':
 
91
            root_transport = get_transport_for_thread(self.root.base)
 
92
            wsgi_app = wsgi.SmartWSGIApp(root_transport)
 
93
            return wsgi.RelpathSetter(wsgi_app, '', 'loggerhead.path_info')
 
94
        else:
 
95
            # TODO: Use something here that uses the transport API
 
96
            # rather than relying on the local filesystem API.
 
97
            base = self.transport.base
 
98
            try:
 
99
                path = util.local_path_from_url(base)
 
100
            except errors.InvalidURL:
 
101
                raise httpexceptions.HTTPNotFound()
 
102
            else:
 
103
                return urlparser.make_static(None, path)
 
104
 
 
105
    def check_serveable(self, config):
 
106
        value = config.get_user_option('http_serve')
 
107
        if value is None:
 
108
            return
 
109
        elif not _bools.get(value.lower(), True):
 
110
            raise httpexceptions.HTTPNotFound()
 
111
 
58
112
    def __call__(self, environ, start_response):
 
113
        path = environ['PATH_INFO']
59
114
        try:
60
115
            b = branch.Branch.open_from_transport(self.transport)
61
116
        except errors.NotBranchError:
 
117
            if path.startswith('/.bzr'):
 
118
                self.check_serveable(LocationConfig(self.transport.base))
 
119
                return self.app_for_bazaar_data(path)(environ, start_response)
62
120
            if not self.transport.listable() or not self.transport.has('.'):
63
121
                raise httpexceptions.HTTPNotFound()
64
122
            return self.app_for_non_branch(environ)(environ, start_response)
65
123
        else:
66
 
            return self.app_for_branch(b)(environ, start_response)
 
124
            self.check_serveable(b.get_config())
 
125
            if path.startswith('/.bzr'):
 
126
                return self.app_for_bazaar_data(path)(environ, start_response)
 
127
            else:
 
128
                return self.app_for_branch(b)(environ, start_response)
 
129
 
 
130
 
 
131
_transport_store = threading.local()
 
132
 
 
133
def get_transport_for_thread(base):
 
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
    thread_transports[base] = transport
 
141
    return transport
67
142
 
68
143
 
69
144
class BranchesFromTransportRoot(object):
70
145
 
71
 
    def __init__(self, transport, config):
 
146
    def __init__(self, base, config):
72
147
        self.graph_cache = lru_cache.LRUCache(10)
73
 
        self.transport = transport
 
148
        self.base = base
74
149
        self._config = config
75
150
 
76
151
    def __call__(self, environ, start_response):
77
152
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
 
153
        environ['loggerhead.path_info'] = environ['PATH_INFO']
78
154
        if environ['PATH_INFO'].startswith('/static/'):
79
155
            segment = path_info_pop(environ)
80
156
            assert segment == 'static'
81
157
            return static_app(environ, start_response)
82
158
        elif environ['PATH_INFO'] == '/favicon.ico':
83
159
            return favicon_app(environ, start_response)
84
 
        elif '/.bzr/' in environ['PATH_INFO']:
85
 
            app = urlparser.make_static(None, self.transport)
86
 
            return app(environ, start_response)
 
160
        elif environ['PATH_INFO'] == '/robots.txt':
 
161
            return robots_app(environ, start_response)
87
162
        else:
 
163
            transport = get_transport_for_thread(self.base)
88
164
            return BranchesFromTransportServer(
89
 
                self.transport, self)(environ, start_response)
 
165
                transport, self)(environ, start_response)
90
166
 
91
167
 
92
168
class UserBranchesFromTransportRoot(object):
93
169
 
94
 
    def __init__(self, transport, config):
 
170
    def __init__(self, base, config):
95
171
        self.graph_cache = lru_cache.LRUCache(10)
96
 
        self.transport = transport
 
172
        self.base = base
97
173
        self._config = config
98
174
        self.trunk_dir = config.get_option('trunk_dir')
99
175
 
100
176
    def __call__(self, environ, start_response):
101
177
        environ['loggerhead.static.url'] = environ['SCRIPT_NAME']
 
178
        environ['loggerhead.path_info'] = environ['PATH_INFO']
102
179
        path_info = environ['PATH_INFO']
103
180
        if path_info.startswith('/static/'):
104
181
            segment = path_info_pop(environ)
106
183
            return static_app(environ, start_response)
107
184
        elif path_info == '/favicon.ico':
108
185
            return favicon_app(environ, start_response)
 
186
        elif environ['PATH_INFO'] == '/robots.txt':
 
187
            return robots_app(environ, start_response)
109
188
        else:
 
189
            transport = get_transport_for_thread(self.base)
110
190
            # segments starting with ~ are user branches
111
191
            if path_info.startswith('/~'):
112
192
                segment = path_info_pop(environ)
113
 
                new_transport = self.transport.clone(segment[1:])
114
193
                return BranchesFromTransportServer(
115
 
                    new_transport, self, segment)(environ, start_response)
 
194
                    transport.clone(segment[1:]), self, segment)(
 
195
                    environ, start_response)
116
196
            else:
117
 
                new_transport = self.transport.clone(self.trunk_dir)
118
197
                return BranchesFromTransportServer(
119
 
                    new_transport, self)(environ, start_response)
 
198
                    transport.clone(self.trunk_dir), self)(
 
199
                    environ, start_response)