File: httpserver.py

package info (click to toggle)
xen-3.0 3.0.3-0-2
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 31,772 kB
  • ctags: 70,362
  • sloc: ansic: 417,153; python: 28,855; asm: 23,892; sh: 5,157; makefile: 4,830; objc: 613; perl: 372; xml: 351
file content (347 lines) | stat: -rw-r--r-- 10,211 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#============================================================================
# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
# Copyright (C) 2006 XenSource Ltd.
#============================================================================

import threading

import string
import socket
import types
from urllib import quote, unquote
import os
import os.path
import fcntl

from xen.xend import sxp
from xen.xend.Args import ArgError
from xen.xend.XendError import XendError

import http
import unix
from resource import Resource, ErrorPage
from SrvDir import SrvDir

class ThreadRequest:
    """A request to complete processing using a thread.
    """
    
    def __init__(self, processor, req, fn, args, kwds):
        self.processor = processor
        self.req = req
        self.fn = fn
        self.args = args
        self.kwds = kwds
        
    def run(self):
        self.processor.setInThread()
        thread = threading.Thread(target=self.main)
        thread.setDaemon(True)
        thread.start()

    def call(self):
        try:
            self.fn(*self.args, **self.kwds)
        except SystemExit:
            raise
        except Exception, ex:
            self.req.resultErr(ex)
        self.req.finish()

    def main(self):
        self.call()
        self.processor.process()
       

class RequestProcessor:
    """Processor for requests on a connection to an http server.
    Requests are executed synchonously unless they ask for a thread by returning
    a ThreadRequest.
    """

    done = False

    inThread = False

    def __init__(self, server, sock, addr):
        self.server = server
        self.sock = sock
        self.srd = sock.makefile('rb')
        self.srw = sock.makefile('wb')
        self.srvaddr = server.getServerAddr()

    def isInThread(self):
        return self.inThread

    def setInThread(self):
        self.inThread = True

    def getServer(self):
        return self.server

    def getRequest(self):
        return HttpServerRequest(self, self.srvaddr, self.srd, self.srw)

    def close(self):
        try:
            self.sock.close()
        except:
            pass

    def finish(self):
        self.done = True
        self.close()

    def process(self):
        while not self.done:
            req = self.getRequest()
            res = req.process()
            if isinstance(res, ThreadRequest):
                if self.isInThread():
                    res.call()
                else:
                    res.run()
                    break
            else:
                req.finish()
                                        
