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