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