ee49eb73cf85b6963d0e92e956639cbb8e2a2f28
[sface.git] / sface / sfiprocess.py
1
2 import os
3 import sys
4 import time
5
6 from distutils.version import LooseVersion
7 from sfa.util.version import version_core
8
9 from PyQt4.QtCore import *
10 from sface.config import config
11 from sface.xmlrpcwindow import get_tracker, XmlrpcReader
12
13 def find_executable(exec_name):
14     """find the given executable in $PATH"""
15     paths = os.getenv("PATH").split(':')
16     for p in paths:
17         exec_path = os.path.join(p, exec_name)
18         if os.path.exists(exec_path):
19             return exec_path
20     return None
21
22
23 class SfiProcess(QObject):
24     def __init__(self, parent=None):
25         QObject.__init__(self, parent)
26
27         env = QProcess.systemEnvironment()
28         env << "PYTHONPATH=%s" % ":".join(sys.path)
29         self.process = QProcess()
30         self.process.setEnvironment(env)
31         self.connect(self.process, SIGNAL("finished(int, QProcess::ExitStatus)"),
32                      self.processFinished)
33
34         self.xmlrpcreader = XmlrpcReader() # this one is for parsing XMLRPC responses
35
36         # holds aggregate output from processStandardOutput(); used by xmlrpc
37         # tracker.
38         self.output = ""
39
40         self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
41                      self.processStandardOutput)
42         self.connect(self.process, SIGNAL("readyReadStandardError()"),
43                      self.processStandardError)
44
45     def __init_command(self, args):
46         self.args = QStringList()
47         self.args << "-d"
48         self.args << config.get_dirname()
49
50         # this shows xmlrpc conversation, see sfi.py docs.
51         # always do this, so we can parse the XML result for faults and show
52         # then to the users.
53         self.args << QString('-D')
54
55         for arg in args:
56             self.args << QString(arg)
57
58         self.exe = find_executable("sfi.py")
59         if not self.exe:
60             print "FATAL.. Could not locate binary sfi.py - not much we can do without that"
61
62     def isRunning(self):
63         return self.process.state() != QProcess.NotRunning
64
65     def processStandardOutput(self):
66         output = self.process.readAllStandardOutput()
67         self.output = self.output + output
68         if config.debug:
69             print output
70
71     def processStandardError(self):
72         print self.process.readAllStandardError()
73
74     def processFinished(self):
75         if self.process.exitStatus() == QProcess.CrashExit:
76             print self.readOutput()
77             print "Process exited with errors:",
78             err = self.process.error()
79             if err == QProcess.FailedToStart:
80                 print "FailedToStart"
81             elif err == QProcess.Crashed:
82                 print "Crashed"
83             elif err == QProcess.Timedout:
84                 print "Timedout"
85             elif err == QProcess.WriteError:
86                 print "WriteError"
87             elif err == QProcess.ReadError:
88                 print "ReadError"
89             elif err == QProcess.UnknownError:
90                 print "UnknownError"
91
92         # extract any faults from the XMLRPC response(s)
93         self.xmlrpcreader.responses = []
94         self.xmlrpcreader.store(self.output)
95         self.xmlrpcreader.extractXml()
96         self.responses = self.xmlrpcreader.responses
97         self.faults = [x for x in self.responses if (x["kind"]=="fault")]
98
99         self.trace_end()
100         self.emit(SIGNAL("finished()"))
101
102     def getFaultString(self):
103         if self.faults == []:
104             return None
105
106         return self.faults[0].get("faultString","") + " (" + self.faults[0].get("faultCode","") + ")"
107
108     def retrieveRspec(self):
109         slice = config.getSlice()
110         mgr = config.getSlicemgr()
111         # Write RSpec to file
112         filename = config.fullpath ("%s.rspec"%slice)
113         try:
114             os.remove(filename)
115         except:
116             pass
117         args = ["-u", config.getUser(), "-a", config.getAuthority(), 
118                 "-r", config.getRegistry(), "-s", mgr, "resources", 
119                 "-o", filename, slice]
120
121         self.__init_command(args)
122         self.start()
123         return filename
124
125     def retrieveResources(self):
126         mgr = config.getSlicemgr()
127         # Write RSpec to file
128         filename = config.getResourcesRSpecFile()
129         try:
130             os.remove(filename)
131         except:
132             pass
133         args = ["-u", config.getUser(), "-a", config.getAuthority(),
134                 "-r", config.getRegistry(), "-s", mgr, "resources",
135                 "-o", filename]
136
137         self.__init_command(args)
138         self.start()
139         return filename
140
141
142     def listRecords(self, hrn, rectype=None, filename=None):
143         args = ["-u", config.getUser(), "-a", config.getAuthority(),
144                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "list", hrn]
145
146         if not filename:
147             if LooseVersion(version_core()['code_tag']) <= LooseVersion("1.0-35"):
148                 # DEPRECATED
149                 filename = config.getAuthorityListRecordFile()
150             else:
151                 filename = config.getAuthorityListFile()
152
153         # we can't tell whether SFI will create one file or many, so delete
154         # leftovers from last time, then we'll know what we got, after we get it.
155         if os.path.exists(filename):
156             os.remove(filename)
157         if os.path.exists(filename + ".1"):
158             os.remove(filename + ".1")
159         args.append("-o")
160         args.append(filename)
161
162         if rectype:
163             args.append("-t")
164             args.append(rectype)
165
166         self.__init_command(args)
167         self.start()
168
169     def getRecord(self, hrn, filename=None):
170         args = ["-u", config.getUser(), "-a", config.getAuthority(),
171                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "show", hrn]
172         if filename:
173             args.append("-o")
174             args.append(filename)
175         self.__init_command(args)
176         self.start()
177
178     def getSliceRecord(self):
179         self.getRecord(config.getSlice(), config.getSliceRecordFile())
180
181     def getAuthorityRecord(self):
182         self.getRecord(config.getAuthority(), config.getAuthorityRecordFile())
183
184     def applyRSpec(self, rspec):
185         # that's what we pass, like in what we'd like to get
186         requested = config.getSliceRSpecFile() + "_new"
187         # that's what we actually receive
188         # just overwrite the slice file as if we'd used 'resources'
189         obtained = config.getSliceRSpecFile()
190         rspec.save(requested)
191         args = ["-u", config.getUser(), "-a", config.getAuthority(),
192                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "create",
193                 "-o", obtained,
194                 config.getSlice(), requested]
195         self.__init_command(args)
196         self.start()
197
198     def updateRecord(self, filename):
199         args = ["-u", config.getUser(), "-a", config.getAuthority(),
200                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "update", filename]
201         self.__init_command(args)
202         self.start()
203
204     def addRecord(self, filename):
205         args = ["-u", config.getUser(), "-a", config.getAuthority(),
206                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "add", filename]
207         self.__init_command(args)
208         self.start()
209
210     def renewSlivers(self, expiration):
211         args = ["-u", config.getUser(), "-a", config.getAuthority(),
212                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "renew",
213                 config.getSlice(), expiration]
214         self.__init_command(args)
215         self.start()
216
217     def start(self):
218         self.respones = []
219         self.faults = []
220         self.output = ""
221         self.trace_command()
222         self.process.start(self.exe, self.args)
223
224     def readOutput(self):
225         if self.process.state() == QProcess.NotRunning:
226             return self.process.readAll()
227
228     def trace_command (self):
229         if config.verbose:
230             self._trace=time.time()
231             command = "%s %s" % (self.exe, self.args.join(" "))
232             print time.strftime('%H:%M:%S'),'Invoking',command
233
234     def trace_end (self):
235         if config.verbose:
236 #            command = "%s %s" % (self.exe, self.args.join(" "))
237             print time.strftime('%H:%M:%S'),"Done [%.3f s]"%(time.time()-self._trace)
238         if config.debug:
239             get_tracker().getAndPrint(self.output)
240