forked from xapi-project/xsconsole
-
Notifications
You must be signed in to change notification settings - Fork 2
/
XSConsoleTask.py
174 lines (145 loc) · 5.71 KB
/
XSConsoleTask.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# Copyright (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from XSConsoleAuth import *
from XSConsoleBases import *
from XSConsoleHotData import *
class TaskEntry:
def __init__(self, inHotOpaqueRef, inSession):
self.hotOpaqueRef = inHotOpaqueRef
self.session = inSession
self.startTime = time.time()
self.completed = False
self.creationTime = None
self.finishTime = None
self.result = None
def Completed(self):
return self.completed
def HandleCompletion(self, inStatus):
if self.completed:
raise Exception('TaskEntry.HandleCompletion called more than once')
self.completed = True
self.completionStatus = inStatus
self.creationTime = TimeUtils.DateTimeToSecs(self.session.xenapi.task.get_created(self.hotOpaqueRef.OpaqueRef()))
self.finishTime = TimeUtils.DateTimeToSecs(self.session.xenapi.task.get_finished(self.hotOpaqueRef.OpaqueRef()))
if inStatus.startswith('success'):
result = self.session.xenapi.task.get_result(self.hotOpaqueRef.OpaqueRef())
result = result.replace("<value>", "").replace("</value>", "")
self.result = HotOpaqueRef(result, 'any')
if inStatus.startswith('failure'):
self.errorInfo = self.session.xenapi.task.get_error_info(self.hotOpaqueRef.OpaqueRef())
Auth.Inst().CloseSession(self.session)
self.session = None
def Status(self):
if self.Completed():
status = self.completionStatus
else:
status = self.session.xenapi.task.get_status(self.hotOpaqueRef.OpaqueRef())
if not status.startswith('pending'):
self.HandleCompletion(status)
return status
def Result(self):
return self.result
def CanCancel(self):
if self.Completed():
retVal = False
else:
allowedOps = self.session.xenapi.task.get_allowed_operations(self.hotOpaqueRef.OpaqueRef())
retVal = ('cancel' in allowedOps)
return retVal
def Message(self):
status = self.Status().lower()
if status.startswith('pending'):
retVal = Lang('In progress')
elif status.startswith('success'):
retVal = Lang('Operation was successful')
elif status.startswith('failure'):
retVal = Lang('Failed: ')+Language.XapiError(self.errorInfo)
elif status.startswith('cancelling'):
retVal = Lang('Cancellation in progress')
elif status.startswith('cancelled'):
retVal = Lang('Cancelled')
else:
retVal = Lang('<Unknown>')
return retVal
def RaiseIfFailed(self):
if self.Status().lower().startswith('failure'):
raise Exception(Language.XapiError(self.errorInfo))
def IsPending(self):
if self.Status().lower().startswith('pending'):
retVal = True
else:
retVal = False
return retVal
def ProgressValue(self):
if self.Completed():
retVal = 1.0
else:
retVal = self.session.xenapi.task.get_progress(self.hotOpaqueRef.OpaqueRef())
return retVal
def DurationSecs(self):
if self.creationTime is not None and self.finishTime is not None:
retVal = self.finishTime - self.creationTime
else:
retVal = time.time() - self.startTime
return retVal
def Cancel(self):
if not self.completed:
self.session.xenapi.task.cancel(self.hotOpaqueRef.OpaqueRef())
class Task:
instance = None
def __init__(self):
self.taskList = {}
self.syncSession = None
@classmethod
def Inst(cls):
if cls.instance is None:
cls.instance = Task()
return cls.instance
def Create(self, inProc):
session = None
try:
session = Auth.Inst().NewSession()
taskRef = inProc(session)
except:
if session is not None:
Auth.Inst().CloseSession(session)
raise
hotTaskRef = HotOpaqueRef(taskRef, 'task')
taskEntry = TaskEntry(hotTaskRef, session)
self.taskList[hotTaskRef] = taskEntry
return taskEntry
def GarbageCollect(self):
# This may be expensive as it must fetch status from xapi for each incomplete task
deleteKeys = []
for key, value in self.taskList.items():
# Forget tasks that have of duration of greater than one day
value.Status()
if value.Completed() or value.DurationSecs() > 86400:
deleteKeys.append(key)
for key in deleteKeys:
del self.taskList[key]
def SyncSession(self):
if self.syncSession is None:
self.syncSession = Auth.Inst().NewSession()
return self.syncSession
def SyncOperation(self, inProc):
retVal = inProc(self.SyncSession())
return retVal
@classmethod
def New(cls, inProc):
return cls.Inst().Create(inProc)
@classmethod
def Sync(cls, inProc):
return cls.Inst().SyncOperation(inProc)