10 Wrapper around safexmlrpc.ServerProxy to automagically add an Auth
11 struct as the first argument to every XML-RPC call. Initialize
14 (node_id, key) => BootAuth
16 session => SessionAuth
18 To authenticate using the Boot Manager authentication method, or
19 the new session-based method.
22 def __init__(self, uri, cacert, auth, timeout = 90, **kwds):
25 self.timeout = timeout
27 if isinstance(auth, (tuple, list)):
28 (self.node_id, self.key) = auth
30 elif isinstance(auth, (str, unicode)):
31 self.node_id = self.key = None
34 self.node_id = self.key = self.session = None
36 self.server = safexmlrpc.ServerProxy(self.uri, self.cacert, self.timeout, allow_none = 1, **kwds)
39 def update_session(self, f="/usr/boot/plnode.txt"):
40 # try authenticatipopulate /etc.planetlab/session
43 return [i[:-1].split('=') for i in open(f).readlines() if i.startswith(key)][0][1].strip('"')
47 auth = (int(plnode("NODE_ID")), plnode("NODE_KEY"))
48 plc = PLCAPI(self.uri, self.cacert, auth, self.timeout)
49 open("/etc/planetlab/session", 'w').write(plc.GetSession().strip())
50 self.session = open("/etc/planetlab/session").read().strip()
53 def check_authentication(self):
55 if self.key or self.session:
57 authstatus = self.AuthCheck()
59 logger.log_exc("failed in plcapi.check_authentication")
63 def add_auth(self, function):
65 Returns a wrapper which adds an Auth struct as the first
66 argument when the function is called.
69 def canonicalize(args):
71 BootAuth canonicalization method. Parameter values are
72 collected, sorted, converted to strings, then hashed with
79 if isinstance(arg, list) or isinstance(arg, tuple):
80 # The old implementation did not recursively handle
81 # lists of lists. But neither did the old API itself.
82 values += canonicalize(arg)
83 elif isinstance(arg, dict):
84 # Yes, the comments in the old implementation are
85 # misleading. Keys of dicts are not included in the
87 values += canonicalize(arg.values())
89 # We use unicode() instead of str().
90 values.append(unicode(arg))
96 Adds an Auth struct as the first argument when the
100 if self.session is not None:
101 # Use session authentication
102 auth = {'AuthMethod': "session",
103 'session': self.session}
105 # Yes, this is the "canonicalization" method used.
106 args = canonicalize(params)
108 msg = "[" + "".join(args) + "]"
110 # We encode in UTF-8 before calculating the HMAC, which is
111 # an 8-bit algorithm.
112 digest = hmac.new(self.key, msg.encode('utf-8'), sha).hexdigest()
114 auth = {'AuthMethod': "hmac",
115 'node_id': self.node_id,
118 # Automagically add auth struct to every call
119 params = (auth,) + params
121 return function(*params)
125 def __getattr__(self, methodname):
126 function = getattr(self.server, methodname)
127 return self.add_auth(function)