-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildServ.pl
3146 lines (2849 loc) · 121 KB
/
buildServ.pl
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
#!/usr/bin/perl -w
#
# [SpringRTS](http://springrts.com/) lobby bot implementing an automated build
# service for the engine through lobby commands.
# When installing this application on a new server, you need to adapt the
# parameterization constants found in the beginning of this file.
#
# Copyright (C) 2008-2011,2013 Yann Riou <[email protected]>
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
use strict;
use POSIX ":sys_wait_h";
use IO::Select;
use File::Copy;
use File::Basename;
use SimpleLog;
use BuildServConf;
use SpringLobbyInterface;
use CGI;
$SIG{TERM} = \&sigTermHandler;
my $buildServVer='0.2';
my %buildServHandlers = (
defineprofile => \&hDefineProfile,
disable => \&hDisable,
enable => \&hEnable,
help => \&hHelp,
helpall => \&hHelpAll,
history => \&hHistory,
listprofiles => \&hListProfiles,
notify => \&hNotify,
pending => \&hPending,
quit => \&hQuit,
rebuild => \&hRebuild,
restart => \&hRestart,
setuploadrate => \&hSetUploadRate,
translate => \&hTranslate,
version => \&hVersion
);
my %targets = (scons => ["game/spring.exe",
"game/unitsync.dll",
"game/ArchiveMover.exe",
"game/AI/Bot-libs/NTai.dll",
"game/AI/Bot-libs/TestGlobalAI.dll",
"game/AI/Bot-libs/KAI-0.2.dll",
"game/AI/Bot-libs/KAIK-0.13.dll",
"game/AI/Bot-libs/JCAI.dll",
"game/AI/Bot-libs/AAI.dll",
"game/AI/Bot-libs/RAI.dll",
"game/AI/Helper-libs/CentralBuildAI.dll",
"game/AI/Helper-libs/EconomyAI.dll",
"game/AI/Helper-libs/MetalMakerAI.dll",
"game/AI/Helper-libs/MexUpgraderAI.dll",
"game/AI/Helper-libs/RadarAI.dll",
"game/AI/Helper-libs/ReportIdleAI.dll",
"game/AI/Helper-libs/SimpleFormationAI.dll",
"game/AI/Interfaces/C/0.1/AIInterface.dll",
"game/AI/Interfaces/Java/0.1/AIInterface.dll",
"game/AI/Skirmish/AAI/0.875/SkirmishAI.dll",
"game/AI/Skirmish/AAI/0.9/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/1.34/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/2.11/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/2.13.5/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.8.2/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.13.1/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.18.1/SkirmishAI.dll",
"game/AI/Skirmish/KAIK/0.13/SkirmishAI.dll",
"game/AI/Skirmish/NTai/XE9.81/SkirmishAI.dll",
"game/AI/Skirmish/NullAI/0.1/SkirmishAI.dll",
"game/AI/Skirmish/NullLegacyCppAI/0.1/SkirmishAI.dll",
"game/AI/Skirmish/RAI/0.601/SkirmishAI.dll"],
cmake => ["game/spring.exe",
"game/spring-dedicated.exe",
"game/unitsync.dll",
"game/springserver.dll",
"game/ArchiveMover.exe",
"game/AI/Bot-libs/NTai.dll",
"game/AI/Bot-libs/TestGlobalAI.dll",
"game/AI/Bot-libs/KAI-0.2.dll",
"game/AI/Bot-libs/KAIK-0.13.dll",
"game/AI/Bot-libs/JCAI.dll",
"game/AI/Bot-libs/AAI.dll",
"game/AI/Bot-libs/RAI.dll",
"game/AI/Helper-libs/CentralBuildAI.dll",
"game/AI/Helper-libs/EconomyAI.dll",
"game/AI/Helper-libs/MetalMakerAI.dll",
"game/AI/Helper-libs/MexUpgraderAI.dll",
"game/AI/Helper-libs/RadarAI.dll",
"game/AI/Helper-libs/ReportIdleAI.dll",
"game/AI/Helper-libs/SimpleFormationAI.dll",
"game/AI/Interfaces/C/0.1/AIInterface.dll",
"game/AI/Interfaces/Java/0.1/AIInterface.dll",
"game/AI/Skirmish/AAI/0.875/SkirmishAI.dll",
"game/AI/Skirmish/AAI/0.9/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/1.34/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/2.11/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/2.13.5/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.8.2/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.13.1/SkirmishAI.dll",
"game/AI/Skirmish/E323AI/3.18.1/SkirmishAI.dll",
"game/AI/Skirmish/KAIK/0.13/SkirmishAI.dll",
"game/AI/Skirmish/NTai/XE9.81/SkirmishAI.dll",
"game/AI/Skirmish/NullAI/0.1/SkirmishAI.dll",
"game/AI/Skirmish/NullLegacyCppAI/0.1/SkirmishAI.dll",
"game/AI/Skirmish/RAI/0.601/SkirmishAI.dll"]);
my $baseSite='buildbot';
my $baseUrl='http://buildbot.eat-peet.net';
my $srcDir="/home/buildserv/spring/src";
my $installDir="/home/buildserv/spring/install";
my $unixUser='buildserv';
my $bsVarDir='/var/ftp/BuildServ/var';
my $spadsGitDir='/var/ftp/BuildServ';
my %defaults = (vcs => "git",
toolchain => "mingw32",
buildsys => "cmake",
profile => "default",
rev => "HEAD");
my $defaultRepoName=buildRepositoryName(\%defaults);
my $defaultRepo="$srcDir/$defaultRepoName";
my $masterGitRepo="$srcDir/git.master";
#my $linkColor='12';
#my $errorColor='4';
my $linkColor=' ->';
my $errorColor=' ->';
my %validBuildFlags=(scons => [qw/gml gmlsim debug debugdefines syncdebug synccheck synctrace optimize profile profile_generate profile_use fpmath use_tcmalloc use_mmgr use_gch dc_allowed arch use_nedmalloc/],
cmake => [qw/SYNCCHECK DIRECT_CONTROL NO_AVI MARCH_FLAG CMAKE_BUILD_TYPE USE_NEDMALLOC USE_GML USE_GML_SIM USE_GML_DEBUG USE_MMGR TRACE_SYNC SYNCDEBUG AI_EXCLUDE_REGEX AI_TYPES/]);
my $speedLimit=110000;
# Basic checks ################################################################
if($#ARGV < 0 || ! (-f $ARGV[0]) || $#ARGV > 1) {
print "usage: $0 <configurationFile>\n";
exit 1;
}
my $confFile=$ARGV[0];
my $sLog=SimpleLog->new(prefix => "[BuildServ] ");
my $buildServ=BuildServConf->new($confFile,$sLog);
sub slog {
$sLog->log(@_);
}
if(! $buildServ) {
slog("Unable to load BuildServ configuration at startup",0);
exit 1;
}
# State variables #############################################################
my %conf=%{$buildServ->{conf}};
my $lSock;
my @sockets=();
my $running=1;
my $quitAfterBuild=0;
my %timestamps=(connectAttempt => 0,
ping => 0,
pong => 0,
repoCheck => 0,
status => 0);
my %tsBroadcastChan;
if($#ARGV) {
if($conf{broadcastChannels}) {
my @broadcastChans=split(/;/,$conf{broadcastChannels});
foreach my $chan (@broadcastChans) {
$tsBroadcastChan{$chan}=time;
}
}
}
my $lobbyState=0; # (0:not_connected, 1:connecting, 2: connected, 3:logged_in, 4:start_data_received)
my $p_answerFunction;
my %lastSentMessages;
my @messageQueue=();
my @lowPriorityMessageQueue=();
my %lastCmds;
my %ignoredUsers;
my %currentRevision=(rev => "Unknown",
author => "Unknown",
date => "Unknown");
my %availableRevision=(rev => "Unknown",
author => "Unknown",
date => "Unknown");
my $buildPid=0;
my $translatePid=0;
my $checkMainRepoPid=0;
my $updatingForRebuild=0;
my $mainRepoCheckedDuringRebuild=0;
my %rebuildParams;
my $rebuildParamsString;
my %buildProfiles;
my $newRevAvailableInTopic=0;
my $rebuildEnabled=0;
my %notifs=(rebuild => {},
translate => {});
my $lobbySimpleLog=SimpleLog->new(logFiles => [$conf{logDir}."/buildServ.log"],
logLevels => [$conf{lobbyInterfaceLogLevel}],
useANSICodes => [0],
useTimestamps => [1],
prefix => "[SpringLobbyInterface] ");
my $lobby = SpringLobbyInterface->new(serverHost => $conf{lobbyHost},
serverPort => $conf{lobbyPort},
simpleLog => $lobbySimpleLog,
warnForUnhandledMessages => 0);
$SIG{CHLD}="";
$ENV{LANG}="C";
loadProfiles(\%buildProfiles);
loadRevisionInfo(\%currentRevision);
my $tmpString;
fetchMasterGitRepo() if($defaults{vcs} eq "git");
readAvailableRev();
$timestamps{repoCheck}=time;
$SIG{CHLD} = \&sigChldHandler;
my $silentRestart=0;
# Subfunctions ################################################################
sub sigTermHandler {
quitAfterBuild("SIGTERM signal received");
}
sub sigChldHandler {
my $childPid;
while ($childPid = waitpid(-1,WNOHANG)) {
last if($childPid == -1);
my $rc=$?;
if($childPid == $buildPid) {
$buildPid=0;
foreach my $notifiedUser (keys %{$notifs{rebuild}}) {
sayPrivate($notifiedUser,"***** Notification (end of build process) *****");
}
$notifs{rebuild}={};
$updatingForRebuild=0;
my $repoName = buildRepositoryName(\%rebuildParams);
if(! $rc && $repoName eq $defaultRepoName && $rebuildParams{upload} eq "yes") {
if($mainRepoCheckedDuringRebuild) {
# slog("Skipping readAvailableRevFromRebuild because main repo has been checked during rebuild",3);
}elsif($rebuildParams{rev} eq "CURRENT") {
# slog("Skipping readAvailableRevFromRebuild because main repo hasn't been updated for rebuild (rev=CURRENT)",3);
}else{
# slog("Reading available rev from rebuild (main repo hasn't been checked during rebuild)",3);
readAvailableRevFromRebuild();
}
my %newRevision=(rev => "Unknown");
loadRevisionInfo(\%newRevision);
if($newRevision{rev} ne "Unknown" && $newRevision{rev} ne $currentRevision{rev}) {
loadRevisionInfo(\%currentRevision);
setTopic();
if($conf{broadcastChannels}) {
my @broadcastChans=split(/;/,$conf{broadcastChannels});
foreach my $chan (@broadcastChans) {
printRevInfo($chan) unless($chan eq $conf{masterChannel} || $chan eq "sy");
}
}
}
}
}elsif($childPid == $translatePid) {
$translatePid=0;
foreach my $notifiedUser (keys %{$notifs{translate}}) {
sayPrivate($notifiedUser,"***** Notification (end of translate process) *****");
}
$notifs{translate}={};
}elsif($childPid == $checkMainRepoPid) {
$checkMainRepoPid=0;
checkMainRepoCallback();
}
}
$SIG{CHLD} = \&sigChldHandler;
}
sub forkedError {
my ($msg,$level)=@_;
slog($msg,$level);
exit 1;
}
sub setStatus {
return if(time - $timestamps{status} < 2);
if($lobbyState > 3) {
my %clientStatus = %{$lobby->{users}->{$conf{lobbyLogin}}->{status}};
my $inGameTarget=0;
$inGameTarget=1 if($buildPid || $translatePid || $checkMainRepoPid);
my $awayTarget=0;
$awayTarget=1 unless($currentRevision{rev} ne "Unknown" && $availableRevision{rev} ne "Unknown"
&& (($defaults{vcs} eq "svn" && $currentRevision{rev} < $availableRevision{rev})
|| ($defaults{vcs} eq "git" && $currentRevision{rev} ne $availableRevision{rev})));
if($clientStatus{inGame} != $inGameTarget || $clientStatus{away} != $awayTarget) {
$timestamps{status}=time;
$clientStatus{inGame}=$inGameTarget;
$clientStatus{away}=$awayTarget;
queueLobbyCommand(["MYSTATUS",$lobby->marshallClientStatus(\%clientStatus)]);
}
}
}
sub saveRevisionInfo {
my $p_revInfo=shift;
my %revInfo=%{$p_revInfo};
if(%revInfo) {
if(! open(REVINFO,">$conf{varDir}/currentRevision.txt")) {
slog("Unable to write current revision informations to $conf{varDir}/currentRevision.txt",1);
return;
}
foreach my $revDataName (keys %revInfo) {
print REVINFO "$revDataName:$revInfo{$revDataName}\n";
}
close(REVINFO);
}else{
slog("Unable to write current revision informations: nothing to write !",2);
}
}
sub loadRevisionInfo {
my $p_revInfo=shift;
if(! open(REVINFO,"<$conf{varDir}/currentRevision.txt")) {
slog("Unable to read current revision informations from $conf{varDir}/currentRevision.txt",1);
return;
}
while(<REVINFO>) {
if(/^(\w+):(.*)$/) {
$p_revInfo->{$1}=$2;
}
}
close(REVINFO);
}
sub saveProfiles {
my $p_profiles=shift;
my %profiles=%{$p_profiles};
if(%profiles) {
if(! open(PROFILES,">$conf{varDir}/buildProfiles.txt")) {
slog("Unable to write build profiles to $conf{varDir}/buildProfiles.txt",1);
return;
}
foreach my $buildsys (keys %profiles) {
print PROFILES "[$buildsys]\n";
foreach my $profile (keys %{$profiles{$buildsys}}) {
my $flagsString=buildFlagsString($profiles{$buildsys}->{$profile});
print PROFILES "$profile:$flagsString\n";
}
}
close(PROFILES);
}else{
slog("Unable to write build profiles: nothing to write !",2);
}
}
sub loadProfiles {
my $p_profiles=shift;
my $buildsys="";
if(! open(PROFILES,"<$conf{varDir}/buildProfiles.txt")) {
slog("Unable to read build profiles from $conf{varDir}/buildProfiles.txt",1);
return;
}
while(<PROFILES>) {
if(/^\[(\w+)\]/) {
$buildsys=$1;
$p_profiles->{$buildsys}={};
next;
}
if(/^(\w+):(.*)$/) {
my $profile=$1;
my @flagStrings=split(/ /,$2);
my %flags;
foreach my $flagString (@flagStrings) {
if($flagString =~ /^(\w+)=([\w\.\|\"\*]+)$/) {
my $flag=$1;
my $value=$2;
if(grep(/^$flag$/,@{$validBuildFlags{$buildsys}})) {
$flags{$flag}=$value;
}else{
slog("Invalid flag \"$flag\"",1);
exit;
}
}else{
slog("Invalid flag string \"$flagString\"",1);
exit;
}
}
$p_profiles->{$buildsys}->{$profile}=\%flags;
}
}
close(PROFILES);
foreach $buildsys (keys %{$p_profiles}) {
slog("Invalid build profiles definition: default profile missing",1) if(! exists $p_profiles->{$buildsys}->{default});
}
}
sub storeSvnRevisionInfo {
my ($svnInfoOutput,$p_hash)=@_;
if($svnInfoOutput =~ /Last Changed Rev\s*:\s*(\d+)\n/) {
$p_hash->{rev}=$1;
}
if($svnInfoOutput =~ /Last Changed Author\s*:\s*(\w+)\n/) {
$p_hash->{author}=$1;
}
if($svnInfoOutput =~ /Last Changed Date\s*:\s*([\d\-\:\+ ]+) \(/) {
$p_hash->{date}=$1;
}
}
sub storeGitRevisionInfo {
my ($gitInfoOutput,$p_hash)=@_;
my @gitInfo=split("\n",$gitInfoOutput);
$p_hash->{rev}=$gitInfo[0];
$p_hash->{author}=$gitInfo[1];
$p_hash->{date}=$gitInfo[2];
}
sub buildFlagsString {
my ($p_flags,$buildsys)=@_;
my $flagPrefix="";
$flagPrefix="-D" if(defined $buildsys && $buildsys eq "cmake");
my %flags=%{$p_flags};
my @flagsStrings;
foreach my $flag (keys %flags) {
push(@flagsStrings,"$flagPrefix$flag=$flags{$flag}");
}
my $flagsString=join(" ",@flagsStrings);
return $flagsString;
}
sub fetchMasterGitRepo {
return unless(-d $masterGitRepo);
chdir($masterGitRepo);
system("git fetch --tags");
system("git fetch");
}
sub readAvailableRev {
if($defaults{vcs} eq "svn" && -d $defaultRepo) {
chdir($defaultRepo);
$tmpString=`svn info -r HEAD`;
storeSvnRevisionInfo($tmpString,\%availableRevision);
}elsif($defaults{vcs} eq "git" && -d $masterGitRepo) {
chdir($masterGitRepo);
$tmpString=`git describe --tags --long origin/master; git-rev-list --max-count=1 --pretty=format:"%an%n%ci" origin/master | grep -v ^commit`;
storeGitRevisionInfo($tmpString,\%availableRevision);
}
}
sub readAvailableRevFromRebuild {
return unless(-d $defaultRepo);
chdir($defaultRepo);
if($defaults{vcs} eq "svn") {
$tmpString=`svn info`;
storeSvnRevisionInfo($tmpString,\%availableRevision);
}elsif($defaults{vcs} eq "git") {
$tmpString=`git describe --tags --long; git-rev-list --max-count=1 --pretty=format:"%an%n%ci" HEAD | grep -v ^commit`;
storeGitRevisionInfo($tmpString,\%availableRevision);
}
}
sub checkMainRepo {
$timestamps{repoCheck}=time;
if($updatingForRebuild) {
slog("checkMainRepo: Cancelling check repository operation (update for rebuild in progress)",2);
return;
}
if($defaults{vcs} eq "git") {
if($checkMainRepoPid) {
# slog("checkMainRepo: Cancelling fetch operation (previous call didn't finish yet)",2);
return;
}
return unless(-d $masterGitRepo);
$checkMainRepoPid = fork();
return if($checkMainRepoPid);
fetchMasterGitRepo();
exit 0;
}elsif($defaults{vcs} eq "svn") {
return unless(-d $defaultRepo);
checkMainRepoCallback();
}
}
sub checkMainRepoCallback {
$mainRepoCheckedDuringRebuild=1;
my $availableRev=$availableRevision{rev};
readAvailableRev();
if($availableRevision{rev} ne $availableRev && $availableRevision{rev} ne "Unknown"
&& (($defaults{vcs} eq "svn" && ($currentRevision{rev} eq "Unknown" || $currentRevision{rev} < $availableRevision{rev}))
|| ($defaults{vcs} eq "git" && $currentRevision{rev} ne $availableRevision{rev}))) {
if($conf{broadcastChannels}) {
my @broadcastChans=split(/;/,$conf{broadcastChannels});
foreach my $chan (@broadcastChans) {
next if($chan eq "sy");
my $buildChanInfo="in \#$conf{masterChannel} ";
$buildChanInfo="" if($chan eq $conf{masterChannel});
sayChan($chan,"New trunk revision available (hit \"!rebuild\" ${buildChanInfo}to build it): $availableRevision{rev} (committed by $availableRevision{author} on $availableRevision{date})") if($rebuildEnabled);
}
}
setTopic() unless($newRevAvailableInTopic);
}
}
sub printRevInfo {
my $chan=shift;
$chan=$conf{masterChannel} unless(defined $chan);
if($currentRevision{rev} ne "Unknown") {
$tsBroadcastChan{$chan}=time;
sayChan($chan,"Latest trunk build uploaded: $currentRevision{rev} (committed by $currentRevision{author} on $currentRevision{date})");
my $uploadedRev=$currentRevision{rev};
$uploadedRev="R$uploadedRev" if($uploadedRev =~ /^\d{1,4}$/);
sayChan($chan," Executable: $baseUrl/spring/executable/spring_exe_$uploadedRev.zip");
sayChan($chan," Base files: $baseUrl/spring/base/spring_base_$uploadedRev.tar");
sayChan($chan," Unitsync: $baseUrl/spring/unitsync/unitsync_$uploadedRev.zip");
sayChan($chan," Debug symbols: $baseUrl/spring/debug/spring_dbg_$uploadedRev.7z");
sayChan($chan," Installer: $baseUrl/spring/installer/$currentRevision{installer}");
}
if($currentRevision{rev} ne "Unknown" && $availableRevision{rev} ne "Unknown") {
if(($defaults{vcs} eq "svn" && $currentRevision{rev} < $availableRevision{rev})
|| ($defaults{vcs} eq "git" && $currentRevision{rev} ne $availableRevision{rev})) {
my $buildChanInfo="in \#$conf{masterChannel} ";
$buildChanInfo="" if($chan eq $conf{masterChannel});
sayChan($chan,"New trunk revision available (hit \"!rebuild\" ${buildChanInfo}to build it): $availableRevision{rev} (committed by $availableRevision{author} on $availableRevision{date})");
}else{
sayChan($chan,"This is the latest trunk revision available on $defaults{vcs} repository.");
}
}
}
sub setTopic {
my $uploadedRev=$currentRevision{rev};
$uploadedRev="R$uploadedRev" if($uploadedRev =~ /^\d{1,4}$/);
my $topic="Hi, welcome to BuildServ (automated build bot). For help, hit \"!help\".\\nLatest trunk build uploaded: $currentRevision{rev} (committed by $currentRevision{author} on $currentRevision{date})\\n Executable: $baseUrl/spring/executable/spring_exe_$uploadedRev.zip\\n Base files: $baseUrl/spring/base/spring_base_$uploadedRev.tar\\n Unitsync: $baseUrl/spring/unitsync/unitsync_$uploadedRev.zip\\n Debug symbols: $baseUrl/spring/debug/spring_dbg_$uploadedRev.7z\\n Installer: $baseUrl/spring/installer/$currentRevision{installer}";
if($currentRevision{rev} ne "Unknown" && $availableRevision{rev} ne "Unknown") {
if(($defaults{vcs} eq "svn" && $currentRevision{rev} < $availableRevision{rev})
|| ($defaults{vcs} eq "git" && $currentRevision{rev} ne $availableRevision{rev})) {
$newRevAvailableInTopic=1;
$topic.="\\nNew trunk revision available (hit \"!rebuild\" to build it)";
}else{
$newRevAvailableInTopic=0;
$topic.="\\nThis is the latest trunk revision available on $defaults{vcs} repository.";
}
}
$tsBroadcastChan{$conf{masterChannel}}=time;
# BuildServ is no longer the default buildbot for SpringRTS
# sayPrivate("ChanServ","!topic #$conf{masterChannel} $topic");
}
sub uploadErrorFile {
my ($errFile,$repo)=@_;
return unless(-f $errFile && -s $errFile);
sayChan($conf{masterChannel},"Uploading STDERR messages ...");
anonFile($errFile,"");
my $output=`lftp $baseSite -e "set net:limit-total-rate $speedLimit;put $errFile -o spring/errors/$errFile;quit"`;
if($output =~ /(\d\d+ bytes transferred(?: in \d+ seconds? \(\d[^\)]+\))?)/) {
sayChan($conf{masterChannel}," [OK] $1");
sayChan($conf{masterChannel}," $errorColor $baseUrl/spring/errors/$errFile");
}else{
print "output=\"$output\"\n";
sayChan($conf{masterChannel}," [ERROR] Unable to check transfer status");
}
}
sub anonFile {
my ($file,$repo)=@_;
my $quotedRepo=quotemeta($repo);
my $alternateRepo=$quotedRepo;
$alternateRepo=~s/mingw32/windows/g;
if(open(IN,"<$file")) {
if(open(OUT,">$file.tmp")) {
while(<IN>) {
s/\/$unixUser//g;
s/$quotedRepo\///g if($quotedRepo);
s/$alternateRepo\///g if($alternateRepo);
print OUT $_;
}
close(OUT);
}
close(IN);
}
if(-f "$file.tmp") {
move("$file.tmp","$file");
}
}
sub getCpuSpeed {
if(-f "/proc/cpuinfo" && -r "/proc/cpuinfo") {
my @cpuInfo=`cat /proc/cpuinfo 2>/dev/null`;
my %cpu;
foreach my $line (@cpuInfo) {
if($line =~ /^([\w\s]*\w)\s*:\s*(.*)$/) {
$cpu{$1}=$2;
}
}
if(defined $cpu{"model name"} && $cpu{"model name"} =~ /(\d+)\+/) {
return $1;
}
if(defined $cpu{"cpu MHz"} && $cpu{"cpu MHz"} =~ /^(\d+)(?:\.\d*)?$/) {
return $1;
}
if(defined $cpu{bogomips} && $cpu{bogomips} =~ /^(\d+)(?:\.\d*)?$/) {
return $1;
}
slog("Unable to parse CPU info from /proc/cpuinfo",2);
return 0;
}else{
slog("Unable to retrieve CPU info from /proc/cpuinfo",2);
return 0;
}
}
sub getLocalLanIp {
my @ifConfOut=`/sbin/ifconfig`;
foreach my $line (@ifConfOut) {
next unless($line =~ /inet addr:\s*(\d+\.\d+\.\d+\.\d+)\s/);
my $ip=$1;
if($ip =~ /^10\./ || $ip =~ /192\.168\./) {
slog("Following local LAN IP address detected: $ip",4);
return $ip;
}
if($ip =~ /^172\.(\d+)\./) {
if($1 > 15 && $1 < 32) {
slog("Following local LAN IP address detected: $ip",4);
return $ip;
}
}
}
slog("No local LAN IP address found",4);
return "*";
}
sub quitAfterBuild {
my $reason=shift;
$quitAfterBuild=1;
my $msg="Bot shutdown scheduled (reason: $reason)";
broadcastMsg($msg);
slog($msg,3);
}
sub restartAfterBuild {
my ($reason,$broadcast)=@_;
$quitAfterBuild=2;
my $msg="Bot restart scheduled (reason: $reason)";
broadcastMsg($msg) if($broadcast);
slog($msg,3);
}
sub computeMessageSize {
my $p_msg=shift;
my $size=0;
{
use bytes;
foreach my $word (@{$p_msg}) {
$size+=length($word)+1;
}
}
return $size;
}
sub checkLastSentMessages {
my $sent=0;
foreach my $timestamp (keys %lastSentMessages) {
if(time - $timestamp > $conf{sendRecordPeriod}) {
delete $lastSentMessages{$timestamp};
}else{
foreach my $msgSize (@{$lastSentMessages{$timestamp}}) {
$sent+=$msgSize;
}
}
}
return $sent;
}
sub queueLobbyCommand {
my @params=@_;
if($params[0]->[0] =~ /SAYPRIVATE/) {
if(@lowPriorityMessageQueue) {
push(@lowPriorityMessageQueue,\@params);
}else{
my $alreadySent=checkLastSentMessages();
my $toBeSent=computeMessageSize($params[0]);
if($alreadySent+$toBeSent+5 >= $conf{maxLowPrioBytesSent}) {
slog("Output flood protection: queueing low priority message(s)",3);
push(@lowPriorityMessageQueue,\@params);
}else{
sendLobbyCommand(\@params,$toBeSent);
}
}
}elsif(@messageQueue) {
push(@messageQueue,\@params);
}else{
my $alreadySent=checkLastSentMessages();
my $toBeSent=computeMessageSize($params[0]);
if($alreadySent+$toBeSent+5 >= $conf{maxBytesSent}) {
slog("Output flood protection: queueing message(s)",2);
push(@messageQueue,\@params);
}else{
sendLobbyCommand(\@params,$toBeSent);
}
}
}
sub sendLobbyCommand {
my ($p_params,$size)=@_;
$size=computeMessageSize($p_params->[0]) unless(defined $size);
my $timestamp=time;
$lastSentMessages{$timestamp}=[] unless(exists $lastSentMessages{$timestamp});
push(@{$lastSentMessages{$timestamp}},$size);
$lobby->sendCommand(@{$p_params});
}
sub checkQueuedLobbyCommands {
return unless($lobbyState > 1 && (@messageQueue || @lowPriorityMessageQueue));
my $alreadySent=checkLastSentMessages();
while(@messageQueue) {
my $toBeSent=computeMessageSize($messageQueue[0]->[0]);
last if($alreadySent+$toBeSent+5 >= $conf{maxBytesSent});
my $p_command=shift(@messageQueue);
sendLobbyCommand($p_command,$toBeSent);
$alreadySent+=$toBeSent;
}
while(@lowPriorityMessageQueue) {
my $toBeSent=computeMessageSize($lowPriorityMessageQueue[0]->[0]);
last if($alreadySent+$toBeSent+5 >= $conf{maxLowPrioBytesSent});
my $p_command=shift(@lowPriorityMessageQueue);
sendLobbyCommand($p_command,$toBeSent);
$alreadySent+=$toBeSent;
}
}
sub answer {
my $msg=shift;
&{$p_answerFunction}($msg);
}
sub broadcastMsg {
my $msg=shift;
sayChan($conf{masterChannel},$msg) if($lobbyState >= 4 && (exists $lobby->{channels}->{$conf{masterChannel}}));
}
sub splitMsg {
my ($longMsg,$maxSize)=@_;
my @messages=($longMsg =~ /.{1,$maxSize}/gs);
return \@messages;
}
sub sayPrivate {
my ($user,$msg)=@_;
my $p_messages=splitMsg($msg,$conf{maxChatMessageLength}-1);
foreach my $mes (@{$p_messages}) {
queueLobbyCommand(["SAYPRIVATE",$user,$mes]);
logMsg("pv_$user","<$conf{lobbyLogin}> $mes") if($conf{logPvChat});
}
}
sub sayChan {
my ($chan,$msg)=@_;
my $p_messages=splitMsg($msg,$conf{maxChatMessageLength}-3);
foreach my $mes (@{$p_messages}) {
queueLobbyCommand(["SAYEX",$chan,"* $mes"]);
}
}
sub getCommandLevels {
my ($source,$user,$cmd)=@_;
my $gameState="stopped";
my $status="outside";
return $buildServ->getCommandLevels($cmd,$source,$status,$gameState);
}
sub getUserAccessLevel {
my $user=shift;
my $p_userData;
if(! exists $lobby->{users}->{$user}) {
return 0;
}else{
$p_userData=$lobby->{users}->{$user};
}
return $buildServ->getUserAccessLevel($user,$p_userData);
}
sub handleRequest {
my ($source,$user,$command)=@_;
my $timestamp=time;
$lastCmds{$user}={} unless(exists $lastCmds{$user});
$lastCmds{$user}->{$timestamp}=0 unless(exists $lastCmds{$user}->{$timestamp});
$lastCmds{$user}->{$timestamp}++;
return if(checkCmdFlood($user));
my @cmd=split(/ /,$command);
my $lcCmd=lc($cmd[0]);
my %answerFunctions = ( pv => sub { sayPrivate($user,$_[0]) },
chan => sub { sayChan($conf{masterChannel},$_[0]) });
$p_answerFunction=$answerFunctions{$source};
if(exists $buildServ->{commands}->{$lcCmd}) {
my $p_levels=getCommandLevels($source,$user,$lcCmd);
my $level=getUserAccessLevel($user);
if(defined $p_levels->{directLevel} && $p_levels->{directLevel} ne "" && $level >= $p_levels->{directLevel}) {
executeCommand($source,$user,\@cmd);
}else{
answer("$user, you are not allowed to call command \"$cmd[0]\" in $source in current context.");
}
}else{
answer("$user, \"$cmd[0]\" is not a valid command.") unless($source eq "chan");
}
}
sub executeCommand {
my ($source,$user,$p_cmd,$checkOnly)=@_;
$checkOnly=0 unless(defined $checkOnly);
my %answerFunctions = ( pv => sub { sayPrivate($user,$_[0]) },
chan => sub { sayChan($conf{masterChannel},$_[0]) });
$p_answerFunction=$answerFunctions{$source};
my @cmd=@{$p_cmd};
my $command=lc(shift(@cmd));
if(exists $buildServHandlers{$command}) {
return &{$buildServHandlers{$command}}($source,$user,\@cmd,$checkOnly);
}else{
answer("$user, \"$command\" is not a valid command.");
return 0;
}
}
sub invalidSyntax {
my ($user,$cmd,$reason)=@_;
$reason="" unless(defined $reason);
$reason=" (".$reason.")" if($reason);
answer("Invalid $cmd command usage$reason. $user, please refer to help sent in private message.");
executeCommand("pv",$user,["help",$cmd]);
}
sub checkCmdFlood {
my $user=shift;
return 0 if(getUserAccessLevel($user) >= $conf{floodImmuneLevel});
if(exists $ignoredUsers{$user}) {
if(time > $ignoredUsers{$user}) {
delete $ignoredUsers{$user};
}else{
return 1;
}
}
my @autoIgnoreData=split(/;/,$conf{cmdFloodAutoIgnore});
my $received=0;
if(exists $lastCmds{$user}) {
foreach my $timestamp (keys %{$lastCmds{$user}}) {
if(time - $timestamp > $autoIgnoreData[1]) {
delete $lastCmds{$user}->{$timestamp};
}else{
$received+=$lastCmds{$user}->{$timestamp};
}
}
}
if($autoIgnoreData[0] && $received >= $autoIgnoreData[0]) {
broadcastMsg("Ignoring $user for $autoIgnoreData[2] minute(s) (command flood protection)");
$ignoredUsers{$user}=time+($autoIgnoreData[2] * 60);
return 1;
}
return 0;
}
sub logMsg {
my ($file,$msg)=@_;
if(! -d $conf{logDir}."/chat") {
if(! mkdir($conf{logDir}."/chat")) {
slog("Unable to create directory \"$conf{logDir}/chat\"",1);
return;
}
}
if(! open(CHAT,">>$conf{logDir}/chat/$file.log")) {
slog("Unable to log chat message into file \"$conf{logDir}/chat/$file.log\"",1);
return;
}
my $dateTime=localtime();
print CHAT "[$dateTime] $msg\n";
close(CHAT);
}
# BuildServ commands handlers #####################################################
sub hDisable {
my ($source,$user,$p_params,$checkOnly)=@_;
$rebuildEnabled=0;
answer("Rebuild commands disabled");
}
sub hEnable {
my ($source,$user,$p_params,$checkOnly)=@_;
$rebuildEnabled=1;
answer("Rebuild commands enabled");
}
sub hHelp {
my ($source,$user,$p_params,$checkOnly)=@_;
my ($cmd)=@{$p_params};
return 0 if($checkOnly);
if(defined $cmd) {
my $helpCommand=lc($cmd);
if(exists $buildServ->{help}->{$helpCommand}) {
my $p_help=$buildServ->{help}->{$helpCommand};
sayPrivate($user,"********** Help for command $cmd **********");
sayPrivate($user,"Syntax:");
sayPrivate($user," ".$p_help->[0]);
sayPrivate($user,"Details / examples:") if($#{$p_help} > 0);
for my $i (1..$#{$p_help}) {
sayPrivate($user," ".$p_help->[$i]);
}
}else{
sayPrivate($user,"\"$cmd\" is not a valid command.");
}
}else{
my $level=getUserAccessLevel($user);
my $p_helpForUser=$buildServ->getHelpForLevel($level);
sayPrivate($user,"********** Available commands for your access level **********");
foreach my $i (0..$#{$p_helpForUser->{direct}}) {
sayPrivate($user,$p_helpForUser->{direct}->[$i]);
}
}
}
sub hHelpAll {
my (undef,$user,undef,$checkOnly)=@_;
return 1 if($checkOnly);
my $p_help=$buildServ->{help};
sayPrivate($user,"********** BuildServ commands **********");
for my $command (sort (keys %{$p_help})) {
next unless($command);
sayPrivate($user,$p_help->{$command}->[0]);
}
}
sub hQuit {
my ($source,$user,undef,$checkOnly)=@_;
return 1 if($checkOnly);
my %sourceNames = ( pv => "private",
chan => "channel #$conf{masterChannel}",
game => "game",
battle => "battle lobby" );
quitAfterBuild("requested by $user in $sourceNames{$source}");
}
sub hDefineProfile {
my ($source,$user,$p_params,$checkOnly)=@_;
my @params=@{$p_params};
if($#params < 2) {
invalidSyntax($user,"defineprofile");
return 0;
}
my $buildSys=shift(@params);