aboutsummaryrefslogtreecommitdiffstats
path: root/iurt2
blob: f0fbd7a41ecdd64c8846d61342381a4066d93d48 (plain)
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
#!/usr/bin/perl
#
# Copyright (C) 2005 Mandrakesoft
# Copyright (C) 2005 Mandriva
# 
# Author: Florent Villard <warly@mandraesoft.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# compare and rebuild packages on different architecture
#
# TODO
#
# - use a cache (rpmctl cache for example) to find maintainer
# - Do not run if the hdlist are broken
# - allow to force packages to rebuild iurt foo-2.3-1mdk.src.rpm
#
use strict;
use Hdlist;
use Data::Dumper;
use URPM;
use File::NCopy qw(copy);
use MIME::Words qw(encode_mimewords);
use Fcntl ':flock';

# maybe time to switch to mkcd::parse_command_line
my ($debug, $unionfs, $nocheckchroot, $force_build, @todo);
my @argv = grep { 
    if ($force_build && !/--/) {
	if (m,(.*/)([^/]*.src.rpm)$, && -f $_) {
	    push @todo, [ $1, $2 ];
	    print STDERR "iurt: force build for $2 (from $1)\n";
	    0
	} else {
	    die "FATAL iurt: $_ does not seems to be a SRPM\n"
	}
    } else { 
	$force_build = 0;
	if (/--debug/) { $debug = 1; 0 }
	elsif (/--unionfs/) { $unionfs = 1; 0 }
	elsif (/--nocheckchroot/) { $nocheckchroot = 1; 0 }
	elsif (/--force_build/) { $force_build = 1; 0 }
	elsif (/--./) { usage("$_ is an unknown option") }
	else { 1 }
    }
} @ARGV;

my $distro_version = shift @argv;
my $distro_tag = $distro_version;
$distro_tag =~ s,/,-,g;
my $my_arch = shift @argv;
my $media = shift @argv;
my @special_srpm_dir = @argv;
my $urpmi_options = "-v --no-verify-rpm --nolock --auto";

$my_arch or usage("no architecture given (media $media, my_arch $my_arch, todo @todo)");
my $real_arch = `uname -m`;
chomp $real_arch;
my %arch_comp = (
    'i586' => { 'i386' => 1, 'i486' => 1, 'i586' => 1 },
    'i686' => { 'i386' => 1, 'i486' => 1, 'i586' => 1, 'i686' => 1 },
    'x86_64' => { 'i386' => 1, 'i486' => 1, 'i586' => 1, 'i686' => 1, 'x86_64' => 1 },
    'ppc' => { 'ppc' => 1 },
    'ppc64' => { 'ppc' => 1, 'ppc64' => 1 },
);
if (!$arch_comp{$real_arch}{$my_arch}) {
    die "FATAL iurt: could not compile $my_arch binaries on a $real_arch"
}

my $HOME = $ENV{HOME};
my $configfile = "$HOME/.iurt.$distro_tag.conf";
print STDERR "iurt: loading config file $configfile\n";
my $config;
if (-f $configfile) {
    $config = do $configfile or die "FATAL iurt: syntax error in $configfile";
} else {
    $config = {}
}

$config->{home} ||= $HOME;
$config->{cache_home} ||= "$HOME/.bugs";
$config->{supported_arch} ||= ['i586', 'x86_64'];
$config->{upload} ||= "$HOME/uploads/";
$config->{local_home} ||= "$HOME";
$config->{repository} ||= "/mnt/BIG/dis/";
$config->{packager} ||= "Iurt";
$config->{install_chroot_binary} ||= 'install-chroot-tar.sh';
$config->{distribution} ||= 'Mandriva Linux';
$config->{vendor} ||= 'Mandriva';
$config->{basesystem_media} ||= "$config->{repository}/$distro_version/$my_arch/media/main/";
$config->{all_media} ||= [ 'main', 'contrib' ];
$config->{log_size_limit} ||= '100M';
$config->{log_size_date} ||= '30';
$config->{no_mail} ||= { };

$config->{upload} .= $distro_version;
$config->{upload} =~ s/community//g;
if ($distro_version ne 'cooker') {
    if ($media ne 'main') {
	$config->{upload} .= "/$media"
    }
} elsif ($media eq 'contrib') {
    $config->{upload} =~ s/cooker/contrib/g;
}

