cleanup for using the config dir properly, and not an hard-wired ~/.sfi/
[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
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.xmlrpctracker = XmlrpcTracker()
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         if config.debug:
48             # this shows xmlrpc conversation, see sfi.py docs.
49             self.args << QString('-D')
50         for arg in args:
51             self.args << QString(arg)
52
53         self.exe = find_executable("sfi.py")
54         if not self.exe:
55             print "FATAL.. Could not locate binary sfi.py - not much we can do without that"
56
57     def isRunning(self):
58         return self.process.state() != QProcess.NotRunning
59
60     def processStandardOutput(self):
61         output = self.process.readAllStandardOutput()
62         self.output = self.output + output
63         if config.debug:
64             print output
65
66     def processStandardError(self):
67         print self.process.readAllStandardError()
68
69     def processFinished(self):
70         if self.process.exitStatus() == QProcess.CrashExit:
71             print self.readOutput()
72             print "Process exited with errors:",
73             err = self.process.error()
74             if err == QProcess.FailedToStart:
75                 print "FailedToStart"
76             elif err == QProcess.Crashed:
77                 print "Crashed"
78             elif err == QProcess.Timedout:
79                 print "Timedout"
80             elif err == QProcess.WriteError:
81                 print "WriteError"
82             elif err == QProcess.ReadError:
83                 print "ReadError"
84             elif err == QProcess.UnknownError:
85                 print "UnknownError"
86         self.trace_end()
87         self.emit(SIGNAL("finished()"))
88
89     def __getRSpec(self, mgr):
90         slice = config.getSlice()
91         # Write RSpec to file for testing.
92         filename = config.fullpath ("%s.rspec"%slice)
93         try:
94             os.remove(filename)
95         except:
96             pass
97         args = ["-u", config.getUser(), "-a", config.getAuthority(), 
98                 "-r", config.getRegistry(), "-s", mgr, "resources", 
99                 "-o", filename, slice]
100
101         self.__init_command(args)
102         self.start()
103         return filename
104
105     def getRSpecFromSM(self):
106         return self.__getRSpec(config.getSlicemgr())
107
108 #    def getRSpecFromAM(self):
109 #        return self.__getRSpec(config.getAggmgr())
110
111     def listRecords(self, hrn, rectype=None, filename=None):
112         args = ["-u", config.getUser(), "-a", config.getAuthority(),
113                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "list", hrn]
114
115         if filename:
116             # we can't tell whether SFI will create one file or many, so delete
117             # leftovers from last time, then we'll know what we got, after we get it.
118             if os.path.exists(filename):
119                 os.remove(filename)
120             if os.path.exists(filename + ".1"):
121                 os.remove(filename + ".1")
122             args.append("-o")
123             args.append(filename)
124
125         if rectype:
126             args.append("-t")
127             args.append(rectype)
128
129         self.__init_command(args)
130         self.start()
131
132     def getRecord(self, hrn, filename=None):
133         args = ["-u", config.getUser(), "-a", config.getAuthority(),
134                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "show", hrn]
135         if filename:
136             args.append("-o")
137             args.append(filename)
138         self.__init_command(args)
139         self.start()
140
141     def getSliceRecord(self):
142         self.getRecord(config.getSlice(), config.getSliceRecordFile())
143
144     def getAuthorityRecord(self):
145         self.getRecord(config.getAuthority(), config.getAuthorityRecordFile())
146
147     def applyRSpec(self, rspec):
148         filename = config.getSliceRSpecFile() + "_new"
149         rspec.save(filename)
150         args = ["-u", config.getUser(), "-a", config.getAuthority(),
151                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "create",
152                 config.getSlice(), filename]
153         self.__init_command(args)
154         self.start()
155         return filename
156
157     def updateRecord(self, filename):
158         args = ["-u", config.getUser(), "-a", config.getAuthority(),
159                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "update", filename]
160         self.__init_command(args)
161         self.start()
162
163     def addRecord(self, filename):
164         args = ["-u", config.getUser(), "-a", config.getAuthority(),
165                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "add", filename]
166         self.__init_command(args)
167         self.start()
168
169     def renewSlivers(self, expiration):
170         args = ["-u", config.getUser(), "-a", config.getAuthority(),
171                 "-r", config.getRegistry(), "-s", config.getSlicemgr(), "renew",
172                 config.getSlice(), expiration]
173         self.__init_command(args)
174         self.start()
175
176     def start(self):
177         self.output = ""
178         self.trace_command()
179         self.process.start(self.exe, self.args)
180
181     def readOutput(self):
182         if self.process.state() == QProcess.NotRunning:
183             return self.process.readAll()
184
185     def trace_command (self):
186         if config.verbose:
187             self._trace=time.time()
188             command = "%s %s" % (self.exe, self.args.join(" "))
189             print time.strftime('%H:%M:%S'),'Invoking',command
190
191     def trace_end (self):
192         if config.verbose:
193 #            command = "%s %s" % (self.exe, self.args.join(" "))
194             print time.strftime('%H:%M:%S'),"Done [%.3f s]"%(time.time()-self._trace)
195         if config.debug:
196             self.xmlrpctracker.getAndPrint(self.output)
197