- change default config file
[plcapi.git] / Server.py
1 #!/usr/bin/python
2 #
3 # Simple standalone HTTP server for testing PLCAPI
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: Server.py,v 1.1 2006/09/06 15:33:59 mlhuang Exp $
9 #
10
11 import os
12 import sys
13 import getopt
14 import traceback
15 import BaseHTTPServer
16
17 from PLC.API import PLCAPI
18
19 class PLCAPIRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
20     """
21     Simple standalone HTTP request handler for testing PLCAPI.
22     """
23
24     def do_POST(self):
25         try:
26             # Read request
27             request = self.rfile.read(int(self.headers["Content-length"]))
28
29             # Handle request
30             response = self.server.api.handle(self.client_address, request)
31
32             # Write response
33             self.send_response(200)
34             self.wfile.write(response)
35             self.wfile.flush()
36
37             self.connection.shutdown(1)
38
39         except Exception, e:
40             # Log error
41             sys.stderr.write(traceback.format_exc())
42             sys.stderr.flush()
43
44     def do_GET(self):
45         self.send_response(200)
46         self.send_header("Content-type", 'text/html')
47         self.end_headers()
48         self.wfile.write("""
49 <html><head>
50 <title>PLCAPI XML-RPC/SOAP Interface</title>
51 </head><body>
52 <h1>PLCAPI XML-RPC/SOAP Interface</h1>
53 <p>Please use XML-RPC or SOAP to access the PLCAPI.</p>
54 </body></html>
55 """)        
56         
57 class PLCAPIServer(BaseHTTPServer.HTTPServer):
58     """
59     Simple standalone HTTP server for testing PLCAPI.
60     """
61
62     def __init__(self, addr, config):
63         self.api = PLCAPI(config)
64         self.allow_reuse_address = 1
65         BaseHTTPServer.HTTPServer.__init__(self, addr, PLCAPIRequestHandler)
66
67 # Defaults
68 addr = "0.0.0.0"
69 port = 8000
70 config = "/etc/planetlab/plc_config"
71
72 def usage():
73     print "Usage: %s [OPTION]..." % sys.argv[0]
74     print "Options:"
75     print "     -p PORT, --port=PORT    TCP port number to listen on (default: %d)" % port
76     print "     -f FILE, --config=FILE  PLC configuration file (default: %s)" % config
77     print "     -h, --help              This message"
78     sys.exit(1)
79
80 # Get options
81 try:
82     (opts, argv) = getopt.getopt(sys.argv[1:], "p:f:h", ["port=", "config=", "help"])
83 except getopt.GetoptError, err:
84     print "Error: " + err.msg
85     usage()
86
87 for (opt, optval) in opts:
88     if opt == "-p" or opt == "--port":
89         try:
90             port = int(optval)
91         except ValueError:
92             usage()
93     elif opt == "-f" or opt == "--config":
94         config = optval
95     elif opt == "-h" or opt == "--help":
96         usage()
97
98 # Start server
99 PLCAPIServer((addr, port), config).serve_forever()