69505544f6b9f4cfb16220d147feb20d64b04315
[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
123     def listRecords(self, hrn, rectype=None, filename=None):
124         args = ["-u", config.getUser(), "-a", config.getAuthority(),
125                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "list", hrn]
126
127         if filename:
128             # we can't tell whether SFI will create one file or many, so delete
129             # leftovers from last time, then we'll know what we got, after we get it.
130             if os.path.exists(filename):
131                 os.remove(filename)
132             if os.path.exists(filename + ".1"):
133                 os.remove(filename + ".1")
134             args.append("-o")
135             args.append(filename)
136
137         if rectype:
138             args.append("-t")
139             args.append(rectype)
140
141         self.__init_command(args)
142         self.start()
143
144     def getRecord(self, hrn, filename=None):
145         args = ["-u", config.getUser(), "-a", config.getAuthority(),
146                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "show", hrn]
147         if filename:
148             args.append("-o")
149             args.append(filename)
150         self.__init_command(args)
151         self.start()
152
153     def getSliceRecord(self):
154         self.getRecord(config.getSlice(), config.getSliceRecordFile())
155
156     def getAuthorityRecord(self):
157         self.getRecord(config.getAuthority(), config.getAuthorityRecordFile())
158
159     def applyRSpec(self, rspec):
160         # that's what we pass, like in what we'd like to get
161         requested = config.getSliceRSpecFile() + "_new"
162         # that's what we actually receive
163         # just overwrite the slice file as if we'd used 'resources'
164         obtained = config.getSliceRSpecFile()
165         rspec.save(requested)
166         args = ["-u", config.getUser(), "-a", config.getAuthority(),
167                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "create",
168                 "-o", obtained,
169                 config.getSlice(), requested]
170         self.__init_command(args)
171         self.start()
172
173     def updateRecord(self, filename):
174         args = ["-u", config.getUser(), "-a", config.getAuthority(),
175                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "update", filename]
176         self.__init_command(args)
177         self.start()
178
179     def addRecord(self, filename):
180         args = ["-u", config.getUser(), "-a", config.getAuthority(),
181                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "add", filename]
182         self.__init_command(args)
183         self.start()
184
185     def renewSlivers(self, expiration):
186         args = ["-u", config.getUser(), "-a", config.getAuthority(),
187                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "renew",
188                 config.getSlice(), expiration]
189         self.__init_command(args)
190         self.start()
191
192     def start(self):
193         self.respones = []
194         self.faults = []
195         self.output = ""
196         self.trace_command()
197         self.process.start(self.exe, self.args)
198
199     def readOutput(self):
200         if self.process.state() == QProcess.NotRunning:
201             return self.process.readAll()
202
203     def trace_command (self):
204         if config.verbose:
205             self._trace=time.time()
206             command = "%s %s" % (self.exe, self.args.join(" "))
207             print time.strftime('%H:%M:%S'),'Invoking',command
208
209     def trace_end (self):
210         if config.verbose:
211 #            command = "%s %s" % (self.exe, self.args.join(" "))
212             print time.strftime('%H:%M:%S'),"Done [%.3f s]"%(time.time()-self._trace)
213         if config.debug:
214             get_tracker().getAndPrint(self.output)
215