python3 - 2to3 + miscell obvious tweaks
[sfa.git] / sfa / planetlab / nodemanager.py
1 import tempfile
2 import subprocess
3 import os
4
5
6 class NodeManager:
7
8     method = None
9
10     def __init__(self, config):
11         self.config = config
12
13     def __getattr__(self, method):
14         self.method = method
15         return self.__call__
16
17     def __call__(self, *args):
18         method = self.method
19         sfa_slice_prefix = self.config.SFA_CM_SLICE_PREFIX
20         sfa_slice = sfa_slice_prefix + "_sfacm"
21         python = "/usr/bin/python2"
22         vserver_path = "/vservers/%s" % (sfa_slice)
23         script_path = "/tmp/"
24         path = "%(vserver_path)s/%(script_path)s" % locals()
25         (fd, filename) = tempfile.mkstemp(dir=path)
26         scriptname = script_path + os.sep + filename.split(os.sep)[-1:][0]
27         # define the script to execute
28         # when providing support for python3 wrt xmlrpclib
29         # looks safer to keep things as-is
30         script = """
31 #!%(python)s
32 import xmlrpclib
33 s = xmlrpclib.ServerProxy('http://127.0.0.1:812')
34 print s.%(method)s%(args)s"""  % locals()
35
36         try:
37             # write the script to a temporary file
38             f = open(filename, 'w')
39             f.write(script % locals())
40             f.close()
41             # make the file executeable
42             chmod_cmd = "/bin/chmod 775 %(filename)s" % locals()
43             (status, output) = subprocess.getstatusoutput(chmod_cmd)
44
45             # execute the commad as a slice with root NM privs
46             cmd = 'su - %(sfa_slice)s -c "%(python)s %(scriptname)s"' % locals()
47             (status, output) = subprocess.getstatusoutput(cmd)
48             return (status, output)
49         finally:
50             os.unlink(filename)