-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
390 lines (314 loc) · 10.2 KB
/
server.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# encoding: utf-8
# Copyright © 2012-2013 David García Garzón and CLAM-project
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from functools import partial
import os
import glob
import datetime
class BadServerPath(Exception) : pass
class ProjectNotFound (Exception) :
def __init__(self, name) :
super(ProjectNotFound, self).__init__(name)
self.message = "Project not found '{}'".format(name)
class ClientNotFound (Exception) :
def __init__(self, name) :
super(ClientNotFound, self).__init__(name)
self.message = "Client not found '{}'".format(name)
class ArgPrepender(object) :
"""Wraps an object so that any method call to the wrapper,
is delegated to the wrapped object but prepending the args
provided on construction."""
def __init__(self, wrapped, *args) :
self.wrapped = wrapped
self.args = args
def __getattr__(self, name) :
return partial(getattr(self.wrapped,name), *self.args)
class AttributeMap() :
def __init__(self, **kwds) : self.update(**kwds)
def __contains__(self, what) : return what in self.__dict__
def update(self, **kwds) : return self.__dict__.update(**kwds)
class Server(object) :
"""A server handles information from executions comming
from several clients for several projects"""
fileAccessTrace = []
def __init__(self, path) :
self._path = path
self._now = None
@property
def now(self) :
"""Holds the current time unless you set it to a concrete time"""
if self._now : return self._now
return datetime.datetime.now()
@now.setter
def now(self, value) :
self._now = value
def _p(self, *args) :
return os.path.join(self._path, *args)
def _assertPathOk(self) :
if not os.path.isdir(self._path) :
raise BadServerPath(self._path)
def _assertProjectOk(self, project) :
self._assertPathOk()
if not os.path.isdir(self._p(project)) :
raise ProjectNotFound(project)
def _assertClientOk(self, project, client) :
self._assertProjectOk(project)
if not os.path.isdir(self._p(project, client)) :
raise ClientNotFound(client)
def _metadataUpdate(self, *args, **kwds) :
filename = self._p(*args)
# print "Updating meta",filename
try : oldmeta = eval(open(filename).read())
except IOError : oldmeta = {}
oldmeta.update(kwds)
metadata = open(self._p(*args),'w')
metadata.write(repr(oldmeta))
def _metadataRead(self, *args) :
filename = self._p(*args)
# print "Reading meta",filename
try :
return eval(open(filename).read())
except IOError :
return {}
def _log(self, project, client, execution, *args) :
log = self._logRead(project, client, execution)
log.append(tuple(args))
logfile = open(self._p(project, client, execution+".log"),'w')
logfile.write(repr(log))
def _logRead(self, project, client, execution) :
filename = self._p(project, client, execution+".log")
# print "Reading log ", filename
try :
return eval(open(filename).read())
except IOError :
return []
def updateStats(self, project, client, execution, stats) :
filename = self._p(project, client, "stats")
f = open(filename, "a")
for key, value in sorted(stats.iteritems()) :
f.write(repr( (execution, key, value))+",")
f.close()
def clientStats(self, project, client) :
filename = self._p(project, client, "stats")
try :
return eval("[" + open(filename).read() + "]")
except IOError :
return []
def createServer(self) :
os.mkdir(self._p())
def createProject(self, project) :
os.mkdir(self._p(project))
self._metadataUpdate(project, "metadata")
def createClient(self, project, client) :
os.mkdir(self._p(project, client))
self._metadataUpdate(project, client, "metadata")
self.clientIdle(project, client, 0)
def setProjectMetadata(self, project, **kwd) :
self._metadataUpdate(project, "metadata", **kwd)
def setClientMetadata(self, project, client, **kwd) :
self._metadataUpdate(project, client, "metadata", **kwd)
def projectMetadata(self, project) :
return self._metadataRead(project, "metadata")
def clientMetadata(self, project, client) :
return self._metadataRead(project, client, "metadata")
def executionInfo(self, project, client, execution) :
return self._metadataRead(project, client, execution+".info")
def projects(self) :
return [
project.split("/")[-2]
for project in sorted(glob.glob(self._p("*","metadata")))
]
def clients(self, project) :
return [
project.split("/")[-2]
for project in sorted(glob.glob(self._p(project,"*","metadata")))
]
def executions(self, project, client) :
return [
project.split("/")[-1][:-5]
for project in sorted(glob.glob(self._p(project,client,"*.info")))
]
def executionStarts(self,
project, client, execution,
**kwds
) :
self._assertClientOk(project,client)
self._metadataUpdate(project, client, execution+".info", **kwds)
self._log(
project, client, execution,
"startExecution")
def taskStarts(self,
project, client, execution,
task, description,
) :
self._log(
project, client, execution,
"startTask", task, description)
def commandStarts(self,
project, client, execution,
task, sequence, command
) :
self._log(
project, client, execution,
"startCommand", task, sequence, command)
def commandEnds(self,
project, client, execution,
task, command, output, ok, info, stats
) :
self._log(project, client, execution,
'endCommand', task, command, output, ok, info, stats)
self.updateStats(project, client, execution, stats)
def taskEnds(self,
project, client, execution,
task, ok,
) :
self._log(
project, client, execution,
"endTask", task, ok)
def executionEnds(self,
project, client, execution,
ok
) :
self._log(
project, client, execution,
"endExecution", ok)
def isRunning(self,
project, client, execution=None) :
if execution is None :
executions = self.executions(project, client)
if not executions : return False
execution = executions[-1]
log = self._logRead(project, client, execution)
return not any([ "endExecution" in entry for entry in log])
def clientStatus(self, project, client) :
executions = self.executions(project, client)
if self.isRunning(project, client) :
return "Running"
expectedIdle = self.expectedIdle(project, client)
if expectedIdle > self.now :
return "Idle"
return "NotResponding"
def clientIdle(self, project, client, minutes) :
nextIdle = self.now + datetime.timedelta(minutes=minutes)
idlefile = open(self._p(project,client,"idle"),'w')
idlefile.write(nextIdle.strftime("%Y-%m-%d %H:%M:%S"))
def expectedIdle(self, project, client) :
filename = self._p(project,client,"idle")
# print "Reading idle", filename
return datetime.datetime.strptime(
open(filename).read(),
"%Y-%m-%d %H:%M:%S")
def execution(self, project, client, execution) :
"""Returns a Pythonic navegable structure with the information
about an execution taken from its execution log"""
summary = AttributeMap(
failedTasks = [],
running = True,
tasks = [],
)
log = self._logRead(project, client, execution)
tasks = {}
commands = {}
for entry in log :
tag = entry[0]
if tag == "startExecution":
summary.starttime = execution
continue
if tag == "endExecution":
summary.running = False
summary.ok, = entry[1:]
continue
if tag == "startTask":
task, description = entry[1:]
tasks[task] = AttributeMap(
id = task,
description=description,
running = True,
commands = [],
)
continue
if tag == "endTask":
task, ok = entry[1:]
tasks[task].update(
task = task,
running = False,
ok = ok,
)
continue
if tag == "startCommand" :
task, command, commandline = entry[1:]
commands[task,command] = AttributeMap(
id = command,
task = task,
commandline = commandline,
running = True,
)
tasks[task].commands.append(commands[task,command])
continue
if tag == "endCommand" :
task, command, output, ok, info, stats = entry[1:]
commands[task,command].update(
command = command,
running = False,
ok = ok,
output = output,
info = info,
stats = stats,
)
continue
summary.tasks = [task for id, task in sorted(tasks.iteritems())]
summary.failedTasks = [
(task.id, task.description)
for task in summary.tasks
if "ok" in task and not task.ok
]
if not summary.running :
summary.ok &= not(summary.failedTasks)
summary.currentTask = None
if summary.tasks and summary.running :
summary.currentTask = (
summary.tasks[-1].id,
summary.tasks[-1].description)
return summary
def client(self, project, client) :
meta = AttributeMap(**self.clientMetadata(project, client))
executions = self.executions(project, client)
expectedIdle = self.expectedIdle(project, client)
doing = "wait" if expectedIdle>self.now and executions else "old"
data = AttributeMap(
name = client,
expectedIdle = expectedIdle,
meta = meta,
doing = doing,
lastExecution = datetime.datetime(1900,1,1,0,0,0),
currentTask = None,
failedTasks = []
)
# TODO: If two running, the newer one remains
for execution in reversed(executions) :
executionData = self.execution(project, client, execution)
executionTime = datetime.datetime.strptime(execution,"%Y%m%d-%H%M%S")
if executionData.running :
data.currentTask = executionData.currentTask
data.doing = 'run'
data.runningSince = executionTime
continue
data.lastExecution = executionTime
data.failedTasks = executionData.failedTasks
data.ok = not data.failedTasks
break
data.status = "int" if "ok" not in data else 'green' if data.ok else "red"
return data