forked from buildbot/buildbot
-
Notifications
You must be signed in to change notification settings - Fork 6
/
builder.py
2592 lines (2203 loc) · 90.1 KB
/
builder.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: buildbot.test.test_status -*-
from zope.interface import implements
from twisted.python import log
from twisted.persisted import styles
from twisted.internet import reactor, defer, threads
from twisted.protocols import basic
from buildbot.process.properties import Properties
from buildbot.util import collections
from buildbot.util.eventual import eventually
import weakref
import os, shutil, sys, re, urllib, itertools
import gc
from cPickle import load, dump
from cStringIO import StringIO
from bz2 import BZ2File
from gzip import GzipFile
# sibling imports
from buildbot import interfaces, util, sourcestamp
SUCCESS, WARNINGS, FAILURE, SKIPPED, EXCEPTION, RETRY = range(6)
Results = ["success", "warnings", "failure", "skipped", "exception", "retry"]
# build processes call the following methods:
#
# setDefaults
#
# currentlyBuilding
# currentlyIdle
# currentlyInterlocked
# currentlyOffline
# currentlyWaiting
#
# setCurrentActivity
# updateCurrentActivity
# addFileToCurrentActivity
# finishCurrentActivity
#
# startBuild
# finishBuild
STDOUT = interfaces.LOG_CHANNEL_STDOUT
STDERR = interfaces.LOG_CHANNEL_STDERR
HEADER = interfaces.LOG_CHANNEL_HEADER
ChunkTypes = ["stdout", "stderr", "header"]
class LogFileScanner(basic.NetstringReceiver):
def __init__(self, chunk_cb, channels=[]):
self.chunk_cb = chunk_cb
self.channels = channels
def stringReceived(self, line):
channel = int(line[0])
if not self.channels or (channel in self.channels):
self.chunk_cb((channel, line[1:]))
class LogFileProducer:
"""What's the plan?
the LogFile has just one FD, used for both reading and writing.
Each time you add an entry, fd.seek to the end and then write.
Each reader (i.e. Producer) keeps track of their own offset. The reader
starts by seeking to the start of the logfile, and reading forwards.
Between each hunk of file they yield chunks, so they must remember their
offset before yielding and re-seek back to that offset before reading
more data. When their read() returns EOF, they're finished with the first
phase of the reading (everything that's already been written to disk).
After EOF, the remaining data is entirely in the current entries list.
These entries are all of the same channel, so we can do one "".join and
obtain a single chunk to be sent to the listener. But since that involves
a yield, and more data might arrive after we give up control, we have to
subscribe them before yielding. We can't subscribe them any earlier,
otherwise they'd get data out of order.
We're using a generator in the first place so that the listener can
throttle us, which means they're pulling. But the subscription means
we're pushing. Really we're a Producer. In the first phase we can be
either a PullProducer or a PushProducer. In the second phase we're only a
PushProducer.
So the client gives a LogFileConsumer to File.subscribeConsumer . This
Consumer must have registerProducer(), unregisterProducer(), and
writeChunk(), and is just like a regular twisted.interfaces.IConsumer,
except that writeChunk() takes chunks (tuples of (channel,text)) instead
of the normal write() which takes just text. The LogFileConsumer is
allowed to call stopProducing, pauseProducing, and resumeProducing on the
producer instance it is given. """
paused = False
subscribed = False
BUFFERSIZE = 2048
def __init__(self, logfile, consumer):
self.logfile = logfile
self.consumer = consumer
self.chunkGenerator = self.getChunks()
consumer.registerProducer(self, True)
def getChunks(self):
f = self.logfile.getFile()
offset = 0
chunks = []
p = LogFileScanner(chunks.append)
f.seek(offset)
data = f.read(self.BUFFERSIZE)
offset = f.tell()
while data:
p.dataReceived(data)
while chunks:
c = chunks.pop(0)
yield c
f.seek(offset)
data = f.read(self.BUFFERSIZE)
offset = f.tell()
del f
# now subscribe them to receive new entries
self.subscribed = True
self.logfile.watchers.append(self)
d = self.logfile.waitUntilFinished()
# then give them the not-yet-merged data
if self.logfile.runEntries:
channel = self.logfile.runEntries[0][0]
text = "".join([c[1] for c in self.logfile.runEntries])
yield (channel, text)
# now we've caught up to the present. Anything further will come from
# the logfile subscription. We add the callback *after* yielding the
# data from runEntries, because the logfile might have finished
# during the yield.
d.addCallback(self.logfileFinished)
def stopProducing(self):
# TODO: should we still call consumer.finish? probably not.
self.paused = True
self.consumer = None
self.done()
def done(self):
if self.chunkGenerator:
self.chunkGenerator = None # stop making chunks
if self.subscribed:
self.logfile.watchers.remove(self)
self.subscribed = False
def pauseProducing(self):
self.paused = True
def resumeProducing(self):
# Twisted-1.3.0 has a bug which causes hangs when resumeProducing
# calls transport.write (there is a recursive loop, fixed in 2.0 in
# t.i.abstract.FileDescriptor.doWrite by setting the producerPaused
# flag *before* calling resumeProducing). To work around this, we
# just put off the real resumeProducing for a moment. This probably
# has a performance hit, but I'm going to assume that the log files
# are not retrieved frequently enough for it to be an issue.
eventually(self._resumeProducing)
def _resumeProducing(self):
self.paused = False
if not self.chunkGenerator:
return
try:
while not self.paused:
chunk = self.chunkGenerator.next()
self.consumer.writeChunk(chunk)
# we exit this when the consumer says to stop, or we run out
# of chunks
except StopIteration:
# if the generator finished, it will have done releaseFile
self.chunkGenerator = None
# now everything goes through the subscription, and they don't get to
# pause anymore
def logChunk(self, build, step, logfile, channel, chunk):
if self.consumer:
self.consumer.writeChunk((channel, chunk))
def logfileFinished(self, logfile):
self.done()
if self.consumer:
self.consumer.unregisterProducer()
self.consumer.finish()
self.consumer = None
def _tryremove(filename, timeout, retries):
"""Try to remove a file, and if failed, try again in timeout.
Increases the timeout by a factor of 4, and only keeps trying for
another retries-amount of times.
"""
try:
os.unlink(filename)
except OSError:
if retries > 0:
reactor.callLater(timeout, _tryremove, filename, timeout * 4,
retries - 1)
else:
log.msg("giving up on removing %s after over %d seconds" %
(filename, timeout))
class LogFile:
"""A LogFile keeps all of its contents on disk, in a non-pickle format to
which new entries can easily be appended. The file on disk has a name
like 12-log-compile-output, under the Builder's directory. The actual
filename is generated (before the LogFile is created) by
L{BuildStatus.generateLogfileName}.
Old LogFile pickles (which kept their contents in .entries) must be
upgraded. The L{BuilderStatus} is responsible for doing this, when it
loads the L{BuildStatus} into memory. The Build pickle is not modified,
so users who go from 0.6.5 back to 0.6.4 don't have to lose their
logs."""
implements(interfaces.IStatusLog, interfaces.ILogFile)
finished = False
length = 0
nonHeaderLength = 0
tailLength = 0
chunkSize = 10*1000
runLength = 0
# No max size by default
logMaxSize = None
# Don't keep a tail buffer by default
logMaxTailSize = None
maxLengthExceeded = False
runEntries = [] # provided so old pickled builds will getChunks() ok
entries = None
BUFFERSIZE = 2048
filename = None # relative to the Builder's basedir
openfile = None
compressMethod = "bz2"
def __init__(self, parent, name, logfilename):
"""
@type parent: L{BuildStepStatus}
@param parent: the Step that this log is a part of
@type name: string
@param name: the name of this log, typically 'output'
@type logfilename: string
@param logfilename: the Builder-relative pathname for the saved entries
"""
self.step = parent
self.name = name
self.filename = logfilename
fn = self.getFilename()
if os.path.exists(fn):
# the buildmaster was probably stopped abruptly, before the
# BuilderStatus could be saved, so BuilderStatus.nextBuildNumber
# is out of date, and we're overlapping with earlier builds now.
# Warn about it, but then overwrite the old pickle file
log.msg("Warning: Overwriting old serialized Build at %s" % fn)
dirname = os.path.dirname(fn)
if not os.path.exists(dirname):
os.makedirs(dirname)
self.openfile = open(fn, "w+")
self.runEntries = []
self.watchers = []
self.finishedWatchers = []
self.tailBuffer = []
def getFilename(self):
return os.path.join(self.step.build.builder.basedir, self.filename)
def hasContents(self):
return os.path.exists(self.getFilename() + '.bz2') or \
os.path.exists(self.getFilename() + '.gz') or \
os.path.exists(self.getFilename())
def getName(self):
return self.name
def getStep(self):
return self.step
def isFinished(self):
return self.finished
def waitUntilFinished(self):
if self.finished:
d = defer.succeed(self)
else:
d = defer.Deferred()
self.finishedWatchers.append(d)
return d
def getFile(self):
if self.openfile:
# this is the filehandle we're using to write to the log, so
# don't close it!
return self.openfile
# otherwise they get their own read-only handle
# try a compressed log first
try:
return BZ2File(self.getFilename() + ".bz2", "r")
except IOError:
pass
try:
return GzipFile(self.getFilename() + ".gz", "r")
except IOError:
pass
return open(self.getFilename(), "r")
def getText(self):
# this produces one ginormous string
return "".join(self.getChunks([STDOUT, STDERR], onlyText=True))
def getTextWithHeaders(self):
return "".join(self.getChunks(onlyText=True))
def getChunks(self, channels=[], onlyText=False):
# generate chunks for everything that was logged at the time we were
# first called, so remember how long the file was when we started.
# Don't read beyond that point. The current contents of
# self.runEntries will follow.
# this returns an iterator, which means arbitrary things could happen
# while we're yielding. This will faithfully deliver the log as it
# existed when it was started, and not return anything after that
# point. To use this in subscribe(catchup=True) without missing any
# data, you must insure that nothing will be added to the log during
# yield() calls.
f = self.getFile()
if not self.finished:
offset = 0
f.seek(0, 2)
remaining = f.tell()
else:
offset = 0
remaining = None
leftover = None
if self.runEntries and (not channels or
(self.runEntries[0][0] in channels)):
leftover = (self.runEntries[0][0],
"".join([c[1] for c in self.runEntries]))
# freeze the state of the LogFile by passing a lot of parameters into
# a generator
return self._generateChunks(f, offset, remaining, leftover,
channels, onlyText)
def _generateChunks(self, f, offset, remaining, leftover,
channels, onlyText):
chunks = []
p = LogFileScanner(chunks.append, channels)
f.seek(offset)
if remaining is not None:
data = f.read(min(remaining, self.BUFFERSIZE))
remaining -= len(data)
else:
data = f.read(self.BUFFERSIZE)
offset = f.tell()
while data:
p.dataReceived(data)
while chunks:
channel, text = chunks.pop(0)
if onlyText:
yield text
else:
yield (channel, text)
f.seek(offset)
if remaining is not None:
data = f.read(min(remaining, self.BUFFERSIZE))
remaining -= len(data)
else:
data = f.read(self.BUFFERSIZE)
offset = f.tell()
del f
if leftover:
if onlyText:
yield leftover[1]
else:
yield leftover
def readlines(self, channel=STDOUT):
"""Return an iterator that produces newline-terminated lines,
excluding header chunks."""
# TODO: make this memory-efficient, by turning it into a generator
# that retrieves chunks as necessary, like a pull-driven version of
# twisted.protocols.basic.LineReceiver
alltext = "".join(self.getChunks([channel], onlyText=True))
io = StringIO(alltext)
return io.readlines()
def subscribe(self, receiver, catchup):
if self.finished:
return
self.watchers.append(receiver)
if catchup:
for channel, text in self.getChunks():
# TODO: add logChunks(), to send over everything at once?
receiver.logChunk(self.step.build, self.step, self,
channel, text)
def unsubscribe(self, receiver):
if receiver in self.watchers:
self.watchers.remove(receiver)
def subscribeConsumer(self, consumer):
p = LogFileProducer(self, consumer)
p.resumeProducing()
# interface used by the build steps to add things to the log
def merge(self):
# merge all .runEntries (which are all of the same type) into a
# single chunk for .entries
if not self.runEntries:
return
channel = self.runEntries[0][0]
text = "".join([c[1] for c in self.runEntries])
assert channel < 10
f = self.openfile
f.seek(0, 2)
offset = 0
while offset < len(text):
size = min(len(text)-offset, self.chunkSize)
f.write("%d:%d" % (1 + size, channel))
f.write(text[offset:offset+size])
f.write(",")
offset += size
self.runEntries = []
self.runLength = 0
def addEntry(self, channel, text):
assert not self.finished
if isinstance(text, unicode):
text = text.encode('utf-8')
if channel != HEADER:
# Truncate the log if it's more than logMaxSize bytes
if self.logMaxSize and self.nonHeaderLength > self.logMaxSize:
# Add a message about what's going on
if not self.maxLengthExceeded:
msg = "\nOutput exceeded %i bytes, remaining output has been truncated\n" % self.logMaxSize
self.addEntry(HEADER, msg)
self.merge()
self.maxLengthExceeded = True
if self.logMaxTailSize:
# Update the tail buffer
self.tailBuffer.append((channel, text))
self.tailLength += len(text)
while self.tailLength > self.logMaxTailSize:
# Drop some stuff off the beginning of the buffer
c,t = self.tailBuffer.pop(0)
n = len(t)
self.tailLength -= n
assert self.tailLength >= 0
return
self.nonHeaderLength += len(text)
# we only add to .runEntries here. merge() is responsible for adding
# merged chunks to .entries
if self.runEntries and channel != self.runEntries[0][0]:
self.merge()
self.runEntries.append((channel, text))
self.runLength += len(text)
if self.runLength >= self.chunkSize:
self.merge()
for w in self.watchers:
w.logChunk(self.step.build, self.step, self, channel, text)
self.length += len(text)
def addStdout(self, text):
self.addEntry(STDOUT, text)
def addStderr(self, text):
self.addEntry(STDERR, text)
def addHeader(self, text):
self.addEntry(HEADER, text)
def finish(self):
if self.tailBuffer:
msg = "\nFinal %i bytes follow below:\n" % self.tailLength
tmp = self.runEntries
self.runEntries = [(HEADER, msg)]
self.merge()
self.runEntries = self.tailBuffer
self.merge()
self.runEntries = tmp
self.merge()
self.tailBuffer = []
else:
self.merge()
if self.openfile:
# we don't do an explicit close, because there might be readers
# shareing the filehandle. As soon as they stop reading, the
# filehandle will be released and automatically closed.
self.openfile.flush()
del self.openfile
self.finished = True
watchers = self.finishedWatchers
self.finishedWatchers = []
for w in watchers:
w.callback(self)
self.watchers = []
def compressLog(self):
# bail out if there's no compression support
if self.compressMethod == "bz2":
compressed = self.getFilename() + ".bz2.tmp"
elif self.compressMethod == "gz":
compressed = self.getFilename() + ".gz.tmp"
d = threads.deferToThread(self._compressLog, compressed)
d.addCallback(self._renameCompressedLog, compressed)
d.addErrback(self._cleanupFailedCompress, compressed)
return d
def _compressLog(self, compressed):
infile = self.getFile()
if self.compressMethod == "bz2":
cf = BZ2File(compressed, 'w')
elif self.compressMethod == "gz":
cf = GzipFile(compressed, 'w')
bufsize = 1024*1024
while True:
buf = infile.read(bufsize)
cf.write(buf)
if len(buf) < bufsize:
break
cf.close()
def _renameCompressedLog(self, rv, compressed):
if self.compressMethod == "bz2":
filename = self.getFilename() + '.bz2'
else:
filename = self.getFilename() + '.gz'
if sys.platform == 'win32':
# windows cannot rename a file on top of an existing one, so
# fall back to delete-first. There are ways this can fail and
# lose the builder's history, so we avoid using it in the
# general (non-windows) case
if os.path.exists(filename):
os.unlink(filename)
os.rename(compressed, filename)
_tryremove(self.getFilename(), 1, 5)
def _cleanupFailedCompress(self, failure, compressed):
log.msg("failed to compress %s" % self.getFilename())
if os.path.exists(compressed):
_tryremove(compressed, 1, 5)
failure.trap() # reraise the failure
# persistence stuff
def __getstate__(self):
d = self.__dict__.copy()
del d['step'] # filled in upon unpickling
del d['watchers']
del d['finishedWatchers']
d['entries'] = [] # let 0.6.4 tolerate the saved log. TODO: really?
if d.has_key('finished'):
del d['finished']
if d.has_key('openfile'):
del d['openfile']
return d
def __setstate__(self, d):
self.__dict__ = d
self.watchers = [] # probably not necessary
self.finishedWatchers = [] # same
# self.step must be filled in by our parent
self.finished = True
def upgrade(self, logfilename):
"""Save our .entries to a new-style offline log file (if necessary),
and modify our in-memory representation to use it. The original
pickled LogFile (inside the pickled Build) won't be modified."""
self.filename = logfilename
if not os.path.exists(self.getFilename()):
self.openfile = open(self.getFilename(), "w")
self.finished = False
for channel,text in self.entries:
self.addEntry(channel, text)
self.finish() # releases self.openfile, which will be closed
del self.entries
class HTMLLogFile:
implements(interfaces.IStatusLog)
filename = None
def __init__(self, parent, name, logfilename, html):
self.step = parent
self.name = name
self.filename = logfilename
self.html = html
def getName(self):
return self.name # set in BuildStepStatus.addLog
def getStep(self):
return self.step
def isFinished(self):
return True
def waitUntilFinished(self):
return defer.succeed(self)
def hasContents(self):
return True
def getText(self):
return self.html # looks kinda like text
def getTextWithHeaders(self):
return self.html
def getChunks(self):
return [(STDERR, self.html)]
def subscribe(self, receiver, catchup):
pass
def unsubscribe(self, receiver):
pass
def finish(self):
pass
def __getstate__(self):
d = self.__dict__.copy()
del d['step']
return d
def upgrade(self, logfilename):
pass
class Event:
implements(interfaces.IStatusEvent)
started = None
finished = None
text = []
# IStatusEvent methods
def getTimes(self):
return (self.started, self.finished)
def getText(self):
return self.text
def getLogs(self):
return []
def finish(self):
self.finished = util.now()
class TestResult:
implements(interfaces.ITestResult)
def __init__(self, name, results, text, logs):
assert isinstance(name, tuple)
self.name = name
self.results = results
self.text = text
self.logs = logs
def getName(self):
return self.name
def getResults(self):
return self.results
def getText(self):
return self.text
def getLogs(self):
return self.logs
class BuildSetStatus:
implements(interfaces.IBuildSetStatus)
def __init__(self, bsid, status, db):
self.id = bsid
self.status = status
self.db = db
def _get_info(self):
return self.db.get_buildset_info(self.id)
# methods for our clients
def getSourceStamp(self):
(external_idstring, reason, ssid, complete, results) = self._get_info()
return self.db.getSourceStampNumberedNow(ssid)
def getReason(self):
(external_idstring, reason, ssid, complete, results) = self._get_info()
return reason
def getResults(self):
(external_idstring, reason, ssid, complete, results) = self._get_info()
return results
def getID(self):
(external_idstring, reason, ssid, complete, results) = self._get_info()
return external_idstring
def getBuilderNamesAndBuildRequests(self):
brs = {}
brids = self.db.get_buildrequestids_for_buildset(self.id)
for (buildername, brid) in brids.items():
brs[buildername] = BuildRequestStatus(brid, self.status, self.db)
return brs
def getBuilderNames(self):
brs = self.db.get_buildrequestids_for_buildset(self.id)
return sorted(brs.keys())
def getBuildRequests(self):
brs = self.db.get_buildrequestids_for_buildset(self.id)
return [BuildRequestStatus(brid, self.status, self.db)
for brid in brs.values()]
def isFinished(self):
(external_idstring, reason, ssid, complete, results) = self._get_info()
return complete
def waitUntilSuccess(self):
return self.status._buildset_waitUntilSuccess(self.id)
def waitUntilFinished(self):
return self.status._buildset_waitUntilFinished(self.id)
class BuildRequestStatus:
implements(interfaces.IBuildRequestStatus)
def __init__(self, brid, status, db):
self.brid = brid
self.status = status
self.db = db
def buildStarted(self, build):
self.status._buildrequest_buildStarted(build.status)
self.builds.append(build.status)
# methods called by our clients
def getSourceStamp(self):
br = self.db.getBuildRequestWithNumber(self.brid)
return br.source
def getBuilderName(self):
br = self.db.getBuildRequestWithNumber(self.brid)
return br.builderName
def getBuilds(self):
builder = self.status.getBuilder(self.getBuilderName())
builds = []
buildnums = sorted(self.db.get_buildnums_for_brid(self.brid))
for buildnum in buildnums:
bs = builder.getBuild(buildnum)
if bs:
builds.append(bs)
return builds
def subscribe(self, observer):
oldbuilds = self.getBuilds()
for bs in oldbuilds:
eventually(observer, bs)
self.status._buildrequest_subscribe(self.brid, observer)
def unsubscribe(self, observer):
self.status._buildrequest_unsubscribe(self.brid, observer)
def getSubmitTime(self):
br = self.db.getBuildRequestWithNumber(self.brid)
return br.submittedAt
def asDict(self):
result = {}
# Constant
result['source'] = self.getSourceStamp().asDict()
result['builderName'] = self.getBuilderName()
result['submittedAt'] = self.getSubmitTime()
# Transient
result['builds'] = [build.asDict() for build in self.getBuilds()]
return result
class BuildStepStatus(styles.Versioned):
"""
I represent a collection of output status for a
L{buildbot.process.step.BuildStep}.
Statistics contain any information gleaned from a step that is
not in the form of a logfile. As an example, steps that run
tests might gather statistics about the number of passed, failed,
or skipped tests.
@type progress: L{buildbot.status.progress.StepProgress}
@cvar progress: tracks ETA for the step
@type text: list of strings
@cvar text: list of short texts that describe the command and its status
@type text2: list of strings
@cvar text2: list of short texts added to the overall build description
@type logs: dict of string -> L{buildbot.status.builder.LogFile}
@ivar logs: logs of steps
@type statistics: dict
@ivar statistics: results from running this step
"""
# note that these are created when the Build is set up, before each
# corresponding BuildStep has started.
implements(interfaces.IBuildStepStatus, interfaces.IStatusEvent)
persistenceVersion = 2
started = None
finished = None
progress = None
text = []
results = (None, [])
text2 = []
watchers = []
updates = {}
finishedWatchers = []
statistics = {}
def __init__(self, parent):
assert interfaces.IBuildStatus(parent)
self.build = parent
self.logs = []
self.urls = {}
self.watchers = []
self.updates = {}
self.finishedWatchers = []
self.statistics = {}
def getName(self):
"""Returns a short string with the name of this step. This string
may have spaces in it."""
return self.name
def getBuild(self):
return self.build
def getTimes(self):
return (self.started, self.finished)
def getExpectations(self):
"""Returns a list of tuples (name, current, target)."""
if not self.progress:
return []
ret = []
metrics = self.progress.progress.keys()
metrics.sort()
for m in metrics:
t = (m, self.progress.progress[m], self.progress.expectations[m])
ret.append(t)
return ret
def getLogs(self):
return self.logs
def getURLs(self):
return self.urls.copy()
def isStarted(self):
return (self.started is not None)
def isFinished(self):
return (self.finished is not None)
def waitUntilFinished(self):
if self.finished:
d = defer.succeed(self)
else:
d = defer.Deferred()
self.finishedWatchers.append(d)
return d
# while the step is running, the following methods make sense.
# Afterwards they return None
def getETA(self):
if self.started is None:
return None # not started yet
if self.finished is not None:
return None # already finished
if not self.progress:
return None # no way to predict
return self.progress.remaining()
# Once you know the step has finished, the following methods are legal.
# Before this step has finished, they all return None.
def getText(self):
"""Returns a list of strings which describe the step. These are
intended to be displayed in a narrow column. If more space is
available, the caller should join them together with spaces before
presenting them to the user."""
return self.text
def getResults(self):
"""Return a tuple describing the results of the step.
'result' is one of the constants in L{buildbot.status.builder}:
SUCCESS, WARNINGS, FAILURE, or SKIPPED.
'strings' is an optional list of strings that the step wants to
append to the overall build's results. These strings are usually
more terse than the ones returned by getText(): in particular,
successful Steps do not usually contribute any text to the
overall build.
@rtype: tuple of int, list of strings
@returns: (result, strings)
"""
return (self.results, self.text2)
def hasStatistic(self, name):
"""Return true if this step has a value for the given statistic.
"""
return self.statistics.has_key(name)
def getStatistic(self, name, default=None):
"""Return the given statistic, if present
"""
return self.statistics.get(name, default)
# subscription interface
def subscribe(self, receiver, updateInterval=10):
# will get logStarted, logFinished, stepETAUpdate
assert receiver not in self.watchers
self.watchers.append(receiver)
self.sendETAUpdate(receiver, updateInterval)
def sendETAUpdate(self, receiver, updateInterval):
self.updates[receiver] = None
# they might unsubscribe during stepETAUpdate
receiver.stepETAUpdate(self.build, self,
self.getETA(), self.getExpectations())
if receiver in self.watchers:
self.updates[receiver] = reactor.callLater(updateInterval,
self.sendETAUpdate,
receiver,
updateInterval)
def unsubscribe(self, receiver):
if receiver in self.watchers:
self.watchers.remove(receiver)
if receiver in self.updates:
if self.updates[receiver] is not None:
self.updates[receiver].cancel()
del self.updates[receiver]
# methods to be invoked by the BuildStep
def setName(self, stepname):
self.name = stepname
def setColor(self, color):
log.msg("BuildStepStatus.setColor is no longer supported -- ignoring color %s" % (color,))
def setProgress(self, stepprogress):
self.progress = stepprogress
def stepStarted(self):
self.started = util.now()
if self.build:
self.build.stepStarted(self)
def addLog(self, name):
assert self.started # addLog before stepStarted won't notify watchers
logfilename = self.build.generateLogfileName(self.name, name)
log = LogFile(self, name, logfilename)
log.logMaxSize = self.build.builder.logMaxSize
log.logMaxTailSize = self.build.builder.logMaxTailSize
log.compressMethod = self.build.builder.logCompressionMethod
self.logs.append(log)
for w in self.watchers:
receiver = w.logStarted(self.build, self, log)
if receiver:
log.subscribe(receiver, True)
d = log.waitUntilFinished()
d.addCallback(lambda log: log.unsubscribe(receiver))
d = log.waitUntilFinished()
d.addCallback(self.logFinished)
return log
def addHTMLLog(self, name, html):
assert self.started # addLog before stepStarted won't notify watchers
logfilename = self.build.generateLogfileName(self.name, name)
log = HTMLLogFile(self, name, logfilename, html)
self.logs.append(log)
for w in self.watchers:
receiver = w.logStarted(self.build, self, log)
# TODO: think about this: there isn't much point in letting
# them subscribe
#if receiver:
# log.subscribe(receiver, True)
w.logFinished(self.build, self, log)
def logFinished(self, log):
for w in self.watchers:
w.logFinished(self.build, self, log)
def addURL(self, name, url):
self.urls[name] = url