make renew a self-contained dialog
[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 __getRSpec(self, mgr):
101         slice = config.getSlice()
102         # Write RSpec to file for testing.
103         filename = os.path.expanduser("~/.sfi/" + slice + ".rspec")
104         try:
105             os.remove(filename)
106         except:
107             pass
108         args = ["-u", config.getUser(), "-a", config.getAuthority(), 
109                 "-r", config.getRegistry(), "-s", mgr, "resources", 
110                 "-o", filename, slice]
111
112         self.__init_command(args)
113         self.start()
114         return filename
115
116     def getRSpecFromSM(self):
117         return self.__getRSpec(config.getSlicemgr())
118
119 #    def getRSpecFromAM(self):
120 #        return self.__getRSpec(config.getAggmgr())
121
122     def listRecords(self, hrn, rectype=None, filename=None):
123         args = ["-u", config.getUser(), "-a", config.getAuthority(),
124                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "list", hrn]
125
126         if filename:
127             # we can't tell whether SFI will create one file or many, so delete
128             # leftovers from last time, then we'll know what we got, after we get it.
129             if os.path.exists(filename):
130                 os.remove(filename)
131             if os.path.exists(filename + ".1"):
132                 os.remove(filename + ".1")
133             args.append("-o")
134             args.append(filename)
135
136         if rectype:
137             args.append("-t")
138             args.append(rectype)
139
140         self.__init_command(args)
141         self.start()
142
143     def getRecord(self, hrn, filename=None):
144         args = ["-u", config.getUser(), "-a", config.getAuthority(),
145                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "show", hrn]
146         if filename:
147             args.append("-o")
148             args.append(filename)
149         self.__init_command(args)
150         self.start()
151
152     def getSliceRecord(self):
153         self.getRecord(config.getSlice(), config.getSliceRecordFile())
154
155     def getAuthorityRecord(self):
156         self.getRecord(config.getAuthority(), config.getAuthorityRecordFile())
157
158     def applyRSpec(self, rspec):
159         filename = config.getSliceRSpecFile() + "_new"
160         rspec.save(filename)
161         args = ["-u", config.getUser(), "-a", config.getAuthority(),
162                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "create",
163                 config.getSlice(), filename]
164         self.__init_command(args)
165         self.start()
166         return filename
167
168     def updateRecord(self, filename):
169         args = ["-u", config.getUser(), "-a", config.getAuthority(),
170                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "update", filename]
171         self.__init_command(args)
172         self.start()
173
174     def addRecord(self, filename):
175         args = ["-u", config.getUser(), "-a", config.getAuthority(),
176                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "add", filename]
177         self.__init_command(args)
178         self.start()
179
180     def renewSlivers(self, expiration):
181         args = ["-u", config.getUser(), "-a", config.getAuthority(),
182                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "renew",
183                 config.getSlice(), expiration]
184         self.__init_command(args)
185         self.start()
186
187     def start(self):
188         self.respones = []
189         self.faults = []
190         self.output = ""
191         self.trace_command()
192         self.process.start(self.exe, self.args)
193
194     def readOutput(self):
195         if self.process.state() == QProcess.NotRunning:
196             return self.process.readAll()
197
198     def trace_command (self):
199         if config.verbose:
200             self._trace=time.time()
201             command = "%s %s" % (self.exe, self.args.join(" "))
202             print time.strftime('%H:%M:%S'),'Invoking',command
203
204     def trace_end (self):
205         if config.verbose:
206 #            command = "%s %s" % (self.exe, self.args.join(" "))
207             print time.strftime('%H:%M:%S'),"Done [%.3f s]"%(time.time()-self._trace)
208         if config.debug:
209             self.xmlrpctracker.getAndPrint(self.output)
210