-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathebb.py
1381 lines (1168 loc) · 52.7 KB
/
ebb.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
# -*- coding: utf-8 -*-
# Copyright © 2014—2016 Dontnod Entertainment
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
''' Easier buildbot configuration. '''
import abc
import cgi
import contextlib
import os
import re
import shlex
import time
import jinja2
from twisted.python import log
from twisted.internet import defer
from twisted.internet import utils
import zope.interface
import buildbot.buildslave
import buildbot.changes
import buildbot.changes.p4poller
import buildbot.changes.gitpoller
import buildbot.config
import buildbot.interfaces
import buildbot.process.factory
import buildbot.schedulers.basic
import buildbot.schedulers.forcesched
import buildbot.schedulers.timed
import buildbot.schedulers.triggerable
import buildbot.status.html
import buildbot.status.mail
import buildbot.status.web.auth
import buildbot.status.web.authz
import buildbot.status.words
import buildbot.steps.shell
import buildbot.steps.source.p4
import buildbot.steps.source.git
import buildbot.steps.python
import buildbot.steps.trigger
import buildbot.util
class Scope(object):
''' Config node : inherit parent config values '''
# Config is created using context managers describing a tree. The top node
# is the active context
_top = None
def __init__(self):
self._parent = Scope._top
self.children = []
if Scope._top is not None:
Scope._top.children.append(self)
self.properties = {}
def __enter__(self):
assert Scope._top != self
Scope._top = self
return self
def __exit__(self, ex_type, value, traceback):
Scope._top = self._parent
@staticmethod
def set(name, value):
''' Sets a property on the active node '''
assert Scope._top is not None
Scope._top.properties[name] = value
@staticmethod
def set_checked(name, value, expected_type):
''' Sets a property on the active node if it's not None, and checks it's
type '''
if value is None:
return
if expected_type is not None:
assert isinstance(value, expected_type)
Scope.set(name, value)
@staticmethod
def append(name, *values):
''' Appends values to a list property with key name on this node '''
assert isinstance(name, basestring)
assert Scope._top is not None
properties = Scope._top.properties
if name not in properties:
properties[name] = []
assert isinstance(properties[name], list)
properties[name].extend(values)
@staticmethod
def update(name, key, value):
''' Adds a {key : value} entry on the dictionary named name on the top
node '''
assert isinstance(name, basestring)
assert Scope._top is not None
properties = Scope._top.properties
if name not in properties:
properties[name] = {}
assert isinstance(properties[name], dict)
properties[name][key] = value
@staticmethod
@contextlib.contextmanager
def push(func, *args, **kwargs):
''' Pushes a scope and calls a function before yielding '''
with Scope() as scope:
func(*args, **kwargs)
yield scope
def get(self, name, default=None, public_only=False):
''' Search for a property up the tree and returns the first occurence
'''
assert isinstance(name, basestring)
if name not in self.properties:
value = None
else:
value = self.properties[name]
if value is not None:
if not isinstance(value, list) and not isinstance(value, dict):
return value
for scope in self._get_related_scopes(public_only):
scope_value = scope.get(name, public_only=True)
if isinstance(scope_value, list):
if value is not None:
assert isinstance(value, list)
scope_value.extend(value)
elif isinstance(scope_value, dict):
if value is not None:
assert isinstance(value, dict)
scope_value.update(value)
if scope_value is not None:
value = scope_value
if isinstance(value, list):
return value[:]
elif isinstance(value, dict):
return value.copy()
return value if value is not None else default
def get_interpolated(self, name, default=None):
''' Search for a property up the tree, and returns it's value
interpolated with this node and all of it's parents property values
'''
assert isinstance(name, basestring)
result = self.get(name, default)
return self.interpolate(result)
def interpolate(self, value):
''' Interpolates value with all properties from current node and it's
parents
'''
if hasattr(value, '__call__'):
return value(self)
elif isinstance(value, basestring):
format_args = self.get_interpolation_values()
try:
return value.format(**format_args)
except KeyError as error:
raise KeyError('Key %s not found while interpolating %s on %s' % (error, value, self))
elif isinstance(value, list):
return [self.interpolate(it) for it in value]
elif isinstance(value, dict):
result = {}
for key, it in value.iteritems():
result[key] = self.interpolate(it)
return result
return value
def get_rendered(self, name, default=None):
''' Search for a property up the tree, and returns it's value
interpolated with this node and all of it's parents property values
'''
assert isinstance(name, basestring)
result = self.get(name, default)
return self.render(result)
def render(self, value):
''' Interpolates value with all properties from current node and it's
parents
'''
if isinstance(value, basestring):
return _Renderer(value, self)
elif isinstance(value, list):
return [self.render(it) for it in value]
elif isinstance(value, dict):
result = {}
for key, it in value.iteritems():
result[key] = self.render(it)
return result
return value
def get_interpolation_values(self, public_only=False):
''' Parses the tree bottom-up, getting string property values '''
result = {}
for scope in self._get_related_scopes(public_only):
scope_values = scope.get_interpolation_values(True)
result.update(scope_values)
for key, value in self.properties.iteritems():
if isinstance(value, basestring):
result[key] = value
return result
def get_parent_of_type(self, parent_type):
''' Find closest parent of specified node type '''
if self._parent is None:
return None
if isinstance(self._parent, parent_type):
return self._parent
return self._parent.get_parent_of_type(parent_type)
def build(self, config):
''' Builds this node '''
for child in self.children:
child.build(config)
self._build(config)
def _get_related_scopes(self, public_only):
if self._parent is not None:
yield self._parent
if not public_only:
for it in self.children:
if isinstance(it, Private):
yield it
def get_properties_names(self, prefix, public_only=False):
''' Returs all properties defined on this node and parent starting
with given prefix '''
result = set()
for scope in self._get_related_scopes(public_only):
result = result | scope.get_properties_names(prefix, True)
for key, _ in self.properties.iteritems():
if key.startswith(prefix + '_'):
result.add(key)
return result
@abc.abstractmethod
def _build(self, config):
pass
def _get_prefixed_properties(self, prefixes, rendered=None, raw=None):
result = {}
rendered = set([] if rendered is None else rendered)
raw = set(() if raw is None else raw)
if not isinstance(prefixes, tuple):
assert isinstance(prefixes, str)
prefixes = (prefixes,)
props = {}
for prefix in prefixes:
interpolated_it = self.get_properties_names(prefix)
raw_it = interpolated_it & raw
rendered_it = interpolated_it & rendered
interpolated_it = interpolated_it - raw_it - rendered_it
props[prefix] = (interpolated_it, raw_it, rendered_it)
for prefix, (interpolated_it, raw_it, rendered_it) in props.iteritems():
for key in interpolated_it:
key_without_prefix = key[len(prefix) + 1:]
result[key_without_prefix] = self.get_interpolated(key)
for key in raw_it:
key_without_prefix = key[len(prefix) + 1:]
result[key_without_prefix] = self.get(key)
for key in rendered_it:
key_without_prefix = key[len(prefix) + 1:]
result[key_without_prefix] = self.get_rendered(key)
# result[name] = self.properties[key]
return result
def _build_class(self,
buildbot_class,
prefixes,
positional=None,
raw=None,
rendered=None,
additional=None):
kwargs = self._get_prefixed_properties(prefixes,
rendered=rendered,
raw=raw)
if additional is not None:
kwargs.update(additional)
args = []
if positional is not None:
for name in positional:
assert name in kwargs, '%s argument missing' % name
args.append(kwargs[name])
del kwargs[name]
return buildbot_class(*args, **kwargs)
class Private(Scope):
''' Defines not inherited values on the parent scope '''
def __init__(self):
super(Private, self).__init__()
def _get_related_scopes(self, public_only):
return []
def _build(self, config):
pass
class Config(Scope):
''' Root config node '''
def __init__(self):
super(Config, self).__init__()
self.buildbot_config = {}
self._parsers = {}
self._schedulers = {}
self._slaves = []
self._triggerables = {}
self._locks = {}
self._builders_scopes = {}
self.buildbot_config['builders'] = []
self.buildbot_config['schedulers'] = []
self.buildbot_config['slaves'] = []
self.buildbot_config['status'] = []
self.buildbot_config['change_source'] = []
self.buildbot_config['prioritizeBuilders'] = self._prioritize_builders
self.slave_list_selector = None
self.next_slave_selector = None
@staticmethod
def db(url, poll_interval=None):
''' Configures db parameters '''
Scope.set_checked('db_db_url', url, basestring)
Scope.set_checked('db_poll_interval', poll_interval, int)
@staticmethod
def site(title, title_url, buildbot_url):
''' Configures site parameters '''
Scope.set_checked('base_title', title, basestring)
Scope.set_checked('base_titleURL', title_url, basestring)
Scope.set_checked('base_buildbotURL', buildbot_url, basestring)
@staticmethod
def logging(compression_limit=None,
compression_method=None,
max_size=None,
max_tail_size=None):
''' Configures logging parameters '''
Scope.set_checked('base_logCompressionLimit', compression_limit, int)
Scope.set_checked('base_logCompressionMethod',
compression_method,
basestring)
Scope.set_checked('base_logMaxSize', max_size, int)
Scope.set_checked('base_logMaxTailSize', max_tail_size, int)
@staticmethod
def horizons(change_horizon=None,
build_horizon=None,
event_horizon=None,
log_horizon=None):
''' Configures horizon parameters '''
Scope.set_checked('base_changeHorizon', change_horizon, int)
Scope.set_checked('base_buildHorizon', build_horizon, int)
Scope.set_checked('base_eventHorizon', event_horizon, int)
Scope.set_checked('base_logHorizon', log_horizon, int)
@staticmethod
def cache(changes=None,
builds=None,
chdicts=None,
build_requests=None,
source_stamps=None,
ssdicts=None,
objectids=None,
usdicts=None):
''' Configures horizon parameters '''
Scope.set_checked('cache_Changes', changes, int)
Scope.set_checked('cache_Builds', builds, int)
Scope.set_checked('cache_chdicts', chdicts, int)
Scope.set_checked('cache_BuildRequests', build_requests, int)
Scope.set_checked('cache_SourceStamps', source_stamps, int)
Scope.set_checked('cache_ssdicts', ssdicts, int)
Scope.set_checked('cache_objectids', objectids, int)
Scope.set_checked('cache_usdicts', usdicts, int)
@staticmethod
def set_protocol(protocol, port):
''' Sets given protocol to given port '''
Scope.update('protocols_%s' % protocol, 'port', port)
@staticmethod
def web_status(port, user, password):
''' Sets web status configuration '''
Scope.set_checked('web_status_port', port, int)
Scope.set_checked('web_status_user', user, str)
Scope.set_checked('web_status_password', password, str)
@staticmethod
def add_renderer_handlers(*handlers):
''' Add rendering handlers that can udpate rendering arguments at build
time '''
Scope.append('config_renderer_handlers', *handlers)
def get_builder(self, name):
''' Returns a declared Builder '''
return self._builders_scopes[name]
def get_slave(self, name):
''' Returns a declared slave '''
for slave in self._slaves:
if slave.get_interpolated('slave_name') == name:
return slave
return None
def build_config(self):
''' Builds the buildbot config '''
self.build(self)
return self.buildbot_config
def add_slave(self, slave):
''' Adds a slave for later tag filtering '''
self._slaves.append(slave)
def add_builder(self, builder, scope):
''' Adds a builder to this config '''
self._builders_scopes[builder.name] = scope
self.buildbot_config['builders'].append(builder)
def get_slave_list(self, *tags):
''' Returns declared slaves matching *all* given tags
Tags can be excluded if they start with “!” '''
# TODO: allow the tag1|tag2 syntax for e.g. 'linux|win64'
result = []
wanted_tagset, unwanted_tagset = set(), set()
for tag in tags:
if tag[:1] != '!':
wanted_tagset.add(tag)
else:
unwanted_tagset.add(tag[1:])
for slave in self._slaves:
slave_tagset = set()
for tag in slave.get_interpolated('_slave_tags', []):
slave_tagset.add(tag)
if len(wanted_tagset - slave_tagset) == 0 and \
len(unwanted_tagset.intersection(slave_tagset)) == 0:
slave_name = slave.get_interpolated('slave_name')
result.append(slave_name)
if len(result) == 0:
print 'Error : no slave found with tags %s and without tags %s' \
% (wanted_tagset, unwanted_tagset)
for slave in self._slaves:
slave_tagset = set()
for tag in slave.get_interpolated('_slave_tags', []):
slave_tagset.add(tag)
args = (slave.get_interpolated('slave_name'),
wanted_tagset - slave_tagset)
print 'Slave %s is missing tags %s' % args
return result
def _build(self, config):
assert config == self
conf_dict = config.buildbot_config
# Db config
conf_dict['db'] = self._get_prefixed_properties('db')
conf_dict['caches'] = self._get_prefixed_properties('cache')
conf_dict['protocols'] = self._get_prefixed_properties('protocols')
conf_dict.update(self._get_prefixed_properties('base'))
self._add_web_status()
def _add_web_status(self):
http_port = self.get('web_status_port')
if http_port is None:
return
users = [(self.get_interpolated('web_status_user'),
self.get_interpolated('web_status_password'))]
auth = buildbot.status.web.auth.BasicAuth(users)
authz = buildbot.status.web.authz.Authz(auth=auth,
view=True,
gracefulShutdown='auth',
forceBuild='auth',
forceAllBuilds='auth',
pingBuilder='auth',
stopBuild='auth',
stopAllBuilds='auth',
cancelPendingBuild='auth',
showUsersPage='auth',
cleanShutdown='auth')
web_status = buildbot.status.html.WebStatus(http_port=http_port,
authz=authz)
self.buildbot_config['status'].append(web_status)
def _prioritize_builders(self, _, builders):
def _get_priority(builder):
try:
return self._builders_scopes[builder.name].get('_builder_priority', 0)
except KeyError:
return 99999
builders.sort(key=_get_priority, reverse=True)
return builders
class Slave(Scope):
''' Creates a new buildbot slave '''
def __init__(self, name):
super(Slave, self).__init__()
self.properties['slave_name'] = name
config = self.get_parent_of_type(Config)
assert config is not None
config.add_slave(self)
@staticmethod
def config(password=None,
max_builds=None,
keepalive_interval=300,
missing_timeout=None):
''' Sets some buildbot slaves settings for current scope '''
Scope.set_checked('slave_password', password, basestring)
Scope.set_checked('slave_max_builds', max_builds, int)
Scope.set_checked('slave_keepalive_interval', keepalive_interval, int)
Scope.set_checked('slave_missing_timeout', missing_timeout, int)
@staticmethod
def add_property(key, value):
''' Adds a build property on this slave '''
Scope.update('slave_properties', key, value)
@staticmethod
def add_notified_on_missing(*emails):
''' Adds emails to notify when slaves in scope are missing '''
Scope.append('slave_notify_on_missing', *emails)
@staticmethod
def add_tags(*tags):
''' Adds specified tags to slaves in scope '''
Scope.append('_slave_tags', *tags)
def _build(self, config):
slave = self._build_class(buildbot.buildslave.BuildSlave, 'slave',
['name', 'password'])
config.buildbot_config['slaves'].append(slave)
class Builder(Scope):
''' Builder wrapper '''
def __init__(self, name, category=None, description=None):
super(Builder, self).__init__()
self._accept_regex = None
self._reject_regex = None
self._factory = buildbot.process.factory.BuildFactory()
self._nightly = None
self.properties['builder_name'] = name
if category is not None:
self.properties['builder_category'] = category
if description is not None:
self.properties['builder_description'] = description
def add_step(self, step):
''' Adds a step to this builder '''
self._factory.addStep(step)
def trigger_on_change(self, accept_regex='.*', reject_regex=None):
''' Triggers this build on change from source control '''
self._accept_regex = accept_regex
self._reject_regex = reject_regex
def trigger_nightly(self,
minute=None,
hour=None,
day_of_month=None,
month=None,
day_of_week=None):
''' Triggers this build nightly '''
self._nightly = {'minute' : minute,
'hour' : hour,
'dayOfMonth': day_of_month,
'month' : month,
'dayOfWeek' : day_of_week}
@staticmethod
def config(name=None,
category=None,
build_dir=None,
slave_build_dir=None,
next_build=None,
can_start_build=None,
merge_requests=None,
forcable=None,
only_important=None,
tree_stable_timer=None,
file_is_important=None,
project=None,
priority=None):
''' Sets builder config values '''
Scope.set_checked('builder_name', name, basestring)
Scope.set_checked('builder_category', category, basestring)
Scope.set_checked('builder_builddir', build_dir, None)
Scope.set_checked('builder_slavebuilddir', slave_build_dir, basestring)
Scope.set_checked('builder_nextBuild', next_build, None)
Scope.set_checked('builder_canStartBuild', can_start_build, None)
Scope.set_checked('builder_mergeRequests', merge_requests, None)
Scope.set_checked('scheduler_onlyImportant', only_important, bool)
Scope.set_checked('branch_scheduler_treeStableTimer', tree_stable_timer, int)
Scope.set_checked('scheduler_fileIsImportant', file_is_important, None)
Scope.set_checked('change_filter_project', project, basestring)
Scope.set_checked('_builder_priority', priority, int)
@staticmethod
def mail_config(from_address=None,
send_to_interested_users=None,
subject=None,
mode=None,
add_logs=None,
relay_host=None,
smpt_port=None,
use_tls=None,
smtp_user=None,
smtp_password=None,
lookup=None,
message_formatter=None,
template_directory=None,
template=None,
body_type=None):
''' Sets mail related settings '''
Scope.set_checked('mail_fromaddr', from_address, str)
Scope.set_checked('mail_sendToInterestedUsers',
send_to_interested_users, bool)
Scope.set_checked('mail_subject', subject, str)
Scope.set_checked('mail_mode', mode, None)
Scope.set_checked('mail_addLogs', add_logs, None)
Scope.set_checked('mail_relayhost', relay_host, str)
Scope.set_checked('mail_smtpPort', smpt_port, int)
Scope.set_checked('mail_useTls', use_tls, bool)
Scope.set_checked('mail_smtpUser', smtp_user, str)
Scope.set_checked('mail_smtpPassword', smtp_password, str)
Scope.set_checked('mail_lookup', lookup, None)
Scope.set_checked('_mail_message_formatter', message_formatter, None)
Scope.set_checked('_mail_template_directory', template_directory, None)
Scope.set_checked('_mail_template', template, None)
Scope.set_checked('_mail_body_type', body_type, None)
@staticmethod
def add_extra_recipients(*emails):
''' Adds extra recipients to users '''
Scope.append('mail_extraRecipients', *emails)
@staticmethod
def add_slave_tags(*tags):
''' Adds builder tags to current scope '''
Scope.append('_builder_slave_tags', *tags)
@staticmethod
def add_env_variable(name, value):
''' Adds an envrionment variable to builders in scope '''
Scope.update('builder_env', name, value)
@staticmethod
def add_tags(*tags):
''' Adds a tag to a builder '''
Scope.append('builder_tags', *tags)
@staticmethod
def add_property(name, value):
''' Adds a property to builders in scope '''
Scope.update('builder_properties', name, value)
def _build(self, config):
if config.slave_list_selector:
slavenames = config.slave_list_selector(self)
else:
slave_tags = self.get_interpolated('_builder_slave_tags', [])
slavenames = config.get_slave_list(*slave_tags)
# TODO locks = get_locks('job', config, scope)
args = {
'slavenames': slavenames,
'nextSlave': config.next_slave_selector,
'factory': self._factory,
}
builder = self._build_class(buildbot.config.BuilderConfig, 'builder', additional=args)
config.add_builder(builder, self)
self._add_single_branch_scheduler(config)
self._add_nightly_scheduler(config)
self._add_mail_status(config)
parent_trigger = self.get_parent_of_type(Trigger)
if parent_trigger is not None:
parent_trigger.add_builder(self.get_interpolated('builder_name'))
def _add_single_branch_scheduler(self, config):
if self._accept_regex is None:
return
builder_name = self.get_interpolated('builder_name')
project_name = self.get_interpolated('project_name')
args = {
'filter_fn': _ChangeFilter(builder_name, project_name,
self.interpolate(self._accept_regex),
self.interpolate(self._reject_regex))
}
change_filter = self._build_class(buildbot.changes.filter.ChangeFilter,
'change_filter',
additional=args)
args = {'name' : '%s single branch scheduler' % builder_name,
'builderNames' : [builder_name],
'change_filter' : change_filter,
'reason' : 'A CL Triggered this build'}
scheduler_class = buildbot.schedulers.basic.SingleBranchScheduler
scheduler = self._build_class(scheduler_class,
('scheduler', 'branch_scheduler'),
additional=args)
config.buildbot_config['schedulers'].append(scheduler)
def _add_nightly_scheduler(self, config):
if self._nightly is None:
return
builder_name = self.get_interpolated('builder_name')
args = {'name' : '%s nightly scheduler' % builder_name,
'builderNames' : [builder_name],
'branch' : None} #We don't use branches the way buildbot expects it
for key, value in self._nightly.iteritems():
if value is not None:
args[key] = value
scheduler_class = buildbot.schedulers.timed.Nightly
scheduler = self._build_class(scheduler_class,
'scheduler',
additional=args)
config.buildbot_config['schedulers'].append(scheduler)
def _add_mail_status(self, config):
extra_recipients = self.get_interpolated('mail_extraRecipients')
send_mail = self.get_interpolated('mail_sendToInterestedUsers')
if extra_recipients or send_mail:
formatter = self.get('_mail_message_formatter')
if formatter is None:
formatter = _HtmlMailFormatter(self)
args = {'messageFormatter': formatter,
'builders': [self.get_interpolated('builder_name')]}
mail_status = self._build_class(buildbot.status.mail.MailNotifier,
'mail',
additional=args)
config.buildbot_config['status'].append(mail_status)
class Repository(Scope):
''' Change source base scope '''
def __init__(self, name, is_polling_enabled):
super(Repository, self).__init__()
self.name = name
self.is_polling_enabled = is_polling_enabled
Scope.update('source_control_repositories', name, self)
@staticmethod
def config(poll_interval=None,
poll_at_launch=None,
hitsmax=None):
''' Common change source parameters '''
Scope.set_checked('change_source_pollInterval', poll_interval, int)
Scope.set_checked('change_source_pollAtLaunch', poll_at_launch, bool)
Scope.set_checked('change_source_hitsmax', hitsmax, int)
@abc.abstractmethod
def get_sync_step(self, config, step_args):
''' Returns a step to sync this repository '''
@abc.abstractmethod
def _build_change_sources(self, config, args):
''' Creates a ChangeSource for this repository '''
def _build(self, config):
if not self.is_polling_enabled:
return
args = self._get_prefixed_properties('change_source')
for change_source in self._build_change_sources(config, args):
# XXX: this attribute works around a bug in buildbot that would
# cause it to only trigger rebuilds for the first project using
# that source
change_source.compare_attrs.append('project')
config.buildbot_config['change_source'].append(change_source)
class P4StreamSource(buildbot.changes.p4poller.P4Source):
def __init__(self, **args):
self._stream = None
super(P4StreamSource, self).__init__(**args)
@defer.inlineCallbacks
#pylint: disable=invalid-name,missing-docstring
def _get_process_output(self, args):
base_get_process_output = super(P4StreamSource, self)._get_process_output
# If action is not 'p4 changes', use the original function
if 'changes' not in args:
tmp = yield base_get_process_output(args)
defer.returnValue(tmp)
# Last argument is the location we're polling
location, suffix = args[-1], ""
if '...' in location:
n = location.index('...')
location, suffix = location[:n], location[n:]
if self._stream:
location = self._stream
client = re.sub('[^a-zA-Z0-9]+', '-', 'poll-' + location).lower()
# All arguments before changes are P4 options
argc = args.index('changes')
baseargs = args[:argc]
# Check whether the location is a stream; otherwise, bail out
tmp = yield base_get_process_output(baseargs + ['streams'])
if 'Stream %s ' % location not in tmp:
tmp = yield base_get_process_output(args)
defer.returnValue(tmp)
# Force p4base to be // in order to catch all changes to this client
self._stream = location
self.p4base = '//'
# Check that our client references the stream
tmp = yield base_get_process_output(baseargs + ['client', '-o', client])
if 'Stream:\t%s' % location not in tmp:
# Ensure the client exists
p4clientcmd = '%s %s client' % (self.p4bin, ' '.join(baseargs))
shargs = '%s -o %s | %s -i' % (p4clientcmd, client, p4clientcmd)
tmp = yield utils.getProcessOutput('/bin/sh', ['-c', shargs])
# Force switch the client stream
tmp = yield base_get_process_output(baseargs + ['client', '-f', '-s', '-S', location, client])
tmp = yield base_get_process_output(['-c', client] + args[:-1] + ['//%s%s' % (client, suffix)])
defer.returnValue(tmp)
class P4Repository(Repository):
''' P4Repository handling '''
def __init__(self, name, is_polling_enabled):
super(P4Repository, self).__init__(name, is_polling_enabled)
@staticmethod
def config(port=None, user=None, password=None, client=None,
binary=None, encoding=None, timezone=None, spec_options=None):
''' Common global p4 parameters '''
# TODO : Add ticket management
Scope.set_checked('p4_common_p4port', port, str)
Scope.set_checked('p4_common_p4user', user, str)
Scope.set_checked('p4_common_p4passwd', password, str)
Scope.set_checked('p4_sync_p4client_spec_options', spec_options, str)
Scope.set_checked('p4_sync_p4client', client, str)
Scope.set_checked('p4_poll_p4bin', binary, str)
Scope.set_checked('p4_poll_encoding', encoding, str)
Scope.set_checked('p4_poll_server_tz', timezone, None)
@staticmethod
def add_views(*views):
''' Adds p4 mappings for current scope '''
Scope.append('p4_sync_p4viewspec', *views)
@staticmethod
def set_stream(stream):
''' Adds p4 stream for current scope '''
Scope.append('_p4stream', stream)
# Hack the “View” entry. The view will be invalid, but it will be
# overridden by the “Stream” entry that we insert.
# See master/buildbot/steps/source/p4.py in the buildbot sources
# to understand why it works.
Scope.append('p4_sync_p4viewspec',
('//ignored/', '...\n\nStream: ' + stream + '\n\n#'))
def get_sync_step(self, _, step_args):
''' Returns sync step for this repository '''
return self._build_class(buildbot.steps.source.p4.P4,
('p4_common', 'p4_sync'),
rendered=['p4_sync_p4client'],
additional=step_args)
def _build_change_sources(self, config, args):
paths_to_poll = []
for (depot_path, _) in self.get('p4_sync_p4viewspec', []):
if depot_path.startswith('//'):
# Get depot from //depot/
base = depot_path[2:-1]
paths_to_poll.append(base)
for base in paths_to_poll:
split_file = lambda branchfile: (None, branchfile)
args['split_file'] = split_file
args['p4base'] = '//' + base
project_name = self.get_interpolated('project_name')
if project_name is not None:
args['project'] = project_name
p4 = self._build_class(P4StreamSource,
('p4_common', 'p4_poll'),
additional=args)
yield p4
class GitRepository(Repository):
''' Git repository '''
def __init__(self, name, repo_url, is_polling_enabled):
super(GitRepository, self).__init__(name, is_polling_enabled)
Scope.set_checked('git_common_repourl', repo_url, str)
@staticmethod
def config(git_bin=None,
use_time_stamps=None,
encoding=None,
branch=None,
submodules=True,
shallow=None,
progress=None,
retry_fetch=None,
clobber_on_failure=None,
method=None):
''' Common global git parameters '''
Scope.set_checked('git_poll_gitbin', git_bin, str)
Scope.set_checked('get_poll_usetimestamps', use_time_stamps, bool)
Scope.set_checked('git_poll_encoding', encoding, str)
Scope.set_checked('git_common_branch', branch, str)
Scope.set_checked('git_sync_submodules', submodules, bool)
Scope.set_checked('git_sync_shallow', shallow, bool)
Scope.set_checked('git_sync_progress', progress, bool)
Scope.set_checked('git_sync_retryFetch', retry_fetch, bool)
Scope.set_checked('git_sync_clobberOnFailure', clobber_on_failure, bool)
Scope.set_checked('git_sync_method', method, str)
assert method in [None, 'clobber', 'fresh', 'clean', 'copy']
def get_sync_step(self, _, step_args):
''' Returns sync step for this repository '''
return self._build_class(buildbot.steps.source.git.Git,
('git_common', 'git_sync'),
additional=step_args)
def _build_change_sources(self, config, args):
project_name = self.get_interpolated('project_name')
if project_name is not None:
args['project'] = project_name
yield self._build_class(buildbot.changes.gitpoller.GitPoller,
('git_common', 'git_poll'),
additional=args)
class Step(Scope):
''' Build step '''
def __init__(self, name):
super(Step, self).__init__()
self.properties['step_name'] = name
@staticmethod
def config(halt_on_failure=None,
flunk_on_warnings=None,
flunk_on_failure=None,
warn_on_warnings=None,
warn_on_failure=None,
always_run=None,