-d $config->{upload} or usage("$config->{upload} does not exist");

my $pidfile = "$config->{cache_home}/iurt.$distro_tag.$my_arch.pid";
if (!$debug) {
    open my $lock, "$pidfile.lock";
    flock($lock,LOCK_EX);
    if (-f $pidfile)  {
	my (@stat) = stat $pidfile;
	open my $test_PID, $pidfile;
	my $pid = <$test_PID>;
	close $test_PID;
	if ($pid && getpgrp $pid != -1) {
	    my $time = $stat[9];
	    if ($time < time - 36000) {
		print STDERR "iurt: an other iurt pid $pid is running for a very long time, killing it\n";
		my $i;
		while ($i < 5 && getpgrp $pid != -1) {
		    kill_for_good($pid);
		    $i++;
		    sleep 1
		}
	    } else  {
		print STDERR "iurt: an other iurt is running for $my_arch, pid $pid, since ",time - $time," seconds\n";
		exit
	    }
	} else {
	    print STDERR "iurt: a previous iurt for $my_arch seems dead, cleaning.\n";
	    unlink $pidfile
	}
    }
    open my $PID, ">$pidfile" or die "FATAL iurt: could not open pidfile $pidfile for writing";
    print $PID $$;
    close $PID;

    flock($lock,LOCK_UN);
    close $lock;
}

my $cachefile = "$config->{cache_home}/iurt.$distro_tag.$my_arch.cache";
print STDERR "iurt: loading cache file $cachefile\n";
my $cache;
if (-f $cachefile) {
    $cache = do $cachefile
} else {
    $cache = { rpm_srpm => {}, failure => {}, queue => {}, warning => {}, run => 0, needed => {}, no_unionfs => {} }
}

my %big;
my %srpm_version;
my @wrong_rpm;
# FIXME need to check if scanning all the architecture is needed (except of noarch unsynchronity this should not be mandatory)
# in that case, @supported_arch may be removed
#
#foreach my $arch (@{$config->{supported_arch}}) {
# 
# We could rely on only parsing the synthesis, hoping that they are correct, however this scan is very fast, so.
my $rpms_dir = "$config->{repository}/$distro_version/$my_arch/media/$media/";
print STDERR "iurt: checking current packages in $rpms_dir\n";
opendir my $rpmdir, $rpms_dir or die "Could not open $rpms_dir: $!"; 
foreach my $rpm (readdir $rpmdir) {
    my ($rarch, $srpm) = update_srpm($rpms_dir, $rpm);
    $rarch or next;
    $big{$rpm} = 1;
    $cache->{queue}{$srpm} = 1;
    check_version($srpm)
}
closedir $rpmdir;

