Refactoring in progress...
[nodemanager.git] / api.py
1 import SimpleXMLRPCServer
2 import SocketServer
3 import cPickle
4 import errno
5 import os
6 import pwd
7 import socket
8 import struct
9 import threading
10 import xmlrpclib
11
12 import accounts
13 import database
14 import logger
15 import tools
16
17
18 API_SERVER_PORT = 812
19
20
21 api_method_dict = {}
22 nargs_dict = {}
23
24 def export_to_api(nargs):
25     def export(method):
26         nargs_dict[method.__name__] = nargs
27         api_method_dict[method.__name__] = method
28         return method
29     return export
30
31 @export_to_api(0)
32 def DumpDatabase():
33     """DumpDatabase(): return the entire node manager DB, pickled"""
34     return cPickle.dumps(dict(database._db), 0)
35
36 @export_to_api(0)
37 def Help():
38     """Help(): get help"""
39     return ''.join([method.__doc__ + '\n' for method in api_method_dict.itervalues()])
40
41 @export_to_api(1)
42 def CreateSliver(rec):
43     """CreateSliver(sliver_name): set up a non-PLC-instantiated sliver"""
44     if not rec['plc_instantiated']:
45         accounts.get(rec['name']).ensure_created(rec)
46
47 @export_to_api(1)
48 def DeleteSliver(rec):
49     """DeleteSliver(sliver_name): tear down a non-PLC-instantiated sliver"""
50     if not rec['plc_instantiated']:
51         accounts.get(rec['name']).ensure_destroyed()
52
53 @export_to_api(1)
54 def Start(rec):
55     """Start(sliver_name): run start scripts belonging to the specified sliver"""
56     accounts.get(rec['name']).start()
57
58 @export_to_api(1)
59 def Stop(rec):
60     """Stop(sliver_name): kill all processes belonging to the specified sliver"""
61     accounts.get(rec['name']).stop()
62
63 @export_to_api(1)
64 def GetEffectiveRSpec(rec):
65     """GetEffectiveRSpec(sliver_name): return the RSpec allocated to the specified sliver, including loans"""
66     return tools.deepcopy(rec.get('eff_rspec', {}))
67
68 @export_to_api(1)
69 def GetRSpec(rec):
70     """GetRSpec(sliver_name): return the RSpec allocated to the specified sliver, excluding loans"""
71     return tools.deepcopy(rec.get('rspec', {}))
72
73 @export_to_api(1)
74 def GetLoans(rec):
75     """GetLoans(sliver_name): return the list of loans made by the specified sliver"""
76     return tools.deepcopy(rec.get('loans', []))
77
78 def validate_loans(obj):
79     """Check that <obj> is a valid loan specification."""
80     def validate_loan(obj):
81         return (type(obj)==list or type(obj)==tuple) and len(obj)==3 and \
82                type(obj[0])==str and \
83                type(obj[1])==str and obj[1] in LOANABLE_RESOURCES and \
84                type(obj[2])==int and obj[2]>0
85     return type(obj)==list and False not in map(validate_loan, obj)
86
87 @export_to_api(2)
88 def SetLoans(rec, loans):
89     """SetLoans(sliver_name, loans): overwrite the list of loans made by the specified sliver"""
90     if not validate_loans(loans):
91         raise xmlrpclib.Fault(102, 'Invalid argument: the second argument must be a well-formed loan specification')
92     rec['loans'] = loans
93     database.deliver_records([rec])
94
95 api_method_list = api_method_dict.keys()
96 api_method_list.sort()
97
98
99 class APIRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
100     # overriding _dispatch to achieve this effect is officially deprecated,
101     # but I can't figure out how to get access to .request
102     # without duplicating SimpleXMLRPCServer code here,
103     # which is more likely to change than the deprecated behavior
104     # is to be broken
105
106     @database.synchronized
107     def _dispatch(self, method_name, args):
108         method_name = str(method_name)
109         try: method = api_method_dict[method_name]
110         except KeyError:
111             raise xmlrpclib.Fault(100, 'Invalid API method %s.  Valid choices are %s' % (method_name, ', '.join(api_method_list)))
112
113         expected_nargs = nargs_dict[method_name]
114         if len(args) != nargs_dict[method_name]:
115             raise xmlrpclib.Fault(101, 'Invalid argument count: got %d, expecting %d.' % (len(args), expected_nargs))
116         else:
117             # Figure out who's calling.
118             # XXX - these ought to be imported directly from some .h file
119             SO_PEERCRED = 17
120             sizeof_struct_ucred = 12
121             ucred = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERCRED,
122                                             sizeof_struct_ucred)
123             xid = struct.unpack('3i', ucred)[2]
124             caller_name = pwd.getpwuid(xid)[0]
125
126             if expected_nargs >= 1:
127                 target_name = args[0]
128                 target_rec = database.get_sliver(target_name)
129                 if not target_rec: raise xmlrpclib.Fault(102, 'Invalid argument: the first argument must be a sliver name.')
130
131                 if caller_name not in (args[0], 'root') and \
132                        (caller_name, method_name) not in target_rec['delegations']:
133                     raise xmlrpclib.Fault(108, 'Permission denied.')
134                 result = method(target_rec, *args[1:])
135             else:
136                 if method_name == 'DumpDatabase' and caller_name != 'root':
137                     raise xmlrpclib.Fault(108, 'Permission denied.')
138                 result = method()
139             if result == None: result = 1
140             return result
141
142 class APIServer_INET(SocketServer.ThreadingMixIn,
143                      SimpleXMLRPCServer.SimpleXMLRPCServer):
144     allow_reuse_address = True
145
146 class APIServer_UNIX(APIServer_INET): address_family = socket.AF_UNIX
147
148 def start():
149     """Start two XMLRPC interfaces: one bound to localhost, the other bound to a Unix domain socket."""
150     serv1 = APIServer_INET(('127.0.0.1', API_SERVER_PORT),
151                            requestHandler=APIRequestHandler, logRequests=0)
152     tools.as_daemon_thread(serv1.serve_forever)
153     unix_addr = '/tmp/node_mgr_api'
154     try: os.unlink(unix_addr)
155     except OSError, e:
156         if e.errno != errno.ENOENT: raise
157     serv2 = APIServer_UNIX(unix_addr,
158                            requestHandler=APIRequestHandler, logRequests=0)
159     tools.as_daemon_thread(serv2.serve_forever)
160     os.chmod(unix_addr, 0666)