source: devel/pb/bin/pb @ 2396

Last change on this file since 2396 was 2396, checked in by bruno, 4 months ago

Replace most of the die by confess and also uses now option --rm for docker run to avois leaving ghost ctn except in debug mode

  • Property svn:executable set to *
File size: 185.0 KB
Line 
1#!/usr/bin/perl -w
2#
3# Project Builder main application
4#
5# $Id$
6#
7# Copyright B. Cornec 2007-today
8# Eric Anderson's changes are (c) Copyright 2012 Hewlett Packard
9# Provided under the GPL v2
10
11# Syntax: see at end
12
13use strict 'vars';
14
15# The modules mentioned here are required by pb when used both
16# locally or inside a VE/VM/RM
17# Additional required modules only used locally are called with a require
18# in their respective section
19use Getopt::Long qw(:config auto_abbrev no_ignore_case);
20use Carp qw/confess cluck/;
21use Data::Dumper;
22use English;
23use File::Basename;
24use File::Copy;
25use File::stat;
26use File::Find;
27use Time::localtime qw(localtime);
28use POSIX qw(strftime);
29use lib qw (lib);
30use ProjectBuilder::Version;
31use ProjectBuilder::Base;
32use ProjectBuilder::Display;
33use ProjectBuilder::Conf;
34use ProjectBuilder::Distribution;
35use ProjectBuilder::VCS;
36use ProjectBuilder::CMS;
37use ProjectBuilder::Env;
38use ProjectBuilder::Filter;
39use ProjectBuilder::Changelog;
40use ProjectBuilder::VE;
41
42# Global variables
43$Global::pb_stop_on_error = 0;      # False by default
44$Global::pb_show_sudo = 0;          # False by default
45
46my %opts;                           # CLI Options
47my $action;                         # action to realize
48my $test = "FALSE";                 # Not used
49my $pbforce = 0;                    # Force VM stop
50my $pbsnap = 0;                     # Do not use snapshot mode for VM/VE by default
51my $pbkeep = 0;                     # keep temporary directory at the end
52my $option = "";                    # Not used
53my @pkgs;                           # list of packages
54my $pbtag;                          # Global Tag variable
55my $pbver;                          # Global Version variable
56my %pbscript;                       # Name of the scripts per V
57my $pbrev;                          # Global REVISION variable
58my $pbtarget = undef;               # Target os-ver-arch you want to build for
59my $pbport;                         # Port to use to connect to the VM/RM
60my $newver;                         # New version to create
61my $pbimage = undef;                # ISO image for the VM to create or docker image for the VE
62my $vetype = undef;                 # Type of Virtual environment to deal with
63
64my @date = pb_get_date();
65my $pbdate = strftime("%Y-%m-%d", @date);
66
67=pod
68
69=head1 NAME
70
71pb, aka project-builder.org - builds packages for your projects
72
73=head1 DESCRIPTION
74
75pb helps you build various packages directly from your project sources.
76Those sources could be handled by a CMS (Configuration Management System)
77such as Subversion, CVS, Git, Mercurial... or being a simple reference to a compressed tar file.
78It's based on a set of configuration files, a set of provided macros to help
79you keeping build files as generic as possible. For example, a single .spec
80file should be required to generate for all rpm based distributions, even
81if you could also have multiple .spec files if required.
82
83=head1 SYNOPSIS
84
85pb [-vhSq][-r pbroot][-p project][[-s script -a account -P port][-T VEtype][-t [os-ver-arch]][-m os-ver-arch[,...]]][-g][-i image] <action> [<pkg1> ...]
86
87pb [--verbose][--help][--man][--quiet][--snapshot][--revision pbroot][--project project][[--script script --account account --port port][-T VEtype][--target [os-ver-arch]][--machine os-ver-arch[,...]]][--nographic][--image image][--rebuild] <action> [<pkg1> ...]
88
89=head1 OPTIONS
90
91=over 4
92
93=item B<-v|--verbose>
94
95Increase verbosity
96
97=item B<-q|--quiet>
98
99Do not print any output.
100
101=item B<-h|--help>
102
103Print a brief help message and exits.
104
105=item B<-S|--snapshot>
106
107Use the snapshot mode of VMs or VEs
108
109=item B<--man>
110
111Prints the manual page and exits.
112
113=item B<-t|--target os-ver-arch>
114
115Name of the target system you want to build for.
116All if none precised.
117
118=item B<-m|--machine os-ver-arch[,os-ver-arch,...]>
119
120Name of the Virtual Machines (VM), Virtual Environments (VE) or Remote Machines (RM)
121you want to build on (comma separated).
122All if none precised (or use the env variable PBV).
123
124=item B<-T|--vetype VEtype]>
125
126Type of Virtual Environments (VE)
127Can be chroot or docker.
128
129=item B<-s|--script script>
130
131Name of the script you want to execute on the related VMs/VEs/RMs.
132
133=item B<-g|--nographic>
134
135Do not launch VMs in graphical mode.
136
137=item B<-i|--image image>
138
139It could be either:
140- The name of the ISO image of the distribution you want to install on the related VMs
141- The name of the docker image of the distribution you want to install on the related VEs
142
143
144=item B<-a|--account account>
145
146Name of the account to use to connect on the related VMs/RMs.
147
148=item B<-P|--port port_number>
149
150Port number to use to connect on the related VMs/RMs.";
151
152=item B<-p|--project project_name>
153
154Name of the project you're working on (or use the env variable PBPROJ)
155
156=item B<-r|--revision revision>
157
158Path Name of the project revision under the CMS (or use the env variable PBROOT)
159
160=item B<-V|--version new_version>
161
162New version of the project to create based on the current one.
163
164=item B<-k|--keep>
165
166Keep the temporary dir where files have been created in or der to help debug
167
168=item B<--rebuild>
169
170Only valid with the checkssh action, it alllows to automatically relaunch the build of the failed packages
171
172=item B<--no-stop-on-error>
173
174Continue through errors with best effort.
175
176=back
177
178=head1 ARGUMENTS
179
180<action> can be:
181
182=over 4
183
184=item B<sbx2build>
185
186Create tar files for the project under your CMS.
187Current state of the exported content is taken.
188CMS supported are SVN, SVK, CVS, Git and Mercurial
189parameters are packages to build
190if not using default list
191
192=item B<cms2build>
193
194Create tar files for the project under your CMS.
195Current state of the CMS is taken.
196CMS supported are SVN, SVK, CVS, Git and Mercurial
197parameters are packages to build
198if not using default list
199
200=item B<build2prep>
201
202Prepare the environment for build by installing required dependencies. Done once on the build system.
203
204=item B<build2pkg>
205
206Create packages for your running distribution
207
208=item B<cms2pkg>
209
210cms2build + build2pkg
211
212=item B<sbx2pkg>
213
214sbx2build + build2pkg
215
216=item B<sbx2pkg2ins>
217
218sbx2pkg + final install of packages
219
220=item B<sbx2prep>
221
222sbx2build + build2prep
223
224=item B<build2ssh>
225
226Send the tar files to a SSH host
227
228=item B<sbx2ssh>
229
230sbx2build + build2ssh
231
232=item B<cms2ssh>
233
234cms2build + build2ssh
235
236=item B<pkg2ssh>
237
238Send the packages built to a SSH host
239
240=item B<build2vm>
241
242Create packages in VMs, launching them if needed
243and send those packages to a SSH host once built
244VM type supported are QEMU and KVM
245
246=item B<build2ve>
247
248Create packages in VEs, creating it if needed
249and send those packages to a SSH host once built
250
251=item B<build2rm>
252
253Create packages in RMs, which should pre-exist,
254and send those packages to a SSH host once built
255RM means Remote Machine, and could be a physical or Virtual one.
256This is one buildfarm integration for pb.
257
258=item B<prepvm>
259
260Prepare the VMs to have all requirements to build the project
261
262=item B<prepve>
263
264Prepare the VEs to have all requirements to build the project
265
266=item B<preprm>
267
268Prepare the RMs to have all requirements to build the project
269
270=item B<sbx2vm>
271
272sbx2build + build2vm
273
274=item B<sbx2ve>
275
276sbx2build + build2ve
277
278=item B<sbx2docker>
279
280sbx2build + build2ve with a potential build of all necessary docker containers to perform it
281
282=item B<sbx2rm>
283
284sbx2build + build2rm
285
286=item B<cms2vm>
287
288cms2build + build2vm
289
290=item B<cms2ve>
291
292cms2build + build2ve
293
294=item B<cms2rm>
295
296cms2build + build2rm
297
298=item B<launchvm>
299
300Launch one virtual machine
301
302=item B<launchve>
303
304Launch one virtual environment
305
306=item B<script2vm>
307
308Launch one virtual machine if needed
309and executes a script on it
310
311=item B<script2ve>
312
313Execute a script in a virtual environment
314
315=item B<script2rm>
316
317Execute a script on a remote machine
318
319=item B<newvm>
320
321Create a new virtual machine
322
323=item B<newve>
324
325Create a new virtual environment
326
327=item B<setupvm>
328
329Setup a virtual machine for pb usage
330
331=item B<setupve>
332
333Setup a virtual environment for pb usage
334
335=item B<setuprm>
336
337Setup a remote machine for pb usage
338
339=item B<sbx2setupvm>
340
341Setup a virtual machine for pb usage using the sandbox version of pb instead of the latest stable
342Reserved to dev team.
343
344=item B<sbx2setupve>
345
346Setup a virtual environment for pb usage using the sandbox version of pb instead of the latest stable
347Reserved to dev team.
348
349=item B<sbx2setuprm>
350
351Setup a remote machine for pb usage using the sandbox version of pb instead of the latest stable
352Reserved to dev team.
353
354=item B<build2setupvm>
355
356Setup a virtual machine for pb usage using the build available
357Reserved to dev team.
358
359=item B<build2setupve>
360
361Setup a virtual environment for pb usage using the build available
362Reserved to dev team.
363
364=item B<build2setuprm>
365
366Setup a remote machine for pb usage using the build available
367Reserved to dev team.
368
369=item B<snapvm>
370
371Snapshot a virtual machine for pb usage
372
373=item B<snapve>
374
375Snapshot a virtual environment for pb usage
376
377=item B<updateconf>
378
379Update the configuration files to the latest format
380
381=item B<updatevm>
382
383Update the distribution in the virtual machine
384
385=item B<updateve>
386
387Update the distribution in the virtual environment
388
389=item B<updaterm>
390
391Update the distribution in the remote machine
392
393=item B<test2pkg>
394
395Test a package locally
396
397=item B<test2vm>
398
399Test a package in a virtual machine
400
401=item B<test2ve>
402
403Test a package in a virtual environment
404
405=item B<test2rm>
406
407Test a package in a remote machine
408
409=item B<checkssh>
410
411Check the delivery of the packages on the repository
412
413=item B<checkps>
414
415Check the process running the VM concerned
416
417=item B<newver>
418
419Create a new version of the project derived
420from the current one
421
422=item B<newproj>
423
424Create a new project and a template set of
425configuration files under pbconf
426
427=item B<announce>
428
429Announce the availability of the project through various means
430
431=item B<sbx2webssh>
432
433Create tar files for the website under your CMS.
434Current state of the exported content is taken.
435Deliver the content to the target server using ssh from the exported dir.
436
437=item B<cms2webssh>
438
439Create tar files for the website from your CMS.
440Deliver the content to the target server using ssh from the DVCS.
441
442=item B<sbx2webpkg>
443
444Create tar files for the website under your CMS.
445Current state of the exported content is taken.
446
447=item B<cms2webpkg>
448
449Create tar files for the website under your CMS.
450
451=item B<getconf>
452
453Print the full configuration parameters as found in the various configuration files. Help to debug conf issues.
454Also accepts a parameter to display only this value, and a VM/VE/RM
455
456=item B<getvar>
457
458Print the full variables expanded based on the distribution tuple. Help to debug conf issues.
459Also accepts a parameter to display only the values for this package, and a VM/VE/RM
460
461=item B<clean>
462
463Purge the build and delivery directories related to the current project
464
465=item B<cleanssh>
466
467Purge the ssh server of its packages (only for testver and test packages)
468
469=back
470
471<pkgs> can be a list of packages, the keyword 'all' or nothing, in which case the default list of packages is taken (corresponding to the defpkgdir list of arguments in the configuration file).
472
473=head1 WEB SITES
474
475The main Web site of the project is available at L<http://www.project-builder.org/>. Bug reports should be filled using the trac instance of the project at L<http://trac.project-builder.org/>.
476
477=head1 USER MAILING LIST
478
479None exists for the moment.
480
481=head1 CONFIGURATION FILES
482
483Each pb user may have a configuration in F<$HOME/.pbrc.yml>. The values in this file may overwrite any other configuration file value.
484
485Here is an example of such a configuration file:
486
487 #
488 # Define for each project the URL of its pbconf repository
489 # No default option allowed here as they need to be all different
490 #
491 # URL of the pbconf content
492 # This is the format of a classical URL with the extension of additional schema such as
493 # svn+ssh, cvs+ssh, ...
494 #
495  pbconfurl:
496    linuxcoe : cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe/pbconf
497
498 # This is normaly defined in the project's configuration file
499 # Url of the project
500 #
501  pbprojurl:
502    linuxcoe : cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe
503 
504 # All these URLs needs to be defined here as the are the entry point
505 # for how to build packages for the project
506 #
507  pbconfurl:
508    pb: svn+ssh://svn.project-builder.org/mondo/svn/pb/pbconf
509  pbconfurl:
510    mondorescue: svn+ssh://svn.project-builder.org/mondo/svn/project-builder/mondorescue/pbconf
511  pbconfurl:
512    collectl: svn+ssh://bruno@svn.mondorescue.org/mondo/svn/project-builder/collectl/pbconf
513  pbconfurl:
514    netperf: svn+ssh://svn.mondorescue.org/mondo/svn/project-builder/netperf/pbconf
515 
516 # Under that dir will take place everything related to pb
517 # If you want to use VMs/chroot/..., then use $ENV{'HOME'} to make it portable
518 # to your VMs/chroot/...
519 # if not defined then /var/cache
520  pbdefdir:
521    default: $ENV{'HOME'}/project-builder
522  pbdefdir:
523    pb: $ENV{'HOME'}
524  pbdefdir:
525    linuxcoe: $ENV{'HOME'}/LinuxCOE/cvs
526  pbdefdir:
527    mondorescue: $ENV{'HOME'}/mondo/svn
528 
529 # pbconfdir points to the directory where the CMS content of the pbconfurl is checked out
530 # If not defined, pbconfdir is under pbdefdir/pbproj/pbconf
531  pbconfdir:
532    linuxcoe: $ENV{'HOME'}/LinuxCOE/cvs/pbconf
533  pbconfdir:
534    mondorescue: $ENV{'HOME'}/mondo/svn/pbconf
535 
536 # pbdir points to the directory where the CMS content of the pbprojurl is checked out
537 # If not defined, pbdir is under pbdefdir/pbproj
538 # Only defined if we have access to the dev of the project
539  pbdir:
540    linuxcoe: $ENV{'HOME'}/LinuxCOE/cvs
541  pbdir:
542    mondorescue: $ENV{'HOME'}/mondo/svn
543 
544 # -daemonize doesn't work with qemu 0.8.2
545  vmopt:
546    default: -m 384
547
548=head1 COMMAND DETAILS
549
550=head2 newproj
551
552The newproj command creates a new project-builder project.  To run this command you first need to define two variables in your ~/.pbrc.yml file:
553
554 pbconfurl I<project> = file:///home/anderse/.git/project-builder-config/I<project>
555 pbdefdir default = $ENV{'HOME'}/cache-project-builder
556
557The first line defines the version controlled configuration information and the second defines the root directory for project-builder to use.
558
559You can then run the command:
560
561 % pb -p I<$project> -r I<$version> newproj I<$pkg>
562
563to create the new project. Running the newproj command will then generate the file $pbdefdir/$project/pbconf/$version/$project.yml, and the directory $pbdefdir/$project/pbconf/$version/$pkg. You will need to edit those files to make the later commands work.
564
565=head2 cms2build
566
567The cms2build command takes your files from the content management system and makes the two tar files that are necessary for building files. You need to have run the newproj command first.  Then there are several steps for running this command:
568
569=over 4
570
571=item Update your $project.yml configuration file.
572
573You need to set the pbprojurl, pbrepo, pbwf, pbpackager, projver, projtag, testver, delivery, and defpkgdir lines as described in the configuration file. The pbprojurl entry is used to find the source for your package. The pbrepo entry is used to build the .repo or .sources.list files for use by downloaders of the package. The pbwf entry indicates that the source tar file is named by I<package-name>-I<version>. The pbpackager entry will be stored in the packages and should be you or your team. The projver/projtag entries indicate the version of the software and the version of the packaging scripts. The testver entry when true indicates that the package is in a test version, so no log file is computed (can be long), and version is made up using a timstamp. The delivery entry gives the subdirectory under which the packages will be delivered on the repository, and the defpkgdir entry corresponds to the local subdirectory hosting the package content.
574
575For example:
576
577 pbprojurl Lintel = file:///home/anderse/projects/Lintel-0.2012.02.28.tar.gz
578 pbrepo Lintel = http://tesla.hpl.hp.com/opensource
579 pbwf Lintel = 1
580 pbpackager Lintel = Eric Anderson <eric.anderson4@hp.com>
581 projver Lintel = 0.2012.02.28
582 projtag Lintel = 1
583 testver Lintel = false
584 delivery Lintel = production
585 defpkgdir Lintel = Lintel-0.2012.02.28
586
587=item Create the build .tar.gz files:
588
589Then you need to take those files and create the initial tar files.  Run a command like:
590
591 % pb -p $project -r $version cms2build
592
593To create the $pbdefdir/$project/pbdelivery/$project-$version.{,pbconf}.tar.gz files, the $version-$projtag.yml and pbrc.yml files in the same directory.
594
595=back
596
597=head2 build2pkg
598
599The build2pkg command takes the tar files created in the cms2build step and attempts to build binary packages for your current operating system. There are two steps:
600
601=over 4
602
603=item Update your filters and build files.
604
605You probably need to edit the files describing the build steps in one of the $pbdefdir/$project/pbconf/$version/$project/{deb,rpm,pkg} directories and the filters in $pbdefdir/$project/pbconf/$version/pbfilter. Note that you can define additional filters and transformations in the filters files. The build files will be filtered by the filters defined in the filters files to generate the inputs to the build step. Therefore, if you change those files, you need to re-run the cms2build step.
606
607=item Build the package.
608
609Then you can run a command like:
610
611 % pb -p $project -r $version build2pkg
612
613To create the files in $project/pbbuild that comprise your binary package(s).
614
615=back
616
617=head2 newve
618 
619The newve command creates a new virtual environment, i.e. a chrooted OS for building packages. Using a virtual environment is an efficient way to build packages on a related set of operating systems. The OS's have to be related because the kernel will be shared.  Steps:
620
621=over 4
622
623=item Update ~/.pbrc.yml
624
625Update your ~/.pbrc.yml file to specify the vepath, velist, velogin, and vetype variables, e.g.:
626
627  vepath:
628    default: $ENV{'HOME'}/cache-project-builder/chroot
629  velist:
630    default: debian-6.0-i386
631  velogin:
632    default: pb
633  vetype:
634    default: chroot
635
636If you are building for rpm style OS's, update the verpmtype option, and install the appropriate tool.
637
638  verpmtype:
639    default: rpmbootstrap
640
641You may also choose to specify a mirror for the OS packages, and optionally http/ftp proxies.  You can specify the proxies either through environment variables ($http_proxy/$https_proxy/$ftp_proxy) or in the configuration file. The configuration file will be used if no corresponding environment variable has been set. For example, for debian and with a local squid proxy:
642
643  rbsmirrorsrv:
644    debian: http://mirrors1.kernel.org/debian/
645  http_proxy:
646    default: http://localhost:3128/
647  https_proxy:
648    default: http://localhost:3128/
649  ftp_proxy:
650    default: http://localhost:3128/
651
652=item Run the cms2build command
653
654If you have deleted your $package/pbdelivery directory, re-run the cms2build command as in the earlier step. This step is necessary to generate the I<package>/pbdelivery/pbrc.yml file.
655
656=item Create the new virtual environment
657
658Initialize the new operating system. This step will install the core OS packages for the virtual environment, e.g.:
659
660 % pb -v -p $project -m debian-6.0-i386 newve
661
662=back
663
664=head2 setupve
665
666The setupve command prepares a virtual environment for use by project builder. In particular it installs project-builder from the packages into the virtual environment. Two sub-steps are necessary:
667
668=over 4
669
670=item Update $project.yml
671
672You need to have a sshhost entry for setupve to work, so add one, even an invalid one, e.g.:
673
674  sshhost:
675    $project: foo.example.org
676
677=item Setup the virtual environment
678
679 % pb -v -p $project -m debian-6.0-i386 setupve
680
681If you prefer to install the current SVN version of project builder, you can substitute the setupve option by the sbx2setupv one.
682
683=back
684
685=head2 build2ve
686
687The build2ve command is similar to the build2pkg command in that it will take the sources created by cms2build and turn them into binary packages. The command has two differences. First, it creates the packages in a virtual environment, i.e. the one made by an earlier setupve setup. Second it copies the resulting packages to a repository and builds the repository meta-data needed.
688
689Three sub-steps are needed:
690
691=over 4
692
693=item Update $project.yml
694
695You need to have a valid sshdir and sshhost entry for build2ve to work, so add them. Note that you need to be able to ssh from the host you run the command on to the repository host, preferably without needing to type in a password, so using ssh-agent or having a special passwordless project-builder ssh key will make this step easier.
696
697  sshhost:
698    $project: localhost
699  sshdir:
700    $project: $home/cache-project-builder/repos
701
702You may also need to specify additional repository files to use or rpms to install. Note the URL for repositories is not the URL of the repository, but the URL of a file that can be put in the yum.repos.d or apt.sources.d directory.
703
704  addrepo:
705    centos-5-i386: http://localhost/pb/centos-extras.repo,http://mirror.centos.org/centos/5/extras/i386/RPMS/chrpath-0.13-3.el5.centos.i386.rpm
706
707=item Update your filters and build files
708
709You may need to update your filter files as in the build2pkg step if you are building for a new OS or architecture.
710
711=item Build the packages and copy them to the repository
712
713 % pb -v -p $project -m debian-6.0-i386 build2ve
714
715=back
716
717*Debugging:* If the build fails (and you did not specify the --no-stop-on-error) option, then the virtual environment and scripts should still be present and configured to build the package. You can run a command like 'sudo setarch i386 chroot $path bash' in order to get into the environment. In your log you should see a command like that. From there you can go into the /home/pb directory as the pb user and run the same style of pb commands as you did when doing build2pkg. This will help you figure out what has gone wrong in the build in the virtual environment.
718
719=head1 AUTHORS
720
721The Project-Builder.org team L<http://trac.project-builder.org/> lead by Bruno Cornec L<mailto:bruno@project-builder.org>.
722
723=head1 COPYRIGHT
724
725Project-Builder.org is distributed under the GPL v2.0 license
726described in the file C<COPYING> included with the distribution.
727
728=cut
729
730# ---------------------------------------------------------------------------
731
732my ($projectbuilderver,$projectbuilderrev,$projectbuilderconfver) = pb_version_init();
733my $appname = "pb";
734
735# Initialize the syntax string
736
737pb_syntax_init("$appname (aka project-builder.org) Version $projectbuilderver-$projectbuilderrev Conf $projectbuilderconfver\n");
738
739GetOptions("help|?|h+" => \$opts{'h'}, 
740        "account|a=s" => \$opts{'a'},
741        "force|f" => \$opts{'f'},
742        "nographic|g" => \$opts{'g'},
743        "image|i=s" => \$opts{'i'},
744        "log-files|l=s" => \$opts{'l'},
745        "machines|mock|m=s" => \$opts{'m'},
746        "man" => \$opts{'man'},
747        "port|P=i" => \$opts{'P'},
748        "project|p=s" => \$opts{'p'},
749        "quiet|q" => \$opts{'q'},
750        "revision|r=s" => \$opts{'r'},
751        "rebuild" => \$opts{'rebuild'},
752        "snapshot|S" => \$opts{'S'},
753        "script|s=s" => \$opts{'s'},
754        "type|T:s" => \$opts{'T'},
755        "target|t:s" => \$opts{'t'},
756        "version" => \$opts{'version'},
757        "V=s" => \$opts{'V'},
758        "verbose|v+" => \$opts{'v'},
759        "keep|k" => \$opts{'k'},
760        "stop-on-error!" => \$Global::pb_stop_on_error,
761) || pb_syntax(-1,0);
762
763if (defined $opts{'l'}) {
764    open(pbLOG,"> $opts{'l'}") || confess "Unable to log to $opts{'l'}: $!";
765    $pbLOG = \*pbLOG;
766    $pbdebug = 0  if ($pbdebug == -1);
767    }
768pb_log_init($pbdebug, $pbLOG);
769
770if (defined $opts{'h'}) {
771    pb_syntax(0,1);
772}
773if (defined $opts{'version'}) {
774    pb_syntax(0,0);
775}
776if (defined $opts{'man'}) {
777    pb_syntax(0,2);
778}
779if (defined $opts{'v'}) {
780    $pbdebug = $opts{'v'};
781}
782if (defined $opts{'f'}) {
783    $pbforce=1;
784}
785if (defined $opts{'q'}) {
786    $pbdebug=-1;
787}
788if (defined $opts{'S'}) {
789    $pbsnap=1;
790}
791if (defined $opts{'k'}) {
792    $pbkeep=1;
793}
794pb_display_init("text","");
795
796# Handle root of the project if defined
797if (defined $opts{'r'}) {
798    $ENV{'PBROOTDIR'} = $opts{'r'};
799}
800# Handle virtual machines if any
801if (defined $opts{'m'}) {
802    $ENV{'PBV'} = $opts{'m'};
803}
804if (defined $opts{'s'}) {
805    $pbscript{'default'} = $opts{'s'};
806    confess "option -s requires a script having a full path name" if ($pbscript{'default'} !~ /^\//);
807}
808if (defined $opts{'a'}) {
809    $ENV{'PBACCOUNT'} = $opts{'a'};
810    confess "option -a requires a -s script option" if (not defined $pbscript{'default'});
811}
812if (defined $opts{'P'}) {
813    $pbport = $opts{'P'};
814}
815if (defined $opts{'V'}) {
816    $newver = $opts{'V'};
817}
818if (defined $opts{'i'}) {
819    $pbimage = $opts{'i'};
820}
821if (defined $opts{'t'}) {
822    $pbtarget = $opts{'t'};
823}
824if (defined $opts{'T'}) {
825    $vetype = $opts{'T'};
826}
827
828# Get Action
829$action = shift @ARGV;
830confess pb_syntax(-1,1) if (not defined $action);
831
832my ($filteredfiles, $supfiles, $defpkgdir, $extpkgdir);
833my $pbinit = undef;
834$pbinit = 1 if ($action =~ /^newproj$/);
835
836# Handles project name if any
837# And get global params
838($filteredfiles, $supfiles, $defpkgdir, $extpkgdir) = pb_env_init($opts{'p'},$pbinit,$action,$pbkeep);
839
840#
841# Check for command requirements
842#
843my ($req,$opt,$pbpara,$pbshowsudo,$pbstoponerr) = pb_conf_get_if("oscmd","oscmdopt","pbparallel","pbshowsudo","pbstoponerr");
844pb_check_requirements($req,$opt,$appname);
845
846$Global::pb_show_sudo = 1 if ((defined $pbshowsudo) && (defined $pbshowsudo->{$ENV{'PBPROJ'}}) && ($pbshowsudo->{$ENV{'PBPROJ'}} =~ /true/oi));
847$Global::pb_stop_on_error = 1 if ((defined $pbstoponerr) && (defined $pbstoponerr->{$ENV{'PBPROJ'}}) && ($pbstoponerr->{$ENV{'PBPROJ'}} =~ /true/oi));
848
849#
850# Check if we can launch some actions in // with Parallel::ForkManager
851#
852my $pbparallel = $pbpara->{$appname} if (defined $pbpara);
853if (not defined $pbparallel) {
854    eval
855    {
856        require Sys::CPU;
857        Sys::CPU->import();
858    };
859    if ($@) {
860        # Sys::CPU not found, defaulting to 1
861        pb_log(1,"ADVISE: Install Sys::CPU to benefit from automatic parallelism optimization.\nOr use pbparallel in your pb.yml file\nOnly 1 process at a time for the moment\n");
862        $pbparallel = 1;
863    } else {
864        # Using the number of cores
865        $pbparallel = Sys::CPU::cpu_count();
866        pb_log(1,"Using parallel mode with $pbparallel processes\n");
867    }
868}
869
870eval
871{
872    require Parallel::ForkManager;
873    Parallel::ForkManager->import();
874};
875# Parallel::ForkManager not found so no // actions
876if ($@) {
877    $pbparallel = undef;
878    pb_log(1,"ADVISE: Install Parallel::ForkManager to benefit from automatic parallelism optimization.\nOnly 1 process at a time for the moment\n");
879}
880
881if ($action ne "getconf") {
882    pb_log(0,"Project: $ENV{'PBPROJ'}\n");
883    pb_log(0,"Action: $action\n");
884}
885
886my $do_install = undef;
887# Possibility to add a 2ins to some commands to launch automatic installation
888$do_install = 1 if ($action =~ /2ins$/);
889
890# Act depending on action
891if ($action =~ /^cms2build$/) {
892    pb_cms2build("CMS");
893} elsif ($action =~ /^sbx2build$/) {
894    pb_cms2build("SandBox");
895} elsif ($action =~ /^build2prep$/) {
896    pb_build2prep();
897} elsif ($action =~ /^sbx2prep$/) {
898    pb_cms2build("SandBox");
899    pb_build2prep();
900} elsif ($action =~ /^build2pkg/) {
901    pb_build2pkg($do_install);
902} elsif ($action =~ /^cms2pkg/) {
903    pb_cms2build("CMS");
904    pb_build2pkg($do_install);
905} elsif ($action =~ /^sbx2pkg/) {
906    pb_cms2build("SandBox");
907    pb_build2pkg($do_install);
908} elsif ($action =~ /^build2ssh$/) {
909    pb_build2ssh();
910} elsif ($action =~ /^cms2ssh$/) {
911    pb_cms2build("CMS");
912    pb_build2ssh();
913} elsif ($action =~ /^sbx2ssh$/) {
914    pb_cms2build("SandBox");
915    pb_build2ssh();
916} elsif ($action =~ /^pkg2ssh$/) {
917    pb_pkg2ssh();
918} elsif ($action =~ /^build2rm$/) {
919    pb_build2v("rm","build");
920} elsif ($action =~ /^build2ve$/) {
921    pb_build2v("ve","build");
922} elsif ($action =~ /^build2vm$/) {
923    pb_build2v("vm","build");
924} elsif ($action =~ /^sbx2preprm$/) {
925    pb_cms2build("SandBox");
926    pb_build2v("rm","prep");
927} elsif ($action =~ /^sbx2prepve$/) {
928    pb_cms2build("SandBox");
929    pb_build2v("ve","prep");
930} elsif ($action =~ /^sbx2prepvm$/) {
931    pb_cms2build("SandBox");
932    pb_build2v("vm","prep");
933} elsif ($action =~ /^preprm$/) {
934    pb_build2v("rm","prep");
935} elsif ($action =~ /^prepve$/) {
936    pb_build2v("ve","prep");
937} elsif ($action =~ /^prepvm$/) {
938    pb_build2v("vm","prep");
939} elsif ($action =~ /^cms2rm$/) {
940    pb_cms2build("CMS");
941    pb_build2v("rm","build");
942} elsif ($action =~ /^cms2ve$/) {
943    pb_cms2build("CMS");
944    pb_build2v("ve","build");
945} elsif ($action =~ /^sbx2rm$/) {
946    pb_cms2build("SandBox");
947    pb_build2v("rm","build");
948} elsif ($action =~ /^sbx2ve$/) {
949    pb_cms2build("SandBox");
950    pb_build2v("ve","build");
951} elsif ($action =~ /^cms2vm$/) {
952    pb_cms2build("CMS");
953    pb_build2v("vm","build");
954} elsif ($action =~ /^sbx2vm$/) {
955    pb_cms2build("SandBox");
956    pb_build2v("vm","build");
957} elsif ($action =~ /^launchvm$/) {
958    pb_parallel_launchv(undef,"vm",undef,3,$pbimage);
959} elsif ($action =~ /^launchve$/) {
960    pb_parallel_launchv(undef,"ve",undef,3,$pbimage);
961} elsif ($action =~ /^script2vm$/) {
962    confess "action script2vm requires a -s script option" if (not defined $pbscript{'default'});
963    pb_script2v(\%pbscript,"vm");
964} elsif ($action =~ /^script2ve$/) {
965    confess "action script2ve requires a -s script option" if (not defined $pbscript{'default'});
966    pb_script2v(\%pbscript,"ve");
967} elsif ($action =~ /^script2rm$/) {
968    confess "action script2rm requires a -s script option" if (not defined $pbscript{'default'});
969    pb_script2v(\%pbscript,"rm");
970} elsif ($action =~ /^newver$/) {
971    pb_newver();
972} elsif ($action =~ /^sbx2docker$/) {
973    my $savproj = $ENV{'PBPROJ'};
974    my $pkg;
975    my @pkg;
976    if ($#ARGV == -1) {
977        $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
978        @pkgs = @$pkg;
979    } else {
980        @pkgs = @ARGV;
981    }
982    #pb_log(1,"Packages to print:".Dumper(@pkgs)."\n");
983   
984    # Get the list of all VE we need to work on
985    my ($vm,$all);
986    if (not defined $ENV{'PBV'}) {
987        ($vm,$all) = pb_get2v("ve");
988    } else {
989        @$vm = split(/,/,$ENV{'PBV'});
990    }
991   
992    # TODO: parallelize
993    foreach my $v (@$vm) {
994        my $done = 0;
995        my $pbos = pb_distro_get_context($v);
996        # Docker images are (for now !) regular and use distro:ver
997        $pbimage = "$pbos->{'name'}".":$pbos->{'version'}";
998        # the first steps needs to be done with the pb project
999        $ENV{'PBPROJ'} = $appname;
1000        my $found = pb_ve_docker_get_image("$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}");
1001        if (($pbforce == 1) || (not defined $found)) {
1002            # pb -p pb -m distro-ver-arch newve -i distro:ver
1003            pb_log(0,"Docker container $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'} not found, creating it\n");
1004            pb_parallel_launchv(undef,"ve",undef,0,$pbimage);
1005        }
1006        $found = pb_ve_docker_get_image("$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-pb");
1007        if (($pbforce == 1) || (not defined $found)) {
1008            pb_log(0,"Docker container $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-pb not found, creating it\n");
1009            # pb -p pb -m distro-ver-arch setupve
1010            if ($savproj eq "pb") {
1011                pb_cms2build("SandBox");
1012                $done = 1;
1013                pb_setup2v("ve","SandBox");
1014            } else {
1015                pb_setup2v("ve");
1016            }
1017        }
1018        # Now back to our original project
1019        $ENV{'PBPROJ'} = $savproj;
1020        $found = pb_ve_docker_get_image("$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-pb-$ENV{'PBPROJ'}");
1021        if (($pbforce == 1) || (not defined $found)) {
1022            pb_log(0,"Docker container $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-pb-$ENV{'PBPROJ'} not found, creating it\n");
1023            # pb -p pb -m distro-ver-arch prepve
1024            if ($savproj eq "pb") {
1025                pb_cms2build("SandBox");
1026                $done = 1;
1027            }
1028            pb_build2v("ve","prep");
1029        }
1030        pb_log(0,"Instantiating a Docker container from $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-pb-$ENV{'PBPROJ'}\n");
1031        if (($savproj ne "pb") || ($done == 0)) {
1032            pb_cms2build("SandBox");
1033        }
1034        pb_build2v("ve","build");
1035    }
1036} elsif ($action =~ /^newve$/) {
1037    pb_parallel_launchv(undef,"ve",undef,0,$pbimage);
1038} elsif ($action =~ /^newvm$/) {
1039    pb_parallel_launchv(undef,"vm",undef,0,$pbimage);
1040    pb_log(0, "Please ensure that sshd is running in your VM by default\n");
1041    pb_log(0, "and that it allows remote root login (PermitRootLogin yes in /etc/ssh/sshd_config)\n");
1042    pb_log(0, "Also ensure that network is up, firewalling correctly configured\n");
1043    pb_log(0, "and perl-YAML, perl-Date-Manip, tar, sudo, ntpdate, make and scp/ssh installed\n");
1044    pb_log(0, "You should then be able to login with ssh -p VMPORT root\@localhost (if VM started with pb)\n");
1045} elsif ($action =~ /^setuprm$/) {
1046    pb_setup2v("rm");
1047} elsif ($action =~ /^setupve$/) {
1048    pb_setup2v("ve");
1049} elsif ($action =~ /^setupvm$/) {
1050    pb_setup2v("vm");
1051} elsif ($action =~ /^sbx2setuprm$/) {
1052    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1053    pb_cms2build("SandBox");
1054    pb_setup2v("rm","SandBox");
1055} elsif ($action =~ /^sbx2setupve$/) {
1056    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1057    pb_cms2build("SandBox");
1058    pb_setup2v("ve","SandBox");
1059} elsif ($action =~ /^sbx2setupvm$/) {
1060    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1061    pb_cms2build("SandBox");
1062    pb_setup2v("vm","SandBox");
1063} elsif ($action =~ /^build2setuprm$/) {
1064    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1065    pb_setup2v("rm","SandBox");
1066} elsif ($action =~ /^build2setupve$/) {
1067    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1068    pb_setup2v("ve","SandBox");
1069} elsif ($action =~ /^build2setupvm$/) {
1070    confess "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
1071    pb_setup2v("vm","SandBox");
1072} elsif ($action =~ /^updaterm$/) {
1073    pb_update2v("rm");
1074} elsif ($action =~ /^updateve$/) {
1075    pb_update2v("ve");
1076} elsif ($action =~ /^updatevm$/) {
1077    pb_update2v("vm");
1078} elsif ($action =~ /^snapve$/) {
1079    pb_snap2v("ve");
1080} elsif ($action =~ /^snapvm$/) {
1081    pb_snap2v("vm");
1082} elsif ($action =~ /^test2pkg$/) {
1083    pb_test2pkg();
1084} elsif ($action =~ /^test2rm$/) {
1085    pb_build2v("rm","test");
1086} elsif ($action =~ /^test2ve$/) {
1087    pb_build2v("ve","test");
1088} elsif ($action =~ /^test2vm$/) {
1089    pb_build2v("vm","test");
1090} elsif ($action =~ /^newproj$/) {
1091    # Nothing to do - already done in pb_env_init
1092} elsif ($action =~ /^updateconf$/) {
1093    foreach my $f (@ARGV) {
1094        my $fyml = $f;
1095        $fyml =~ s/\.pbf/.yml/;
1096        $fyml =~ s/\.pb/.yml/;
1097        $fyml =~ s/\.pbrc/.pbrc.yml/;
1098        pb_vcs_conf_update_v0($f,$fyml);
1099    }
1100} elsif ($action =~ /^getconf$/) {
1101    my $pbos = pb_distro_get_context($ENV{'PBV'});
1102    pb_log(1,"Arguments to print:".Dumper(@ARGV)."\n");
1103    pb_distro_conf_print($pbos,@ARGV);
1104} elsif ($action =~ /^getvar$/) {
1105    my $pbos = pb_distro_get_context($ENV{'PBV'});
1106    my $pkg;
1107    my @pkg;
1108    if ($#ARGV == -1) {
1109        $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
1110        @pkgs = @$pkg;
1111    } else {
1112        @pkgs = @ARGV;
1113    }
1114    pb_log(1,"Packages to print:".Dumper(@pkgs)."\n");
1115    pb_filter_var_print($pbos,@pkgs);
1116} elsif ($action =~ /^clean$/) {
1117    pb_clean();
1118} elsif ($action =~ /^announce$/) {
1119    # For announce only. Require avoids the systematic load of these modules
1120    require DBI;
1121    require DBD::SQLite;
1122
1123    pb_announce("Announce");
1124} elsif ($action =~ /^cleanssh$/) {
1125    pb_announce("Clean");
1126} elsif ($action =~ /^checkssh$/) {
1127    pb_announce("Check");
1128} elsif ($action =~ /^checkps$/) {
1129    my ($ptr2) = pb_conf_get("vmcmd");
1130    my $vmcmd = $ptr2->{$ENV{'PBPROJ'}};
1131    my ($vexist,$vmmport) = pb_check_ps($vmcmd,$ENV{'PBV'});
1132    if (! $vexist) {
1133        pb_log(0,"No VM found for $ENV{'PBV'}\n");
1134    } else {
1135        pb_log(0,"Found an existing VM for $ENV{'PBV'} PID: $vexist - SSH port: $vmmport\n");
1136    }
1137} elsif ($action =~ /^sbx2webpkg$/) {
1138    require DBI;
1139    require DBD::SQLite;
1140
1141    pb_cms2build("SandBox","Web");
1142} elsif ($action =~ /^sbx2webssh$/) {
1143    require DBI;
1144    require DBD::SQLite;
1145
1146    pb_cms2build("SandBox","Web");
1147    pb_send2target("Web");
1148} elsif ($action =~ /^cms2webpkg$/) {
1149    require DBI;
1150    require DBD::SQLite;
1151
1152    pb_cms2build("CMS","Web");
1153} elsif ($action =~ /^cms2webssh$/) {
1154    require DBI;
1155    require DBD::SQLite;
1156
1157    pb_cms2build("CMS","Web");
1158    pb_send2target("Web");
1159} else {
1160    pb_log(0,"\'$action\' is not available\n");
1161    pb_syntax(-2,1);
1162}
1163
1164pb_exit();
1165
1166sub pb_cms2build {
1167
1168    my $param = shift;
1169    my $web = shift;
1170
1171    my $pkg;
1172    my @pkgs;
1173    my $webdir;
1174
1175    my %pkgs;
1176    my $pb;             # Structure to store conf info
1177
1178    confess "pb_cms2build requires a parameter: SandBox or CMS" if (not defined $param);
1179
1180    # If Website, then pkg is only the website
1181    if (defined $web) {
1182        ($webdir) = pb_conf_get("webdir");
1183        pb_log(2,"webdir: ".Dumper($webdir)."\n");
1184        $pkgs[0] = $webdir->{$ENV{'PBPROJ'}};
1185        $extpkgdir = $webdir;
1186        pb_log(0,"Package: $pkgs[0]\n");
1187    } else {
1188        $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
1189        @pkgs = @$pkg;
1190    }
1191
1192    my ($scheme, $uri) = pb_vcs_init($pbinit,$param);
1193
1194    # We need 2 lines here
1195    my ($pkgv, $pkgt, $testver) = pb_conf_get_if("pkgver","pkgtag","testver");
1196
1197    # declare packager and repo for filtering
1198    my ($tmp1, $tmp2) = pb_conf_get("pbpackager","pbrepo");
1199    $ENV{'PBPACKAGER'} = $tmp1->{$ENV{'PBPROJ'}};
1200    $ENV{'PBREPO'} = $tmp2->{$ENV{'PBPROJ'}};
1201    my ($delivery) = pb_conf_get_if("delivery");
1202    $delivery->{$ENV{'PBPROJ'}} = "" if (not defined $delivery->{$ENV{'PBPROJ'}});
1203
1204    # If we deal with a test dir, we want to keep the date in tar file and dir name
1205    my $pbextdirpkg = "";
1206    my $pbextdir = "";
1207    if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
1208        $pbextdirpkg = strftime("%Y%m%d%H%M%S", @date);
1209        $pbextdir = ".0.".$pbextdirpkg;
1210    }
1211
1212    foreach my $pbpkg (@pkgs) {
1213        $ENV{'PBPKG'} = $pbpkg;
1214        $pbrev = $ENV{'PBREVISION'};
1215
1216        if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
1217            $pbver = $pkgv->{$pbpkg};
1218        } else {
1219            $pbver = $ENV{'PBPROJVER'};
1220        }
1221        # If it's a test version, then build a tag to fit distributions need
1222        if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
1223            my $letter = "";
1224            if ($scheme =~ /svn/) {
1225                $letter = "s";
1226            } elsif ($scheme =~ /cvs/) {
1227                $letter = "c";
1228            } elsif ($scheme =~ /svk/) {
1229                $letter = "k";
1230            } elsif ($scheme =~ /hg/) {
1231                $letter = "h";
1232            } elsif ($scheme =~ /git/) {
1233                $letter = "g";
1234            } else {
1235                $letter = "f";
1236            }
1237            $pbtag = "0.$pbextdirpkg.$letter$pbrev";
1238            $ENV{'PBPROJTAG'} = $pbtag;
1239        } elsif ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
1240            $pbtag = $pkgt->{$pbpkg};
1241        } else {
1242            $pbtag = $ENV{'PBPROJTAG'};
1243        }
1244
1245        if (($pbtag =~ /:/) && ($scheme =~ /svn/)) {
1246            confess "RPM doesn't support release tag with ':'. Try to svn up before running pb";
1247        }
1248
1249        pb_log(0,"\n");
1250        pb_log(0,"Management of $pbpkg $pbver-$pbtag\n");
1251        confess "Unable to get env var PBDESTDIR" if (not defined $ENV{'PBDESTDIR'});
1252
1253        my $dest = "$ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir";
1254        # Create the structure if needed
1255        pb_mkdir_p($dest);
1256        # Clean up dest if necessary. The export will recreate it
1257        pb_rm_rf($dest) if (-d $dest);
1258
1259        # Export CMS tree for the concerned package to dest
1260        # And generate some additional files
1261        $OUTPUT_AUTOFLUSH=1;
1262
1263        # computes in which dir we have to work
1264        my $dir = $defpkgdir->{$pbpkg};
1265        $dir = $extpkgdir->{$pbpkg} if (not defined $dir);
1266        $dir = $webdir->{$ENV{'PBPROJ'}} if (defined $web);
1267        confess "Variable \$dir not defined. Check the package name first.\nIf this is the one expected, please report to dev team with log of a verbose run and this info ".Dumper($defpkgdir,$extpkgdir,$webdir) if (not defined $dir);
1268        pb_log(2,"def:".Dumper($defpkgdir)."ext: ".Dumper($extpkgdir)."dir: $dir\n");
1269
1270        # Exporting content from CMS
1271        my $sourcedir = undef;
1272        my $sourceuri = $uri;
1273        if ($param eq "SandBox") {
1274            # Point to the local instance
1275            $sourcedir = "$ENV{'PBDIR'}/$dir";
1276        } else {
1277            # Get it from a subdir of the URI with same version as localy but different root
1278            # Only if using a real CMS
1279            my ($scheme, $account, $host, $port, $path) = pb_get_uri($uri);
1280            if (($scheme !~ /^file/) && ($scheme !~ /^(ht|f)tp/)) {
1281                $sourceuri = "$ENV{'PBDIR'}/$dir"; 
1282                $sourceuri =~ s|^$ENV{'PBPROJDIR'}/|$uri/|;
1283            }
1284        }
1285        my $preserve = pb_vcs_export($sourceuri,$sourcedir,$dest);
1286
1287        # Generated fake content for test versions to speed up stuff
1288        my $chglog;
1289
1290        # Get project info on authors and log file
1291        # TODO: Make it CMS aware
1292        $chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
1293        $chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
1294        $chglog = undef if (! -f $chglog);
1295
1296        # TODO: Make it CMS aware
1297        my $authors = "$ENV{'PBROOTDIR'}/$pbpkg/pbauthors";
1298        $authors = "$ENV{'PBROOTDIR'}/pbauthors" if (! -f $authors);
1299        $authors = "/dev/null" if (! -f $authors);
1300
1301        # Extract cms log history and store it
1302        if ((defined $chglog) && (! -f "$dest/NEWS")) {
1303            pb_log(2,"Generating NEWS file from $chglog\n");
1304            copy($chglog,"$dest/NEWS") || confess "Unable to create $dest/NEWS";
1305        }
1306        pb_cms_log($scheme,"$ENV{'PBDIR'}/$dir",$dest,$chglog,$authors,$testver);
1307
1308        my %build;
1309        # We want to at least build for the underlying distro
1310        # except if a target was given, in which case we only build for it
1311        # if -t was passed without target then build for the native distro.
1312        my $pbos = pb_distro_get_context($pbtarget);
1313        my $tmpl = pb_get_distros($pbos,$pbtarget);
1314
1315        # Setup $pb structure to allow filtering later on, on files using that structure
1316        $pb->{'tag'} = $pbtag;
1317        $pb->{'rev'} = $pbrev;
1318        $pb->{'ver'} = $pbver;
1319        $pb->{'pkg'} = $pbpkg;
1320        $pb->{'suf'} = $pbos->{'suffix'};
1321        $pb->{'realpkg'} = $pbpkg;
1322        $pb->{'date'} = $pbdate;
1323        $pb->{'defpkgdir'} = $defpkgdir;
1324        $pb->{'extpkgdir'} = $extpkgdir;
1325        $pb->{'chglog'} = $chglog;
1326        $pb->{'extdir'} = $pbextdir;
1327        $pb->{'packager'} = $ENV{'PBPACKAGER'};
1328        $pb->{'proj'} = $ENV{'PBPROJ'};
1329        $pb->{'repo'} = "$ENV{'PBREPO'}/$delivery->{$ENV{'PBPROJ'}}";
1330        $pb->{'patches'} = ();
1331        $pb->{'sources'} = ();
1332   
1333        my $tmpd = "$ENV{'PBTMP'}/cms.$$";
1334        pb_mkdir_p($tmpd) if (defined $pbparallel);
1335
1336        # Get only all.yml filter at this stage for pbinit
1337        my $ptr = pb_get_filters($pbpkg);
1338
1339        # Do not do that for website
1340        if (not defined $web) {
1341            my %virt;
1342            # De-duplicate similar VM/VE/RM
1343            foreach my $d (split(/,/,$tmpl)) {
1344                # skip ill-formatted vms (name-ver-arch)
1345                next if ($d !~ /-/);
1346                $virt{$d} = $d;
1347            }
1348
1349            # Try to use // processing here
1350            my $all_ok = 1;
1351            my $pm = new Parallel::ForkManager($pbparallel) if (defined $pbparallel);
1352            $pm->run_on_finish(sub { my ($pid, $code, $id, $signal, $dump) = @_;
1353                                    $all_ok = 0 unless (($code == 0) && ($signal == 0) && ($dump == 0)); }) if (defined $pbparallel);
1354
1355            pb_log(0,"Preparing delivery ...\n");
1356            foreach my $v (keys %virt) {
1357                $pm->start and next if (defined $pbparallel);
1358
1359                # Distro context
1360                my $pbos = pb_distro_get_context($v);
1361   
1362                $pb->{'pbos'} = $pbos;
1363                $pb->{'suf'} = $pbos->{'suffix'};
1364                pb_log(3,"DEBUG: pb: ".Dumper($pb)."\n");
1365
1366                # Get all filters to apply
1367                $ptr = pb_get_filters($pbpkg,$pbos);
1368   
1369                pb_log(2,"DEBUG Filtering PBDATE => $pbdate, PBTAG => $pbtag, PBVER => $pbver\n");
1370   
1371                # We need to compute the real name of the package
1372                my $pbrealpkg = pb_cms_get_real_pkg($pbpkg,$pbos->{'type'});
1373                $pb->{'realpkg'} = $pbrealpkg;
1374                pb_log(2,"Virtual package $pbpkg has a real package name of $pbrealpkg on $pbos->{'name'}-$pbos->{'version'}\n") if ($pbrealpkg ne $pbpkg);
1375   
1376                # Filter build files from the less precise up to the most with overloading
1377                # Filter all files found, keeping the name, and generating in dest
1378   
1379                # Find all build files first relatively to PBROOTDIR
1380                # Find also all specific files referenced in the .yml conf file
1381                my %bfiles = ();
1382                my %pkgfiles = ();
1383                # Used in Filter.pm by pb_filter_file
1384
1385                $build{$v} = "no";
1386                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'os'}") {
1387                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'os'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1388                    $build{$v} = "yes";
1389                } 
1390                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'type'}") {
1391                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'type'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1392                    $build{$v} = "yes";
1393                } 
1394                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'family'}") {
1395                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'family'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1396                    $build{$v} = "yes";
1397                } 
1398                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}") {
1399                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1400                    $build{$v} = "yes";
1401                } 
1402                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}") {
1403                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1404                    $build{$v} = "yes";
1405                } 
1406                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") {
1407                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
1408                    $build{$v} = "yes";
1409                }
1410                pb_log(2,"DEBUG($v) bfiles: ".Dumper(\%bfiles)."\n");
1411   
1412                if ($build{$v} ne "no") {
1413                    # Apply now all the filters on all the files concerned
1414                    # destination dir depends on the type of file
1415                    # For patch support
1416                    # TODO: Make it CMS aware
1417                    $pb->{'patches'} = pb_list_sfiles("$ENV{'PBROOTDIR'}/$pbpkg/pbpatch", $pb->{'patches'}, $pbos, "$ENV{'PBROOTDIR'}/$pbpkg/pbextpatch");
1418                    pb_log(2,"DEBUG($v) patches: ".Dumper($pb->{'patches'})."\n");
1419                    # TODO: Make it CMS aware
1420                    $pb->{'sources'} = pb_list_sfiles("$ENV{'PBROOTDIR'}/$pbpkg/pbsrc", $pb->{'sources'}, $pbos, "$ENV{'PBROOTDIR'}/$pbpkg/pbextsrc");
1421                    pb_log(2,"DEBUG($v) sources: ".Dumper($pb->{'sources'})."\n");
1422   
1423                    if (defined $pb->{'patches'}->{$v}) {
1424                        # Filter potential patches (local + remote)
1425                        pb_mkdir_p("$dest/pbconf/$v/pbpatch");
1426                        # If Debian based distribution, then prepare what will be done at build time
1427                        my ($patchcmd,$patchopt);
1428                        if ($pbos->{'type'} eq "deb") {
1429                            ($patchcmd,$patchopt) = pb_distro_get_param($pbos,pb_conf_get_if("ospatchcmd","ospatchopt"));
1430                            open(SCRIPT,"> $dest/pbconf/$v/pbpatch/pbapplypatch") || confess "Unable to create $dest/pbconf/$v/pbpatch/pbapplypatch";
1431                            print SCRIPT "#!/bin/bash\n";
1432                            print SCRIPT "set -x\n" if ($pbdebug gt 1);
1433                        }
1434                        foreach my $pf (split(/,/,$pb->{'patches'}->{$v})) {
1435                            my $pp = basename($pf);
1436                            pb_vcs_export($pf,undef,"$dest/pbconf/$v/pbpatch");
1437                            pb_filter_file_inplace($ptr,"$dest/pbconf/$v/pbpatch/$pp",$pb);
1438                            pb_system("gzip -9f $dest/pbconf/$v/pbpatch/$pp","","quiet");
1439                            if ($pbos->{'type'} eq "deb") {
1440                                # If Debian based distribution, then prepare what will be done at build time
1441                                # by applying the patches that will be available under the debian/patches dir
1442                                print SCRIPT "$patchcmd $patchopt \< debian/patches/$pp\n";
1443                            }
1444                        }
1445                        if ($pbos->{'type'} eq "deb") {
1446                            close(SCRIPT);
1447                            chmod 0755,"$dest/pbconf/$v/pbpatch/pbapplypatch";
1448                        }
1449                        #pb_system("cat $dest/pbconf/$v/pbpatch/pbapplypatch","APPLY","verbose");
1450                    }
1451                    if (defined $pb->{'sources'}->{$v}) {
1452                        pb_mkdir_p("$dest/pbconf/$v/pbsrc");
1453                        foreach my $pf (split(/,/,$pb->{'sources'}->{$v})) {
1454                            my $pp = basename($pf);
1455                            pb_vcs_export($pf,undef,"$dest/pbconf/$v/pbsrc");
1456                            pb_filter_file_inplace($ptr,"$dest/pbconf/$v/pbsrc/$pp",$pb);
1457                        }
1458                    }
1459                    # Filter build files at the end, as they depend on patches and sources
1460                    foreach my $f (keys %bfiles) {
1461                        pb_filter_file("$ENV{'PBROOTDIR'}/$bfiles{$f}",$ptr,"$dest/pbconf/$v/$f",$pb);
1462                    }
1463                    foreach my $f (keys %pkgfiles) {
1464                        pb_filter_file("$ENV{'PBROOTDIR'}/$pkgfiles{$f}",$ptr,"$dest/pbconf/$v/$f",$pb);
1465                    }
1466                }
1467
1468                if (defined $pbparallel) {
1469                    # Communicate results back to parent
1470                    my $str = "";
1471                    $str .= "build $v = $build{$v}\n" if (defined $build{$v});
1472                    $str .= "patches $v = $pb->{'patches'}->{$v}\n" if (defined $pb->{'patches'}->{$v});
1473                    $str .= "sources $v = $pb->{'sources'}->{$v}\n" if (defined $pb->{'sources'}->{$v});
1474                    pb_set_content("$tmpd/$$","$str");
1475                    $pm->finish;
1476                }
1477            }
1478            # In the parent, we need to get the result from the children
1479            $pm->wait_all_children if (defined $pbparallel);
1480            confess "Aborting, one or more of the children failed." if ((not $all_ok) && ($Global::pb_stop_on_error));
1481            my $made = "";
1482            my %h = ();
1483            my %tmp;
1484            my %tmp2;
1485            my $pt;
1486            my $k;
1487
1488            foreach $k (<$tmpd/*>) {
1489                $made .= pb_get_content($k);
1490            }
1491            pb_rm_rf($tmpd);
1492            pb_log(3,"MADE:\n$made");
1493
1494            # Rebuild local hashes
1495            foreach $k (split(/\n/,$made)) {
1496                if ($k =~ /^\s*([A-z0-9-_]+)\s+([[A-z0-9-_.]+)\s*=\s*(.+)$/) {
1497                    $h{$1}->{$2}=$3;
1498                }
1499            }
1500            pb_log(2,"HASH: ".Dumper(%h));
1501
1502            # Patches
1503            pb_log(0,"Delivered and compressed patches ");
1504            $pt = $h{'patches'};
1505            foreach $k (keys %$pt) {
1506                foreach my $v1 (split(/,/,$pt->{$k})) {
1507                    $tmp{$v1} = "";
1508                }
1509            }
1510            if (keys %tmp) {
1511                foreach $k (keys %tmp) {
1512                    pb_log(0,"$k ");
1513                }
1514            } else {
1515                pb_log(0,"N/A");
1516            }
1517            pb_log(0,"\n");
1518
1519            # Sources
1520            pb_log(0,"Delivered additional sources ");
1521            $pt = $h{'sources'};
1522            foreach $k (keys %$pt) {
1523                foreach my $v1 (split(/,/,$pt->{$k})) {
1524                    $tmp2{$v1} = "";
1525                }
1526            }
1527            if (keys %tmp2) {
1528                foreach $k (keys %tmp2) {
1529                    pb_log(0,"$k ");
1530                }
1531            } else {
1532                pb_log(0,"N/A");
1533            }
1534            pb_log(0,"\n");
1535
1536            # Build files
1537            my @found;
1538            my @notfound;
1539            $pt = $h{'build'};
1540            foreach my $b (keys %$pt) {
1541                push @found,$b if ($pt->{$b} =~ /yes/);
1542                push @notfound,$b if ($pt->{$b} =~ /no/);
1543            }
1544            pb_log(0,"Build files have been generated for ... ".join(',',sort(@found))."\n") if (@found);
1545            pb_log(0,"No Build files found for ".join(',',sort(@notfound))."\n") if (@notfound);
1546
1547        } else {
1548            # Instead call News generation
1549            pb_web_news2html($dest);
1550            # And create an empty pbconf
1551            pb_mkdir_p("$dest/pbconf");
1552            # And prepare the pbscript to execute remotely
1553            open(SCRIPT,"> $ENV{'PBTMP'}/pbscript") || confess "Unable to create $ENV{'PBTMP'}/pbscript";
1554            print SCRIPT "#!/bin/bash\n";
1555            print SCRIPT "#set -x\n";
1556            print SCRIPT "echo ... Extracting Website content\n";
1557            print SCRIPT "find . -type f | grep -Ev '^./$pbpkg-$pbver$pbextdir.tar.gz|^./pbscript' | xargs rm -f non-existent\n";
1558            print SCRIPT "find * -type d -depth | xargs rmdir 2> /dev/null \n";
1559            print SCRIPT "tar xfz $pbpkg-$pbver$pbextdir.tar.gz\n";
1560            print SCRIPT "mv $pbpkg-$pbver$pbextdir/* .\n";
1561            print SCRIPT "rm -f $pbpkg-$pbver$pbextdir.tar.gz\n";
1562            print SCRIPT "rmdir $pbpkg-$pbver$pbextdir\n";
1563            print SCRIPT "find . -type f -print0 | xargs -0 chmod 644\n";
1564            print SCRIPT "find . -type d -print0 | xargs -0 chmod 755\n";
1565            close(SCRIPT);
1566            chmod 0755,"$ENV{'PBTMP'}/pbscript";
1567        }
1568
1569        # Apply filters to the non-build files
1570        my $liste ="";
1571        if (defined $filteredfiles->{$pbpkg}) {
1572            foreach my $f (split(/,/,$filteredfiles->{$pbpkg})) {
1573                pb_filter_file_inplace($ptr,"$dest/$f",$pb);
1574                $liste = "$f $liste";
1575            }
1576        }
1577        pb_log(2,"Files ".$liste."have been filtered\n");
1578
1579        # TODO: Make it CMS aware
1580        # Execute the pbinit script if any
1581        if (-x "$ENV{'PBROOTDIR'}/$pbpkg/pbinit") {
1582            pb_filter_file("$ENV{'PBROOTDIR'}/$pbpkg/pbinit",$ptr,"$ENV{'PBTMP'}/pbinit",$pb);
1583            chmod 0755,"$ENV{'PBTMP'}/pbinit";
1584            pb_system("cd $dest ; $ENV{'PBTMP'}/pbinit","Executing init script from $ENV{'PBROOTDIR'}/$pbpkg/pbinit under $dest","verbose");
1585        }
1586
1587        # Do we have additional script to run to prepare the environement for the project ?
1588        # Then include it in the pbconf delivery
1589        foreach my $pbvf (<$ENV{'PBROOTDIR'}/$pbpkg/pbv*.pre>,<$ENV{'PBROOTDIR'}/$pbpkg/pbv*.post>, <$ENV{'PBROOTDIR'}/$pbpkg/pbtest*>) {
1590            pb_log(1,"Handling file $pbvf\n");
1591            if (-x "$pbvf") {
1592                my $target = "$ENV{'PBTMP'}/".basename($pbvf);
1593                pb_filter_file("$pbvf",$ptr,$target,$pb);
1594                chmod 0755,"$target";
1595                pb_log(1,"Capturing file $pbvf in $target\n");
1596            }
1597        }
1598
1599        # Prepare the dest directory for archive
1600        chdir "$ENV{'PBDESTDIR'}" || confess "Unable to change dir to $ENV{'PBDESTDIR'}";
1601        if (defined $preserve) {
1602            # In that case we want to preserve the original tar file for checksum purposes
1603            # The one created is btw equivalent in that case to this one
1604            # Maybe check basename of both to be sure they are the same ?
1605            pb_log(0,"Preserving original tar file ");
1606            move("$preserve","$pbpkg-$pbver$pbextdir.tar.gz");
1607        } else {
1608            # Possibility to look at PBSRC to guess more the filename
1609            pb_system("tar cfz $pbpkg-$pbver$pbextdir.tar.gz --exclude=$pbpkg-$pbver$pbextdir/pbconf $pbpkg-$pbver$pbextdir","Creating $pbpkg tar files compressed");
1610        }
1611        pb_log(0,"Under $ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.tar.gz\n");
1612        pb_system("tar cfz $pbpkg-$pbver$pbextdir.pbconf.tar.gz $pbpkg-$pbver$pbextdir/pbconf","Creating pbconf tar files compressed");
1613        pb_log(0,"Under $ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.pbconf.tar.gz\n");
1614
1615        # Keep track of version-tag per pkg
1616        $pkgs{$pbpkg} = "$pbver-$pbtag";
1617
1618        # Final cleanup
1619        pb_rm_rf($dest) if (-d $dest);
1620    }
1621
1622    # Keep track of per package version
1623    pb_log(2,"DEBUG pkgs: ".Dumper(%pkgs)."\n");
1624    open(PKG,"> $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml") || confess "Unable to create $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml";
1625    print PKG "---\n";
1626    print PKG "pbpkg:\n";
1627    foreach my $pbpkg (keys %pkgs) {
1628        print PKG "  $pbpkg: $pkgs{$pbpkg}\n";
1629    }
1630    close(PKG);
1631
1632    # Keep track of what is generated by default
1633    # We need to store the dir and info on version-tag
1634    # Base our content on the existing .yml file
1635    copy("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.yml","$ENV{'PBDESTDIR'}/pbrc.yml");
1636    my $lh;
1637    $lh = pb_conf_cache("$ENV{'PBDESTDIR'}/pbrc.yml",$lh);
1638    $lh->{'pbroot'}->{$ENV{'PBPROJ'}} = $ENV{'PBROOTDIR'};
1639    $lh->{'projver'}->{$ENV{'PBPROJ'}} = $ENV{'PBPROJVER'};
1640    $lh->{'projtag'}->{$ENV{'PBPROJ'}} = $ENV{'PBPROJTAG'};
1641    $lh->{'pbpackager'}->{$ENV{'PBPROJ'}} = $ENV{'PBPACKAGER'};
1642    $lh->{'pbextdir'}->{$ENV{'PBPROJ'}} = $pbextdir;
1643    pb_conf_write("$ENV{'PBDESTDIR'}/pbrc.yml",$lh);
1644}
1645
1646sub pb_test2pkg {
1647    # Get the running distro to test on
1648    my $pbos = pb_distro_get_context();
1649
1650    # Get list of packages to test
1651    # Get content saved in cms2build
1652    my $ptr = pb_get_pkg();
1653    @pkgs = @$ptr;
1654
1655    # Additional potential repo
1656    my $forcerepo = pb_distro_setuprepo($pbos);
1657    foreach my $pbpkg (@pkgs) {
1658        # We need to install the package to test, and deps brought with it
1659        pb_distro_installdeps(undef,$pbos,$forcerepo,$pbpkg);
1660        pb_system("$ENV{'PBDESTDIR'}/pbtest","Launching test for $pbpkg","verbose");
1661    }
1662}
1663
1664sub pb_build2prep {
1665
1666    pb_log(0,"INFO: ------ Starting to prepare build environement ------\n");
1667
1668    # Get the running distro to build on
1669    my $pbos = pb_distro_get_context();
1670
1671    # If needed we may add repository to the build env
1672    my $forcerepo = pb_distro_setuprepo($pbos);
1673    pb_log(1,"Forcing full package install with forcerepo\n") if (defined $forcerepo);
1674
1675    # Get list of packages to build
1676    my $ptr = pb_get_pkg();
1677    @pkgs = @$ptr;
1678   
1679    # Get content saved in cms2build
1680    my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
1681    $pkg = { } if (not defined $pkg);
1682    my $pbextdir = pb_get_extdir();
1683
1684    foreach my $pbpkg (@pkgs) {
1685        my $vertag = $pkg->{$pbpkg};
1686        my @buildfiles;
1687        pb_log(2,"Vertag: $vertag\n");
1688        # get the version of the current package - maybe different
1689        ($pbver,$pbtag) = split(/-/,$vertag);
1690
1691        my $src2="$ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.pbconf.tar.gz";
1692        pb_log(2,"Pbconf file: $src2\n");
1693        pb_log(2,"Working directory: $ENV{'PBBUILDDIR'}\n");
1694
1695        my $ftype;
1696        if ($pbos->{'type'} eq "rpm") {
1697            $ftype = "\.spec\$";
1698        } elsif ($pbos->{'type'} eq "deb") {
1699            $ftype = "\/control\$";
1700        } elsif ($pbos->{'type'} eq "ebuild") {
1701            $ftype = "\.ebuild\$";
1702        } elsif ($pbos->{'type'} eq "tgz") {
1703            $ftype = "\/pbslack\$";
1704        } elsif ($pbos->{'type'} eq "pkg") {
1705            # Solaris - no deps management up to Solaris 10
1706        } elsif ($pbos->{'type'} eq "hpux") {
1707            # TODO: HP-UX
1708        } elsif ($pbos->{'type'} eq "apk") {
1709            $ftype = "\/APKBUILD\$";
1710        } else {
1711            confess "Unknown OS type format $pbos->{'type'}";
1712        }
1713
1714        @buildfiles = pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$ENV{'PBTMP'}","build");
1715        pb_log(2,"buildfiles ".Dumper(\@buildfiles)."\n");
1716        foreach my $f (@buildfiles) {
1717            if ($f =~ /$ftype/) {
1718                pb_distro_installdeps($f,$pbos,$forcerepo);
1719            }
1720        }
1721    }
1722    pb_log(0,"INFO: ------ Finished preparing build environment ------\n");
1723}
1724
1725sub pb_build2pkg {
1726
1727    my $do_install = shift;
1728
1729        # Call build2prep in case we have new deps we want to take in account
1730        # without redoing the prep phase (can be long and that helps debugging
1731        # build dependencies issues
1732    pb_build2prep();
1733    pb_log(0,"INFO: ------ Starting to build package ------\n");
1734    # Get the running distro to build on
1735    my $pbos = pb_distro_get_context();
1736
1737    # Get list of packages to build
1738    my $ptr = pb_get_pkg();
1739    @pkgs = @$ptr;
1740
1741    # Get content saved in cms2build
1742    my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
1743    $pkg = { } if (not defined $pkg);
1744    my $pbextdir = pb_get_extdir();
1745
1746    pb_mkdir_p("$ENV{'PBBUILDDIR'}") if (! -d "$ENV{'PBBUILDDIR'}");
1747    chdir "$ENV{'PBBUILDDIR'}" || confess "Unable to chdir to $ENV{'PBBUILDDIR'}";
1748    my $made = ""; # pkgs made during build
1749    my $pm;
1750    my $all_ok = 1;
1751
1752    if (defined $pbparallel) {
1753        $pm = new Parallel::ForkManager($pbparallel);
1754        $pm->run_on_finish(sub { my ($pid, $code, $id, $signal, $dump) = @_;
1755                                $all_ok = 0 unless (($code == 0) && ($signal == 0) && ($dump == 0)); });
1756    }
1757
1758    # We need to communicate info back from the children if parallel so prepare a dir for that
1759    my $tmpd = "$ENV{'PBTMP'}/build.$$";
1760    pb_mkdir_p($tmpd) if (defined $pbparallel);
1761
1762    # Do it here as this doesn't work in // mode as it dies if it fails
1763    if ($pbos->{'type'} eq "rpm") {
1764        foreach my $d ('RPMS','SRPMS','SPECS','SOURCES','BUILD') {
1765                if (! -d "$ENV{'PBBUILDDIR'}/$d") {
1766                    pb_mkdir_p("$ENV{'PBBUILDDIR'}/$d");
1767                }
1768            }
1769    }
1770
1771    foreach my $pbpkg (@pkgs) {
1772        $pm->start and next if (defined $pbparallel);
1773
1774        my $vertag = $pkg->{$pbpkg};
1775        pb_log(2,"Vertag: $vertag\n");
1776        # get the version of the current package - maybe different
1777        ($pbver,$pbtag) = split(/-/,$vertag);
1778
1779        my $src="$ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.tar.gz";
1780        my $src2="$ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.pbconf.tar.gz";
1781        pb_log(2,"Source file: $src\n");
1782        pb_log(2,"Pbconf file: $src2\n");
1783
1784        pb_log(2,"Working directory: $ENV{'PBBUILDDIR'}\n");
1785        if ($pbos->{'type'} eq "rpm") {
1786            # Remove in case a previous link/file was there
1787            unlink "$ENV{'PBBUILDDIR'}/SOURCES/".basename($src);
1788            symlink "$src","$ENV{'PBBUILDDIR'}/SOURCES/".basename($src) || confess "Unable to symlink $src in $ENV{'PBBUILDDIR'}/SOURCES";
1789            # We need to first extract the spec file
1790            my @buildfile = pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$ENV{'PBBUILDDIR'}/SPECS","build");
1791
1792            # We need to handle potential patches to upstream sources
1793            pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","$ENV{'PBBUILDDIR'}/SOURCES","patch");
1794
1795            # We need to handle potential additional sources to upstream sources
1796            pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}/SOURCES","src");
1797
1798            pb_log(2,"buildfile: ".Dumper(\@buildfile)."\n");
1799            # set LANGUAGE to check for correct log messages
1800            $ENV{'LANGUAGE'}="C";
1801            # Older Redhat use _target_platform in %configure incorrectly
1802            my $specialdef = "";
1803            if (($pbos->{'name'} eq "rhel") && ($pbos->{'version'} eq "2.1")) {
1804                $specialdef = "--define \'_target_platform \"\"\'";
1805            }
1806            my $buildcmd = "rpmbuild";
1807            if (($pbos->{'name'} eq "redhat") && ($pbos->{'version'} =~ /^6/)){
1808                $buildcmd = "rpm" ;
1809            }
1810
1811            foreach my $f (@buildfile) {
1812                if ($f =~ /\.spec$/) {
1813                    pb_system("$buildcmd $specialdef --define \"packager $ENV{'PBPACKAGER'}\" --define \"_topdir $ENV{'PBBUILDDIR'}\" -ba $f","Building package with $f under $ENV{'PBBUILDDIR'}","verbose");
1814                    last;
1815                }
1816            }
1817            # Get the name of the generated packages
1818            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || confess "Unable to open $ENV{'PBTMP'}/system.$$.log";
1819            while (<LOG>) {
1820                chomp($_);
1821                next if ($_ !~ /^Wrote:/);
1822                s|.*/([S]*RPMS.*)|$1|;
1823                $made .=" $_";
1824            }
1825            close(LOG);
1826
1827        } elsif ($pbos->{'type'} eq "deb") {
1828            pb_system("tar xfz $src","Extracting sources");
1829            pb_system("tar xfz $src2","Extracting pbconf");
1830
1831            chdir "$pbpkg-$pbver$pbextdir" || confess "Unable to chdir to $pbpkg-$pbver$pbextdir";
1832            pb_rm_rf("debian");
1833            my $confdir = "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
1834            confess "Configuration directory $confdir is not a directory\nIs os description listed in your {ve,vm,rm}list values?" if (not -d $confdir);
1835            symlink "$confdir","debian" || confess "Unable to symlink 'debian' to $confdir";
1836            chmod 0755,"debian/rules";
1837
1838            # We need to handle potential patches to upstream sources
1839            pb_mkdir_p("debian/patches");
1840            my @f = pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","debian/patches","patch");
1841
1842            # By default we use format 1.0 - Cf man dpkg-source
1843            my $debsrcfmt = "1.0";
1844            my $debsrcfile = "debian/source/format";
1845            if (-f $debsrcfile) {
1846                $debsrcfmt = pb_get_content($debsrcfile);
1847            }
1848
1849            if ($debsrcfmt =~ /^3.*quilt/) {
1850                # If we use quilt to manage patches, we then setup the env correctly
1851                # as per http://pkg-perl.alioth.debian.org/howto/quilt.html
1852                # Generate Debian patch series for quilt
1853                open(SERIE,"> debian/patches/series") || confess "Unable to write in debian/patches/series";
1854                $ENV{'QUILT_PATCHES'}="debian/patches";
1855            } else {
1856                # If we use dpatch to manage patches, we then setup the 00list file as well
1857                open(SERIE,"> debian/patches/00list") || confess "Unable to write in debian/patches/00list";
1858            }
1859            foreach my $f (sort @f) {
1860                # Skip the script made to apply the patches to the Debian tree
1861                next if ($f =~ /pbapplypatch/);
1862                # We also need to uncompress them
1863                pb_system("gzip -d $f","","quiet");
1864                $f =~ s/\.gz$//;
1865                print SERIE "$f\n";
1866            }
1867            close(SERIE);
1868            if (@f) {
1869                # We have patches...
1870                my $patch_file = "debian/patches/pbapplypatch";
1871                if (($debsrcfmt =~ /^1.*/) && (-x $patch_file)) {
1872                    # In that case we need to apply the patches ourselves locally
1873                    pb_system("cat $patch_file","APPLY","verbose");
1874                    pb_system("$patch_file","Applying patches to $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'} tree");
1875                }
1876                # ...so modify the name of files to be Debian compliant
1877                move("../$src","../$pbpkg-$pbver$pbextdir.orig.tar.gz");
1878            }
1879
1880            # We need to handle potential additional sources to upstream sources
1881            #pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}/debian","src");
1882
1883            pb_system("dpkg-buildpackage -us -uc -rfakeroot","Building package","verbose");
1884
1885            # Get the name of the generated packages
1886            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || confess "Unable to open $ENV{'PBTMP'}/system.$$.log";
1887            while (<LOG>) {
1888                chomp();
1889                pb_log(3,"In loop: $_\n");
1890                next unless (/^dpkg-deb.*\.\.\/(.*_.*\.deb).*/);
1891                my $tmp = $1;
1892                #doesn't work in my case
1893                #confess "Missing file $tmp" if (not -f "../$tmp");
1894                $made = "$made $tmp";
1895            }
1896            close(LOG);
1897            pb_log(2,"Now made is: $made\n");
1898
1899            open(CTRL,"debian/control") || confess "Unable to open debian/control: $!";
1900            while (<CTRL>) {
1901                pb_log(3,"In loop: $_\n");
1902                next unless (/^Source: (\S+)/o);
1903                my $tmp = $1;
1904                $made = "$made $tmp"."_*.dsc $tmp"."_*.tar.gz $tmp"."_*.changes";
1905                #doesn't work in my case
1906                #foreach my $glob (("$1\_*.changes", "$1\_*.dsc", "$1\_*.tar.gz")) {
1907                    #my @file = glob($glob);
1908                    #confess "Missing file for $glob" unless (@file > 0);
1909                    #confess "Too many files for $glob" if (@file > 1);
1910                    #confess "Missing file $file[0]" if (not -f $file[0]);
1911                    #$made .= " $file[0]";
1912                #}
1913            }
1914            close(CTRL);
1915            #pb_display_file("$ENV{'PBTMP'}/system.$$.log");
1916            pb_log(2,"Finally made is: $made\n");
1917
1918            chdir ".." || confess "Unable to chdir to parent dir";
1919            pb_rm_rf("$pbpkg-$pbver$pbextdir");
1920        } elsif ($pbos->{'type'} eq "ebuild") {
1921            my @ebuildfile;
1922            # For gentoo we need to take pb as subsystem name
1923            # We put every apps here under sys-apps. hope it's correct
1924            # We use pb's home dir in order to have a single OVERLAY line
1925            my $tmpe = "$ENV{'HOME'}/portage/pb/sys-apps/$pbpkg";
1926            pb_mkdir_p($tmpe) if (! -d "$tmpe");
1927            pb_mkdir_p("$ENV{'HOME'}/portage/distfiles") if (! -d "$ENV{'HOME'}/portage/distfiles");
1928
1929            # We need to first extract the ebuild file
1930            @ebuildfile = pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$tmpe","build");
1931
1932            # Prepare the build env for gentoo
1933            my $found = 0;
1934            my $pbbd = $ENV{'HOME'};
1935            $pbbd =~ s|/|\\/|g;
1936            if (-r "/etc/make.conf") {
1937                open(MAKE,"/etc/make.conf");
1938                while (<MAKE>) {
1939                    $found = 1 if (/$pbbd\/portage/);
1940                }
1941                close(MAKE);
1942            }
1943            if ($found == 0) {
1944                pb_system("sudo sh -c 'echo PORTDIR_OVERLAY=\"$ENV{'HOME'}/portage\" >> /etc/make.conf'");
1945            }
1946            #$found = 0;
1947            #if (-r "/etc/portage/package.keywords") {
1948            #open(KEYW,"/etc/portage/package.keywords");
1949            #while (<KEYW>) {
1950            #$found = 1 if (/portage\/pb/);
1951            #}
1952            #close(KEYW);
1953            #}
1954            #if ($found == 0) {
1955            #pb_system("sudo sh -c \"echo portage/pb >> /etc/portage/package.keywords\"");
1956            #}
1957
1958            # Build
1959            foreach my $f (@ebuildfile) {
1960                if ($f =~ /\.ebuild$/) {
1961                    move($f,"$tmpe/$pbpkg-$pbver.ebuild");
1962                    pb_system("cd $tmpe ; ebuild $pbpkg-$pbver.ebuild clean ; ebuild $pbpkg-$pbver.ebuild digest ; ebuild $pbpkg-$pbver.ebuild package","verbose");
1963                    # Now move it where pb expects it
1964                    pb_mkdir_p("$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg");
1965                    if ($pbtag eq 0) {
1966                        # This is assumed to be a test version
1967                        my $nver = substr($pbver,0,-14);
1968                        my $ntag = substr($pbver,-14);
1969                        my $ebtg = "portage/pb/sys-apps/$pbpkg/$pbpkg-$nver"."_p$ntag.ebuild";
1970                        move("$tmpe/$pbpkg-$pbver.ebuild","$ENV{'PBBUILDDIR'}/$ebtg");
1971                        $made="$made $ebtg";
1972                    } else {
1973                        my $ebtg = "portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver-r$pbtag.ebuild";
1974                        move("$tmpe/$pbpkg-$pbver.ebuild","$ENV{'PBBUILDDIR'}/$ebtg");
1975                        $made="$made $ebtg";
1976                    }
1977                }
1978            }
1979
1980        } elsif ($pbos->{'type'} eq "apk") {
1981            pb_mkdir_p("$ENV{'PBBUILDDIR'}/tmp");
1982
1983            # We need to first extract the APKBUILD file
1984            my @apkfile = pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$ENV{'PBBUILDDIR'}/tmp","build");
1985
1986            chdir "$ENV{'PBBUILDDIR'}/tmp" || confess "Unable to chdir to $ENV{'PBBUILDDIR'}/tmp";
1987
1988            # Build
1989            my $keyfile = pb_ssh_get(1);
1990            pb_mkdir_p("$ENV{'HOME'}/.abuild");
1991            open(CONF,"> $ENV{'HOME'}/.abuild/abuild.conf") || cluck "Unable to create the abuild conf file" && next;
1992            print CONF "PACKAGER_PRIVKEY=\"$keyfile\"\n" if (defined $keyfile);
1993            close(CONF);
1994            foreach my $f (@apkfile) {
1995                if ($f =~ /APKBUILD$/) {
1996                    pb_system("ls -al $ENV{'HOME'}/.ssh ; pwd ; ls -alR ../.. ; sh -x /usr/bin/abuild checksum ; abuild unpack ; abuild -r -P .. build ; abuild -P .. rootpkg ; abuild -P pkg index","verbose");
1997                }
1998            }
1999            # Get the name of the generated packages
2000            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || confess "Unable to open $ENV{'PBTMP'}/system.$$.log";
2001            while (<LOG>) {
2002                chomp($_);
2003                next if ($_ !~ /: Create /);
2004                s|.*: Create (.*.apk)|$1|;
2005                $made .= " $_";
2006            }
2007            close(LOG);
2008
2009        } elsif ($pbos->{'type'} eq "tgz") {
2010            # Slackware family
2011            $made="$made $pbpkg/$pbpkg-$pbver-*-$pbtag.tgz";
2012
2013            pb_system("tar xfz $src","Extracting sources");
2014            pb_system("tar xfz $src2","Extracting pbconf");
2015            chdir "$pbpkg-$pbver$pbextdir" || confess "Unable to chdir to $pbpkg-$pbver$pbextdir";
2016            symlink "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}","install" || confess "Unable to symlink to pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2017            if (-x "install/pbslack") {
2018                pb_system("./install/pbslack","Building software");
2019                pb_system("sudo /sbin/makepkg -p -l y -c y $pbpkg","Packaging $pbpkg","verbose");
2020            }
2021            chdir ".." || confess "Unable to chdir to parent dir";
2022            pb_rm_rf("$pbpkg-$pbver$pbextdir");
2023        } elsif ($pbos->{'type'} eq "pkg") {
2024            # Solaris
2025            $made="$made $pbpkg-$pbver-$pbtag.pkg.gz";
2026            my $pkgdestdir="$ENV{'PBBUILDDIR'}/install";
2027
2028            # Will host resulting packages
2029            pb_mkdir_p("$pbos->{'type'}");
2030            pb_mkdir_p("$pkgdestdir/pbdelivery");
2031            pb_system("tar xfz $src","Extracting sources under $ENV{'PBBUILDDIR'}");
2032            pb_system("tar xfz $src2","Extracting pbconf under $ENV{'PBBUILDDIR'}");
2033            # We need to handle potential patches to upstream sources
2034            pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","$ENV{'PBBUILDDIR'}","patch");
2035
2036            # We need to handle potential additional sources to upstream sources
2037            pb_extract_build_files($src2,"$pbpkg-$pbver$pbextdir/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}","src");
2038
2039            chdir "$pbpkg-$pbver$pbextdir" || confess "Unable to chdir to $pbpkg-$pbver$pbextdir";
2040            if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild") {
2041                chmod 0755,"pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild";
2042                # pkginfo file is mandatory
2043                confess "Unable to find pkginfo file in pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}" if (! -f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pkginfo");
2044                # Build
2045                pb_system("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild $pkgdestdir/pbdelivery","Building software and installing under $pkgdestdir/pbdelivery");
2046                # Copy complementary files
2047                if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/prototype") {
2048                    copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/prototype", $pkgdestdir) 
2049                } else {
2050                    # No prototype provided, calculating it
2051                    open(PROTO,"> $pkgdestdir/prototype") || confess "Unable to create prototype file";
2052                    print PROTO "i pkginfo\n";
2053                    print PROTO "i depend\n" if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend");
2054                    $ENV{'PBSOLDESTDIR'} = "$pkgdestdir/pbdelivery";
2055                    find(\&create_solaris_prototype, "$pkgdestdir/pbdelivery");
2056                }
2057                copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend", $pkgdestdir) if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend");
2058                copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pkginfo", $pkgdestdir);
2059                pb_system("cd $pkgdestdir/pbdelivery ; pkgmk -o -f ../prototype -r $pkgdestdir/pbdelivery -d $ENV{'PBBUILDDIR'}/$pbos->{'type'}","Packaging $pbpkg","verbose");
2060                pb_system("cd $ENV{'PBBUILDDIR'}/$pbos->{'type'} ;  echo \"\" | pkgtrans -o -n -s $ENV{'PBBUILDDIR'}/$pbos->{'type'} $ENV{'PBBUILDDIR'}/$pbpkg-$pbver-$pbtag.pkg all","Transforming $pbpkg","verbose");
2061                pb_system("cd $ENV{'PBBUILDDIR'} ;  gzip -9f $pbpkg-$pbver-$pbtag.pkg","Compressing $pbpkg-$pbver-$pbtag.pkg","verbose");
2062            } else {
2063                pb_log(0,"No pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild file found for $pbpkg-$pbver\n");
2064            }
2065            chdir ".." || confess "Unable to chdir to parent dir";
2066            pb_rm_rf("$pbpkg-$pbver$pbextdir","$ENV{'PBBUILDDIR'}/$pbos->{'type'}","$pkgdestdir");
2067        } elsif ($pbos->{'type'} eq "hpux") {
2068            # HP-UX
2069            pb_system("tar xfz $src","Extracting sources");
2070            pb_system("tar xfz $src2","Extracting pbconf");
2071
2072            chdir "$pbpkg-$pbver$pbextdir" || confess "Unable to chdir to $pbpkg-$pbver$pbextdir";
2073            pb_system("buildpackage ","Building package","verbose");
2074            # Get the name of the generated packages
2075            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || confess "Unable to open $ENV{'PBTMP'}/system.$$.log";
2076            while (<LOG>) {
2077                chomp();
2078                my $tmp = $_;
2079                next if ($tmp !~ /^SD BUILD.*:/);
2080                $tmp =~ s|.*../(.*)_(.*).sd.*|$1|;
2081                $made = "$made $tmp"."_*.sd";
2082            }
2083            close(LOG);
2084            $made="$made $pbpkg-$pbver-$pbtag.sd";
2085
2086            chdir ".." || confess "Unable to chdir to parent dir";
2087            pb_rm_rf("$pbpkg-$pbver$pbextdir");
2088        } else {
2089            confess "Unknown OS type format $pbos->{'type'}";
2090        }
2091        if (defined $pbparallel) {
2092            # Communicate results back to parent
2093            pb_set_content("$tmpd/$$",$made);
2094            $pm->finish;
2095        }
2096    }
2097    if (defined $pbparallel) {
2098        # In the parent, we need to get the result from the children
2099        $pm->wait_all_children;
2100        foreach my $f (<$tmpd/*>) {
2101            $made .= " ".pb_get_content($f);
2102        }
2103        confess "Aborting, one or more of the children failed." if ((not $all_ok) && ($Global::pb_stop_on_error));
2104        pb_rm_rf($tmpd);
2105    }
2106
2107    # Sign packages
2108    pb_sign_pkgs($pbos,$made);
2109    pb_log(0,"INFO: ------ Finished building package ------\n");
2110
2111    # Find the appropriate check cmd/opts
2112    my ($chkcmd,$chkopt) = pb_distro_get_param($pbos,pb_conf_get_if("oschkcmd","oschkopt"));
2113
2114    my $ret = "";
2115    # Packages check if needed
2116    if ($pbos->{'type'} eq "rpm") {
2117        if ((defined  $chkcmd) && (-x $chkcmd)) {
2118            my $cmd = "$chkcmd";
2119            $cmd .= " $chkopt" if (defined $chkopt);
2120            $cmd .= " $made";
2121            my $ret = pb_system("$cmd","Checking validity of rpms with $chkcmd","mayfailverbose");
2122            pb_log(0,"ERROR: when checking packages validity\n") if ($ret ne 0);
2123        }
2124        my $rpms ="";
2125        my $srpms ="";
2126        foreach my $f (split(/ /,$made)) {
2127            $rpms .= "$ENV{'PBBUILDDIR'}/$f " if ($f =~ /^RPMS\//);
2128            $srpms .= "$ENV{'PBBUILDDIR'}/$f " if ($f =~ /^SRPMS\//);
2129        }
2130        pb_log(0,"SRPM packages generated: $srpms\n");
2131        pb_log(0,"RPM packages generated: $rpms\n");
2132        $ret = $rpms;
2133    } elsif ($pbos->{'type'} eq "deb") {
2134        my $made2 = "";
2135        foreach my $f (split(/ /,$made)) {
2136            $made2 .= "$f " if ($f =~ /\.deb$/);
2137        }
2138        if ((defined  $chkcmd) && (-x $chkcmd)) {
2139            my $ret = pb_system("$chkcmd $chkopt $made2","Checking validity of debs with $chkcmd","mayfail");
2140            pb_log(0,"ERROR: when checking packages validity\n") if ($ret ne 0);
2141        }
2142        pb_log(0,"deb packages generated: $made2\n");
2143        $ret = $made2;
2144    } else {
2145        pb_log(0,"No check done for $pbos->{'type'} yet\n");
2146        pb_log(0,"Packages generated: $made\n");
2147        $ret = $made;
2148    }
2149
2150    # Keep track of what is generated so that we can get them back from VMs/RMs
2151    my $pbstore = "$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2152    open(KEEP,"> $pbstore") || confess "Unable to create $pbstore $!";
2153    print KEEP "$made\n";
2154    close(KEEP);
2155    pb_distro_installdeps(undef,$pbos,undef,$ret,"local") if ($do_install);
2156}
2157
2158sub pb_build2ssh {
2159    pb_send2target("Sources");
2160    pb_send2target("CPAN");
2161}
2162
2163sub pb_pkg2ssh {
2164    pb_send2target("Packages");
2165}
2166
2167# By default deliver to the the public site hosting the
2168# ftp structure (or whatever) or a VM/VE/RM
2169sub pb_send2target {
2170
2171    my $cmt = shift;
2172    my $pbscript1 = shift;
2173    my $v = shift;
2174    my $vexist = shift;         # 0 is FALSE
2175    my $vpid = shift;           # 0 is FALSE
2176    my $snapme = shift;         # 0 is FALSE
2177    my $pbstep = shift;         # 3 is usage of container
2178
2179    $vexist = 0 if (not defined $vexist);
2180    $vpid = 0 if (not defined $vpid);
2181    $snapme = 0 if (not defined $snapme);
2182    $pbstep = 3 if (not defined $pbstep);
2183    pb_log(2,"DEBUG: pb_send2target($cmt,".Dumper($v).",$vexist,$vpid)\n");
2184    my $host = "sshhost";
2185    my $login = "sshlogin";
2186    my $dir = "sshdir";
2187    my $port = "sshport";
2188    my $conf = "sshconf";
2189    my $tmout = undef;
2190    my $path = undef;
2191
2192    if ($cmt =~ /^VM/) {
2193        $login = "vmlogin";
2194        $dir = "pbdefdir";
2195        # Specific VM
2196        $tmout = "vmtmout";
2197        $path = "vmpath";
2198        $host = "vmhost";
2199        $port = "vmport";
2200    } elsif ($cmt =~ /^RM/) {
2201        $login = "rmlogin";
2202        $dir = "pbdefdir";
2203        # Specific RM
2204        $tmout = "rmtmout";
2205        $path = "rmpath";
2206        $host = "rmhost";
2207        $port = "rmport";
2208    } elsif ($cmt =~ /^VE/) {
2209        $login = "velogin";
2210        $dir = "pbdefdir";
2211        # Specific VE
2212        $path = "vepath";
2213        $conf = "rbsconf";
2214    } elsif ($cmt eq "Web") {
2215        $host = "websshhost";
2216        $login = "websshlogin";
2217        $dir = "websshdir";
2218        $port = "websshport";
2219    } elsif ($cmt eq "CPAN") {
2220        $host = "cpanpause";
2221        $login = "";
2222        $dir = "cpandir";
2223        $port = "";
2224    }
2225    my $cmd = "";
2226    my $src = "";
2227    my $cpanpkg = 0;
2228    my $pbos;
2229
2230    my $pbextdir = pb_get_extdir();
2231
2232    if ($cmt ne "Announce") {
2233        # Get list of packages to build
2234        my $ptr = pb_get_pkg();
2235        my @pkgs = ();
2236        @pkgs = @$ptr if (defined $ptr);
2237
2238        # Get the running distro to consider
2239        $pbos = pb_distro_get_context($v);
2240
2241        my $pkg = { };
2242        # Get content saved in cms2build
2243        if ((defined $ENV{'PBDESTDIR'}) && (defined $ENV{'PBPROJVER'}) && (defined $ENV{'PBPROJTAG'}) && (-f "$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml")) {
2244            ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
2245            $pkg = { } if (not defined $pkg);
2246        }
2247
2248        pb_mkdir_p("$ENV{'PBBUILDDIR'}") if (! -d "$ENV{'PBBUILDDIR'}");
2249        chdir "$ENV{'PBBUILDDIR'}" || confess "Unable to chdir to $ENV{'PBBUILDDIR'}";
2250        foreach my $pbpkg (@pkgs) {
2251            my $vertag = $pkg->{$pbpkg};
2252            # get the version of the current package - maybe different
2253            pb_log(2,"Vertag: $vertag\n");
2254            ($pbver,$pbtag) = split(/-/,$vertag);
2255
2256            if (($cmt eq "Sources") || ($cmt =~ /(V[EM]|RM)(build|prep)/)) {
2257                $src = "$src $ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.tar.gz $ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.pbconf.tar.gz";
2258                my $cmd2 = "ln -sf $pbpkg-$pbver$pbextdir.tar.gz $pbpkg-latest.tar.gz";
2259                #my $cmd2 = "ln $pbpkg-$pbver$pbextdir.tar.gz $pbpkg-latest.tar.gz 2> /dev/null ; if [ \$? -ne 0 ]; then ln -sf $pbpkg-$pbver$pbextdir.tar.gz $pbpkg-latest.tar.gz ; fi";
2260                if ($cmd eq "") {
2261                    $cmd = $cmd2;
2262                } else {
2263                    $cmd = "$cmd ; $cmd2";
2264                }
2265            } elsif ($cmt eq "Web") {
2266                $src = "$src $ENV{'PBDESTDIR'}/$pbpkg-$pbver$pbextdir.tar.gz"
2267            }
2268
2269            # Do we have one perl package
2270            my @nametype = pb_conf_get_if("namingtype");
2271            my $type = $nametype[0]->{$pbpkg};
2272            if ((defined $type) && ($type eq "perl")) {
2273                $cpanpkg = 1;
2274            }
2275        }
2276        # Adds conf file for availability of conf elements
2277        pb_conf_add("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.yml") if ((defined $ENV{'PBROOTDIR'}) && (-f "$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.yml"));
2278    }
2279    my ($rbsconf,$testver,$delivery) = pb_conf_get_if($conf,"testver","delivery");
2280    if ($cmt eq "CPAN") {
2281        # Do not deliver on Pause if this is a test version
2282        return if (not defined $testver);
2283        return if ($testver =~ /true/);
2284        # Do not deliver on Pause if this is not a perl package
2285        return if ($cpanpkg == 0);
2286    }
2287
2288    if ($cmt =~ /(V[EM]|RM)(build|prep)/) {
2289        $src="$src $ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.yml $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml $ENV{'PBETC'} $ENV{'PBDESTDIR'}/pbrc.yml $pbscript{$v}";
2290    } elsif ($cmt =~ /(V[EM]|RM)Script/) {
2291        $src="$src $pbscript{$v}";
2292    } elsif ($cmt =~ /(V[EM]|RM)test/) {
2293        $src="$src $ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.yml $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml $ENV{'PBETC'} $ENV{'PBDESTDIR'}/pbrc.yml $pbscript{$v} $ENV{'PBDESTDIR'}/pbtest";
2294    } elsif (($cmt eq "Announce") || ($cmt eq "Web") || ($cmt eq "CPAN")) {
2295        $src="$src $ENV{'PBTMP'}/pbscript";
2296    } elsif ($cmt eq "Packages") {
2297        # Get package list from file made during build2pkg
2298        open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") || confess "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2299        $src = <KEEP>;
2300        chomp($src);
2301        close(KEEP);
2302    }
2303    if (($cmt eq "Sources") || ($cmt eq "Packages") || ($cmt eq "CPAN")) {
2304        my ($pbpackager) = pb_conf_get("pbpackager");
2305        $ENV{'PBPACKAGER'} = $pbpackager->{$ENV{'PBPROJ'}};
2306        pb_log(0,"Exporting public key for $ENV{'PBPACKAGER'}\n");
2307        # Using pb_system is not working due to redirection below
2308        system("gpg --export -a \'$ENV{'PBPACKAGER'}\' > $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey");
2309        chmod 0644,"$ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey";
2310        $src = "$src $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey";
2311
2312        my ($gpgaddkey) = pb_conf_get_if("pbadditionalgpg");
2313        my $pbadditionalgpg;
2314        $pbadditionalgpg = $gpgaddkey->{$ENV{'PBPROJ'}} if (defined $gpgaddkey);
2315        if (defined $pbadditionalgpg) {
2316            foreach my $k (split(/,/,$pbadditionalgpg)) {
2317                pb_log(0,"Exporting public key $k\n");
2318                system("gpg --export -a \'$k\' > $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}-$k.pubkey");
2319                $src = "$src $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}-$k.pubkey";
2320            }
2321        }
2322    }
2323    # Remove potential leading spaces (cause problem with basename)
2324    $src =~ s/^ *//;
2325    my $basesrc = "";
2326    foreach my $i (split(/ +/,$src)) {
2327        $basesrc .= " ".basename($i);
2328    }
2329
2330    pb_log(2,"values: ".Dumper(($host,$login,$dir,$port,$tmout,$path,$conf))."\n");
2331    my ($sshhost,$sshdir) = pb_conf_get($host,$dir);
2332    # Not mandatory...
2333    $delivery->{$ENV{'PBPROJ'}} = "" if (not defined $delivery->{$ENV{'PBPROJ'}});
2334    my ($sshlogin,$sshport) = pb_conf_get_if($login,$port);
2335    $sshport->{$ENV{'PBPROJ'}} = 22 if (not defined $sshport->{$ENV{'PBPROJ'}});
2336    $sshlogin->{$ENV{'PBPROJ'}} = getpwuid($UID) if (not defined $sshlogin->{$ENV{'PBPROJ'}});
2337    my ($vtmout,$vepath);
2338    # ...Except those in virtual context
2339    if ($cmt =~ /^VE/) {
2340        ($vepath) = pb_conf_get($path);
2341    }
2342    if ($cmt =~ /^(V|R)M/) {
2343        $vtmout = pb_distro_get_param($pbos,pb_conf_get_if($tmout));
2344    }
2345    my $remhost = $sshhost->{$ENV{'PBPROJ'}};
2346    my $remdir = $sshdir->{$ENV{'PBPROJ'}};
2347    if ($cmt =~ /^V[EM]|RM/) {
2348        # In that case our real host is in the xxhost with the OS as key, not project as above
2349        $remhost = pb_distro_get_param($pbos,$sshhost);
2350    }
2351    pb_log(2,"ssh: ".Dumper(($remhost,$sshlogin,$remdir,$sshport,$vepath,$rbsconf))."\n");
2352    pb_log(2,"ssh: ".Dumper($vtmout)."\n") if (defined $vtmout);
2353
2354    my $mac;
2355    if ($cmt !~ /^VE/) {
2356        $mac = "$sshlogin->{$ENV{'PBPROJ'}}\@$remhost";
2357        # Overwrite account value if passed as parameter or forced
2358        $mac = "$ENV{'PBACCOUNT'}\@$remhost" if (defined $ENV{'PBACCOUNT'});
2359    } else {
2360        # VE
2361        $mac = $sshlogin->{$ENV{'PBPROJ'}};
2362        # Overwrite account value if passed as parameter (typically for setup2v)
2363        $mac = $ENV{'PBACCOUNT'} if (defined $ENV{'PBACCOUNT'});
2364    }
2365    pb_log(2, "DEBUG: mac: $mac\n");
2366
2367    my $tdir;
2368    my $bdir;
2369    if (($cmt eq "Sources") || ($cmt =~ /(V[EM]|RM)Script/)) {
2370        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/src";
2371    } elsif ($cmt eq "CPAN") {
2372        $tdir = "$remdir";
2373    } elsif ($cmt =~ /(V[EM]|RM)(build|test|prep)/) {
2374        $tdir = $remdir."/$ENV{'PBPROJ'}/pbdelivery";
2375        $bdir = $remdir."/$ENV{'PBPROJ'}/pbbuild";
2376        # Remove a potential $ENV{'HOME'} as bdir should be relative to pb's home
2377        $bdir =~ s|\$ENV.+\}/||;
2378    } elsif ($cmt eq "Announce") {
2379        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}";
2380    } elsif ($cmt eq "Web") {
2381        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}";
2382    } elsif ($cmt eq "Packages") {
2383        if (($pbos->{'type'} eq "rpm") || ($pbos->{'type'} eq "pkg") || ($pbos->{'type'} eq "hpux") || ($pbos->{'type'} eq "tgz") || ($pbos->{'type'} eq "apk")) {
2384            # put packages under an arch subdir
2385            $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}";
2386        } elsif (($pbos->{'type'} eq "deb") || ($pbos->{'type'} eq "ebuild")) {
2387            # No need for an arch subdir
2388            $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}";
2389        } else {
2390            confess "Please teach the dev team where to deliver ($pbos->{'type'} type of packages\n";
2391        }
2392
2393        my $repodir = $tdir;
2394        $repodir =~ s|^$remdir/||;
2395        my $repotag = "";
2396        $repotag = "-$delivery->{$ENV{'PBPROJ'}}" if ($delivery->{$ENV{'PBPROJ'}} ne "");
2397
2398        my ($pbrepo) = pb_conf_get("pbrepo");
2399
2400        # Script for Repository management
2401        $v = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}" if (not defined $v);
2402        $pbscript{$v} = "$ENV{'PBBUILDDIR'}/pbscript.$$";
2403       
2404        # That script should be part of the delivery
2405        $src = "$src $pbscript{$v}";
2406        open(PBS,"> $pbscript{$v}") || confess "Unable to create $pbscript{$v}";
2407        if ($pbos->{'type'} eq "rpm") {
2408            my $pbsha = pb_distro_get_param($pbos,pb_conf_get("ossha"));
2409            my ($gpgcheck) = pb_conf_get_if("pbgpgcheck");
2410            my $pbgpgcheck;
2411            $pbgpgcheck = $gpgcheck->{$ENV{'PBPROJ'}} if (defined $gpgcheck);
2412            my $pbgpgkey = "$pbrepo->{$ENV{'PBPROJ'}}/$repodir/$ENV{'PBPROJ'}.pubkey";
2413            my ($gpgaddpkey) = pb_conf_get_if("pbadditionalgpg");
2414            my $pbadditionalgpg;
2415            $pbadditionalgpg = $gpgaddpkey->{$ENV{'PBPROJ'}} if (defined $gpgaddpkey);
2416            if (defined $pbadditionalgpg) {
2417                foreach my $k (split(/,/,$pbadditionalgpg)) {
2418                    $pbgpgkey .= " $pbrepo->{$ENV{'PBPROJ'}}/$repodir/$ENV{'PBPROJ'}-$k.pubkey";
2419                }
2420            }
2421            # By default force GPG check in repo even if we support signature of packages to fail. This is a best practice
2422            $pbgpgcheck = 1 if (not defined $pbgpgcheck);
2423            # Also make a pbscript to generate dnf/yum/urpmi bases
2424            print PBS << "EOF";
2425#!/bin/bash
2426# Prepare a script to ease dnf/yum setup
2427EOF
2428            print PBS "set -x\n" if ($pbdebug gt 1);
2429            print PBS << "EOF";
2430cat > $ENV{'PBPROJ'}$repotag.repo << EOT
2431[$ENV{'PBPROJ'}$repotag]
2432name=$pbos->{'name'} $pbos->{'version'} $pbos->{'arch'} - $ENV{'PBPROJ'} Vanilla Packages
2433baseurl=$pbrepo->{$ENV{'PBPROJ'}}/$repodir
2434enabled=1
2435gpgcheck=$pbgpgcheck
2436gpgkey=$pbgpgkey
2437EOT
2438chmod 644 $ENV{'PBPROJ'}$repotag.repo
2439
2440# Clean up old repo content
2441rm -rf headers/ repodata/
2442# Create yum repo
2443if [ -x /usr/bin/yum-arch ]; then
2444    yum-arch .
2445fi
2446# Create repodata
2447createrepo -s $pbsha .
2448# Link to the key
2449if [ -s $ENV{'PBPROJ'}.pubkey ]; then
2450    # Avoiding creating empty repomd.xml.key; fails on opensuse 12.1
2451    (cd repodata ; ln -sf ../$ENV{'PBPROJ'}.pubkey repomd.xml.key)
2452fi
2453# sign the repomd (at least useful for SLES - which requires a local key)
2454# gpg -a --detach-sign repodata/repomd.xml
2455# SLES also looks for media.1/info.txt
2456EOF
2457            if ($pbos->{'family'} eq "md") {
2458                # For Mandriva add urpmi management
2459                print PBS << "EOF";
2460# Prepare a script to ease urpmi setup
2461cat > $ENV{'PBPROJ'}$repotag.addmedia << EOT
2462#rpm --import $pbrepo->{$ENV{'PBPROJ'}}/$repodir/$ENV{'PBPROJ'}.pubkey
2463urpmi.addmedia $ENV{'PBPROJ'}$repotag $pbrepo->{$ENV{'PBPROJ'}}/$repodir with media_info/hdlist.cz
2464EOT
2465chmod 755 $ENV{'PBPROJ'}$repotag.addmedia
2466
2467# Clean up old repo content
2468rm -f hdlist.cz synthesis.hdlist.cz
2469# Create urpmi repo
2470genhdlist2 --clean .
2471if [ \$\? -ne 0 ]; then
2472    genhdlist .
2473fi
2474(cd media_info ; ln -sf ../$ENV{'PBPROJ'}.pubkey pubkey)
2475EOF
2476            }
2477            if ($pbos->{'name'} eq "fedora") {
2478                # Extract the spec file to please Fedora maintainers :-(
2479                print PBS << "EOF";
2480for p in $basesrc; do
2481    echo \$p | grep -q 'src.rpm'
2482    if [ \$\? -eq 0 ]; then
2483        rpm2cpio \$p | cpio -ivdum --quiet '*.spec'
2484    fi
2485done
2486EOF
2487            }
2488            if ($pbos->{'family'} eq "novell") {
2489                # Add ymp scripts for one-click install on SuSE
2490                print PBS << "EOF";
2491# Prepare a script to ease SuSE one-click install
2492# Cf: http://de.opensuse.org/1-Klick-Installation/ISV
2493#
2494cat > $ENV{'PBPROJ'}$repotag.ymp << EOT
2495<?xml version="1.0" encoding="utf-8"?>
2496<!-- vim: set sw=2 ts=2 ai et: -->
2497<metapackage xmlns:os="http://opensuse.org/Standards/One_Click_Install" xmlns="http://opensuse.org/Standards/One_Click_Install">
2498    <group><!-- The group of software, typically one for project-builder.org -->
2499        <name>$ENV{'PBPROJ'} Bundle</name> <!-- Name of the software group -->
2500        <summary>Software bundle for the $ENV{'PBPROJ'}$repotag project</summary> <!--This message is shown to the user and should describe the whole bundle -->
2501        <description>This is the summary of the $ENV{'PBPROJ'}$repotag Project
2502             
2503            Details are available on a per package basis below
2504
2505        </description><!--This is also shown to the user -->
2506        <remainSubscribed>false</remainSubscribed> <!-- Don't know what it mean -->
2507        <repositories><!-- List of needed repositories -->
2508            <repository>
2509                <name>$ENV{'PBPROJ'}$repotag Repository</name> <!-- Name of the repository  -->
2510                <summary>This repository contains the $ENV{'PBPROJ'}$repotag project packages.</summary> <!-- Summary of the repository -->
2511                <description>This repository contains the $ENV{'PBPROJ'}$repotag project packages.</description><!-- This description is shown to the user -->
2512                <url>$pbrepo->{$ENV{'PBPROJ'}}/$repodir</url><!--URL of repository, which is added -->
2513            </repository>
2514        </repositories>
2515        <software><!-- A List of packages, which should be added through the one-click-installation -->
2516EOT
2517for p in $basesrc; do
2518    sum=`rpm -q --qf '%{SUMMARY}' \$p`
2519    name=`rpm -q --qf '%{NAME}' \$p`
2520    desc=`rpm -q --qf '%{description}' \$p`
2521    cat >> $ENV{'PBPROJ'}$repotag.ymp << EOT
2522            <item>
2523                <name>\$name</name><!-- Name of the package, is shown to the user and used to identify the package at the repository -->
2524                <summary>\$sum</summary> <!-- Summary of the package -->
2525                <description>\$desc</description> <!-- Description, is shown to the user -->
2526            </item>
2527EOT
2528done
2529cat >> $ENV{'PBPROJ'}$repotag.ymp << EOT
2530        </software>
2531    </group>
2532</metapackage>
2533EOT
2534chmod 644 $ENV{'PBPROJ'}$repotag.ymp
2535EOF
2536            }
2537        } elsif ($pbos->{'type'} eq "deb") {
2538            # Also make a pbscript to generate apt bases
2539            # Cf: http://www.debian.org/doc/manuals/repository-howto/repository-howto.fr.html
2540            # This dirname removes ver
2541            my $debarch = pb_get_debarch($pbos);
2542            my $projcomponent = pb_get_debpc($pbos);
2543            my $rpd = dirname("$pbrepo->{$ENV{'PBPROJ'}}/$repodir");
2544            # Remove extra . in path to fix #522
2545            $rpd =~ s|/./|/|g;
2546            print PBS << "EOF";
2547#!/bin/bash
2548# Prepare a script to ease apt setup
2549cat > $ENV{'PBPROJ'}$repotag.sources.list << EOT
2550deb $rpd $pbos->{'version'} $projcomponent
2551deb-src $rpd $pbos->{'version'} $projcomponent
2552EOT
2553chmod 644 $ENV{'PBPROJ'}$repotag.sources.list
2554
2555# Up two levels to deal with the dist dir cross versions
2556cd ..
2557mkdir -p dists/$pbos->{'version'}/$projcomponent/binary-$debarch dists/$pbos->{'version'}/$projcomponent/source dists/$pbos->{'version'}/$projcomponent/binary-all
2558
2559# Prepare a script to create apt info file
2560# Reuse twice after
2561TMPD=`mktemp -d /tmp/pb.XXXXXXXXXX` || exit 1
2562mkdir -p \$TMPD
2563cat > \$TMPD/Release << EOT
2564Archive: unstable
2565Component: $projcomponent
2566Origin: $ENV{'PBPROJ'}$repotag
2567Label: $ENV{'PBPROJ'}$repotag dev repository $pbrepo->{$ENV{'PBPROJ'}}
2568EOT
2569
2570echo "Creating Packages metadata"
2571for i in dists/$pbos->{version}/$projcomponent/binary-*; do
2572    arch=`basename \$i | sed 's/binary-//'`
2573    echo "Packages for \$arch:"
2574    dpkg-scanpackages -a\$arch $pbos->{'version'} /dev/null > dists/$pbos->{'version'}/$projcomponent/binary-\$arch/Packages
2575    gzip -9 < dists/$pbos->{'version'}/$projcomponent/binary-\$arch/Packages > dists/$pbos->{'version'}/$projcomponent/binary-\$arch/Packages.gz
2576    bzip2 -9 < dists/$pbos->{'version'}/$projcomponent/binary-\$arch/Packages > dists/$pbos->{'version'}/$projcomponent/binary-\$arch/Packages.bz2
2577done
2578echo "Creating Contents metadata"
2579apt-ftparchive contents $pbos->{'version'} | gzip -c9 > dists/$pbos->{'version'}/Contents.gz
2580echo "Creating Release metadata ($pbos->{'arch'} aka $debarch)"
2581cat \$TMPD/Release > dists/$pbos->{'version'}/$projcomponent/binary-all/Release
2582echo "Architecture: all" >> dists/$pbos->{'version'}/$projcomponent/binary-all/Release
2583cat \$TMPD/Release > dists/$pbos->{'version'}/$projcomponent/binary-$debarch/Release
2584echo "Architecture: $debarch" >> dists/$pbos->{'version'}/$projcomponent/binary-$debarch/Release
2585echo "Creating Source metadata"
2586dpkg-scansources $pbos->{'version'} /dev/null > dists/$pbos->{'version'}/$projcomponent/source/Sources
2587gzip -9 < dists/$pbos->{'version'}/$projcomponent/source/Sources > dists/$pbos->{'version'}/$projcomponent/source/Sources.gz
2588bzip2 -9 < dists/$pbos->{'version'}/$projcomponent/source/Sources > dists/$pbos->{'version'}/$projcomponent/source/Sources.bz2
2589cat \$TMPD/Release > dists/$pbos->{'version'}/$projcomponent/source/Release
2590echo "Architecture: Source" >> dists/$pbos->{'version'}/$projcomponent/source/Release
2591echo "Creating Release metadata"
2592apt-ftparchive -o APT::FTPArchive::Release::Suite=$pbos->{version} release dists/$pbos->{'version'} > dists/$pbos->{'version'}/Release
2593rm -rf \$TMPD
2594EOF
2595        } elsif ($pbos->{'type'} eq "ebuild") {
2596            # make a pbscript to generate links to latest version
2597            print PBS << "EOF";
2598#!/bin/bash
2599# Prepare a script to create correct links
2600cd $tdir
2601for p in $src; do
2602    echo \$p | grep -q '.ebuild'
2603    if [ \$\? -eq 0 ]; then
2604        j=`basename \$p`
2605        pp=`echo \$j | perl -pe 's/-[0-9\.]+-r[0-9].*\.ebuild/.ebuild/'`
2606        ln -sf \$j \$pp
2607    fi
2608done
2609EOF
2610        } elsif ($pbos->{'type'} eq "apk") {
2611            # TODO
2612        }
2613        close(PBS);
2614        chmod 0755,$pbscript{$v};
2615    } else {
2616        return;
2617    }
2618
2619    # Useless for VE
2620    my $nport = pb_get_port($sshport,$pbos,$cmt) if ($cmt !~ /^VE/);
2621
2622    # Remove a potential $ENV{'HOME'} as tdir should be relative to pb's home
2623    if ($cmt =~ /^VE/o) {
2624        $tdir =~ s|\$ENV.+\}/|| or cluck "for $cmt: $tdir must have \$ENV{'HOME'} in it or the remainder of the code won't work since some parts use relative pathing and others will try absolute.  Use a symlink if necessary to place the real files in a different place than under your home directory" && return;
2625    } else {
2626        # process, ok if not present.
2627        $tdir =~ s|\$ENV.+\}/||;
2628    }
2629
2630    my $tm = "";
2631    if ($cmt =~ /^(V|R)M/) {
2632        $tm = "sleep $vtmout" if (defined $vtmout);
2633    }
2634
2635    # ssh communication if not VE or CPAN
2636    # should use a hash instead...
2637    my ($shcmd,$shcmdroot,$cpcmd,$cptarget,$cp2target);
2638    my $tpdir;
2639    my $tp;
2640    my $context = "$ENV{'PBTMP'}";
2641    my %tag;
2642    my $dkaccount = "";
2643    my $cmd1 = "";
2644    my $cidfile;
2645    my $homedir = "";
2646    if ($cmt =~ /^VE/) {
2647        $tp = pb_path_expand($vepath->{$ENV{'PBPROJ'}});
2648        $vetype = pb_ve_get_type($vetype);
2649        if ($vetype eq "docker") {
2650            $tpdir = "/";
2651            $cidfile = "$context/ctn-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.cid";
2652        } else {
2653            $tpdir = pb_path_expand("$tp/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2654        }
2655        my $arch = pb_get_arch();
2656        if ($vetype eq "chroot") {
2657            $shcmdroot = "sudo /usr/sbin/chroot $tpdir ";
2658            $shcmd = "$shcmdroot /bin/su - $mac -c ";
2659        } elsif ($vetype eq "schroot") {
2660            $shcmd = "schroot $tp -u $mac -- ";
2661        } elsif ($vetype eq "docker") {
2662            # docker manages the storage so rely on it
2663            $shcmdroot = "";
2664            my $docrepo = pb_ve_docker_repo();
2665            $cmd1 = pb_check_req("docker",0);
2666            #my ($dockeropt) =  pb_conf_get_if("dockeropt");
2667            # pbimage is used for docker and is setup to the right name depending on the step:
2668            # TODO: This is not coded yet
2669            my $pbimage = undef;
2670            # step 0 : nothing at creation -> tag n-v-a (made in VE.pm)
2671            # step 1 : n-v-a + setup -> tag n-v-a-pb
2672            # step 2 : n-v-a-pb + build -> tag n-v-a-pb-pbproj
2673            # step 3 : n-v-a-pb-pbproj at use
2674            if ((not defined $pbimage) || ($pbimage eq "")) {
2675                # If no image name given, create a naming convention
2676                $tag{1} = "$docrepo$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2677                $tag{2} = "$tag{1}-pb";
2678                $tag{3} = "$tag{2}-$ENV{'PBPROJ'}";
2679            } else {
2680                # If we were given an image name, just use it
2681                $tag{1} = $pbimage;
2682                $tag{2} = $pbimage;
2683                $tag{3} = $pbimage;
2684            }
2685            # If we do not create the image, then use the one we should have
2686            # TODO: we don't do anything with found !!
2687            my $found = pb_ve_docker_get_image($tag{$pbstep});
2688            cluck "No image $tag{$pbstep} available in Docker, please create one first\n" if (not defined $found);
2689            # Now we use that image to do what is needed
2690            # use a dockerfile to ease the creation of next images
2691            # the context is in an empty temp dir
2692            my $tmpd = "$context/Dockerfile";
2693            open(DOCKER, "> $tmpd") || confess "Unable to create the docker file $tmpd";
2694            print DOCKER "FROM $tag{$pbstep}\n";
2695            print DOCKER "MAINTAINER project-builder.org aka pb\n";
2696            if ($pbstep == 1) {
2697                # setup done as root
2698                $dkaccount = "root";
2699            } else {
2700                # Rest done as pb
2701                $dkaccount = "pb";
2702            }
2703            print DOCKER "USER $dkaccount\n";
2704            if ($pbstep <= 2) {
2705                $shcmd = "$cmd1 build -t $tag{$pbstep+1} $context";
2706            } else {
2707                # As we are in run phase use docker run. cmd will be completed below
2708                my $rmatend = "--rm" if ($pbdebug lt 1);
2709                $shcmd = "$cmd1 run $rmatend --cidfile=\"$cidfile\" --user $dkaccount --name $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-$cmt";
2710            }
2711            #$shcmd = "$cmd1 build $dockeropt->{$ENV{'PBPROJ'}} -t $tag{$pbstep+1} $context";
2712        }
2713        $shcmd = "setarch i386 $shcmd" if (($pbos->{'arch'} =~ /i[3456]86/) && ($arch eq 'x86_64'));
2714        if (($cmt =~ /VE/) && ($vetype ne "docker")) {
2715            # We need to get the home dir of the target account to deliver in the right place
2716            open(PASS,"$tpdir/etc/passwd") || confess "Unable to open $tpdir/etc/passwd: $!";
2717            while (<PASS>) {
2718                my ($c1,$c2,$c3,$c4,$c5,$c6,$c7) = split(/:/);
2719                $homedir = $c6 if ($c1 =~ /^$mac$/);
2720                pb_log(3,"Homedir: $homedir - account: $c6\n");
2721            }
2722            close(PASS);
2723            $cpcmd = "sudo /bin/cp -r ";
2724        }
2725        if (($cmt =~ /VE/) && ($vetype eq "docker")) {
2726            if ($pbstep >= 2) {
2727                # We need to get the home dir of the target account to deliver in the right place
2728                $homedir = `$cmd1 run --rm --cidfile="$cidfile" $tag{$pbstep} grep -E '^$dkaccount:' /etc/passwd | cut -d: -f6`;
2729                chomp($homedir);
2730                open(CID,"$cidfile") || cluck "Unable to open $cidfile";
2731                my $cid = <CID>;
2732                close(CID);
2733                unlink("$cidfile");
2734            } else {
2735                $homedir = "/";
2736            }
2737            $cpcmd = "cp -r ";
2738        }
2739        $cptarget = "$tpdir/$homedir/$tdir";
2740        if ($cmt =~ /VE(build|prep)/) {
2741            $cp2target = "$tpdir/$homedir/$bdir";
2742        }
2743        pb_log(2,"On VE using $cptarget as target dir to copy to\n");
2744    } elsif ($cmt eq "CPAN") {
2745        my $ftpput = pb_check_req("ncftpput",1);
2746        my $ftpget = pb_check_req("wget",1);
2747        my ($cpanuser,$cpanpasswd) = pb_conf_get_if("cpanuser","cpanpasswd");
2748        return if ((not defined $cpanuser) || (not defined $cpanuser->{$ENV{'PBPROJ'}}));
2749        return if ((not defined $cpanpasswd) || (not defined $cpanpasswd->{$ENV{'PBPROJ'}}));
2750        my ($cpansubdir) = pb_conf_get_if("cpansubdir");
2751        $shcmd = "$ftpget --post-data \'HIDDENNAME=".$cpanuser->{$ENV{'PBPROJ'}};
2752        $shcmd .= "&user=".$cpanuser->{$ENV{'PBPROJ'}};
2753        $shcmd .= "&password=".$cpanpasswd->{$ENV{'PBPROJ'}};
2754        $shcmd .= "&SUBMIT_pause99_add_uri_upload=\"Upload the checked files\"";
2755        $shcmd .= "&pause99_add_uri_subdirtext=".$cpansubdir->{$ENV{'PBPROJ'}} if ((defined $cpansubdir) && (defined $cpansubdir->{$ENV{'PBPROJ'}}));
2756        foreach my $s (split(/ /,$src)) {
2757            $shcmd .= "&pause99_add_uri_upload=".basename($s);
2758        }
2759        $shcmd .= "'";
2760        $cpcmd = "$ftpput $host $dir";
2761        $cptarget = "CPAN";
2762    } else {
2763        my $keyopt = "";
2764        if ($cmt !~ /Packages/) {
2765            my $keyfile = pb_ssh_get(0,$remhost,$nport);
2766            $keyopt = "-i $keyfile" if (defined $keyfile);
2767        }
2768        my $sshcmd = pb_check_req("ssh",1);
2769        my $scpcmd = pb_check_req("scp",1);
2770        $shcmd = "$sshcmd $keyopt -q -o NoHostAuthenticationForLocalhost=yes -p $nport $mac";
2771        $cpcmd = "$scpcmd $keyopt -p -o NoHostAuthenticationForLocalhost=yes -P $nport";
2772        $cptarget = "$mac:$tdir";
2773        if ($cmt =~ /^(V|R)M(build|prep)/) {
2774            $cp2target = "$mac:$bdir";
2775        }
2776    }
2777   
2778    my $logres = "";
2779    # Do not touch when just announcing
2780    if (($cmt ne "Announce") && ($cmt ne "CPAN")) {
2781        # For docker everything is done in the Dockerfile for steps < 3
2782        if (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep < 3)) {
2783            print DOCKER "RUN mkdir -p $cptarget\n";
2784            print DOCKER "RUN cd $cptarget ; for i in $basesrc; do if [ -f \$i ]; then rm -f \$i; fi; done\n";
2785        } elsif (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep >= 3)) {
2786            # Nothing to do here
2787        } else {
2788            pb_system("$shcmd \"mkdir -p $tdir ; cd $tdir ; echo \'for i in $basesrc; do if [ -f \$i ]; then rm -f \$i; fi; done ; $cmd\' | bash -e\"","Preparing $tdir on $cptarget");
2789        }
2790    } else {
2791        $logres = "> ";
2792    }
2793
2794    if ($cmt =~ /SandBox/) {
2795        # Install from sandbox mean using the result of the just passed sbx2build command
2796        # Get content saved in cms2build
2797        my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
2798        my $pbextdir = pb_get_extdir();
2799        if (not defined $pkg) {
2800            cluck "Unable to get package list from $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml";
2801            return;
2802        }
2803
2804        # We consider 2 specific packages
2805        my $vertag1 = $pkg->{"ProjectBuilder"};
2806        my $vertag2 = $pkg->{"project-builder"};
2807        # get the version of the current package - maybe different
2808        pb_log(2,"Vertag1: $vertag1\n");
2809        pb_log(2,"Vertag2: $vertag2\n");
2810        my ($pbver1,$tmp1) = split(/-/,$vertag1);
2811        my ($pbver2,$tmp2) = split(/-/,$vertag2);
2812        if ($cmt =~ /VE/) {
2813            # Copy inside the VE
2814            if ($vetype ne "docker") {
2815                copy("$ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1$pbextdir.tar.gz","$tpdir/tmp");
2816                copy("$ENV{'PBDESTDIR'}/project-builder-$pbver2$pbextdir.tar.gz","$tpdir/tmp");
2817            } else {
2818                copy("$ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1$pbextdir.tar.gz","$context");
2819                copy("$ENV{'PBDESTDIR'}/project-builder-$pbver2$pbextdir.tar.gz","$context");
2820                print DOCKER "COPY ProjectBuilder-$pbver1$pbextdir.tar.gz /tmp/\n";
2821                print DOCKER "COPY project-builder-$pbver2$pbextdir.tar.gz /tmp/\n";
2822            }
2823        } else {
2824            pb_system("$cpcmd $ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1$pbextdir.tar.gz $ENV{'PBDESTDIR'}/project-builder-$pbver2$pbextdir.tar.gz $mac:/tmp","Copying local project files to VM/RM");
2825        }
2826    }
2827           
2828    pb_log(0,"Sources handled ($cmt): $src\n");
2829    # For docker everything is done in the Dockerfile
2830    if (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep < 3)) {
2831        foreach my $f (split(/ +/,$src)) {
2832            copy("$f","$context");
2833            print DOCKER "COPY ".basename($f)." $cptarget/\n";
2834        }
2835        print DOCKER "RUN cd $cptarget ; $cmd\n" if ((defined $cmd) && ($cmd ne ""));
2836    } elsif (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep >= 3)) {
2837        # Nothing to do
2838    } else {
2839        pb_system("cd $ENV{'PBBUILDDIR'} ; $cpcmd $src $cptarget 2> /dev/null","$cmt delivery in $cptarget");
2840    }
2841
2842    # For VE we need to change the owner manually
2843    if ($cmt =~ /^VE/) {
2844        if ($vetype ne "docker") {
2845            my $sudomode = pb_distro_get_param($pbos,pb_conf_get("ossudoersmode"));
2846            my $res = pb_system("$shcmdroot sed -i '/requiretty/d' /etc/sudoers","Removing potential requiretty in sudoers","quiet");
2847            pb_system("$shcmdroot sed '/requiretty/d' /etc/sudoers > /tmp/sudoers.new ; mv /tmp/sudoers.new $tpdir/tmp/sudoers.new ; $shcmdroot mv /tmp/sudoers.new /etc/sudoers ; $shcmdroot chown root:root /etc/sudoers ; $shcmdroot chmod $sudomode /etc/sudoers","Removing again potential requiretty in sudoers as sed -i failed") if (($res ne 0) && (-f "$tpdir/etc/sudoers"));
2848            pb_system("$shcmd \"sudo chown -R $mac $tdir\"","Adapt owner in $tdir to $mac");
2849        } else {
2850            print DOCKER "RUN sed -i '/requiretty/d' /etc/sudoers\n" if ($pbstep == 1);
2851            # Bug in at least Fedora 23 where the dir wasn't owned correctly - doesn't hurt anyway
2852            print DOCKER "RUN chown root:root /etc\n" if ($pbstep == 1);
2853            print DOCKER "RUN chmod 755 /etc\n" if ($pbstep == 1);
2854        }
2855    }
2856
2857    # Use the right script name depending on context
2858    my $pbscript2;
2859    if (($cmt =~ /^(V[EM]|RM)/) || ($cmt =~ /Packages/)){
2860        $pbscript2 = $pbscript{$v};
2861    } else {
2862        $pbscript2 = "pbscript";
2863    }
2864
2865    # It's already ready for CPAN
2866    my $shcmdbase = $shcmd;
2867    my $dkcmd;
2868    if ($cmt ne "CPAN") {
2869        if (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep < 3)) {
2870            copy("$pbscript2","$context");
2871            my $s = basename($pbscript2);
2872            print DOCKER "COPY $s $cptarget/\n";
2873            # call directly with perl to avoid text file busy error messages
2874            print DOCKER "RUN cd $cptarget ; perl ./$s ; if [ '$pbkeep' = '0' ]; then rm -f $s; fi\n";
2875            print DOCKER "RUN rm -rf $cptarget/*\n";
2876            print DOCKER "RUN chown -R $dkaccount $cptarget\n" if ($pbstep == 1);
2877            close(DOCKER);
2878        } elsif (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep >= 3)) {
2879            $dkcmd = "/bin/bash $homedir/$tdir-2/".basename($pbscript2);
2880        } else {
2881            my $s = basename($pbscript2);
2882            $shcmd .= " \"echo \'cd $tdir ; if [ -x $s ]; then ./$s; fi ;  if [ $pbkeep == 0 ]; then rm -f $s; fi\' | bash\"";
2883        }
2884    }
2885    my $cmdverb = "verbose";
2886    if (($cmt eq "Announce") || ($cmt eq "CPAN")) {
2887        $cmdverb = undef;
2888    } elsif (defined ($v)) {
2889        $cmdverb = "verbose_\[$v\] ";
2890    }
2891    # this is where we launch the execution
2892    if (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep >= 3)) {
2893        pb_mkdir_p("$ENV{'PBTMP'}/vebuild");
2894        my $tsrc = "";
2895        foreach my $f (split(/ +/,$src)) {
2896            copy("$f","$ENV{'PBTMP'}/vebuild");
2897            $tsrc .= " ".basename($f);
2898        }
2899        my $ts = "$ENV{'PBTMP'}/vebuild/".basename($pbscript2);
2900        open(DOCKER," > $ts") || cluck "Unable to create $ts" && return;
2901        print DOCKER "#!/bin/bash\n";
2902        print DOCKER "# Put content from host to guest, copying to have the correct uid/gid and rights to do so\n";
2903        print DOCKER "# set -x\n";
2904        print DOCKER "for i in $tsrc; do\n";
2905        print DOCKER "  # Cleanup first to avoid rights issues for root owned files e.g.\n";
2906        print DOCKER "  rm -f $homedir/$tdir/\$i\n";
2907        print DOCKER "  cp $homedir/$tdir-2/\$i $homedir/$tdir\n";
2908        print DOCKER "done\n";
2909        print DOCKER "(cd $homedir/$tdir-2 ; ls -al)\n";
2910        print DOCKER pb_get_content($pbscript2);
2911        print DOCKER "\n# Get content back from guest in a host dir\n";
2912        # Host dir seen as TDIR in container
2913        $cp2target = "$ENV{'PBBUILDDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2914        pb_mkdir_p("$cp2target");
2915        chmod 0777,"$cp2target";
2916        print DOCKER "TDIR=$homedir/$bdir-2/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}\n";
2917        print DOCKER "for i in $homedir/$bdir/*; do\n";
2918        print DOCKER "  # Cleanup first to avoid rights issues for root owned files e.g.\n";
2919        print DOCKER "  j=\`basename \$i\`\n";
2920        print DOCKER "  if [ -d \$TDIR/\$j ]; then\n";
2921        print DOCKER "    rmdir --ignore-fail-on-non-empty \$TDIR/\$j\n";
2922        print DOCKER "  else\n";
2923        print DOCKER "    rm -f \$TDIR/\$j\n";
2924        print DOCKER "  fi\n";
2925        print DOCKER "  cp -r \$i \$TDIR\n";
2926        print DOCKER "done\n";
2927        print DOCKER "find \$TDIR -type f -print0 | xargs -0 chmod 644 && /bin/true\n";
2928        print DOCKER "find \$TDIR -type d -print0 | xargs -0 chmod 777 2> /dev/null && /bin/true\n";
2929        #print DOCKER "ls -al \$TDIR\n";
2930        print DOCKER "exit 0\n";
2931        close(DOCKER);
2932        $shcmd .= " -v $ENV{'PBBUILDDIR'}:$homedir/$bdir-2 -v $ENV{'PBTMP'}/vebuild:$homedir/$tdir-2 -w $homedir/$tdir-2 $tag{$pbstep} $dkcmd";
2933    }
2934    my $ret = pb_system("$shcmd","Executing pbscript on $cptarget if needed",$cmdverb);
2935   
2936    # If target is deb family then sign Release file for Packages
2937    my $pbos2 = pb_distro_get_context($v);
2938    if (($cmt =~ /Packages/) && ($pbos2->{'type'} eq "deb")) {
2939        my $debarch = pb_get_debarch($pbos2);
2940        my $projcomponent = pb_get_debpc($pbos2);
2941        for my $f ("dists/$pbos2->{'version'}/$projcomponent/binary-$debarch/Release","dists/$pbos2->{'version'}/$projcomponent/binary-all/Release","dists/$pbos2->{'version'}/$projcomponent/source/Release","dists/$pbos2->{'version'}/Release") {
2942            my $debdir = dirname($cptarget);
2943            pb_system("cd $ENV{'PBBUILDDIR'} ; $cpcmd $debdir/$f . 2> /dev/null","Getting deb $f file from $debdir");
2944            pb_sign_file("$ENV{'PBBUILDDIR'}/Release");
2945            pb_system("$cpcmd $ENV{'PBBUILDDIR'}/Release.gpg $debdir/$f.gpg 2> /dev/null","Putting deb $f.gpg file to $debdir");
2946            my ($void,$debfile) = split(/:/,$debdir);
2947            pb_system("$shcmdbase \"chmod 644 $debfile/$f.gpg\"","Set mode to 644 for $debfile/$f.gpg");
2948        }
2949    } 
2950
2951    if ($cmt =~ /^(V[EM]|RM)build/) {
2952        # Get back info on pkg produced, compute their name and get them from the VM/RM
2953        pb_system("$cpcmd $cp2target/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'} $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$ 2> /dev/null","Get package names in $cp2target");
2954        if (not -f "$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$") {
2955            pb_log(0,"ERROR with $v on getting $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$\n");
2956            pb_exit(-1);
2957        } else {
2958            open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$") || confess "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$";
2959            my $src = <KEEP>;
2960            chomp($src);
2961            close(KEEP);
2962            unlink("$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$");
2963
2964            $src =~ s/^ *//;
2965            pb_mkdir_p("$ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2966            # Change pgben to make the next send2target happy
2967            my $made = "";
2968   
2969            # For VM/RM we don't want shell expansion to hapen locally but remotely
2970            my $delim = '\'';
2971            if ($cmt =~ /^VEbuild/) {
2972                # For VE we need to support shell expansion locally
2973                $delim = "";
2974            }   
2975
2976            open(KEEP,"> $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") || confess "Unable to write $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2977            foreach my $p (split(/ +/,$src)) {
2978                my $j = basename($p);
2979                pb_system("$cpcmd $cp2target/$delim$p$delim $ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'} 2> /dev/null","Recovery of package $j in $ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2980                $made="$made $pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$j"; # if (($pbos->{'type'} ne "rpm") || ($j !~ /.src.rpm$/));
2981            }
2982       
2983            print KEEP "$made\n";
2984            close(KEEP);
2985            if (($cmt =~ /^VE/) && ($vetype eq "docker") && ($pbstep >= 3)) {
2986                pb_rm_rf("$cp2target");
2987                if ($pbdebug ge 1) {
2988                    pb_log(2,"WARNING: Container  $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}-$cmt NOT removed\n");
2989                }
2990            } else {
2991                pb_system("$shcmdbase \"rm -rf $tdir $bdir\"","$cmt cleanup");
2992            }
2993
2994            # Sign packages locally
2995            pb_sign_pkgs($pbos,$made);
2996
2997            # We want to send them to the ssh account so overwrite what has been done before
2998            pb_log(2,"Before sending pkgs, vexist: $vexist, vpid: $vpid\n");
2999            pb_send2target("Packages","$ENV{'PBDESTDIR'}/pbscript.$$",$pbos->{'name'}."-".$pbos->{'version'}."-".$pbos->{'arch'},$vexist,$vpid);
3000            pb_rm_rf("$ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
3001        }
3002    }
3003    unlink("$pbscript{$v}") if ((($cmt =~ /^(V[ME]|RM)/) || ($cmt =~ /Packages/)) && ($pbkeep eq 0) && ($cmt !~ /Script/));
3004
3005    pb_log(2,"Before halt, vexist: $vexist, vpid: $vpid\n");
3006    if ((! $vexist) && ($cmt =~ /^VM/)) {
3007        # If in setupvm then takes a snapshot just before halting
3008        if ($snapme != 0) {
3009            my ($vmmonport,$vmtype) = pb_conf_get("vmmonport","vmtype");
3010            # For monitoring control
3011            if ((($vmtype->{$ENV{'PBPROJ'}}) eq "kvm") || (($vmtype->{$ENV{'PBPROJ'}}) eq "qemu")) {
3012                eval
3013                {
3014                require Net::Telnet;
3015                Net::Telnet->import();
3016                };
3017                if ($@) {
3018                    # Net::Telnet not found
3019                    pb_log(1,"ADVISE: Install Net::Telnet to benefit from monitoring control and snapshot feature.\nWARNING: No snapshot created");
3020                } else {
3021                    my $t = new Net::Telnet (Timeout => 120, Host => "localhost", Port => $vmmonport->{$ENV{'PBPROJ'}}) || confess "Unable to dialog on the monitor";
3022                    # move to monitor mode
3023                    my @lines = $t->cmd("c");
3024                    # Create a snapshot named pb
3025                    @lines = $t->cmd("savevm pb");
3026                    # Write the new status in the VM
3027                    @lines = $t->cmd("commit all");
3028                    # End
3029                    @lines = $t->cmd("quit");
3030                }
3031            }
3032        }
3033        my $hoption = "-p";
3034        my $hpath = pb_distro_get_param($pbos,pb_conf_get("ospathcmd-halt"));
3035        # Solaris doesn't support -p of halt
3036        if ($pbos->{'type'} eq "pkg") {
3037            $hoption = "" ;
3038        }
3039        pb_system("$shcmdbase \"sudo $hpath $hoption \"; $tm ; echo \'if [ -d /proc/$vpid ]; then kill -9 $vpid; fi \' | bash ; sleep 10","VM $v halt (pid $vpid)");
3040    }
3041    if (($cmt =~ /^VE/) && ($snapme != 0)) {
3042        if ($vetype eq "docker") {
3043            foreach my $f (split(/ +/,$src)) {
3044                unlink("$context/$f");
3045            }
3046        } else {
3047            pb_ve_snap($pbos,$tp);
3048        }
3049    }
3050}
3051
3052sub pb_script2v {
3053
3054my $pbscript=shift;
3055my $vtype=shift;
3056my $pbstep=shift;   # Which step are we in (0: create, 1: setup pb, 2: prep pbproj, 3: use to build)
3057my $pbforce=shift;  # Force stop of VM. Default not.
3058my $snapme=shift;   # Do we have to create a snapshot. Default not.
3059my $pbimage=shift;  # Which image to use to start the VM/VE
3060
3061$pbforce = 0 if (not defined $pbforce);
3062$snapme = 0 if (not defined $snapme);
3063$pbstep = 3 if (not defined $pbstep);
3064
3065pb_log(2,"DEBUG: pb_script2v($vtype,$pbstep,$pbforce,$snapme)\n");
3066pb_log(2,"DEBUG: pb_script2v(pbscript: ".Dumper($pbscript)."\n") if (defined $pbscript);
3067pb_parallel_launchv($pbscript,$vtype,uc($vtype)."Script",$pbstep,$pbimage,$pbforce,$snapme,$pbsnap);
3068}
3069
3070sub pb_parallel_launchv {
3071
3072my $pbscript=shift;
3073my $vtype = shift;
3074my $action = shift;         # It an action is defined then use send2target
3075my $pbstep=shift;           # Which step are we in (0: create, 1: setup, 2: build 3: use)
3076my $pbimage=shift;          # Which image to use to start the VM/VE
3077my $pbforce=shift;          # Force stop of VM. Default not.
3078my $snapme = shift;         # By default do not snap a VM/VE/RM
3079my $usesnap = shift;        # By default study the usage of the snapshot feature of VM/VE/RM   
3080my $vm;
3081my $all;
3082
3083$pbforce = 0 if (not defined $pbforce);
3084$snapme = 0 if (not defined $snapme);
3085$usesnap = 1 if (not defined $usesnap);
3086
3087# Adapt // mode to memory size
3088$pbparallel = pb_set_parallel($vtype);
3089
3090pb_log(2,"DEBUG: pb_parallel_launch(vtype,step,force,snapme,usesnap: $vtype,$pbstep,$pbforce,$snapme,$usesnap)\n");
3091pb_log(2,"DEBUG: pb_parallel_launch(pbscript: ".Dumper($pbscript)."\n");
3092
3093my ($vexist,$vpid) = (undef,undef);
3094my $pm;
3095my $all_ok = 1;
3096if (defined $pbparallel) {
3097    $pm = new Parallel::ForkManager($pbparallel);
3098
3099    # Set which port the VM/RM will use to communicate
3100    $pm->run_on_start(\&pb_set_port);
3101    $pm->run_on_finish(sub { my ($pid, $code, $id, $signal, $dump) = @_;
3102                            unless ($code == 0 && $signal == 0 && $dump == 0) {
3103                                $all_ok = 0;
3104                                pb_log(0,"ERROR: pid $pid failed\n");
3105                                pb_log(0,"code: $code - signal: $signal - dump: $dump\n");
3106                            }
3107                        });
3108}
3109
3110# Determine on which V to work
3111if (defined $ENV{'PBV'}) {
3112    @$vm = split(/,/,$ENV{'PBV'});
3113} else {
3114    ($vm,$all) = pb_get2v($vtype);
3115}
3116
3117$vetype = pb_ve_get_type($vetype);
3118if ((($vtype =~ /vm/) || (($vtype =~ /ve/) && ($vetype eq "docker"))) && (((not defined $pbimage) || ($pbimage eq "")) && ($pbstep == 0))) {
3119    confess "-i image parameter needed";
3120}
3121
3122my $counter = 0;
3123foreach my $v (@$vm) {
3124    $counter++;
3125    # Modulo 2 * pbparallel (to avoid synchronization problems)
3126    $counter = 1 if ((defined $pbparallel) && ($counter > 2 * $pbparallel));
3127    $pm->start($counter) and next if (defined $pbparallel);
3128   
3129    # If launched via script2v then get the script passed as the one for the that VM
3130    if (not defined $pbscript->{$v}) {
3131        $pbscript->{$v} = $pbscript->{'default'};
3132    }
3133    #
3134    # Launch a single operation
3135    ($vexist,$vpid) = pb_launchv($pbscript->{$v},$vtype,$v,$action,$pbstep,$pbforce,$snapme,$pbsnap,$pbimage);
3136   
3137    # Skip that VM/RM if something went wrong
3138    if (($vtype =~ /(v|r)m/) && ($vpid == 0) && ($vexist == 0)) {
3139        $pm->finish if (defined $pbparallel);
3140        next;
3141    }
3142
3143   
3144    $pm->finish if (defined $pbparallel);
3145}
3146$pm->wait_all_children if (defined $pbparallel);
3147confess "Aborting, one or more of the children failed." if ((not $all_ok) && ($Global::pb_stop_on_error));
3148}
3149
3150sub pb_launchv {
3151
3152my $pbscript1=shift;        # Just the script name to execute, not the hash
3153my $vtype = shift;
3154my $v = shift;              # Only 1 VM/VE/RM treated here
3155my $action = shift;         # It an action is defined then use send2target
3156my $pbstep=shift;           # Which step are we in (0: create, 1: setup, 2: build 3: use)
3157my $pbforce=shift;          # Force stop of VM. Default not.
3158my $snapme = shift;         # By default do not snap a VM/VE/RM
3159my $usesnap = shift;            # By default study the usage of the snapshot feature of VM/VE/RM   
3160my $pbimage=shift;          # Which image to use to start the VM/VE
3161my $vexist = undef;
3162my $vpid = undef;
3163
3164$pbforce = 0 if (not defined $pbforce);
3165$snapme = 0 if (not defined $snapme);
3166$usesnap = 1 if (not defined $usesnap);
3167
3168# Check that v exists
3169confess "No VM/VE/RM defined, unable to launch" if (not defined $v);
3170
3171# If creation or snapshot creation mode, no snapshot usable
3172if (($pbstep == 0) || ($snapme == 1)) {
3173    $usesnap = 0;
3174}
3175
3176pb_log(2,"DEBUG: pb_launchv(vtype,v,step,force,snapme,usesnap: $vtype,$v,$pbstep,$pbforce,$snapme,$usesnap)\n");
3177pb_log(2,"DEBUG: pb_launchv(pbimage: $pbimage)\n") if (defined $pbimage);
3178pb_log(2,"DEBUG: pb_launchv(pbscript $pbscript1)\n") if (defined $pbscript1);
3179pb_log(2,"DEBUG: pb_launchv(action: $action)\n") if (defined $action);
3180# Keep only the first VM in case many were given
3181if ($v =~ /,/) {
3182    pb_log(0,"WARNING: pruning to just the first of several VM/VE/RMs listed ($v)\n");
3183    $v =~ s/,.*//;
3184}
3185
3186my $pbos = pb_distro_get_context($v);
3187
3188pb_apply_conf_proxy($pbos);
3189
3190# Launch the VMs/VEs
3191if ($vtype eq "vm") {
3192    my ($ptr,$ptr2,$vmpath,$vmport,$vms) = pb_conf_get("vmtype","vmcmd","vmpath","vmport","vmsize");
3193    my ($vmopt,$vmmm,$vmtmout,$vmsnap,$vmbuildtm,$vmmonport) = pb_conf_get_if("vmopt","vmmem","vmtmout","vmsnap","vmbuildtm","vmmonport");
3194    my $vmsize = pb_distro_get_param($pbos,$vms);
3195
3196    my $vmtype = $ptr->{$ENV{'PBPROJ'}};
3197    my $vmcmd = $ptr2->{$ENV{'PBPROJ'}};
3198
3199    if (defined $opts{'g'}) {
3200        if (($vmtype eq "kvm") || ($vmtype eq "qemu")) {
3201            $ENV{'PBVMOPT'} = "--nographic";
3202        }
3203    }
3204    if (not defined $ENV{'PBVMOPT'}) {
3205        $ENV{'PBVMOPT'} = "";
3206    }
3207    # Save the current status for later restoration
3208    $ENV{'PBOLDVMOPT'} = $ENV{'PBVMOPT'};
3209
3210    if (defined $vmopt->{$v}) {
3211        $ENV{'PBVMOPT'} .= " $vmopt->{$v}" if ($ENV{'PBVMOPT'} !~ / $vmopt->{$v}/);
3212    } elsif (defined $vmopt->{$ENV{'PBPROJ'}}) {
3213        $ENV{'PBVMOPT'} .= " $vmopt->{$ENV{'PBPROJ'}}" if ($ENV{'PBVMOPT'} !~ / $vmopt->{$ENV{'PBPROJ'}}/);
3214    }
3215
3216    # How much memory to allocate for VMs
3217    if (defined $vmmm) {
3218        my $vmmem = pb_distro_get_param($pbos,$vmmm);
3219        if (defined $vmmem) {
3220            $ENV{'PBVMOPT'} .= " -m $vmmem";
3221        }
3222    }
3223
3224    # Are we allowed to use snapshot feature
3225    if ($usesnap == 1) {
3226        if ((defined $vmsnap->{$v}) && ($vmsnap->{$v} =~ /true/i)) {
3227            $ENV{'PBVMOPT'} .= " -snapshot";
3228        } elsif ((defined $vmsnap->{$ENV{'PBPROJ'}}) && ($vmsnap->{$ENV{'PBPROJ'}} =~ /true/i)) {
3229            $ENV{'PBVMOPT'} .= " -snapshot";
3230        } elsif ($pbsnap eq 1) {
3231            $ENV{'PBVMOPT'} .= " -snapshot";
3232        }
3233    } 
3234    if ($snapme != 0) {
3235        if (($vmtype eq "kvm") || ($vmtype eq "qemu")) {
3236            # Configure the monitoring to automate the creation of the 'pb' snapshot
3237            $ENV{'PBVMOPT'} .= " -serial mon:telnet::$vmmonport->{$ENV{'PBPROJ'}},server,nowait" if ((defined $vmmonport) && (defined $vmmonport->{$ENV{'PBPROJ'}}));
3238            # In that case no snapshot call needed
3239            $ENV{'PBVMOPT'} =~ s/ -snapshot//;
3240        }
3241    }
3242   
3243    # Set a default timeout of 2 minutes if none defined externally or in conf files
3244    if (not defined $ENV{'PBVMTMOUT'}) {
3245        if (defined $vmtmout->{$v}) {
3246            $ENV{'PBVMTMOUT'} = $vmtmout->{$v};
3247        } elsif (defined $vmtmout->{$ENV{'PBPROJ'}}) {
3248            $ENV{'PBVMTMOUT'} = $vmtmout->{$ENV{'PBPROJ'}};
3249        }
3250    }
3251    if (not defined $ENV{'PBVMTMOUT'}) {
3252        $ENV{'PBVMTMOUT'} = "120";
3253    }
3254
3255    my $nport = pb_get_port($vmport,$pbos,$vtype);
3256
3257    my $cmd;
3258    my $vmm;        # has to be used for pb_check_ps
3259    if (($vmtype eq "qemu") || ($vmtype eq "kvm")) {
3260        $vmm = "$vmpath->{$ENV{'PBPROJ'}}/$v.qemu";
3261        if (($pbstep == 0) || (defined $pbimage)) {
3262            $ENV{'PBVMOPT'} .= " -cdrom $pbimage -boot d";
3263        }
3264        # Always redirect the network and always try to use a 'pb' snapshot
3265        #$cmd = "$vmcmd $ENV{'PBVMOPT'} -net nic,model=virtio -net user,hostfwd=tcp::$nport:22 -loadvm pb $vmm"
3266        #$cmd = "$vmcmd $ENV{'PBVMOPT'} -redir tcp:$nport:10.0.2.15:22 $vmm"
3267        $cmd = "$vmcmd $ENV{'PBVMOPT'} -net nic -net user,hostfwd=tcp:127.0.0.1:$nport-:22 $vmm"
3268    } elsif ($vmtype eq "xen") {
3269    } elsif ($vmtype eq "vmware") {
3270    } else {
3271        confess "VM of type $vmtype not supported. Report to the dev team";
3272    }
3273    # Restore the ENV VAR Value
3274    $ENV{'PBVMOPT'} = $ENV{'PBOLDVMOPT'};
3275
3276    my ($tmpcmd,$void) = split(/ +/,$cmd);
3277    my $vmmport = undef;
3278    ($vexist,$vmmport) = pb_check_ps($tmpcmd,$vmm);
3279    $vpid = 0;
3280   
3281    if (! $vexist) {
3282        if ($pbstep == 0) {
3283            confess("Found an existing Virtual machine $vmm. Won't overwrite") if (-r $vmm);
3284            if (($vmtype eq "qemu") || ($vmtype eq "xen") || ($vmtype eq "kvm")) {
3285                my $command = pb_check_req("qemu-img",0);
3286                pb_system("$command create -f qcow2 $vmm $vmsize","Creating the QEMU VM");
3287            } elsif ($vmtype eq "vmware") {
3288            } else {
3289            }
3290        }
3291        if (! -f "$vmm") {
3292            pb_log(0,"Unable to find VM $vmm\n");
3293        } else {
3294            # Is the SSH port free? if not kill the existing process using it after a build timeout period
3295            my ($vmssh,$void) = pb_check_ps($tmpcmd,$vmm);
3296            if ($vmssh) {
3297                my $buildtm = $ENV{'PBVMTMOUT'};
3298                if (defined $vmbuildtm->{$v}) {
3299                    $buildtm = $vmbuildtm->{$v};
3300                } elsif (defined $vmbuildtm->{$ENV{'PBPROJ'}}) {
3301                    $buildtm = $vmbuildtm->{$ENV{'PBPROJ'}};
3302                }
3303
3304                sleep $buildtm;
3305                pb_log(0,"WARNING: Killing the process ($vmssh) using port $void (previous failed VM ?)\n");
3306                kill 15,$vmssh;
3307                # Let it time to exit
3308                sleep 5;
3309            }
3310            pb_system("$cmd &","Launching the VM $vmm");
3311            # Using system allows to kill it externaly if needed,sosupport that in the call
3312            pb_system("sleep $ENV{'PBVMTMOUT'}","Waiting $ENV{'PBVMTMOUT'} s for VM $v to come up","mayfail");
3313            ($vpid,$void) = pb_check_ps($tmpcmd,$vmm);
3314            pb_log(0,"VM $vmm launched (pid $vpid)\n");
3315        }
3316    } else {
3317        pb_log(0,"Found an existing VM $vmm (pid $vexist - Port $vmmport)\n");
3318        # Set the correct port here based on what is done
3319        $pbport = $vmmport;
3320        $vpid = $vexist;
3321    }
3322    pb_log(2,"DEBUG: pb_launchv returns ($vexist,$vpid)\n");
3323
3324    # After the VM is launched, then setup the SSH access if not in creation phase
3325    if ($pbstep != 0) {
3326        if (defined $pbport) {
3327            pb_ssh_setup($vtype,$pbport);
3328        } else {
3329            pb_ssh_setup($vtype,$nport);
3330        }
3331    }
3332   
3333    # Skip that VM if something went wrong
3334    return($vexist,$vpid) if (($vpid == 0) && ($vexist == 0));
3335   
3336    # If force stopping the VM then reset vexist
3337    if ($pbforce == 1) {
3338        $vpid = $vexist;
3339        $vexist = 0;
3340    }
3341} elsif ($vtype eq "ve") {
3342    # Force the creation of the VE and no snapshot usable
3343    $vetype = pb_ve_get_type($vetype);
3344    pb_ve_launch($v,$pbstep,$usesnap,$vetype,$pbimage);
3345    $vexist = 0;
3346    $vpid = 0;
3347} else {
3348    # Get RM context
3349    my ($ptr,$rmpath,$rmport) = pb_conf_get("rmtype","rmpath","rmport");
3350
3351    # Nothing more to do for RM. No real launch
3352    # For the moment we support the RM is already running
3353    # For ProLiant may be able to power them on if needed later on as an example.
3354    $vexist = 0;
3355    $vpid = 0;
3356   
3357    # After the RM is launched, then setup the SSH access
3358    my $nport = pb_get_port($rmport,$pbos,$vtype);
3359    pb_ssh_setup($vtype,$nport);
3360}
3361
3362# Gather all required files to send them to the VM/VE/RM
3363# and launch the build through pbscript
3364if (defined $action) {
3365    pb_log(2,"DEBUG: Before send2target, vexist: $vexist, vpid: $vpid, vtype: $vtype, v: $v, action: $action\n");
3366    pb_send2target($action,$pbscript1,$v,$vexist,$vpid,$snapme,$pbstep);
3367}
3368return($vexist,$vpid);
3369}
3370
3371# Return string for date synchro
3372sub pb_date2v {
3373
3374my $vtype = shift;
3375my $pbos = shift;
3376my $nontp = shift || 0;
3377
3378pb_log(1,"Entering pb_date2v\n");
3379# VE gets time from parent OS.
3380return "/bin/true" if ($vtype) =~ /^ve/o; 
3381
3382my ($ntp) = pb_conf_get_if($vtype."ntp");
3383my $vntp = undef;
3384my $ntpline = undef;
3385$vntp = $ntp->{$ENV{'PBPROJ'}} if (defined $ntp);
3386
3387if ((defined $vntp) && ($vntp !~ /^\s*$/)) {
3388    pb_log(2,"ntp server is $vntp\n");
3389    # ntp command depends on pbos
3390    my $vntpcmd = pb_distro_get_param($pbos,pb_conf_get("oscmdntp"));
3391    $ntpline = "sudo $vntpcmd $vntp";
3392}
3393# Force new date to be in the future compared to the date
3394# of the host by adding 1 minute
3395my @date=pb_get_date();
3396$date[1]++;
3397my $upddate = strftime("%m%d%H%M%Y", @date);
3398my $dateline = "sudo /bin/date $upddate";
3399if ((defined $ntpline) && ($nontp == 0)) {
3400    pb_log(1,"pb_date2v returns $ntpline\n");
3401    return($ntpline);
3402} else {
3403    pb_log(1,"pb_date2v returns $dateline\n");
3404    return($dateline);
3405}
3406}
3407
3408sub pb_build2v {
3409
3410my $vtype = shift;
3411my $action = shift;     #build, test or prep
3412my $pbforce=shift;      # Force stop of VM. Default not.
3413
3414$action = "build" if (not defined $action);
3415$pbforce = 0 if (not defined $pbforce);
3416
3417my $pbstep;
3418
3419$vetype = pb_ve_get_type($vetype);
3420if ($action eq "prep") {
3421    $pbstep = 2;
3422} else {
3423    $pbstep = 3;
3424    # Need to be traversed by others if using containers
3425    if (($vtype eq "ve") && ($vetype eq "docker")) {
3426        chmod 0751,"$ENV{'PBBUILDDIR'}";
3427    }
3428}
3429
3430pb_log(1,"Entering in pb_build2v ($action in $vtype) \n");
3431
3432# We prepare scripts for all V of this vtype to allow sharing that part
3433my ($v,$all) = pb_get2v($vtype);
3434
3435# Send tar files when we do a global generation
3436pb_build2ssh() if (($all == 1) && ($action eq "build"));
3437
3438# Adapt // mode to memory size
3439$pbparallel = pb_set_parallel($vtype);
3440
3441my ($vexist,$vpid) = (undef,undef);
3442my $pm;
3443my $all_ok = 1;
3444if (defined $pbparallel) {
3445    $pm = new Parallel::ForkManager($pbparallel);
3446
3447    # Set which port the VM/RM will use to communicate
3448    $pm->run_on_start(\&pb_set_port);
3449    $pm->run_on_finish(sub { my ($pid, $code, $id, $signal, $dump) = @_;
3450                            unless ($code == 0 && $signal == 0 && $dump == 0) {
3451                                $all_ok = 0;
3452                                pb_log(0,"ERROR: pid $pid failed\n");
3453                                pb_log(0,"code: $code - signal: $signal - dump: $dump\n");
3454                            }
3455                        });
3456}
3457
3458my $counter = 0;
3459foreach my $v (@$v) {
3460    $counter++;
3461    $pbscript{$v} = "$ENV{'PBDESTDIR'}/pb$action-$v";
3462    # Modulo 2 * pbparallel (to avoid synchronization problems)
3463    $counter = 1 if ((defined $pbparallel) && ($counter > 2 * $pbparallel));
3464    $pm->start($counter) and next if (defined $pbparallel);
3465    #
3466    # Prepare the script to be executed on the VM/VE/RM
3467    open(SCRIPT,"> $pbscript{$v}") || confess "Unable to create $pbscript{$v}";
3468    print SCRIPT "#!/bin/bash\n";
3469
3470    # Transmit the verbosity level to the virtual env/mach.
3471    my $verbose = "";
3472    my $i = 0;                          # minimal debug level
3473    while ($i lt $pbdebug) {
3474        $verbose .= "-v ";
3475        $i++;
3476    }
3477    print SCRIPT "set -e\n" if ($Global::pb_stop_on_error);
3478    # Activate script verbosity if at least 2 for pbdebug
3479    print SCRIPT "set -x\n" if ($i gt 1);
3480    # Quiet if asked to be so on the original system
3481    $verbose = "-q" if ($pbdebug eq -1);
3482
3483    print SCRIPT "echo ... Execution needed\n";
3484    print SCRIPT "echo ==== Start of script for $vtype $v =====\n";
3485    print SCRIPT "# This is in directory pbdelivery\n";
3486    print SCRIPT "# Setup the variables required for building\n";
3487    print SCRIPT "export PBPROJ=$ENV{'PBPROJ'}\n";
3488
3489    if (($action eq "build") || ($action eq "prep")) {
3490        print SCRIPT "# Preparation for pb\n";
3491        print SCRIPT "rm -f \$HOME/.pbrc.yml\n";
3492        print SCRIPT "rm -f \$HOME/.pbrc\n";
3493        print SCRIPT "cp .pbrc.yml \$HOME\n";
3494        # TODO: Why ?
3495        print SCRIPT "cd ..\n";
3496    }
3497
3498    # VE needs a good /proc, tolerate one being potentially left around after a failure
3499    if (($vtype eq "ve") && ($vetype ne "docker")) {
3500        print SCRIPT "[ -d /proc/1 ] || sudo /bin/mount -t proc /proc /proc\n";
3501    }
3502
3503    # Get distro context
3504    my $pbos = pb_distro_get_context($v);
3505   
3506    my $ntpline = pb_date2v($vtype,$pbos);
3507    print SCRIPT "# Time sync\n";
3508    print SCRIPT "echo setting up date with $ntpline\n";
3509    print SCRIPT "$ntpline\n";
3510    print SCRIPT "if [ \$\? -ne 0 ]; then\n";
3511    # Force if bad status a trick using date
3512    $ntpline = pb_date2v($vtype,$pbos, 1);
3513    print SCRIPT "  $ntpline\n";
3514    print SCRIPT "fi\n";
3515    # Use potential local proxy declaration in case we need it to download repo, pkgs, ...
3516    if (defined $ENV{'http_proxy'}) {
3517        print SCRIPT "export http_proxy=\"$ENV{'http_proxy'}\"\n";
3518    }
3519    if (defined $ENV{'https_proxy'}) {
3520        print SCRIPT "export https_proxy=\"$ENV{'https_proxy'}\"\n";
3521    }
3522    if (defined $ENV{'ftp_proxy'}) {
3523        print SCRIPT "export ftp_proxy=\"$ENV{'ftp_proxy'}\"\n";
3524    }
3525
3526    # Get list of packages to build/test and get some ENV vars as well
3527    my $ptr = pb_get_pkg();
3528    @pkgs = @$ptr;
3529    my $p = join(' ',@pkgs) if (@pkgs);
3530    print SCRIPT "export PBPROJVER=$ENV{'PBPROJVER'}\n";
3531    print SCRIPT "export PBPROJTAG=$ENV{'PBPROJTAG'}\n";
3532    print SCRIPT "export PBPACKAGER=\"$ENV{'PBPACKAGER'}\"\n";
3533    # TODO: setup apk pkg/keys here
3534
3535    # We may need to do some other tasks before building. Read a script here to finish setup
3536    if (-x "$ENV{'PBTMP'}/pb$vtype".".pre") {
3537        print SCRIPT "# Special pre-instructions to be launched\n";
3538        print SCRIPT pb_get_content("$ENV{'PBTMP'}/pb$vtype".".pre");
3539    }
3540
3541    if (-x "$ENV{'PBTMP'}/pb$vtype"."$action.pre") {
3542        print SCRIPT "# Special pre-$action instructions to be launched\n";
3543        print SCRIPT pb_get_content("$ENV{'PBTMP'}/pb$vtype"."$action.pre");
3544    }
3545
3546    print SCRIPT "# $action\n";
3547    print SCRIPT "echo $action"."ing packages on $vtype...\n";
3548
3549    if (($action eq "test") && (! -x "$ENV{'PBDESTDIR'}/pbtest")) {
3550        cluck "No test script ($ENV{'PBDESTDIR'}/pbtest) found when in test mode. Aborting ...";
3551        next;
3552    }
3553    print SCRIPT "pb --version\n";
3554    my $act = "$action"."2pkg";
3555    $act = "build2prep" if ($action eq "prep");
3556    print SCRIPT "pb $verbose -p $ENV{'PBPROJ'} $act $p\n";
3557
3558    if (($vtype eq "ve") && ($vetype ne "docker")) {
3559        print SCRIPT "sudo /bin/umount /proc\n";
3560    }
3561
3562    # We may need to do some other tasks after building. Read a script here to exit properly
3563    if (-x "$ENV{'PBTMP'}/pb$vtype"."$action.post") {
3564        print SCRIPT "# Special post-$action instructions to be launched\n";
3565        print SCRIPT pb_get_content("$ENV{'PBTMP'}/pb$vtype"."$action.post");
3566    }
3567
3568    if (-x "$ENV{'PBTMP'}/pb$vtype".".post") {
3569        print SCRIPT "# Special post-instructions to be launched\n";
3570        print SCRIPT pb_get_content("$ENV{'PBTMP'}/pb$vtype".".post");
3571    }
3572
3573    print SCRIPT "echo ==== End of script $$ for $vtype $v =====\n";
3574    close(SCRIPT);
3575    chmod 0755,"$pbscript{$v}";
3576   
3577    $pm->finish if (defined $pbparallel);
3578}
3579$pm->wait_all_children if (defined $pbparallel);
3580confess "Aborting, one or more of the children failed." if ((not $all_ok) && ($Global::pb_stop_on_error));
3581
3582# Launch the VM/VE/RM
3583# docker image to use if needed
3584# Gather all required files to send them to the VM/VE
3585# and launch the build through pbscript
3586pb_parallel_launchv(\%pbscript,$vtype,uc($vtype).$action,$pbstep,$pbimage,$pbforce);
3587}
3588
3589
3590sub pb_clean {
3591
3592    my $sleep=10;
3593    confess "Unable to get env var PBDESTDIR" if (not defined $ENV{'PBDESTDIR'});
3594    confess "Unable to get env var PBBUILDDIR" if (not defined $ENV{'PBBUILDDIR'});
3595    pb_log(0,"We will now wait $sleep s before removing both directories\n$ENV{'PBDESTDIR'} and $ENV{'PBBUILDDIR'}.\nPlease break me if this is wrong\n");
3596    sleep $sleep;
3597    pb_rm_rf($ENV{'PBDESTDIR'});
3598    pb_rm_rf($ENV{'PBBUILDDIR'});
3599}
3600
3601sub pb_newver {
3602
3603    confess "-V Version parameter needed" if ((not defined $newver) || ($newver eq ""));
3604
3605    # Need this call for PBDIR
3606    my ($scheme2,$uri) = pb_vcs_init($pbinit);
3607
3608    my ($pbconf,$pbprojurl) = pb_conf_get("pbconfurl","pbprojurl");
3609    $uri = $pbconf->{$ENV{'PBPROJ'}};
3610    my ($scheme, $account, $host, $port, $path) = pb_get_uri($uri);
3611
3612    # Checking CMS repositories status
3613    ($scheme2, $account, $host, $port, $path) = pb_get_uri($pbprojurl->{$ENV{'PBPROJ'}});
3614
3615    if ($scheme !~ /^svn/) {
3616        confess "Only SVN is supported at the moment";
3617    }
3618
3619    my $res = pb_vcs_isdiff($scheme,$ENV{'PBROOTDIR'});
3620    confess "ERROR: No differences accepted in CMS for $ENV{'PBROOTDIR'} before creating a new version" if ($res != 0);
3621
3622    $res = pb_vcs_isdiff($scheme2,$ENV{'PBDIR'});
3623    confess "ERROR: No differences accepted in CMS for $ENV{'PBDIR'} before creating a new version" if ($res != 0);
3624
3625    # Tree identical between PBCONFDIR and PBROOTDIR. The delta is what
3626    # we want to get for the root of the new URL
3627
3628    my $oldver = $ENV{'PBROOTDIR'};
3629    $oldver =~ s|^$ENV{'PBCONFDIR'}||;
3630
3631    pb_log(2, "PBCONFDIR: $ENV{'PBCONFDIR'}\nPBROOTDIR: $ENV{'PBROOTDIR'}\n");
3632
3633    my $newurl = "$uri/$newver";
3634    # Should probably use projver in the old file
3635    my $oldvertxt= basename($oldver);
3636    my $newvertxt = basename($newver);
3637
3638    # Duplicate and extract project-builder part
3639    pb_log(2,"Copying $uri/$oldver to $newurl\n");
3640    pb_vcs_copy($scheme,"$uri/$oldver",$newurl);
3641    pb_log(2,"Checkout $newurl to $ENV{'PBCONFDIR'}/$newver\n");
3642    pb_vcs_up($scheme,"$ENV{'PBCONFDIR'}");
3643
3644    # Duplicate and extract project
3645    my $newurl2 = "$pbprojurl->{$ENV{'PBPROJ'}}/$newver";
3646
3647    pb_log(2,"Copying $pbprojurl->{$ENV{'PBPROJ'}}/$oldver to $newurl2\n");
3648    pb_vcs_copy($scheme2,"$pbprojurl->{$ENV{'PBPROJ'}}/$oldver",$newurl2);
3649
3650    my $tmp = $ENV{'PBDIR'};
3651    $tmp =~ s|$oldver$||;
3652    pb_log(2,"Checkout $newurl2 to $tmp/$newver\n");
3653    pb_vcs_up($scheme2,"$tmp");
3654
3655    # Update the .yml file
3656    open(FILE,"$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml") || confess "Unable to open $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml";
3657    open(OUT,"> $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml.new") || confess "Unable to write to $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml.new";
3658    while(<FILE>) {
3659        if (/^projver\s+$ENV{'PBPROJ'}\s*=\s*$oldvertxt$/) {
3660            s/^projver\s+$ENV{'PBPROJ'}\s*=\s*$oldvertxt$/projver $ENV{'PBPROJ'} = $newvertxt/;
3661            pb_log(0,"Changing projver from $oldvertxt to $newvertxt in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml\n");
3662        }
3663        if (/^testver/) {
3664            s/^testver/#testver/;
3665            pb_log(0,"Commenting testver in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml\n") if (/^testver/);
3666        }
3667        if (/^delivery/) {
3668            my $txt = $_;
3669            chomp($txt);
3670            pb_log(0,"Please check delivery ($txt) in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml\n");
3671        }
3672        print OUT $_;
3673    }
3674    close(FILE);
3675    close(OUT);
3676    rename("$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml.new","$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.yml");
3677
3678    # Checking pbcl files
3679    foreach my $f (<$ENV{'PBROOTDIR'}/*/pbcl>) {
3680        # Compute new pbcl file
3681        my $f2 = $f;
3682        $f2 =~ s|$ENV{'PBROOTDIR'}|$ENV{'PBCONFDIR'}/$newver/|;
3683        open(PBCL,$f) || confess "Unable to open $f";
3684        my $foundnew = 0;
3685        while (<PBCL>) {
3686            $foundnew = 1 if (/^$newvertxt \(/);
3687        }
3688        close(PBCL);
3689        open(OUT,"> $f2") || confess "Unable to write to $f2: $!";
3690        open(PBCL,$f) || confess "Unable to open $f";
3691        # We skip as long as we do not reach the new version in the log (case of devel)
3692        my $skip = 1;
3693        # We let the 4 first lines
3694        my $cnt = 0;
3695        while (<PBCL>) {
3696            $skip = 0 if (/^$newvertxt \(/);
3697            if ((/^$oldvertxt \(/) && ($foundnew == 0)) {
3698                print OUT "$newvertxt ($pbdate)\n";
3699                print OUT "- TBD\n";
3700                print OUT "\n";
3701                pb_log(0,"WARNING: version $newvertxt not found in $f so added to $f2...\n") if ($foundnew == 0);
3702            }
3703            if ($cnt <= 4) {
3704                print OUT "$_" if (not /^$oldvertxt \(/);
3705            } else {
3706                print OUT "$_" if ($skip == 0);
3707            }
3708            $cnt++;
3709        }
3710        close(OUT);
3711        close(PBCL);
3712    }
3713
3714    pb_log(2,"Checkin $ENV{'PBCONFDIR'}/$newver\n");
3715    pb_vcs_checkin($scheme,"$ENV{'PBCONFDIR'}/$newver","updated to $ENV{'PBCONFDIR'}");
3716}
3717
3718#
3719# Return the list of VMs/VEs/RMs we are working on
3720# $all is a flag to know if we return all of them
3721# or only some (if all we publish also tar files in addition to pkgs
3722#
3723sub pb_get2v {
3724
3725my $vtype = shift;
3726my @v;
3727my $all = 0;
3728my $pbv = 'PBV';
3729my $vlist = $vtype."list";
3730
3731# Get VM/VE list
3732if ((not defined $ENV{$pbv}) || ($ENV{$pbv} =~ /^all$/)) {
3733    my ($ptr) = pb_conf_get($vlist);
3734    $ENV{$pbv} = $ptr->{$ENV{'PBPROJ'}};
3735    $all = 1;
3736}
3737pb_log(2,"$vtype: $ENV{$pbv}\n");
3738@v = split(/,/,$ENV{$pbv});
3739return(\@v,$all);
3740}
3741
3742# This function creates a giant script to configure a particular VM/VE/RM, it then copies the
3743# script to the target.
3744
3745# Function to create a potentialy missing pb account on the VM/VE/RM, and adds it to sudo
3746# Needs to use root account to connect to the VM/VE/RM
3747# pb will take your local public SSH key to access
3748# the pb account in the VM/VE/RM later on if needed
3749sub pb_setup2v {
3750
3751my $vtype = shift;
3752my $sbx = shift;
3753my $pbstep = 1;
3754
3755my ($vm,$all) = pb_get2v($vtype);
3756
3757# Adapt // mode to memory size
3758$pbparallel = pb_set_parallel($vtype);
3759
3760my $pm;
3761my $all_ok = 1;
3762if (defined $pbparallel) {
3763    $pm = new Parallel::ForkManager($pbparallel);
3764
3765    # Set which port the VM/RM will use to communicate
3766    $pm->run_on_start(\&pb_set_port);
3767    $pm->run_on_finish(sub { my ($pid, $code, $id, $signal, $dump) = @_;
3768                            $all_ok = 0 unless (($code == 0) && ($signal == 0) && ($dump == 0)); 
3769                        });
3770}
3771
3772my $counter = 0;
3773foreach my $v (@$vm) {
3774    # Script generated - should be before the fork - after the %pbscript hash isn't updated correctly
3775    $pbscript{$v} = "$ENV{'PBDESTDIR'}/setupv-$v";
3776
3777    $counter++;
3778    if (defined $pbparallel) {
3779        # Modulo 2 * pbparallel (to avoid synchronization problems)
3780        $counter = 1 if ($counter > 2 * $pbparallel);
3781        $pm->start($counter) and next;
3782    }
3783
3784    # Get distro context
3785    my $pbos = pb_distro_get_context($v);
3786   
3787    # Deal with date sync.
3788    my $ntpline = pb_date2v($vtype,$pbos);
3789
3790    # Name of the account to deal with for VM/VE/RM
3791    # Do not use the one passed potentially with -a
3792    my ($pbac) = pb_conf_get($vtype."login");
3793    if ((not defined $pbac) || (not defined $pbac->{$ENV{'PBPROJ'}})) {
3794        cluck "No $vtype"."login defined in your project yml conf file";
3795        next;
3796    }
3797
3798    my $key = "";
3799
3800    # Prepare the script to be executed on the VM/VE/RM
3801    # in $ENV{'PBDESTDIR'}/setupv
3802
3803    pb_log(2,"Preparing setup script for $v in $pbscript{$v}\n");
3804    open(SCRIPT,"> $pbscript{$v}") || confess "Unable to create $pbscript{$v}";
3805   
3806    print SCRIPT << 'EOF';
3807#!/usr/bin/perl -w
3808
3809use strict;
3810use File::Copy;
3811
3812# We should not need in this script more functions than what is provided
3813# by Base, Conf and Distribution to avoid problems at exec time.
3814# They are appended at the end.
3815
3816# Define mandatory global vars
3817EOF
3818    my $ppref = "our";
3819    $ppref = "my" if (($pbos->{'name'} =~ /^redhat/) && ($pbos->{'version'} =~ /^6/));
3820    print SCRIPT << "EOF";
3821$ppref \$pbdebug = $pbdebug;
3822$ppref \$pbLOG;
3823$ppref \$pbsynmsg = "pbscript";
3824$ppref \$pbdisplaytype = "text";
3825$ppref \$pblocale = "";
3826$ppref \$PBCONFVER = $projectbuilderconfver;
3827EOF
3828    print SCRIPT << 'EOF';
3829pb_log_init($pbdebug, $pbLOG);
3830EOF
3831    print SCRIPT << "EOF";
3832\$Global::pb_stop_on_error = $Global::pb_stop_on_error;
3833pb_temp_init($pbkeep);
3834pb_conf_init("$ENV{'PBPROJ'}");
3835
3836EOF
3837
3838    if ($vtype eq "ve") {
3839        $vetype = pb_ve_get_type($vetype);
3840        if ($vetype ne "docker") {
3841            print SCRIPT << "EOF";
3842# For VE we first need to mount some FS
3843pb_system("mount -t proc /proc /proc") unless (-d "/proc/$$");
3844EOF
3845        }
3846        print SCRIPT << "EOF";
3847# For VE we need a good null dev
3848# Except for RedHat 6.2 where it's good and doesn't like being recreated
3849EOF
3850        print SCRIPT "pb_system('rm -f /dev/null; mknod /dev/null c 1 3; chmod 777 /dev/null');\n" unless (($pbos->{'name'} =~ /^redhat/) && ($pbos->{'version'} =~ /^6/));
3851    } elsif ($vtype =~ /(v|r)m/) {
3852        # Nothing to do now.
3853        my $useless = 0;
3854    } else {
3855        confess "Unknown virtual type $vtype";
3856    }
3857
3858    print SCRIPT << 'EOF';
3859
3860# Adds $pbac->{$ENV{'PBPROJ'}} as an account if needed
3861#
3862my $file="/etc/passwd";
3863open(PBFILE,$file) || die "Unable to open $file";
3864my $found = 0;
3865while (<PBFILE>) {
3866EOF
3867    print SCRIPT << "EOF";
3868    \$found = 1 if (/^$pbac->{$ENV{'PBPROJ'}}:/);
3869EOF
3870
3871# TODO: use an external parameter
3872my $home = "/home";
3873# Solaris doesn't like that we use /home
3874$home = "/export/home" if ($pbos->{'type'} eq "pkg");
3875
3876    print SCRIPT << "EOF";
3877}
3878close(PBFILE);
3879
3880if ( \$found == 0 ) {
3881    if ( ! -d "$home" ) {
3882        pb_mkdir_p("$home");
3883    }
3884EOF
3885    # TODO: Level of portability of these cmds ? Critical now for RM
3886    # TODO: use an external parameter
3887    print SCRIPT << "EOF";
3888    # Most Linux distros
3889    if ( -x "/usr/sbin/groupadd" ) {
3890        pb_system("/usr/sbin/groupadd $pbac->{$ENV{'PBPROJ'}}","Adding group $pbac->{$ENV{'PBPROJ'}}");
3891    # Alpine with busybox
3892    } elsif ( -x "/usr/sbin/addgroup" ) {
3893        pb_system("/usr/sbin/addgroup $pbac->{$ENV{'PBPROJ'}}","Adding group $pbac->{$ENV{'PBPROJ'}}");
3894    } else {
3895        die "Unable to find a command to add a group on this distribution";
3896    }
3897    # Most Linux distros
3898    if ( -x "/usr/sbin/useradd" ) {
3899        pb_system("/usr/sbin/useradd -g $pbac->{$ENV{'PBPROJ'}} -m -d $home/$pbac->{$ENV{'PBPROJ'}} $pbac->{$ENV{'PBPROJ'}}","Adding user $pbac->{$ENV{'PBPROJ'}} (group $pbac->{$ENV{'PBPROJ'}} - home $home/$pbac->{$ENV{'PBPROJ'}})");
3900    # Alpine with busybox
3901    } elsif ( -x "/usr/sbin/adduser" ) {
3902        pb_system("/usr/sbin/adduser -G $pbac->{$ENV{'PBPROJ'}} -h $home/$pbac->{$ENV{'PBPROJ'}} -D $pbac->{$ENV{'PBPROJ'}}","Adding user $pbac->{$ENV{'PBPROJ'}} (group $pbac->{$ENV{'PBPROJ'}} - home $home/$pbac->{$ENV{'PBPROJ'}})");
3903        pb_system("/usr/sbin/addgroup $pbac->{$ENV{'PBPROJ'}} abuild","Adding $pbac->{$ENV{'PBPROJ'}} to group abuild");
3904    } else {
3905        die "Unable to find a command to add a user on this distribution";
3906    }
3907}
3908EOF
3909
3910    # Copy the content of our local conf file to the VM/VE/RM
3911    my $content = pb_get_content(pb_distro_conffile());
3912    print SCRIPT << "EOF";
3913    #
3914    # Create a temporary local conf file for distribution support
3915    # This is created here before its use later. Its place is hardcoded, so no choice for the path
3916    #
3917    my \$tempconf = pb_distro_conffile();
3918    pb_mkdir_p(dirname(\$tempconf));
3919    open(CONF,"> \$tempconf") || die "Unable to create \$tempconf";
3920    print CONF q{$content};
3921    close(CONF);
3922EOF
3923
3924    if ($vtype =~ /(v|r)m/) {
3925        print SCRIPT << "EOF";
3926# allow ssh entry to build
3927#
3928mkdir "$home/$pbac->{$ENV{'PBPROJ'}}/.ssh",0700;
3929# Allow those accessing root to access the build account
3930copy("\$ENV{'HOME'}/.ssh/authorized_keys","$home/$pbac->{$ENV{'PBPROJ'}}/.ssh/authorized_keys");
3931chmod 0600,".ssh/authorized_keys";
3932pb_system("chown -R $pbac->{$ENV{'PBPROJ'}}:$pbac->{$ENV{'PBPROJ'}} $home/$pbac->{$ENV{'PBPROJ'}}","Finish setting up the account env for $pbac->{$ENV{'PBPROJ'}}");
3933
3934EOF
3935}
3936    print SCRIPT << 'EOF';
3937# No passwd for build account only keys
3938$file="/etc/shadow";
3939if (-f $file) {
3940    open(PBFILE,$file) || die "Unable to open $file";
3941    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
3942    while (<PBFILE>) {
3943EOF
3944    print SCRIPT << "EOF";
3945        s/^$pbac->{$ENV{'PBPROJ'}}:\!\!:/$pbac->{$ENV{'PBPROJ'}}:*:/;
3946        s/^$pbac->{$ENV{'PBPROJ'}}:\!:/$pbac->{$ENV{'PBPROJ'}}:*:/; #SLES 9 e.g.
3947        s/^$pbac->{$ENV{'PBPROJ'}}:\\*LK\\*:/$pbac->{$ENV{'PBPROJ'}}:NP:/;  #Solaris e.g.
3948EOF
3949        print SCRIPT << 'EOF';
3950        print PBOUT $_;
3951    }
3952    close(PBFILE);
3953    close(PBOUT);
3954    rename("$file.new",$file);
3955    chmod 0640,$file;
3956    }
3957
3958# TODO: systemd support
3959# Keep the VM in text mode
3960$file="/etc/inittab";
3961if (-f $file) {
3962    open(PBFILE,$file) || die "Unable to open $file";
3963    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
3964    while (<PBFILE>) {
3965        s/^(..):5:initdefault:$/$1:3:initdefault:/;
3966        print PBOUT $_;
3967    }
3968    close(PBFILE);
3969    close(PBOUT);
3970    rename("$file.new",$file);
3971    chmod 0640,$file;
3972}
3973
3974# pb has to be added to portage group on gentoo
3975
3976# We need to have that pb_distro_get_context function
3977# Get it from ProjectBuilder::Distribution
3978# And we now need the conf file required for this to work created above
3979
3980my $pbos = pb_distro_get_context(); 
3981print "distro tuple: ".Dumper($pbos)."\n";
3982
3983# Adapt sudoers
3984# sudo is not default on Solaris and needs to be installed first
3985# from http://www.sunfreeware.com/programlistsparc10.html#sudo
3986if ($pbos->{'type'} eq "pkg") {
3987    $file="/usr/local/etc/sudoers";
3988} else {
3989    $file="/etc/sudoers";
3990}
3991open(PBFILE,$file) || die "Unable to open $file";
3992open(PBOUT,"> $file.new") || die "Unable to open $file.new";
3993while (<PBFILE>) {
3994EOF
3995    # Skip what will be generated
3996    print SCRIPT << "EOF";
3997    next if (/^$pbac->{$ENV{'PBPROJ'}}\\s+/);
3998    next if (/^Defaults:$pbac->{$ENV{'PBPROJ'}}\\s+/);
3999    next if (/^Defaults:root\\s+\!requiretty/);
4000    next if (/^Defaults:root\\s+env_keep/);
4001EOF
4002    print SCRIPT << 'EOF';
4003    s/Defaults\s+requiretty/# disable Defaults: requiretty/;
4004    print PBOUT $_;
4005}
4006close(PBFILE);
4007EOF
4008    print SCRIPT << "EOF";
4009# Some distro force requiretty at compile time, so disable here
4010print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}} !requiretty\\n";
4011print PBOUT "Defaults:root !requiretty\\n";
4012EOF
4013    # RH 6.2 sudo doesn't support env_keep
4014    if (($pbos->{'name'} ne "redhat") && ($pbos->{'version'} ne "6.2")) {
4015        print SCRIPT << "EOF";
4016# Keep proxy configuration while using sudo
4017print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}}    env_keep += \\\"http_proxy https_proxy ftp_proxy\\\"\\n";
4018print PBOUT "Defaults:root    env_keep += \\\"http_proxy https_proxy ftp_proxy\\\"\\n";
4019EOF
4020    }
4021    # Try to restrict security to what is really needed
4022    if ($vtype =~ /^vm/) {
4023        my $hpath = pb_distro_get_param($pbos,pb_conf_get("ospathcmd-halt"));
4024        my @sudocmds = pb_get_sudocmds($pbos,$ntpline,"sudo $hpath","sudo /bin/date");
4025        print SCRIPT << "EOF";
4026# This is needed in order to be able on VM to halt the machine from the $pbac->{$ENV{'PBPROJ'}} account at least
4027# Build account $pbac->{$ENV{'PBPROJ'}} in VM also needs to setup date and install deps.
4028# Nothing else should be needed
4029EOF
4030        foreach my $c (@sudocmds) {
4031            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\\n\";\n";
4032        }
4033    } elsif ($vtype =~ /^rm/) {
4034        my @sudocmds = pb_get_sudocmds($pbos,$ntpline);
4035        print SCRIPT << "EOF";
4036# Build account $pbac->{$ENV{'PBPROJ'}} in RM only needs to setup date and install deps if needed each time
4037EOF
4038        foreach my $c (@sudocmds) {
4039            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\\n\";\n";
4040        }
4041    } else {
4042        print SCRIPT << "EOF";
4043# Build account $pbac->{$ENV{'PBPROJ'}} for VE needs to do a lot in the host (and chroot), so allow without restriction for now
4044print PBOUT "$pbac->{$ENV{'PBPROJ'}}   ALL=(ALL) NOPASSWD:ALL\n";
4045EOF
4046    }
4047    my $sudomode = pb_distro_get_param($pbos,pb_conf_get("ossudoersmode"));
4048    print SCRIPT << 'EOF';
4049close(PBOUT);
4050rename("$file.new",$file);
4051EOF
4052    print SCRIPT << "EOF";
4053chmod 0$sudomode,\$file;
4054
4055EOF
4056
4057    if ($vtype =~ /(v|r)m/) {
4058        # Sync date
4059        # do it after sudoers is setup
4060        print SCRIPT "my \$res = pb_system(\"$ntpline\",\"Updating time with $ntpline\",\"mayfailverbose\");\n";
4061        print SCRIPT "if (\$res != 0) {\n";
4062        # try again with another method
4063        $ntpline = pb_date2v($vtype,$pbos,1);
4064        print SCRIPT "  pb_system(\"$ntpline\",\"Updating time with $ntpline\",\"mayfailverbose\");\n";
4065        print SCRIPT "}\n";
4066    }
4067
4068    my ($addrepo) = pb_conf_read("$ENV{'PBDESTDIR'}/pbrc.yml","addrepo");
4069    my $pbrepo = pb_distro_get_param($pbos,$addrepo);
4070    print SCRIPT << 'EOF';
4071   
4072# We may need a proxy configuration. Get it from the local env
4073pb_apply_conf_proxy($pbos);
4074
4075# First install all required packages
4076pb_system("dnf clean all","Cleaning dnf env","mayfail") if (($pbos->{'name'} eq "fedora") && ($pbos->{'version'} >= 22));
4077pb_system("yum clean all","Cleaning yum env","mayfail") if ((($pbos->{'name'} eq "fedora") && ($pbos->{'version'} < 22)) || ($pbos->{'name'} eq "asianux") || ($pbos->{'name'} eq "rhel"));
4078my ($ospkgdep) = pb_conf_get_if("ospkgdep");
4079
4080my $pkgdep = pb_distro_get_param($pbos,$ospkgdep);
4081my $forcerepo;
4082EOF
4083    print SCRIPT "\$forcerepo = pb_distro_setuprepo_gen(\$pbos,\"$pbrepo\");\n" if ((defined $pbrepo) && ($pbrepo ne ""));
4084    print SCRIPT << 'EOF';
4085pb_distro_installdeps(undef,$pbos,$forcerepo,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgdep))));
4086
4087EOF
4088    my $itype = pb_distro_get_param($pbos,pb_conf_get("pbinstalltype"));
4089    # Install from sandbox mean a file base install
4090    $itype = "file" if (defined $sbx);
4091    if ($itype =~ /^file/) {
4092        my $cmdget;
4093        my ($pbver1,$pbver2,$pbextdir);
4094        my ($tmp1,$tmp2);
4095        if (defined $sbx) {
4096            # Install from sandbox mean using the result of the just passed sbx2build command
4097            # Get content saved in cms2build
4098            my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
4099            $pbextdir = pb_get_extdir();
4100            confess "Unable to get package list" if (not defined $pkg);
4101
4102            # We consider 2 specific packages
4103            my $vertag1 = $pkg->{"ProjectBuilder"};
4104            my $vertag2 = $pkg->{"project-builder"};
4105            # get the version of the current package - maybe different
4106            pb_log(2,"Vertag1: $vertag1\n");
4107            pb_log(2,"Vertag2: $vertag2\n");
4108            ($pbver1,$tmp1) = split(/-/,$vertag1);
4109            ($pbver2,$tmp2) = split(/-/,$vertag2);
4110            $cmdget = "mv /tmp/ProjectBuilder-$pbver1$pbextdir.tar.gz ProjectBuilder-latest.tar.gz ; mv /tmp/project-builder-$pbver2$pbextdir.tar.gz project-builder-latest.tar.gz";
4111        } else {
4112            # TODO: shouldn't we have a variable to specify the source file?
4113            # And shouldn't we be getting the one that matches the current pb version?
4114            # For the moment, just take the latest stable one
4115            my $wget = pb_check_req("wget",0);
4116            $cmdget = "$wget --passive-ftp ftp://ftp.project-builder.org/src/ProjectBuilder-latest.tar.gz; $wget --passive-ftp ftp://ftp.project-builder.org/src/project-builder-latest.tar.gz";
4117        }
4118        print SCRIPT << 'EOF';
4119# Then install manually the missing perl modules
4120my ($osperldep,$osperlver) = pb_conf_get_if("osperldep","osperlver");
4121   
4122my $perldep = pb_distro_get_param($pbos,$osperldep);
4123my $bashopt = "";
4124$bashopt = "-x" if ($pbdebug ge 1);
4125my $verbopt = "mayfail";
4126$verbopt = "mayfailverbose" if ($pbdebug ge 1);
4127foreach my $m (split(/,/,$perldep)) {
4128    # Skip empty deps
4129    next if ($m =~ /^\s*$/);
4130    my $dir = $m;
4131    $dir =~ s/-.*//;
4132    pb_system("echo \"rm -rf $m* ; wget http://search.cpan.org/CPAN/modules/by-module/$dir/$m-$osperlver->{$m}.tar.gz ; gzip -cd $m-$osperlver->{$m}.tar.gz | tar xf - ; cd $m* ; if [ -f Build.PL ]; then perl Build.PL; ./Build ; ./Build install ; else perl Makefile.PL; make ; make install ; fi; cd .. ; rm -rf $m*\" | bash -e $bashopt" ,"Installing perl module $m-$osperlver->{$m}",$verbopt);
4133}
4134EOF
4135        print SCRIPT << 'EOF';
4136pb_system("rm -rf ProjectBuilder-* ; rm -rf project-builder-* ; rm -rf `perl -V:installvendorlib  | awk -F\"'\" '{print \$2}'`/ProjectBuilder ;
4137EOF
4138        print SCRIPT " $cmdget ; ";
4139        print SCRIPT << "EOF"
4140gzip -cd ProjectBuilder-latest.tar.gz | tar xf - ; cd ProjectBuilder-$pbver1$pbextdir ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf ProjectBuilder-* ; gzip -cd project-builder-latest.tar.gz | tar xf - ; cd project-builder-$pbver2$pbextdir ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf project-builder-* ;","Building Project-Builder");
4141EOF
4142    } elsif ($itype =~ /^pkg/) {
4143        # pkg based install. We need to point to the project-builder.org repository
4144        print SCRIPT << 'EOF';
4145my $pkgforpb = pb_distro_get_param($pbos,pb_conf_get_if("ospkg"));
4146my $forcerepo = pb_distro_setuposrepo($pbos);
4147pb_log(1,"Forcing full package install with forcerepo\n") if (defined $forcerepo);
4148pb_distro_installdeps(undef,$pbos,$forcerepo,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgforpb))));
4149EOF
4150    } else {
4151        # Unknown install type
4152        confess("Unknown install type $itype->{$ENV{'PBPROJ'}} for param pbinstalltype");
4153    }
4154    print SCRIPT << 'EOF';
4155pb_system("pbdistrocheck",undef,"verbose");
4156pb_system("pb --version",undef,"verbose");
4157EOF
4158    if ($vtype eq "ve"){
4159        if ($vetype ne "docker") {
4160            print SCRIPT << 'EOF';
4161# For VE we need to umount some FS at the end
4162
4163pb_system("umount /proc","Unmounting /proc","mayfail");
4164EOF
4165        }
4166        print SCRIPT << 'EOF';
4167# Create a basic network file if not already there
4168
4169my $nf="/etc/sysconfig/network";
4170if ((! -f $nf) && ($pbos->{'type'} eq "rpm") && ($pbos->{'family'} ne "novell")) {
4171    open(NF,"> $nf") || die "Unable to create $nf";
4172    print NF "NETWORKING=yes\n";
4173    print NF "HOSTNAME=localhost\n";
4174    close(NF);
4175}
4176chmod 0755,$nf;
4177EOF
4178    }
4179
4180    # Adds pb_distro_get_context and all functions needed from ProjectBuilder::Distribution, Conf and Base
4181    foreach my $m ("ProjectBuilder/Base.pm","ProjectBuilder/Distribution.pm","ProjectBuilder/Conf.pm") {
4182        foreach my $d (@INC) {
4183            my $f = "$d/$m";
4184            if (-f "$f") {
4185                open(PBD,"$f") || confess "Unable to open $f: $!";
4186                while (<PBD>) {
4187                    next if (/^package/);
4188                    next if (/^use Exporter/);
4189                    next if (/^use ProjectBuilder::/);
4190                    next if (/^our /);
4191                    print SCRIPT $_;
4192                }
4193                close(PBD);
4194                # We just need the first one of each file wrt @INC - hopefully that's the right one.
4195                last;
4196            }
4197        }
4198    }
4199    # Use a fake pb_version_init version here
4200    print SCRIPT << "EOF";
4201sub pb_version_init {
4202
4203return("$projectbuilderver","$projectbuilderrev","$projectbuilderconfver");
4204}
42051;
4206EOF
4207    close(SCRIPT);
4208    chmod 0755,"$pbscript{$v}";
4209
4210    $pm->finish if (defined $pbparallel);
4211}
4212$pm->wait_all_children if (defined $pbparallel);
4213confess "Aborting, one or more of the children failed." if ((not $all_ok) && ($Global::pb_stop_on_error));
4214
4215# These build scripts need to be run as root and force stop of VM at end
4216$ENV{'PBACCOUNT'} = "root";
4217
4218$sbx = "" if (not defined $sbx);
4219# Launch the VM/VE/RM
4220pb_log(2,"DEBUG: before parallel launch, pbscript hash is:".Dumper(%pbscript)."\n");
4221pb_parallel_launchv(\%pbscript,$vtype,uc($vtype)."Script".$sbx,$pbstep,$pbimage,$pbforce,0,$pbsnap);
4222
4223return;
4224}
4225
4226# Function to create a snapshot named 'pb' for VMs and a compressed tar for VEs
4227sub pb_snap2v {
4228
4229my $vtype = shift;
4230my $pbstep = 2;
4231
4232my ($vm,$all) = pb_get2v($vtype);
4233
4234# Script generated
4235my $pbscript = "$ENV{'PBDESTDIR'}/snapv.$$";
4236
4237my ($pbac) = pb_conf_get($vtype."login");
4238
4239foreach my $v (@$vm) {
4240    if ($vtype eq "ve") {
4241        # Get distro context
4242        my $pbos = pb_distro_get_context($v);
4243        my ($vepath) = pb_conf_get("vepath");
4244
4245        # Test if an existing snapshot exists and remove it if there is a VE
4246        if ((-f "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz") &&
4247            (! -d "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}")) {
4248                pb_system("sudo rm -f $vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz","Removing previous snapshot $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz");
4249        }
4250    }
4251
4252    # Prepare the script to be executed on the VM/VE
4253    open(SCRIPT,"> $pbscript") || confess "Unable to create $pbscript";
4254    print SCRIPT << 'EOF';
4255    #!/bin/bash
4256    sleep 2
4257EOF
4258    close(SCRIPT);
4259    chmod 0755,"$pbscript";
4260
4261    # Force shutdown of VM/VE
4262    # Force snapshot of VM/VE
4263    pb_script2v($pbscript,$vtype,$pbstep,1,$v,1);
4264}
4265return;
4266}
4267
4268# Function to update VMs/VEs/RMs with the latest distribution content
4269sub pb_update2v {
4270
4271my $vtype = shift;
4272my $pbstep = 2;
4273
4274my ($vm,$all) = pb_get2v($vtype);
4275
4276# Script generated
4277my $pbscript = "$ENV{'PBDESTDIR'}/updatev.$$";
4278
4279my ($pbac) = pb_conf_get($vtype."login");
4280
4281foreach my $v (@$vm) {
4282    # Get distro context
4283    my $pbos = pb_distro_get_context($v);
4284
4285    # Prepare the script to be executed on the VM/VE/RM
4286    # in $ENV{'PBDESTDIR'}/updatev
4287    open(SCRIPT,"> $pbscript") || confess "Unable to create $pbscript";
4288   
4289    print SCRIPT << 'EOF';
4290    #!/bin/bash
4291    sleep 2
4292EOF
4293    # VE needs a good /proc
4294    $vetype = pb_ve_get_type($vetype);
4295    if (($vtype eq "ve") && ($vetype ne "docker")) {
4296        print SCRIPT "sudo /bin/mount -t proc /proc /proc\n";
4297    }
4298    print SCRIPT "$pbos->{'update'}\n";
4299    if (($vtype eq "ve") && ($vetype ne "docker")) {
4300        print SCRIPT "sudo /bin/umount /proc\n";
4301    }
4302    close(SCRIPT);
4303    chmod 0755,"$pbscript";
4304
4305    # Force shutdown of VM except
4306    pb_script2v($pbscript,$vtype,$pbstep,1,$v);
4307}
4308return;
4309}
4310
4311sub pb_announce {
4312
4313    my $antype = shift;
4314
4315    # Get all required parameters
4316    my ($pbpackager,$pbrepo) = pb_conf_get("pbpackager","pbrepo");
4317    my ($pkgv, $pkgt, $testver) = pb_conf_get_if("pkgver","pkgtag","testver");
4318    if (((not defined $testver) || (not defined $testver->{$ENV{'PBPROJ'}}) || ($testver->{$ENV{'PBPROJ'}} !~ /true/i)) && ($antype eq "Clean")) {
4319        # We just clean for test versions
4320        pb_log(0,"Unable to clean SSH repository for non testver version\n");
4321        return;
4322    }
4323    my $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
4324    my @pkgs = @$pkg;
4325    my %pkgs;
4326    my $first = 0;
4327
4328    # Get all distros concerned
4329    my $pbos = pb_distro_get_context();
4330    my $distrolist = pb_get_distros($pbos,undef);
4331    my %dl;
4332    my %theorlist;
4333    my %archlist;
4334    foreach my $d (split(/,/,$distrolist)) {
4335        my ($d1,$d2,$d3) = split(/-/,$d);
4336        $dl{$d1}++;
4337    }
4338
4339    # Command to find packages on repo
4340    my $findstr = "find ".join(" ",keys %dl)." ";
4341    my $srcstr = "";
4342    # Generated announce files
4343    my @files;
4344
4345    foreach my $pbpkg (@pkgs) {
4346        if ($first != 0) {
4347            $findstr .= "-o ";
4348        }
4349        $first++;
4350        if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
4351            $pbver = $pkgv->{$pbpkg};
4352        } else {
4353            $pbver = $ENV{'PBPROJVER'};
4354        }
4355        if ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
4356            $pbtag = $pkgt->{$pbpkg};
4357        } else {
4358            $pbtag = $ENV{'PBPROJTAG'};
4359        }
4360
4361        # TODO: use virtual/real names here now
4362        my $pbrealpkg = $pbpkg;
4363        my $pbrealpkgrpm = pb_cms_get_real_pkg($pbpkg,"rpm");
4364        my $pbrealpkgdeb = pb_cms_get_real_pkg($pbpkg,"deb");
4365        if ($antype eq "Clean") {
4366            # We only clean test versions anyway
4367            $pbtag = "0";
4368            my $nver = $pbver;
4369            my $ntag = "[2-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]";
4370            $pbver .= $ntag;
4371            # TODO add apk
4372            $findstr .= "-name \'$pbrealpkgrpm-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgrpm-debug-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag"."_*\.deb\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag.dsc\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag.tar.gz\' -o -name \'$pbrealpkg-$nver"."_p$ntag\.ebuild\' -o -name \'$pbrealpkg-$pbver-$pbtag*\.pkg\.gz\' -o -name \'$pbrealpkg-$pbver-$pbtag*\.sd\' ";
4373            $srcstr .= "src/$pbrealpkg-$pbver.tar.gz src/$pbrealpkg-$pbver.pbconf.tar.gz ";
4374        } else {
4375            # "Announce" and "Check"
4376            my @date=pb_get_date();
4377            # the matching is only done on packages made the same day for test version. Hopefully this is enough
4378            my $nver;
4379            if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
4380                $pbtag = "0";
4381                my $ntag .= strftime("%Y%m%d*", @date);
4382                $nver = $pbver."_p$ntag*";
4383                $pbver .= "$ntag*";
4384            } else { 
4385                $nver = $pbver."-r$pbtag";
4386            }
4387            $findstr .= "-name \'$pbrealpkgrpm-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag"."_*\.deb\' -o -name \'$pbrealpkg-$nver\.ebuild\' -o -name \'$pbrealpkg-$pbver\.pkg\.gz\' -o -name \'$pbrealpkg-$pbver\.sd\' ";
4388        }
4389
4390        if ($antype eq "Announce") {
4391            my $chglog;
4392
4393            pb_vcs_init($pbinit);
4394            # Get project info on log file and generate tmp files used later on
4395            $chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
4396            $chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
4397            $chglog = undef if (! -f $chglog);
4398
4399            open(OUT,"> $ENV{'PBTMP'}/$pbpkg.ann") || confess "Unable to create $ENV{'PBTMP'}/$pbpkg.ann: $!";
4400            my $pb;
4401            $pb->{'realpkg'} = $pbrealpkg;
4402            $pb->{'ver'} = $pbver;
4403            $pb->{'tag'} = $pbtag;
4404            $pb->{'date'} = $pbdate;
4405            $pb->{'extdir'} = pb_get_extdir();
4406            $pb->{'chglog'} = $chglog;
4407            $pb->{'packager'} = $pbpackager;
4408            $pb->{'proj'} = $ENV{'PBPROJ'};
4409            $pb->{'repo'} = $pbrepo;
4410            $pb->{'pbos'}->{'type'} = "announce";
4411            $pb->{'pbos'}->{'suffix'} = "none";
4412            pb_changelog($pb,\*OUT,"yes");
4413            close(OUT);
4414            push(@files,"$ENV{'PBTMP'}/$pbpkg.ann");
4415        } elsif ($antype eq "Check") {
4416            # For the check we also build the theoritical complete list we should get
4417            foreach my $d (split(/,/,$distrolist)) {
4418                $pbos = pb_distro_get_context($d);
4419                if ($pbos->{'type'} eq "rpm") {
4420                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkgrpm-$pbver-$pbtag$pbos->{'suffix'}"} = 0;
4421                } elsif ($pbos->{'type'} eq "deb") {
4422                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = 0;
4423                    # TODO are we always using the last arch ?
4424                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = "$pbos->{'arch'}";
4425                } elsif ($pbos->{'type'} eq "ebuild") {
4426                    my $prefix = "-r";
4427                    $prefix = "_p" if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i));
4428                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver$prefix$pbtag.ebuild"} = 0;
4429                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver$prefix$pbtag.ebuild"} = "$pbos->{'arch'}";
4430                } elsif ($pbos->{'type'} eq "apk") {
4431                    # TODO
4432                } elsif ($pbos->{'type'} eq "pkg") {
4433                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkg-$pbver-$pbtag.pkg.gz"} = 0;
4434                } else {
4435                    pb_log(1,"No theoritical list possible for type $pbos->{'type'}\n");
4436                }
4437            }
4438        }
4439        pb_log(2,"theorlist initial: ".Dumper(%theorlist)."\n");
4440        pb_log(2,"archlist: ".Dumper(%archlist)."\n");
4441    }
4442    if ($antype eq "Announce") {
4443        $findstr .= " | grep -Ev \'src.rpm\'";
4444    } elsif ($antype eq "Clean") {
4445        $findstr .= " | xargs rm -f -v $srcstr ";
4446    }
4447
4448    # Prepare the command to run and execute it
4449    open(PBS,"> $ENV{'PBTMP'}/pbscript") || confess "Unable to create $ENV{'PBTMP'}/pbscript";
4450    print PBS "#!/bin/bash\n";
4451    print PBS "set -x\n" if ($pbdebug gt 1);
4452    print PBS "$findstr | sort 2> /dev/null\n";
4453    close(PBS);
4454    chmod 0755,"$ENV{'PBTMP'}/pbscript";
4455    pb_send2target("Announce","$ENV{'PBTMP'}/pbscript");
4456
4457    my $sl = "Project $ENV{'PBPROJ'} version $ENV{'PBPROJVER'} is now available";
4458    if ($antype eq "Announce") {
4459        # Get subject line
4460        pb_log(0,"Please enter the title of your announce\n");
4461        pb_log(0,"(By default: $sl)\n");
4462        my $sl2 = <STDIN>;
4463        $sl = $sl2 if ($sl2 !~ /^$/);
4464
4465        # Prepare a template of announce
4466        open(ANN,"> $ENV{'PBTMP'}/announce.html") || confess "Unable to create $ENV{'PBTMP'}/announce.html: $!";
4467        print ANN << "EOF";
4468$sl</p>
4469
4470<p>The project team is happy to announce the availability of a newest version of $ENV{'PBPROJ'} $ENV{'PBPROJVER'}. Enjoy it as usual!</p>
4471<p>
4472Now available at <a href="$pbrepo->{$ENV{'PBPROJ'}}">$pbrepo->{$ENV{'PBPROJ'}}</a>
4473</p>
4474<p>
4475EOF
4476    }
4477
4478    open(LOG,"$ENV{'PBTMP'}/system.$$.log") || confess "Unable to read $ENV{'PBTMP'}/system.$$.log: $!";
4479    if ($antype eq "Announce") {
4480        my $col = 2;
4481        my $i = 1;
4482        print ANN << 'EOF';
4483<TABLE WIDTH="100%" CELLPADDING="0" CELLSPACING="0" BORDER="0">
4484<TR>
4485EOF
4486        while (<LOG>) {
4487            print ANN "<TD><A HREF=\"$pbrepo->{$ENV{'PBPROJ'}}/$_\">$_</A></TD>";
4488            $i++;
4489            if ($i > $col) {
4490                print ANN "</TR>\n<TR>";
4491                $i = 1;
4492            }
4493        }
4494    } elsif ($antype eq "Clean") {
4495        while (<LOG>) {
4496            # skip errors
4497            next if ($_ !~ /^removed /);
4498            pb_log(0,"$_");
4499        }
4500    } else {
4501        # In "Check" mode we need to compare the 2 lists (real and theoritical)
4502        while (<LOG>) {
4503            # Get package name and remove what is in extra for the theoritical list (arch at the end)
4504            chomp();
4505            # skip find errors
4506            next if (/^find:/);
4507            my $p = $_;
4508            $p =~ s/\.(i[3456]86|x86_64|noarch|src)\.rpm$//;
4509            $p =~ s/_(i[3456]86|amd64|all)\.deb$//;
4510            $p =~ s/(-0\.[0-9]{8})[0-9]{6}/$1*/ if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i));
4511            $p =~ s/(-r|_p[0-9]+)\.ebuild/$1*/ if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i));
4512            # TODO apk
4513            $theorlist{$p} = -2 if (not defined $theorlist{$p});
4514            $theorlist{$p} = $theorlist{$p} + 1;
4515        }
4516        pb_log(2,"theorlist after check: ".Dumper(%theorlist)."\n");
4517    }
4518    close(LOG);
4519
4520    # Nothing more for the cleanssh case
4521    return if ($antype eq "Clean");
4522
4523    if ($antype eq "Check") {
4524        my ($chkex) = pb_conf_get_if("checkexclude");
4525        my $vmbuildlist = "";
4526        my $vebuildlist = "";
4527        my $rmbuildlist = "";
4528        my @pt = pb_conf_get_if("vmlist","velist","rmlist");
4529        foreach my $t (sort keys %theorlist) {
4530            if (defined $theorlist{$t} and $theorlist{$t} >= 1) {
4531                pb_log(1,"Packages found for $t\n");
4532            } elsif (defined $theorlist{$t} and $theorlist{$t} < 0) {
4533                pb_log(0,"Extra Package found for $t\n");
4534            } else {
4535                pb_log(2,"Analyzing $t\n");
4536                my ($os,$ver,$arch,$package) = split(/\//,$t);
4537                # Some distro have no arch subdir
4538                if (not defined $package) {
4539                    $package = $arch;
4540                    # TODO: If both arch have failed, we just make the last one
4541                    $arch = $archlist{$t} if (defined $archlist{$t});
4542                }
4543                my $pbos = pb_distro_get_context("$os-$ver-$arch");
4544                my $pkgn = $package;
4545                if ($pbos->{'type'} ne "deb") {
4546                    # package name is more easily found from the end for non deb
4547                    # as '-' is the separator, but it can also be used in names
4548                    $pkgn = reverse($package);
4549                    # search the second '-' and isolate the now last part which is the full name
4550                    $pkgn =~ s/([^-]+)-([^-]+)-([\S])+$/$3/;
4551                } else {
4552                    $pkgn =~ s/([^_]+)_([\S])+$/$2/;
4553                }
4554                my $found = 0;
4555                # Handle the exclusion of OSes
4556                my $excl = "";
4557                $excl .= $chkex->{$pkgn} if (defined $chkex->{$pkgn});
4558                $excl .= $chkex->{"all"} if (defined $chkex->{"all"});
4559
4560                pb_log(2,"Searching in excl $excl\n");
4561                foreach my $ex (split(/,/,$excl)) {
4562                    $found = 1 if ("$os-$ver-$arch" =~ /^$ex/);
4563                }
4564                # Skip as excluded
4565                next if ($found == 1);
4566                pb_log(0,"Package NOT found for $t\n");
4567                # Avoid duplicates in list
4568                next if ($vmbuildlist =~ /$os-$ver-$arch/);
4569                next if ($vebuildlist =~ /$os-$ver-$arch/);
4570                next if ($rmbuildlist =~ /$os-$ver-$arch/);
4571                # check with which method we need to build
4572                if ((defined $pt[0]->{$ENV{'PBPROJ'}}) and ($pt[0]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
4573                    $vmbuildlist = "$os-$ver-$arch" if ($vmbuildlist eq "");
4574                    $vmbuildlist .= ",$os-$ver-$arch" if ($vmbuildlist !~ /$os-$ver-$arch/);
4575                    next;
4576                }
4577                if ((defined $pt[1]->{$ENV{'PBPROJ'}}) and ($pt[1]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
4578                    $vebuildlist = "$os-$ver-$arch" if ($vebuildlist eq "");
4579                    $vebuildlist .= ",$os-$ver-$arch" if ($vebuildlist !~ /$os-$ver-$arch/);
4580                    next;
4581                }
4582                if ((defined $pt[2]->{$ENV{'PBPROJ'}}) and ($pt[2]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
4583                    $rmbuildlist = "$os-$ver-$arch" if ($rmbuildlist eq "");
4584                    $rmbuildlist .= ",$os-$ver-$arch" if ($rmbuildlist !~ /$os-$ver-$arch/);
4585                }
4586            }
4587        }
4588        # If we want to rebuild automatically, let's do it
4589        if (defined $opts{'rebuild'}) {
4590            # SandBox or CMS
4591            pb_log(0,"Rebuilding from SandBox\n");
4592            pb_log(0,"for VMs: $vmbuildlist\n") if ($vmbuildlist ne "");
4593            pb_log(0,"for VEs: $vebuildlist\n") if ($vebuildlist ne "");
4594            pb_log(0,"for RMs: $rmbuildlist\n") if ($rmbuildlist ne "");
4595            pb_cms2build("SandBox");
4596            # Which mode
4597            $ENV{'PBV'} = $vmbuildlist;
4598            pb_build2v("vm","build") if ($vmbuildlist ne "");
4599            $ENV{'PBV'} = $vebuildlist;
4600            pb_build2v("ve","build") if ($vebuildlist ne "");
4601            $ENV{'PBV'} = $rmbuildlist;
4602            pb_build2v("rm","build") if ($rmbuildlist ne "");
4603        }
4604        # For the check part this is now finished
4605        return;
4606    }
4607
4608    print ANN << "EOF";
4609</TR>
4610</TABLE>
4611</p>
4612
4613<p>As usual source packages are also available in the same directory.</p>
4614
4615<p>
4616Changes are :
4617</p>
4618<p>
4619EOF
4620    # Get each package changelog content
4621    foreach my $f (sort(@files)) {
4622        open(IN,"$f") || confess "Unable to read $f:$!";
4623        while (<IN>) {
4624            print ANN $_;
4625        }
4626        close(IN);
4627        print ANN "</p><p>\n";
4628    }
4629    print ANN "</p>\n";
4630    close(ANN);
4631
4632    # Allow for modification
4633    my $editor = "vi";
4634    $editor = $ENV{'EDITOR'} if (defined $ENV{'EDITOR'});
4635    pb_system("$editor $ENV{'PBTMP'}/announce.html","Allowing modification of the announce","noredir");
4636
4637    # Store it in DB for external usage (Web pages generation)
4638    my $dbh = pb_connect_db();
4639
4640    # To read whole file
4641    local $/;
4642    open(ANN,"$ENV{'PBTMP'}/announce.html") || confess "Unable to read $ENV{'PBTMP'}/announce.html: $!";
4643    my $announce = <ANN>;
4644    close(ANN);
4645   
4646    pb_log(2,"INSERT INTO announces VALUES (NULL, $pbdate, $announce)");
4647    my $sth = $dbh->prepare(qq{INSERT INTO announces VALUES (NULL,?,?)})
4648                    || confess "Unable to insert into db";
4649    $sth->execute($pbdate, $announce);
4650    $sth->finish();
4651    $dbh->disconnect;
4652
4653    # Then deliver it on the Web
4654    # $TOOLHOME/livwww www
4655
4656    # Mail it to project's ML
4657    open(ML,"| w3m -dump -T text/html > $ENV{'PBTMP'}/announce.txt") || confess "Unable to create $ENV{'PBTMP'}/announce.txt: $!";
4658    print ML << 'EOF';
4659<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x html1/DTD/xhtml1-strict.dtd">
4660
4661<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en" lang="en">
4662  <head>
4663  </head>
4664  <body>
4665  <p>
4666EOF
4667    open(ANN,"$ENV{'PBTMP'}/announce.html") || confess "Unable to read $ENV{'PBTMP'}/announce.html: $!";
4668    while(<ANN>) {
4669        print ML $_;
4670    }
4671    print ML << 'EOF';
4672</body>
4673</html>
4674EOF
4675    close(ML);
4676
4677    # To read whole file
4678    local $/;
4679    open(ANN,"$ENV{'PBTMP'}/announce.txt") || confess "Unable to read $ENV{'PBTMP'}/announce.txt: $!";
4680    my $msg = <ANN>;
4681    close(ANN);
4682   
4683    # Preparation of headers
4684    eval
4685    {
4686        require Mail::Sendmail;
4687        Mail::Sendmail->import();
4688    };
4689    if ($@) {
4690        # Mail::Sendmail not found not sending mail !
4691        pb_log(0,"No Mail::Sendmail module found so not sending any mail !\n");
4692    } else {
4693        my ($pbml,$pbsmtp) = pb_conf_get("pbml","pbsmtp");
4694        my %mail = (   
4695            To          =>  $pbml->{$ENV{'PBPROJ'}},
4696            From        =>  $pbpackager->{$ENV{'PBPROJ'}},
4697            Smtp        =>  $pbsmtp->{$ENV{'PBPROJ'}},
4698            Body        =>  $msg,
4699            Subject     =>  "[ANNOUNCE] $sl",
4700        );
4701           
4702        # Send mail
4703        if (! sendmail(%mail)) {
4704            if ((defined $Mail::Sendmail::error) and (defined $Mail::Sendmail::log)) {
4705                confess "Unable to send mail ($Mail::Sendmail::error): $Mail::Sendmail::log";
4706            }
4707        }
4708    }
4709}
4710
4711#
4712# Creates a set of HTML file containing the news for the project
4713# based on what has been generated by the pb_announce function
4714#
4715sub pb_web_news2html {
4716
4717    my $dest = shift || $ENV{'PBTMP'};
4718
4719    # Get all required parameters
4720    my ($pkgv, $pkgt) = pb_conf_get_if("pkgver","pkgtag");
4721
4722
4723    my $dbh = pb_connect_db();
4724    # For date handling
4725    $ENV{'LANGUAGE'}="C";
4726    my $firstjan = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year(), 0, 0, -1);
4727    my $oldfirst = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year()-1, 0, 0, -1);
4728    pb_log(2,"firstjan: $firstjan, oldfirst: $oldfirst, pbdate:$pbdate\n");
4729    my $all = $dbh->selectall_arrayref("SELECT id,date,announce FROM announces ORDER BY date DESC");
4730    my %news;
4731    $news{"cy"} = "";   # current year's news
4732    $news{"ly"} = "";   # last year news
4733    $news{"py"} = "";   # previous years news
4734    $news{"fp"} = "";   # first page news
4735    my $cpt = 4;        # how many news for first page
4736    # Extract info from DB
4737    foreach my $row (@$all) {
4738        my ($id, $date, $announce) = @$row;
4739        $news{"cy"} = $news{"cy"}."<p><B>$date</B> $announce\n" if ((($date cmp $pbdate) le 0) && (($firstjan cmp $date) le 0));
4740        $news{"ly"} = $news{"ly"}."<p><B>$date</B> $announce\n" if ((($date cmp $firstjan) le 0) && (($oldfirst cmp $date) le 0));
4741        $news{"py"} = $news{"py"}."<p><B>$date</B> $announce\n" if (($date cmp $oldfirst) le 0);
4742        $news{"fp"} = $news{"fp"}."<p><B>$date</B> $announce\n" if ($cpt > 0);
4743        $cpt--;
4744    }
4745    pb_log(1,"news{fp}: ".$news{"fp"}."\n");
4746    $dbh->disconnect;
4747
4748    # Generate the HTML content
4749    foreach my $pref (keys %news) {
4750        open(NEWS,"> $dest/pb_web_$pref"."news.html") || confess "Unable to create $dest/pb_web_$pref"."news.html: $!";
4751        print NEWS "$news{$pref}";
4752        close(NEWS);
4753    }
4754}
4755
4756sub pb_connect_db {
4757
4758    # Store in DB for external usage (Web pages generation)
4759    my $db = "$ENV{'PBCONFDIR'}/announces3.sql";
4760
4761    my $precmd = "";
4762    if (! -f $db) {
4763        $precmd = "CREATE TABLE announces (id INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, announce VARCHAR[65535])";
4764        # we should add the $db to the VCS as well here
4765    }
4766
4767    my $dbh = DBI->connect("dbi:SQLite:dbname=$db","","",
4768                        { RaiseError => 1, AutoCommit => 1 })
4769                        || confess "Unable to connect to $db";
4770
4771    if ($precmd ne "") {
4772        my $sth = $dbh->prepare(qq{$precmd})
4773                    || confess "Unable to create table into $db";
4774        $sth->execute();
4775    }
4776
4777    return($dbh);
4778}
4779
4780
4781# Return the SSH key file to use
4782# Potentially create it if needed
4783
4784sub pb_ssh_get {
4785
4786my $create = shift || 0;    # Do not create keys by default. In that case prefer native keys, not pb's ones
4787my $target = shift || "localhost";
4788my $nport = shift || "22";
4789
4790my ($pbagent) = pb_conf_get_if("pbusesshagent");
4791# use ssh-agent if asked so.
4792return(undef) if (($create == 0) && (defined $pbagent->{$ENV{'PBPROJ'}}) && ($pbagent->{$ENV{'PBPROJ'}} =~ /true/io));
4793
4794# Check the SSH environment
4795my $keyfile = undef;
4796
4797# Check whether ecdsa is accepted by the remote host
4798my $ecdsa = 0;
4799my $dsa = 0;
4800my $rsa = 0;
4801open(SCAN,"ssh-keyscan -p $nport -t ecdsa $target 2>/dev/null |") || pb_log(0,"Unable to check ECDSA support for $target");
4802while(<SCAN>) {
4803    $ecdsa = 1 if ($_ =~ /ecdsa-/);
4804    pb_log(2,"Found ECDSA support on $target ($nport)\n");
4805}
4806close(SCAN);
4807
4808open(SCAN,"ssh-keyscan -p $nport -t rsa $target 2>/dev/null |") || pb_log(0,"Unable to check DSA support for $target");
4809while(<SCAN>) {
4810    $rsa = 1 if ($_ =~ /ssh-rsa/);
4811    pb_log(2,"Found RSA support on $target ($nport)\n");
4812}
4813close(SCAN);
4814
4815open(SCAN,"ssh-keyscan -p $nport -t dsa $target 2>/dev/null |") || pb_log(0,"Unable to check DSA support for $target");
4816while(<SCAN>) {
4817    $dsa = 1 if ($_ =~ /ssh-dss/);
4818    pb_log(2,"Found DSA support on $target ($nport)\n");
4819}
4820close(SCAN);
4821
4822# We have specific keys by default - create them if needed
4823if (!(-e "$ENV{'HOME'}/.ssh/pb_ecdsa") && ($create eq 1)) {
4824    my $res = pb_system("ssh-keygen -q -b 521 -N '' -f $ENV{'HOME'}/.ssh/pb_ecdsa -t ecdsa","Generating ECDSA SSH keys for pb");
4825    if (($res != 0) && !(-e "$ENV{'HOME'}/.ssh/pb_dsa") && ($create eq 1)) {
4826        # ecdsa may not be supported if old ssh
4827        pb_system("ssh-keygen -q -b 1024 -N '' -f $ENV{'HOME'}/.ssh/pb_dsa -t dsa","Generating DSA SSH keys for pb");
4828    }
4829}
4830
4831if (!(-e "$ENV{'HOME'}/.ssh/pb_rsa") && ($create eq 1)) {
4832    pb_system("ssh-keygen -q -b 2048 -N '' -f $ENV{'HOME'}/.ssh/pb_rsa -t rsa","Generating RSA SSH keys for pb");
4833}
4834
4835# We still favour RSA and fall back to ECDSA if not available
4836# Some ECDSA implementation are not working correctly e.g. RHEL7, Fedora 20/21
4837#$keyfile = "$ENV{'HOME'}/.ssh/pb_rsa" if (-s "$ENV{'HOME'}/.ssh/pb_rsa");
4838if ($rsa != 0) {
4839    # And we favour a specific key over a generic one except if in delivery to ftp server
4840    $keyfile = "$ENV{'HOME'}/.ssh/id_rsa" if ((-s "$ENV{'HOME'}/.ssh/id_rsa") && ($create eq 0));
4841    $keyfile = "$ENV{'HOME'}/.ssh/pb_rsa" if (-s "$ENV{'HOME'}/.ssh/pb_rsa");
4842} else {
4843    if ($ecdsa != 0) {
4844        # And we favour a specific key over a generic one except if in delivery to ftp server
4845        $keyfile = "$ENV{'HOME'}/.ssh/id_ecdsa" if ((-s "$ENV{'HOME'}/.ssh/id_ecdsa") && ($ecdsa != 0) && ($create eq 0));
4846        $keyfile = "$ENV{'HOME'}/.ssh/pb_ecdsa" if ((-s "$ENV{'HOME'}/.ssh/pb_ecdsa") && ($ecdsa != 0));
4847    } elsif ($dsa != 0) {
4848        # And we favour a specific key over a generic one except if in delivery to ftp server
4849        $keyfile = "$ENV{'HOME'}/.ssh/id_dsa" if ((-s "$ENV{'HOME'}/.ssh/id_dsa") && ($dsa != 0) && ($create eq 0));
4850        $keyfile = "$ENV{'HOME'}/.ssh/pb_dsa" if ((-s "$ENV{'HOME'}/.ssh/pb_dsa") && ($dsa != 0));
4851    }
4852}
4853if (defined $keyfile) {
4854    pb_log(2,"Using ssh key file $keyfile\n");
4855} else {
4856    pb_log(0, "Unable to find your public ssh key under $ENV{'HOME'}/.ssh\n");
4857}
4858return($keyfile);
4859}
4860
4861
4862# Returns the pid of a running VM command using a specific VM file, and the port used if the VM exists
4863sub pb_check_ps {
4864    my $vmcmd = shift;
4865    my $vmm = shift;
4866    my $vexist = 0;             # FALSE by default
4867    my $vmport = undef;         # NONE by default
4868
4869    if ($vmcmd =~ /qemu/) {
4870        # Remove the suffix as qemu changes it at launch
4871        $vmcmd =~ s/qemu-.*/qemu/;
4872    }
4873    open(PS, "ps auxhww|") || confess "Unable to call ps";
4874    while (<PS>) {
4875        next if (! /$vmcmd/);
4876        next if (! /$vmm/);
4877        my $void1;
4878        ($void1, $vexist, $vmport) = split(/ +/,$_,3);
4879        pb_log(2,"pb_check_ps $vmport\n");
4880        $vmport =~ s/.*=tcp:127\.0\.0\.1:([0-9]+)-:22.*/$1/;
4881        chomp($vmport);
4882        pb_log(2,"pb_check_ps found a VM $vexist using port $vmport\n");
4883        last;
4884    }
4885    return($vexist,$vmport);
4886}
4887
4888
4889sub pb_extract_build_files {
4890
4891my $src=shift;
4892my $dir=shift;
4893my $ddir=shift;
4894my $mandatory=shift || "build";
4895
4896my $flag = "mayfail" if (($mandatory eq "patch") || ($mandatory eq "src"));
4897my $res;
4898
4899if ($src =~ /tar\.gz$/) {
4900    $res = pb_system("tar xfpz $src $dir","Extracting $mandatory files from $src",$flag);
4901} elsif ($src =~ /tar\.bz2$/) {
4902    $res = pb_system("tar xfpj $src $dir","Extracting $mandatory files from $src",$flag);
4903} else {
4904    confess "Unknown compression algorithm for $src";
4905}
4906# If not mandatory return now
4907return() if (($res != 0) and (($mandatory eq "patch") || ($mandatory eq "src")));
4908return(pb_move_extracted_files($dir,$ddir));
4909}
4910
4911sub pb_move_extracted_files {
4912
4913my $dir = shift;
4914my $ddir = shift;
4915my @files;
4916
4917# In a recursive function , we need a local var as DIR handle
4918my $bdir;
4919
4920opendir($bdir,"$dir") || cluck "Unable to open directory $dir: $!" && return;
4921foreach my $f (readdir($bdir)) {
4922    next if ($f =~ /^\./);
4923    # Skip potential patch dir
4924    next if ($f =~ /^pbpatch/);
4925    # Skip potential source dir
4926    next if ($f =~ /^pbsrc/);
4927    # Skip potential backup files
4928    next if ($f =~ /~$/);
4929    if ((-d "$dir/$f") && (! -l "$dir/$f")) {
4930        # Case of the bug debian subdir
4931        pb_mkdir_p("$ddir/$f");
4932        push @files,pb_move_extracted_files("$dir/$f","$ddir/$f");
4933    } else {
4934        move("$dir/$f","$ddir") || confess "Unable to move $dir/$f to $ddir";
4935        pb_log(2,"mv $dir/$f $ddir\n");
4936        push @files,"$ddir/$f";
4937    }
4938}
4939closedir($bdir);
4940# Not enough but still a first cleanup
4941pb_rm_rf("$dir");
4942return(@files);
4943}
4944
4945sub pb_list_bfiles {
4946
4947my $dir = shift;
4948my $pbpkg = shift;
4949my $bfiles = shift;
4950my $pkgfiles = shift;
4951my $supfiles = shift;
4952# subdir to keep if recursive mode, empty by default
4953my $subdir = shift || "";
4954# In a recursive function , we need a local var as DIR handle
4955my $bdir;
4956
4957pb_log(2,"DEBUG: entering pb_list_bfiles in $dir: ".Dumper($bfiles)."\n");
4958opendir($bdir,"$dir") || confess "Unable to open dir $dir: $!";
4959foreach my $f (readdir($bdir)) {
4960    pb_log(3,"DEBUG: pb_list_bfiles found $f\n");
4961    next if ($f =~ /^\./);
4962    if (-d "$dir/$f") {
4963        # Recurse for directories (Debian 3.0 format e.g.)
4964        pb_log(2,"DEBUG: pb_list_bfiles recurse in $dir/$f\n");
4965        pb_list_bfiles("$dir/$f",$pbpkg,$bfiles,$pkgfiles,$supfiles,$f);
4966        next;
4967    }
4968
4969    my $key = $f;
4970    # if recursive then store also the subdir
4971    $key = "$subdir/$f" if ($subdir ne "");
4972    $bfiles->{$key} = "$dir/$f";
4973    $bfiles->{$key} =~ s~$ENV{'PBROOTDIR'}~~;
4974    if (defined $supfiles->{$pbpkg}) {
4975        $pkgfiles->{$key} = "$dir/$f" if ($f =~ /$supfiles->{$pbpkg}/);
4976    }
4977}
4978closedir($bdir);
4979pb_log(2,"DEBUG: exiting pb_list_bfiles: ".Dumper($bfiles)."\n");
4980}
4981
4982sub pb_add_comma {
4983
4984my $str = shift;
4985my $addstr = shift;
4986
4987$str .= "," if (defined $str);
4988$str .= $addstr;
4989return($str);
4990}
4991
4992sub pb_list_sfiles {
4993
4994my $sdir = shift;
4995my $ptr = shift;
4996my $pbos = shift;
4997my $extdir = shift;
4998
4999pb_log(2,"DEBUG: entering pb_list_sfiles: ".Dumper($ptr)."\n");
5000my $key = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
5001
5002# Prepare local sources for this distro - They are always applied first - May be a problem one day
5003# This function works for both patches and additional sources
5004foreach my $p (sort(<$sdir/*>)) {
5005    $ptr->{$key} = pb_add_comma($ptr->{$key},"file://$p") if (($p =~ /\.all$/) || ($p =~ /\.$pbos->{'os'}$/) || ($p =~ /\.$pbos->{'type'}$/) || ($p =~ /\.$pbos->{'family'}$/) || ($p =~ /\.$pbos->{'name'}$/) || ($p =~ /\.$pbos->{'name'}-$pbos->{'version'}$/) ||($p =~ /\.$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}$/));
5006}
5007
5008# Prepare also remote sources to be included - Applied after the local ones
5009foreach my $p ("all","$pbos->{'os'}","$pbos->{'type'}","$pbos->{'family'}","$pbos->{'name'}","$pbos->{'name'}-$pbos->{'version'}","$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") {
5010    my $f = "$extdir.".".$p";
5011    next if (not -f $f);
5012    if (not open(PATCH,$f)) {
5013        pb_display("Unable to open existing external source file content $f\n");
5014        next;
5015    }
5016    while (<PATCH>) {
5017        chomp();
5018        $ptr->{$key} = pb_add_comma($ptr->{$key},"$_");
5019    }
5020    close(PATCH);
5021}
5022pb_log(2,"DEBUG: exiting pb_list_sfiles: ".Dumper($ptr)."\n");
5023return($ptr);
5024}
5025   
5026#
5027# Return the list of packages we are working on in a non CMS action
5028#
5029sub pb_get_pkg {
5030
5031my @pkgs = ();
5032
5033# In script actions that file may not exist.
5034return(\@pkgs) if ((not defined $ENV{'PBDESTDIR'}) || (not defined $ENV{'PBPROJVER'}) || (not defined $ENV{'PBPROJTAG'}) || (! -f "$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml"));
5035
5036my ($var) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.yml","pbpkg");
5037@pkgs = keys %$var if (defined $var);
5038
5039pb_log(0,"Packages: ".join(',',@pkgs)."\n") if (@pkgs);
5040return(\@pkgs);
5041}
5042
5043# Manages VM/RM SSH port communication
5044sub pb_get_port {
5045
5046my $port = shift;
5047my $pbos = shift;
5048my $cmt = shift;
5049my $nport;
5050
5051confess "No port passed in parameter. Report to dev team\n" if (not defined $port);
5052# key is project on VM, but machine tuple for RM
5053if ($cmt =~ /^RM/i) {
5054    confess "No port passed in parameter. You may miss a RM config file. Report to dev team\n" if (not defined $port->{"$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}"});
5055    $nport = $port->{"$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}"};
5056} else {
5057    confess "No port passed in parameter. You may miss a VE config file or a vmport entry for $ENV{'PBPROJ'}. Report to dev team\n" if ((not defined $port->{'PBPROJ'}) and ($cmt =~ /^VE/i));
5058    $nport = $port->{$ENV{'PBPROJ'}};
5059}
5060pb_log(2,"pb_get_port with $nport\n") if (defined $nport);
5061if ($cmt =~ /^VM/i) {
5062    # Maybe a port was given as parameter so overwrite
5063    $nport = "$pbport" if (defined $pbport);
5064    # Maybe in // mode so use the env var set up as an offset to the base port
5065    $nport = $nport + $ENV{'PBVMPORT'} -1 if ((defined $pbparallel) && (defined $ENV{'PBVMPORT'}));
5066}
5067pb_log(2,"pb_get_port returns $nport\n");
5068return($nport);
5069}
5070
5071sub pb_set_port { 
5072       
5073my ($pid,$ident) = @_;
5074pb_log(2,"pb_set_port for VM ($pid), id $ident\n");
5075$ENV{'PBVMPORT'} = $ident;
5076pb_log(2,"pb_set_port sets PBVMPORT in env to $ENV{'PBVMPORT'}\n");
5077}
5078
5079sub pb_set_parallel {
5080
5081my $vtype = shift;
5082
5083pb_log(2,"pb_set_parallel vtype: $vtype\n");
5084# Take care of memory size if VM, parallel mode and more than 1 action
5085if ((defined $pbparallel) && ($pbparallel ne 1) && ($vtype eq "vm")) {
5086    eval
5087    {
5088        require Linux::SysInfo;
5089        Linux::SysInfo->import();
5090    };
5091    if ($@) {
5092        # Linux::SysInfo not found
5093        pb_log(1,"ADVISE: Install Linux::SysInfo to benefit from automatic parallelism optimization.\nOr optimize manually pbparallel in your pb.yml file\nUsing $pbparallel processes max at a time for the moment\nWARNING: This may consume too much memory for your system\n");
5094    } else {
5095        # Using the memory size
5096        my $si = Linux::SysInfo::sysinfo();
5097        if (not defined $si) {
5098            pb_log(1,"ADVISE: Install Linux::SysInfo to benefit from automatic parallelism optimization.\nOr optimize manually pbparallel in your pb.yml file\nUsing $pbparallel processes max at a time for the moment\nWARNING: This may consume too much memory for your system\n");
5099        } else {
5100            # Keep the number of VM whose memory can be allocated
5101            my $ram = $si->{"totalram"}-$si->{"sharedram"}-$si->{"bufferram"};
5102            my $ram2;
5103            my ($vmmem) = pb_conf_get_if("vmmem");
5104
5105            my $v = "default";
5106            if ((defined $vmmem) and (defined $vmmem->{$v})) {
5107                $ram2 = $vmmem->{$v};
5108            } else {
5109                # Default for KVM/QEMU
5110                $ram2 = 128;
5111            }
5112            $pbparallel = sprintf("%d",$ram/$ram2);
5113        }
5114        pb_log(1,"Using $pbparallel processes at a time\n");
5115    }
5116}
5117pb_log(2,"pb_set_parallel returns: $pbparallel\n") if (defined $pbparallel);
5118return($pbparallel);
5119}
5120
5121sub pb_get_sudocmds { 
5122       
5123my $pbos = shift;
5124my @cmds = @_;
5125my %sudocmds;
5126
5127pb_log(2,"pb_get_sudocmds entering with lines:".Dumper(@cmds)."\n");
5128foreach my $c (split(/;/,$pbos->{'update'}),split(/;/,$pbos->{'install'}),@cmds) {
5129    pb_log(2,"pb_get_sudocmds analyses $c\n");
5130