e1ab86dc73bf17d593f6f42448e6cf838238f989
[sfa.git] / sfa / server / SfaAggregateModPython.py
1 #
2 # Apache mod_python interface
3 #
4 # Aaron Klingaman <alk@absarokasoft.com>
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 #
7 # Copyright (C) 2004-2006 The Trustees of Princeton University
8 #
9
10 import sys
11 import traceback
12 import xmlrpclib
13 from mod_python import apache
14
15 from sfa.plc.api import SfaAPI
16 from sfa.util.debug import log
17
18 api = SfaAPI(interface='aggregate')
19
20 class unbuffered:
21     """\r
22     Write to /var/log/httpd/error_log. See\r
23 \r
24     http://www.modpython.org/FAQ/faqw.py?req=edit&file=faq02.003.htp\r
25     """\r
26 \r
27     def write(self, data):\r
28         sys.stderr.write(data)\r
29         sys.stderr.flush()\r
30 \r
31 #log = unbuffered()
32
33 def handler(req):
34     try:
35         if req.method != "POST":
36             req.content_type = "text/html"
37             req.send_http_header()
38             req.write("""
39 <html><head>
40 <title>SFA Aggregate API XML-RPC/SOAP Interface</title>
41 </head><body>
42 <h1>SFA Aggregate API XML-RPC/SOAP Interface</h1>
43 <p>Please use XML-RPC or SOAP to access the SFA API.</p>
44 </body></html>
45 """)
46             return apache.OK
47
48         # Read request
49         request = req.read(int(req.headers_in['content-length']))
50
51         # mod_python < 3.2: The IP address portion of remote_addr is
52         # incorrect (always 0.0.0.0) when IPv6 is enabled.
53         # http://issues.apache.org/jira/browse/MODPYTHON-64?page=all
54         (remote_ip, remote_port) = req.connection.remote_addr
55         remote_addr = (req.connection.remote_ip, remote_port)
56
57         # Handle request
58         response = api.handle(remote_addr, request)
59
60         # Write response
61         req.content_type = "text/xml; charset=" + api.encoding
62         req.send_http_header()
63         req.write(response)
64
65         return apache.OK
66
67     except Exception, err:
68         # Log error in /var/log/httpd/(ssl_)?error_log
69         print >> log, err, traceback.format_exc()
70         return apache.HTTP_INTERNAL_SERVER_ERROR