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