my %provides;
my %pack_provide;
foreach my $m (@{$config->{all_media}}) {
    my $synthesis_file = "$config->{repository}/$distro_version/$my_arch/media/$m/media_info/synthesis.hdlist.cz";
    if (-f $synthesis_file) {
	print STDERR "Parsing $synthesis_file\n";
	if (open my $syn, "zcat $synthesis_file |") { 
	    my @prov;
	    while (<$syn>) {
		if (/^\@provides@(.*)/) {
		    foreach my $p (split '@', $1) {
			$p =~ /([^[]+)(?:\[(.*)\])?/g;
			push @prov, $1;
			$provides{$1} = $2 || 1
		    }
		} elsif (/\@info\@([^@]+)@/) {
		    my ($name) = $1 =~ /(.*)-[^-]+-[^-]+\..*$/;
		    foreach (@prov) {
			$pack_provide{$_} = $name
		    }
		    @prov = ()
		}
	    }	    
	} else {
	    print STDERR "ERROR: Could not open $synthesis_file, will not precheck dependecies avaibility\n";
	}
    }
}
#}

my %maint;

-d "$config->{upload}/build/$my_arch" or mkdir "$config->{upload}/build/$my_arch";
my $clean;
my %rep;
my %done_rpm;
#
# FIXME all the rep but the first one are cleaned
# this may not be usefull anymore
#
my $to_compile;
foreach my $dir ("$config->{repository}/$distro_version/SRPMS/$media/", @special_srpm_dir) {
	print STDERR "iurt: checking SRPMS dir $dir\n";
	opendir my $rpmdir, $dir or next;
	foreach my $srpm (readdir $rpmdir) {
	        # this is for the output of the new svn system
		if ($srpm =~ /^\@\d+:(.*)/) {
			link "$dir/$srpm", "$dir/$1";
			# unlink "$dir/$srpm";
			$srpm = $1
		}
		$srpm =~ /(.*)-[^-]+-[^-]+\.src\.rpm$/ or next;
		if ($config->{unwanted_packages} && $srpm =~ /$config->{unwanted_packages}/) { next }
		my $ok = 1;
		if (check_version($srpm)) { 
			defined $cache->{failure}{$srpm} and next;
			if (!$cache->{queue}{$srpm} && check_needed($srpm)) {
				my $hdr = rpm2header("$dir/$srpm");
				check_arch($hdr) and next;
				my $changelog = $hdr->queryformat("%{CHANGELOGNAME}");
				my ($mail) = $changelog =~ /<(.*@.*)>/;
				$maint{$srpm} = $mail;
				print "iurt: will try to compile $srpm\n";
				$to_compile++;
				push @todo, [ $dir , $srpm ]
			}
			foreach my $arch (@{$config->{supported_arch}}) {
				$ok &&= $cache->{queue}{$srpm}
			}
		}
		if ($clean && ($rep{$srpm} || $ok)) {
			print "iurt: cleaning $dir/$srpm\n";
			unlink "$dir/build/$srpm";
			unlink "$dir/$srpm"
		}
		$rep{$srpm} = 1
	}
	$clean = 1;
	closedir $rpmdir
}

dump_cache();

if (!@todo && !$debug) {
    print "iurt: nothing to do\n";
    unlink $pidfile;
    exit
}
print "iurt: will try to compile $to_compile packages\n";

$cache->{run} ||= 1;
my $run = ++$cache->{run};

my $local_spool = "$config->{local_home}/iurt/$distro_tag/$my_arch";
if (!-d "$config->{local_home}/iurt/$distro_tag/") {
    mkdir "$config->{local_home}/iurt/$distro_tag";
    if (!-d $local_spool) {
	mkdir $local_spool;
	mkdir "$local_spool/log"
    }
}

my $debug_tag = '_debug' if $debug;
my $chroot = "$config->{local_home}/chroot$debug_tag";
my $chroot_tar = "$chroot-$distro_tag.$my_arch.tar.gz";
my $unionfs_dir;
if (!$nocheckchroot) {
    print "iurt: checking basesystem tar\n";
    system(qq{sudo pkill -9 -u root -f "urpmi $urpmi_options --root $chroot"});
    clean_chroot($chroot, 1) or die "FATAL iurt: Could no prepare initial chroot";
    perform_command("sudo $config->{install_chroot_binary} cooker $config->{basesystem_media} $chroot_tar $chroot 501 basesystem tar rpm-build", 
	mail => $config->{admin},
	error => "[REBUILD] Creating the inital chroot for $distro_tag on $my_arch failed", 
	hash => 'chroot_inititialization', 
	timeout => 600, 
	log => "$local_spool/log/", 
	debug_mail => $debug,
	die => 1);

}
dump_rpmmacros("$chroot/home/builder/.rpmmacros") or die "FATAL iurt: could not dump rpm macros";
if ($unionfs) {
    $unionfs_dir = "$config->{local_home}/iurt_unionfs$debug_tag";
    -d $unionfs_dir or mkdir $unionfs_dir
}
my $s = sub { print "iurt: dumping cache...\n"; dump_cache(); exit };
$SIG{TERM} = $s;
$SIG{INT} = $s;

my %done;
my $wait_limit;
my $done;
my $home = $config->{local_home};
my $union_id = 1;
my $unionfs_tmp = $unionfs;	
foreach (my $i ; $i < @todo; $i++) {
	my ($dir, $srpm) = @{$todo[$i]};
	$done{$srpm} and next;
	$done{$srpm} = 1;
	check_version($srpm) or next;
	if ($debug) { $debug++ == 2 and exit }
	$done++;
	print "iurt: packages $srpm [$done/$to_compile]\n";
	# FIXME unfortunately urpmi stalls quite often
	my $match = "urpmi $urpmi_options --root $chroot";
	if (!clean_process($match)) {
	    dump_cache();
	    die "FATAL iurt: Could not have urpmi working !"
	}
	my $need_chroot_cleaning;
	if ($cache->{no_unionfs}{$srpm}) {
	    $unionfs_tmp = 0
	} elsif ($unionfs) {
	    $need_chroot_cleaning = 1 if !$unionfs_tmp;
	    $unionfs_tmp = 1
	}
	if ($unionfs_tmp && !$need_chroot_cleaning) {
	    my $mount_point = "$unionfs_dir/unionfs.$run.$union_id";
	    print STDERR "Cleaning $mount_point\n";
	    if (!clean_mnt($mount_point)) {
		dump_cache();
		die "FATAL iurt: could not kill remaining processes acceding $mount_point"
	    }
	    my $tmpfs;
	    
	    # we cannont just rm -rf $tmpfs, this create defunct processes afterwards (and lock particularly hard the urpmi database)
	    $union_id = clean_unionfs($unionfs_dir, $run, $union_id);
	    $tmpfs = "$unionfs_dir/tmpfs.$run.$union_id";
	    $chroot = "$unionfs_dir/unionfs.$run.$union_id";
	    mkdir $tmpfs or die "Could not create $tmpfs ($!)";
	    mkdir $chroot or die "Could not create $chroot ($!)";
	    system(qq{sudo mount -t tmpfs none $tmpfs}) and die "FATAL iurt: could not mount $tmpfs ($!)";
	    system(qq{sudo mount -o dirs=$tmpfs=rw:$home/chroot=ro -t unionfs none $chroot}) and die "FATAL iurt: could not mount $tmpfs and $home/chroot with unionfs ($!)";
	    system("sudo mount none -t proc $chroot/proc") and die "FATAL iurt: could not mount /proc in the chroot.";
	} else {
	    print STDERR "iurt: installing a new chroot for $srpm in $chroot\n";
	    clean_chroot($chroot)
	}
	my ($srpm_name) = $srpm =~ /(.*)-[^-]+-[^-]+\.src\.rpm$/ or next;
	my $maintainer = `rpmmon -s -p $srpm_name`;
	my $cc = "$maint{$srpm}";#, maintainers\@mandriva.com";
	chomp $maintainer;
	if (!$maintainer || $maintainer eq 'NOT_FOUND') {
		$maintainer = $cc;
		#$cc = 'maintainers@mandriva.com'
	}
	#($maintainer, $cc) = ($config->{admin},'');
	print "Installing build dependencies of $srpm...\n";
	
	#system(qq{sudo pkill -9 dd-u root -f "$todo[$i-1][1]"}) if $i - 1 >= 0;
	#system(qq{sudo pkill -9 -u root -f "urpmi $urpmi_options --root $chroot"});
	perform_command("sudo urpmi $urpmi_options --root $chroot $dir/$srpm", 
		mail => $maintainer, 
		error => "[REBUILD] install of build dependencies of $srpm failed on $my_arch",  
		hash => "install_deps_$srpm", 
		timeout => 600, 
		freq => 1,
		cc => $cc, 
		debug_mail => $debug,
		error_regexp => 'cannot be installed',
		wait_regexp => 'database locked',
		wait_callback => sub { $wait_limit++; if ($wait_limit > 10) { $wait_limit = 0; system(qq{sudo pkill -9 urpmi}) } },
		log => "$local_spool/log/",
		callback => sub { 
			my ($opt, $output) = @_;
			print "calling callback for $opt->{hash}\n" if $debug;
			my ($missing_deps, $version) = $output =~ /\(due to unsatisfied ([^[)]*)(?:\[(.*)\])?/;
			$missing_deps or return;
			my $p = $pack_provide{$missing_deps} || $missing_deps;
			my $other_maint = `rpmmon -p $p`;
			$version ||= 0;
			chomp $other_maint;
			print "missing dep: $missing_deps ($other_maint)\n";
			if ($other_maint && $other_maint ne 'NOT_FOUND') {
			    $opt->{mail} = $other_maint;
			    $opt->{error} = "[missing] $missing_deps, needed to build $srpm, is not available on $my_arch";
			}
			# remember what is needed, and do not try to recompile until it is available
			push @{$cache->{needed}{$srpm}}, [ $missing_deps, $version, $other_maint || $maintainer ];
		},
	) or next;
	perform_command("sudo chroot $chroot rpm -qa", 
		hash => "rpm_qa_$srpm", 
		timeout => 60, 
		debug_mail => $debug,
		log => "$local_spool/log/") or next;
	print "Copying $srpm to $chroot\n";
	perform_command("sudo cp $dir/$srpm $chroot/home/builder/rpm/SRPMS/", 
		mail => $config->{admin}, 
		error => "[REBUILD] cannot copy $srpm to $chroot", 
		debug_mail => $debug,
		hash => "copy_$srpm") or next;
	print "Compiling $srpm\n";
	#system(qq{sudo chroot $chroot /bin/su builder -c "mkdir rpm/RPMS/x86_64 rpm/RPMS/noarch"});
	if (!perform_command(qq{TMP=/home/builder/tmp/ sudo chroot $chroot /bin/su builder -c "rpm --rebuild /home/builder/rpm/SRPMS/$srpm"}, 
			mail => $maintainer, 
			error => "[REBUILD] $srpm from $distro_tag does not build correctly on $my_arch", 
			hash => "build_$srpm", 
			timeout => 18000, 
			debug_mail => $debug,
			cc => $cc, 
			log => "$local_spool/log/", 
			error_regexp => 'rror.*ailed|Bad exit status|RPM build error',
			callback => sub { 
			    my ($opt, $output) = @_;
			    print STDERR "iurt: calling callback for $opt->{hash}\n" if $debug;
			    if ($unionfs_tmp && $output =~ /no space left on device/i) {
				print STDERR "ERROR iurt: running out of space to compile $srpm in unionfs mode, will recompile it in normal mode\n";
				$cache->{no_unionfs}{$srpm} = 1
			    }
			}, 
			freq => 1) && !glob "$chroot/home/builder/rpm/RPMS/*/*.rpm") {
		    # FIXME
		    # The simple algo used here is : 
		    #  try to compile it with unionfs, if it runs out of space, compile it without the next time
		    #
		    #  This could be improved in keeping this srpm name for future version, but if we compile it 
		    #  on a new machine with more ram, or if next version compiles just fine with unionfs, we will
		    #  loose the unionfs advantage. 
		    #
		    #  Maybe the right thing to do would be to first try to increate the tmpfs size (more than 50 % of the 
		    #  physical RAM), but this will lead to more swap usage, and slower compilation (and lost of the unionfs
		    #  plus). Or to keep the faulty package an unionfs exception for some time, to save some more extra builds.
		    # 
		    if (!$unionfs_tmp) {
			$cache->{failure}{$srpm} = 1
		    } elsif ($cache->{no_unionfs}{$srpm}) {
			$cache->{failure}{$srpm} = 1
		    }
		next
	}
	# do some cleaning if the compilation is successful
	delete $cache->{needed}{$srpm} if defined $cache->{needed}{$srpm};
	if (!perform_command("sudo urpmi $urpmi_options --root $chroot $chroot/home/builder/rpm/RPMS/*/*.rpm", 
			mail => $maintainer, 
			error => "[REBUILD] binaries packages generated from $srpm do not install correctly", 
			hash => "binary_test_$srpm", 
			timeout => 300, 
			debug_mail => $debug,
			freq => 1, 
			error_regexp => 'unable to access',
			log => "$local_spool/log/")) {
		$cache->{failure}{$srpm} = 1;
		next
	}
	if ($debug) {
	    print "iurt: debug mode, skip other packages\n";
	    exit
	} else {
	    system("cp $chroot/home/builder/rpm/RPMS/*/*.rpm $local_spool") and print "ERROR: could not copy rpm files from $chroot/home/builder/rpm/RPMS/ to $local_spool ($!)\n";
	    process_queue()
	}
}

print STDERR "iurt: reprocess generated packages queue\n";
process_queue();

dump_cache();

print STDERR "ERROR iurt: RPM with a wrong SRPM name\n" if @wrong_rpm;
if (open my $file, ">$local_spool/log/wrong_srpm_names.log") {
    foreach (@wrong_rpm) {
	print $file "$_->[1] -> $_->[0] (", $cache->{rpm_srpm}{$_->[1]},")\n";
    }
}

if ($config->{rsync_to}) {
    	# remove some old and very big log files not to saturate the server
	system(qq{find $local_spool/log/ -name "*.log" \( -size +$config->{log_size_limit} -or -mtime +$config->{log_size_date} \) -exec rm -f {} \;});
	system("rsync --delete -alHPe 'ssh -c arcfour' $local_spool/log/ $config->{rsync_to}/$distro_tag/$my_arch/log/");
}

# one last try to clean
print STDERR "iurt: try to clean remaining unionfs\n";
if ($unionfs) {
    print STDERR "Cleaning old unionfs remaining dir\n";
    opendir my $dir, $unionfs_dir;
    while (readdir $dir) {
	/unionfs\.(\d+)\.(\d+)/ or next;
	clean_unionfs($unionfs_dir, $1, $2);
    }
    closedir $dir
}

unlink $pidfile;

exit;

sub usage {
	my ($error) = @_;
	print "
	ERROR iurt: $error" if $error;
	print "
	
	usage:
	
		iurt [options] <distro version> <arch> <media>
			e.g. iurt community/2006.0 x86_64 main

		options:
			--debug: Compile one package in debug mode (do not send mail, create
				 chroot_debug directory). This mode can be used on a system
				 where a iurt is already running.
			--force_build <force_srpm_build_1> <force_srpm_build_2> ... <force_srpm_build_n>
		       		      list of extra srpm to build
			--unionfs: Use a tmpfs mounted with the chroot via unionfs as build chroot.
				   This is much faster but you need some memory.
			--nocheckchroot: start building without the inital check of the chroot.
";
	exit
}

sub clean_chroot {
    my ($chroot, $only_clean) = @_;
    if (-d $chroot) {
	system("sudo umount $chroot/proc");
	perform_command("sudo rm -rf $chroot", 
	    mail => $config->{admin},
	    error => "[REBUILD] Deleting of old chroot $chroot failed", 
	    hash => 'chroot_deletion', 
	    debug_mail => $debug,
	    die => 1);
    }
   return 1 if $only_clean;
   mkdir $chroot;
   perform_command("pushd $chroot && sudo tar xvf $chroot_tar", 
		mail => $config->{admin}, 
		error => "[REBUILD] creating the initial chroot $chroot failed", 
		hash => 'chroot_init', 
		debug_mail => $debug,
		die => 1);

   dump_rpmmacros("$chroot/home/builder/.rpmmacros") or return;
   system("sudo mount none -t proc $chroot/proc") and return;
   1
}

sub clean_process {
    my ($match) = @_;
    return clean($match, "pgrep -u root -f", "sudo pkill -9 -u root -f");
}

sub clean_mnt {
    my ($mount_point) = @_;
    return clean($mount_point, "fuser", "sudo fuser -k");
}

sub clean {
    my ($var, $cmd, $kill_cmd) = @_;
    my $ps;
    my $i;
    while ($ps = `$cmd "$var"`) {
	system(qq{$kill_cmd "$var"});
	sleep 1;
	chomp $ps;
	print STDERR "Trying to removed previous blocked processes for $var ($ps)\n";
	return 0 if $i++ > 10
    }
    1
}

sub clean_unionfs {
    my ($unionfs_dir, $run, $union_id) = @_;
    system("sudo umount $unionfs_dir/unionfs.$run.$union_id/proc") and print STDERR "ERROR iurt: could not umount $unionfs_dir/unionfs.$run.$union_id/proc\n";
    foreach my $t ("unionfs",'tmpfs') {
	# unfortunately quite oftem the unionfs is busy and could not be unmounted
	my $d = "$unionfs_dir/$t.$run.$union_id";
	while (check_mounted($d, $t)) {
	    system("sudo fuser -k $d");
	    print STDERR "iurt: umounting $d\n";
	    if (system(qq{sudo umount $d &> /dev/null})) {
		print STDERR "WARNING iurt: could not umount $d ($!)\n";
		$union_id++;
		return $union_id
	    }
	}
	print STDERR "iurt: removing $d\n";
	system(qq{sudo rm -rf $d});
    }
    $union_id
}


sub check_mounted {
    my ($mount_point, $type) = @_;
    open my $mount, '/proc/mounts' or die 'FATAL iurt: could not open /proc/mounts';
    $mount_point =~ s,//+,/,g;
    while (<$mount>) {
	return 1 if /^\w+ $mount_point $type /
    }
    0
}

sub check_needed {
    my ($srpm) = @_;
    if (!defined $cache->{needed}{$srpm} && !ref $cache->{needed}{$srpm}) { return 1 } 
    my @n;
    my $ok = 1;
    foreach my $t (@{$cache->{needed}{$srpm}}) {
	my ($name, $version, $maint) = @$t;
	my ($p_version) = $provides{$name};
	if ($p_version) {
	    next if $version == $p_version;
	    next if URPM::ranges_overlap($version, $p_version)
	}
	$ok = 0;
	push @n, [ $name, $version ];
	my $v ||= $version;
	print STDERR "ERROR iurt: $srpm needs $name $v to be compiled.\n";
	# try to recompile it once in a while
	return 1 if ! $cache->{warning}{"install_deps_$srpm"}{$maint}++ % 72
    }
    delete $cache->{needed}{$srpm};
    $cache->{needed}{$srpm} = \@n if @n;
    $ok
}

sub process_queue {
	my $dir = "$config->{local_home}/iurt/$distro_tag/$my_arch";
	opendir my $rpmdir, $dir or next;
	foreach my $rpm (readdir $rpmdir) {
		my ($rarch, $srpm) = update_srpm($dir, $rpm);
		$rarch or next;
		# recheck if the package has not been uploaded in the meantime
		if (! -f "$rpms_dir/$rpm") {
		    my $ok = copy "$dir/$rpm", "$config->{upload}/RPMS/";
		    # try to keep the opportunity to prevent disk full
		    if (!$ok){
			print "ERROR process_queue: cannot copy $dir/$rpm to $config->{upload}/RPMS/ ($!)\n";
			next
		    }
		}
		unlink "$dir/$rpm";
		$cache->{queue}{$srpm} = 1
	}
	closedir $rpmdir;
}

sub update_srpm {
	my ($dir, $rpm) = @_;
	my ($arch) = $rpm =~ /([^\.]+)\.rpm$/ or return 0;
	my $srpm = $cache->{rpm_srpm}{$rpm};
	if (!$srpm) {
		my $hdr = rpm2header("$dir/$rpm");
		$hdr or return 0;
		$srpm = $hdr->queryformat("%{SOURCERPM}");
		$cache->{rpm_srpm}{$rpm} = $srpm
	}
	$srpm = fix_srpm_name($srpm, $rpm);
	$arch, $srpm
}

sub dump_cache {
	my $filename = $cachefile;
	return if $debug;
	open my $file, ">$filename.tmp" or die "FATAL iurt dump_cache: cannot open $filename.tmp";
	flock($file,LOCK_EX);
	seek($file, 0, 2);
	$Data::Dumper::Indent = 1;
	$Data::Dumper::Terse = 1;
	print $file Data::Dumper->Dump([ $cache ], [ "cache" ]);
	unlink $filename;
	link "$filename.tmp", $filename;
	flock($file,LOCK_UN)
}

sub sendmail {
	my ($to, $cc, $subject, $text, $from, $debug) = @_;
	do { print "Cannot find sender-email-address [$to]\n"; return } unless defined($to);
	$from ||= $config->{packager};
	my $MAIL;
	if (!$debug) { open $MAIL,  "| /usr/sbin/sendmail -t" or return } else { open $MAIL,  ">&STDOUT" or return }
	my $sender = encode_mimewords($to);
	my $subject = encode_mimewords($subject);
	print $MAIL "To: $sender\n";
	if ($cc) { $cc = encode_mimewords($cc); print $MAIL "Cc: $cc\n" }
	print $MAIL "From: $from\n";
	print $MAIL "Subject: $subject\n";
	print $MAIL "\n";
	print $MAIL $text; 
	close($MAIL)
}

sub check_arch {
	my ($hdr) = @_;
	my (@exclusive_arch) = $hdr->queryformat('%{EXCLUSIVEARCH}');
	grep { $_ eq $my_arch || $_ eq '(none)' } @exclusive_arch or return 1; 
	my (@exclude_arch) = $hdr->queryformat('%{EXCLUDEARCH}');
	grep { $_ eq $my_arch } @exclusive_arch and return 1 
}

sub check_version {
	my ($srpm) = @_;
	my ($srpm_name) = $srpm =~ /(.*)-[^-]+-[^-]+\.src\.rpm/;
	if (URPM::ranges_overlap("= $srpm",">= $srpm_version{$srpm_name}")) {
		$srpm_version{$srpm_name} = $srpm;
		return 1
	}
	0
}

sub fix_srpm_name {
	my ($srpm, $rpm) = @_;
	my $old_srpm = $srpm;
	if ($srpm =~ s/^lib64/lib/){
		push @wrong_rpm, [ $old_srpm, $rpm ];
		$cache->{rpm_srpm}{$rpm} = $srpm
	}
	$srpm
}

sub perform_command {
    my ($command, %opt) = @_;
    $opt{timeout} ||= 300;
    $opt{freq} ||= 24;
    print "Timeout $opt{timeout}\n";
    # from alarm perldoc
    my $output;
    my $kill;
    if ($opt{debug}) {
	print "Would have rum $command with a timeout of $opt{timeout}\n";
	return 1
    }
    eval {
	local $SIG{ALRM} = sub { print "Timeout!\n"; $kill = 1; die "alarm\n" }; # NB: \n required
	alarm $opt{timeout};
	print "$command\n";
	if ($opt{log}) {
	    #$output = `$command 2>&1 2>&1 | tee $opt{log}/$opt{hash}.$run.log`;
	    system("$command &> $opt{log}/$opt{hash}.$run.log");
	} else {
	    $output = `$command 2>&1`;
	}
	alarm 0;
    };
    if ($@) {
	# timed out
	die unless $@ eq "alarm\n";   # propagate unexpected errors
	return 0
    } else {
	# Keep the run first on the harddrive so that one can check the command status tailing it
	if ($opt{log} && open my $log, "$opt{log}/$opt{hash}.$run.log") {
	    local $/;
	    $output = <$log>
	}
	my $err = $?;
	if ($kill) {
	    $output = "Command has been killed after $opt{timeout} seconds: $command\n$output"
	} else {
	    $output = "Command failed: $command\n$output"
	}
	if (ref $opt{callback}) {
	    $opt{callback}(\%opt, $output)
	}
	if ($opt{wait_regexp} && $output =~ /$opt{wait_regexp}/) {
	    $opt{wait_callback}(\%opt, $output) if ref $opt{wait_callback};
	    print STDERR "ERROR iurt: $opt{wait_regexp} !\n";
	    sendmail($config->{admin}, '' , "$opt{hash} on $my_arch for $media: could not proceed", "$opt{wait_regexp}\n\n$output", 0, 0, $opt{debug_mail});
	    if ($opt{die}) {
		dump_cache();
		die "FATAL iurt: $opt{error}."
	    }
	    return 0
	}
	if ($err || $opt{error_regexp} && $output =~ /$opt{error_regexp}/) {
	    if ($opt{mail} && $config->{sendmail} && !$config->{no_mail}{$opt{mail}}) {
		if (! ($cache->{warning}{$opt{hash}}{$opt{mail}} % $opt{freq})) {
		    sendmail($opt{mail}, $opt{cc} , $opt{error} , $output, 0, 0, $opt{debug_mail});
		} elsif ($config->{admin}) {
		    sendmail($config->{admin}, '' , $opt{error}, $output, 0, 0, $opt{debug_mail});
		}
	    }
	    $cache->{warning}{$opt{hash}}{$opt{mail}}++;
	    print STDERR "\n$output\n";
	    if ($opt{die}) {
		dump_cache();
		die "FATAL iurt: $opt{error}."
	    }
	    return 0
	}
    }
    1
}

sub kill_for_good {
    my ($pid) = @_;
    kill 14, $pid;
    sleep 2;
    if (getpgrp $pid != -1) {
	kill 15, $pid;
	sleep 2;
	if (getpgrp $pid  != -1) {
	    kill 9, $pid
	}
    }
}

sub dump_rpmmacros {
	my ($file) = @_;
	open my $f, qq{| sudo sh -c "cat > $file"} or return 0;
	print $f qq{\%_topdir                \%(echo \$HOME)/rpm
\%_tmppath               \%(echo \$HOME)/rpm/tmp/
\%distribution           $config->{distribution}
\%vendor                 $config->{vendor}
\%packager               $config->{packager}}
}