class HttpServerRequest(http.HttpRequest):
    """A single request to an http server.
    """

    def __init__(self, processor, addr, srd, srw):
        self.processor = processor
        self.prepath = ''
        http.HttpRequest.__init__(self, addr, srd, srw)

    def getServer(self):
        return self.processor.getServer()

    def process(self):
        """Process the request. If the return value is a ThreadRequest
        it is evaluated in a thread.
        """
        try:
            self.prepath = []
            self.postpath = map(unquote, string.split(self.request_path[1:], '/'))
            resource = self.getResource()
            return self.render(resource)
        except SystemExit:
            raise
        except Exception, ex:
            self.processError(ex)

    def processError(self, ex):
        import traceback; traceback.print_exc()
        self.sendError(http.INTERNAL_SERVER_ERROR, msg=str(ex))
        self.setCloseConnection('close')

    def finish(self):
        self.sendResponse()
        if self.close_connection:
            self.processor.finish()

    def prePathURL(self):
        url_host = self.getRequestHostname()
        port = self.getPort()
        if self.isSecure():
            url_proto = "https"
            default_port = 443
        else:
            url_proto = "http"
            default_port = 80
        if port != default_port:
            url_host += (':%d' % port)
        url_path = quote(string.join(self.prepath, '/'))
        return ('%s://%s/%s' % (url_proto, url_host, url_path))

    def getResource(self):
        return self.getServer().getResource(self)

    def render(self, resource):
        val = None
        if resource is None:
            self.sendError(http.NOT_FOUND)
        else:
            try:
                while True:
                    val = resource.render(self)
                    if not isinstance(val, Resource):
                        break
                val = self.result(val)
            except SystemExit:
                raise
            except Exception, ex:
                self.resultErr(ex)
        return val

    def threadRequest(self, _fn, *_args, **_kwds):
        """Create a request to finish request processing in a thread.
        Use this to create a ThreadRequest to return from rendering a
        resource if you need a thread to complete processing.
        """
        return ThreadRequest(self.processor, self, _fn, _args, _kwds)
            
    def result(self, val):
        if isinstance(val, Exception):
            return self.resultErr(val)
        else:
            return self.resultVal(val)

    def resultVal(self, val):
        """Callback to complete the request.

        @param val: the value
        """
        if val is None:
            return val
        elif isinstance(val, ThreadRequest):
            return val
        elif self.useSxp():
            self.setHeader("Content-Type", sxp.mime_type)
            sxp.show(val, out=self)
        else:
            self.write('<html><head></head><body>')
            self.printPath()
            if isinstance(val, types.ListType):
                self.write('<code><pre>')
                PrettyPrint.prettyprint(val, out=self)
                self.write('</pre></code>')
            else:
                self.write(str(val))
            self.write('</body></html>')
        return None

    def resultErr(self, err):
        """Error callback to complete a request.

        @param err: the error
        """
        if not isinstance(err, (ArgError, sxp.ParseError, XendError)):
            raise
        #log.exception("op=%s: %s", op, str(err))
        if self.useSxp():
            self.setHeader("Content-Type", sxp.mime_type)
            sxp.show(['xend.err', str(err)], out=self)
        else:
            self.setHeader("Content-Type", "text/plain")
            self.write('Error ')
            self.write(': ')
            self.write(str(err))
        return None

    def useSxp(self):
        """Determine whether to send an SXP response to a request.
        Uses SXP if there is no User-Agent, no Accept, or application/sxp is in Accept.

        returns 1 for SXP, 0 otherwise
        """
        ok = 0
        user_agent = self.getHeader('User-Agent')
        accept = self.getHeader('Accept')
        if (not user_agent) or (not accept) or (accept.find(sxp.mime_type) >= 0):
            ok = 1
        return ok

    def printPath(self):
        pathlist = [x for x in self.prepath if x != '' ]
        s = "/"
        self.write('<h1><a href="/">/</a>')
        for x in pathlist:
            s += x + "/"
            self.write(' <a href="%s">%s</a>/' % (s, x))
        self.write("</h1>")
        
class HttpServer:

    backlog = 5

    closed = False

    def __init__(self, root, interface, port=8080):
        self.root = root
        self.interface = interface
        self.port = port
        # ready indicates when we are ready to begin accept connections
        # it should be set after a successful bind
        self.ready = False

    def run(self):
        self.bind()
        self.listen()
        self.ready = True

        while not self.closed:
            (sock, addr) = self.accept()
            self.processRequest(sock, addr)


    def stop(self):
        self.close()


    def bind(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        flags = fcntl.fcntl(self.socket.fileno(), fcntl.F_GETFD)
        flags |= fcntl.FD_CLOEXEC
        fcntl.fcntl(self.socket.fileno(), fcntl.F_SETFD, flags)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((self.interface, self.port))

    def listen(self):
        self.socket.listen(self.backlog)

    def accept(self):
        return self.socket.accept()

    def close(self):
        self.closed = True
        try:
            self.socket.close()
        except:
            pass

    def processRequest(self, sock, addr):
        try:
            rp = RequestProcessor(self, sock, addr)
            rp.process()
        except SystemExit:
            raise
        except Exception, ex:
            print 'HttpServer>processRequest> exception: ', ex
            try:
                sock.close()
            except:
                pass

    def getServerAddr(self):
        return (socket.gethostname(), self.port)

    def getResource(self, req):
        return self.root.getRequestResource(req)


class UnixHttpServer(HttpServer):

    def __init__(self, root, path):
        HttpServer.__init__(self, root, 'localhost')
        self.path = path
        
    def bind(self):
        self.socket = unix.bind(self.path)
        flags = fcntl.fcntl(self.socket.fileno(), fcntl.F_GETFD)
        flags |= fcntl.FD_CLOEXEC
        fcntl.fcntl(self.socket.fileno(), fcntl.F_SETFD, flags)