fix problem with adding networks to RSpecs (QString was not automatically type converted)
[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 get_tracker, 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
33         # holds aggregate output from processStandardOutput(); used by xmlrpc
34         # tracker.
35         self.output = ""
36
37         self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
38                      self.processStandardOutput)
39         self.connect(self.process, SIGNAL("readyReadStandardError()"),
40                      self.processStandardError)
41
42     def __init_command(self, args):
43         self.args = QStringList()
44         self.args << "-d"
45         self.args << config.get_dirname()
46
47         # this shows xmlrpc conversation, see sfi.py docs.
48         # always do this, so we can parse the XML result for faults and show
49         # then to the users.
50         self.args << QString('-D')
51
52         for arg in args:
53             self.args << QString(arg)
54
55         self.exe = find_executable("sfi.py")
56         if not self.exe:
57             print "FATAL.. Could not locate binary sfi.py - not much we can do without that"
58
59     def isRunning(self):
60         return self.process.state() != QProcess.NotRunning
61
62     def processStandardOutput(self):
63         output = self.process.readAllStandardOutput()
64         self.output = self.output + output
65         if config.debug:
66             print output
67
68     def processStandardError(self):
69         print self.process.readAllStandardError()
70
71     def processFinished(self):
72         if self.process.exitStatus() == QProcess.CrashExit:
73             print self.readOutput()
74             print "Process exited with errors:",
75             err = self.process.error()
76             if err == QProcess.FailedToStart:
77                 print "FailedToStart"
78             elif err == QProcess.Crashed:
79                 print "Crashed"
80             elif err == QProcess.Timedout:
81                 print "Timedout"
82             elif err == QProcess.WriteError:
83                 print "WriteError"
84             elif err == QProcess.ReadError:
85                 print "ReadError"
86             elif err == QProcess.UnknownError:
87                 print "UnknownError"
88
89         # extract any faults from the XMLRPC response(s)
90         self.xmlrpcreader.responses = []
91         self.xmlrpcreader.store(self.output)
92         self.xmlrpcreader.extractXml()
93         self.responses = self.xmlrpcreader.responses
94         self.faults = [x for x in self.responses if (x["kind"]=="fault")]
95
96         self.trace_end()
97         self.emit(SIGNAL("finished()"))
98
99     def getFaultString(self):
100         if self.faults == []:
101             return None
102
103         return self.faults[0].get("faultString","") + " (" + self.faults[0].get("faultCode","") + ")"
104
105     def retrieveRspec(self):
106         slice = config.getSlice()
107         mgr = config.getSlicemgr()
108         # Write RSpec to file
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 retrieveResources(self):
123         mgr = config.getSlicemgr()
124         # Write RSpec to file
125         filename = config.getResourcesRSpecFile()
126         try:
127             os.remove(filename)
128         except:
129             pass
130         args = ["-u", config.getUser(), "-a", config.getAuthority(),
131                 "-r", config.getRegistry(), "-s", mgr, "resources",
132                 "-o", filename]
133
134         self.__init_command(args)
135         self.start()
136         return filename
137
138
139     def listRecords(self, hrn, rectype=None, filename=None):
140         args = ["-u", config.getUser(), "-a", config.getAuthority(),
141                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "list", "-F", "xmllist", hrn]
142
143         if not filename:
144             filename = config.getAuthorityListFile()
145
146         # we can't tell whether SFI will create one file or many, so delete
147         # leftovers from last time, then we'll know what we got, after we get it.
148         if os.path.exists(filename):
149             os.remove(filename)
150         if os.path.exists(filename + ".1"):
151             os.remove(filename + ".1")
152         args.append("-o")
153         args.append(filename)
154
155         if rectype:
156             args.append("-t")
157             args.append(rectype)
158
159         self.__init_command(args)
160         self.start()
161
162     def getRecord(self, hrn, filename=None):
163         args = ["-u", config.getUser(), "-a", config.getAuthority(),
164                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "show", hrn]
165         if filename:
166             args.append("-o")
167             args.append(filename)
168         self.__init_command(args)
169         self.start()
170
171     def getSliceRecord(self):
172         self.getRecord(config.getSlice(), config.getSliceRecordFile())
173
174     def getAuthorityRecord(self):
175         self.getRecord(config.getAuthority(), config.getAuthorityRecordFile())
176
177     def applyRSpec(self, rspec):
178         # that's what we pass, like in what we'd like to get
179         requested = config.getSliceRSpecFile() + "_new"
180         # that's what we actually receive
181         # just overwrite the slice file as if we'd used 'resources'
182         obtained = config.getSliceRSpecFile()
183         rspec.save(requested)
184         args = ["-u", config.getUser(), "-a", config.getAuthority(),
185                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "create",
186                 "-o", obtained,
187                 config.getSlice(), requested]
188         self.__init_command(args)
189         self.start()
190
191     def updateRecord(self, filename):
192         args = ["-u", config.getUser(), "-a", config.getAuthority(),
193                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "update", filename]
194         self.__init_command(args)
195         self.start()
196
197     def addRecord(self, filename):
198         args = ["-u", config.getUser(), "-a", config.getAuthority(),
199                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "add", filename]
200         self.__init_command(args)
201         self.start()
202
203     def renewSlivers(self, expiration):
204         args = ["-u", config.getUser(), "-a", config.getAuthority(),
205                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "renew",
206                 config.getSlice(), expiration]
207         self.__init_command(args)
208         self.start()
209
210     def start(self):
211         self.respones = []
212         self.faults = []
213         self.output = ""
214         self.trace_command()
215         self.process.start(self.exe, self.args)
216
217     def readOutput(self):
218         if self.process.state() == QProcess.NotRunning:
219             return self.process.readAll()
220
221     def trace_command (self):
222         if config.verbose:
223             self._trace=time.time()
224             command = "%s %s" % (self.exe, self.args.join(" "))
225             print time.strftime('%H:%M:%S'),'Invoking',command
226
227     def trace_end (self):
228         if config.verbose:
229 #            command = "%s %s" % (self.exe, self.args.join(" "))
230             print time.strftime('%H:%M:%S'),"Done [%.3f s]"%(time.time()-self._trace)
231         if config.debug:
232             get_tracker().getAndPrint(self.output)
233