Class: Simp::Rake::Build::Pkg

Inherits:
Rake::TaskLib
  • Object
show all
Includes:
Simp::Rake, Constants
Defined in:
lib/simp/rake/build/pkg.rb

Instance Attribute Summary

Attributes included from Simp::Rake

#module_paths, #puppetfile

Instance Method Summary collapse

Methods included from Constants

#distro_build_dir, #init_member_vars

Methods included from Simp::Rake

#clean_yaml, #encode_line, #get_cpu_limit, #help, #load_puppetfile, #run_pager

Methods included from CommandUtils

#which

Constructor Details

#initialize(base_dir) ⇒ Pkg

Returns a new instance of Pkg.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/simp/rake/build/pkg.rb', line 16

def initialize( base_dir )
  init_member_vars( base_dir )

  @cpu_limit = get_cpu_limit
  @verbose = ENV.fetch('SIMP_PKG_verbose','no') == 'yes'
   = 'last_rpm_build_metadata.yaml'
  @rpm_dependency_file = File.join(@base_dir, 'build', 'rpm', 'dependencies.yaml')
  @build_keys_dir = ENV.fetch('SIMP_PKG_build_keys_dir', File.join(@base_dir, '.dev_gpgkeys'))
  @long_gpg_socket_err_msg = "    If the problem is 'socket name <xxx> is too long', use SIMP_PKG_build_keys_dir\n    to override\n    \#{@build_keys_dir}\n    with a shorter path. The socket name must be < 108 characters.\n\n  MSG\n  # nil = default not set; use local preference\n  @fetch_published_rpm_default = ENV['SIMP_PKG_fetch_published_rpm'] ? (\n    ENV['SIMP_PKG_fetch_published_rpm'] =~ /\\A(yes|true)\\Z/i ? true : false\n  ) : nil\n\n  define_tasks\nend\n"

Instance Method Details

#define_tasksObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'lib/simp/rake/build/pkg.rb', line 39

def define_tasks
  namespace :pkg do
    ##############################################################################
    # Main tasks
    ##############################################################################

    # Have to get things set up inside the proper namespace
    task :prep,[:method] do |t,args|

      # This doesn't get caught for things like 'rake clean'
      if $simp6 && $simp6_build_dir
        @build_dir = $simp6_build_dir || @distro_build_dir
        @dvd_src = File.join(@build_dir, File.basename(@dvd_src))
      end

      args.with_defaults(:method => 'tracking')

      @build_dirs = {
        :modules => get_module_dirs(args[:method]),
        :aux => [
          # Anything in here gets built!
          "#{@src_dir}/assets/*"
        ],
        :doc => "#{@src_dir}/doc"
      }

      @build_dirs[:aux].map!{|dir| dir = Dir.glob(dir)}
      @build_dirs[:aux].flatten!
      @build_dirs[:aux].delete_if{|f| !File.directory?(f)}

      @pkg_dirs = {
        :simp => "#{@build_dir}/SIMP"
      }
    end

    clean_failures = []
    clean_failures_lock = Mutex.new

    task :clean => [:prep] do |t,args|
      @build_dirs.each_pair do |k,dirs|
        Parallel.map(
          Array(dirs),
          :in_processes => @cpu_limit,
          :progress => t.name
        ) do |dir|
          Dir.chdir(dir) do
            begin
              rake_flags = Rake.application.options.trace ? '--trace' : ''
              %x{rake clean #{rake_flags}}
              clean_failures_lock.synchronize do
                clean_failures << dir unless $?.success?
              end
            rescue Exception => e
              clean_failures_lock.synchronize do
                clean_failures << dir
              end
              raise Parallel::Kill
            end
          end
        end
      end

      unless clean_failures.empty?
        fail(%(Error: The following directories had failures in #{task.name}:\n  * #{clean_failures.join("\n  * ")}))
      end
    end

    task :clobber => [:prep] do |t,args|
      @build_dirs.each_pair do |k,dirs|
        Parallel.map(
          Array(dirs),
          :in_processes => @cpu_limit,
          :progress => t.name
        ) do |dir|
          Dir.chdir(dir) do
            rake_flags = Rake.application.options.trace ? '--trace' : ''
            sh %{rake clobber #{rake_flags}}
          end
        end
      end
    end

    desc "      Prepare a GPG signing key to sign build packages\n\n        * :key - the name of the build keys subdirectory to prepare\n          (defaults to 'dev')\n\n          - The default build keys directory is\n            `\#{@build_keys_dir}`\n\n\n      When :key is `dev`, a temporary signing key is created, if needed:\n\n        * A 14-day `dev` key will be created if none exists or the existing\n          key has expired.  This includes creating\n          - A `dev` directory in the build keys directory\n          - gpg-agent assets to create/update the key within that `dev`\n            directory\n\n      When :key is *not* `dev`, the logic is much stricter:\n\n        - You must already have created the `<:key>` subdirectory within\n          the build keys directory and placed a valid GPG signing key and\n          requisite gpg-agent assets to access the key within the directory.\n        - If the directory or key are missing, the task will fail.\n\n      ENV vars:\n        - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n        - Set `SIMP_PKG_build_keys_dir` to override the default build keys path.\n    DESC\n    task :key_prep,[:key] => [:prep] do |t,args|\n      args.with_defaults(:key => 'dev')\n      key = args.key\n      key_dir = File.join(@build_keys_dir,key)\n      dvd_dir = @dvd_src\n\n      FileUtils.mkdir_p @build_keys_dir\n\n      Dir.chdir(@build_keys_dir) do\n        if key == 'dev'\n          require 'simp/local_gpg_signing_key'\n\n          begin\n            Simp::LocalGpgSigningKey.new(key_dir,{verbose: @verbose}).ensure_key\n          rescue Exception => e\n            raise(\"\#{e.message}\\n\\n\#{@long_gpg_socket_err_msg}\")\n          end\n        else\n          unless File.directory?(key_dir)\n            fail(\"Could not find GPG keydir '\#{key_dir}' in '\#{Dir.pwd}'\")\n          end\n        end\n\n        Dir.chdir(key_dir) do\n          rpm_build_keys = Dir.glob('RPM-GPG-KEY-*')\n          if rpm_build_keys.empty?\n            fail(\"Could not find any RPM-GPG-KEY-* files in '\#{key_dir}'\")\n          end\n\n          # Copy development keys into the root of the ISO for convenience\n          if key == 'dev'\n            unless File.directory?(dvd_dir)\n              fail(\"Could not find DVD ISO root directory '\#{dvd_dir}'\")\n            end\n\n            rpm_build_keys.each do |gpgkey|\n              FileUtils.cp(gpgkey, dvd_dir, :verbose => @verbose)\n            end\n          # Otherwise, make sure it isn't present for the build\n          else\n            Dir[File.join(dvd_dir,'RPM-GPG-KEY-SIMP*')].each do |to_del|\n              FileUtils.rm(to_del)\n            end\n          end\n        end\n      end\n    end\n\n    def populate_rpm_dir(rpm_dir)\n      srpm_dir = File.join(File.dirname(rpm_dir), 'SRPMS')\n\n      FileUtils.mkdir_p(rpm_dir)\n      FileUtils.mkdir_p(srpm_dir)\n\n      rpm_metadata = %x(find -P \#{@src_dir} -xdev -type f -name \#{@rpm_build_metadata}).lines.map(&:strip).sort\n\n      fail(\"No \#{@rpm_build_metadata} files found under \#{@src_dir}\") if rpm_metadata.empty?\n\n      rpm_metadata.each do |mf|\n        metadata = YAML.load_file(mf)\n        rpms = metadata['rpms']\n        srpms = metadata['srpms']\n\n        fail(\"No RPMs found at \#{rpm_dir}\") if (rpms.nil? || rpms.empty?)\n\n        have_signed_rpm = false\n        Dir.chdir(rpm_dir) do\n          rpms.each_key do |rpm|\n            if @verbose\n              puts \"Copying \#{rpm} to \#{rpm_dir}\"\n            end\n\n            arch = rpms[rpm]['metadata'][:arch]\n            FileUtils.mkdir_p(arch)\n\n            FileUtils.cp(rpms[rpm]['path'], arch)\n\n            if rpms[rpm][:signature]\n              have_signed_rpm = true\n            end\n          end\n        end\n\n        Dir.chdir(srpm_dir) do\n          srpms.each_key do |srpm|\n            if have_signed_rpm && !srpms[srpm][:signature]\n              if @verbose\n                puts \"Found signed RPM - skipping copy of '\#{srpm}'\"\n              end\n\n              next\n            end\n\n            if @verbose\n              puts \"Copying '\#{srpm}' to '\#{srpm_dir}'\"\n            end\n\n            arch = srpms[srpm]['metadata'][:arch]\n            FileUtils.mkdir_p(arch)\n\n            FileUtils.cp(srpms[srpm]['path'], arch)\n          end\n        end\n      end\n    end\n\n\n=begin\n    desc <<~DESC\n      Build the entire SIMP release.\n\n        * :docs - Build the docs. Set this to false if you wish to skip building the docs.\n        * :key - The GPG key to sign the RPMs with. Defaults to 'dev'.\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n          - Set `SIMP_YUM_makecache=no` if you do NOT want to rebuild the\n            build-specific YUM cache\n    DESC\n=end\n    task :build,[:docs,:key] => [:prep,:key_prep] do |t,args|\n      args.with_defaults(:key => 'dev')\n      args.with_defaults(:docs => 'true')\n\n      check_dvd_env\n\n      get_yum_helper\n\n      Rake::Task['pkg:aux'].invoke\n      if \"\#{args.docs}\" == 'true'\n        Rake::Task['pkg:doc'].invoke\n      end\n      Rake::Task['pkg:modules'].invoke\n\n      populate_rpm_dir(@rpm_dir)\n\n      Rake::Task['pkg:signrpms'].invoke(args[:key])\n    end\n\n    desc <<~DESC\n      Build the Puppet module RPMs.\n\n        * :method - The Puppetfile from which the repository information\n                    should be read. Defaults to 'tracking'\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n    DESC\n    task :modules,[:method] => [:prep] do |t,args|\n      build(@build_dirs[:modules],t)\n    end\n\n    desc <<~DESC\n      Build a single Puppet Module RPM.\n\n        * :name   - The path, or name, of the module to build. If a name is\n                    given, the Puppetfile.<method> will be used to find the\n                    module.\n                    Note: This is the *short* name. So, to build\n                    puppetlabs-stdlib, you would just enter 'stdlib'\n        * :method - The Puppetfile from which the repository information should be read. Defaults to 'tracking'\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n          - Set `SIMP_YUM_makecache=no` if you do NOT want to rebuild the\n            build-specific YUM cache\n    DESC\n    task :single,[:name,:method] => [:prep] do |t,args|\n      fail(\"You must pass :name to '\#{t.name}'\") unless args[:name]\n\n      mod_path = File.absolute_path(args[:name])\n      get_yum_helper\n\n      if args[:name].include?('/')\n        fail(\"'\#{args[:name]}' does not exist!\") unless File.directory?(mod_path)\n      else\n        load_puppetfile(args[:method])\n        local_module = puppetfile.modules.select{|m| m[:name] == args[:name]}.first\n\n        unless local_module\n          fail(\"'\#{args[:name]}' was not found in the Puppetfile\")\n        end\n\n        mod_path = local_module[:path]\n      end\n\n      build(Array(mod_path), t)\n\n      puts(\"Your packages can be found in '\#{mod_path}/dist'\")\n    end\n\n    desc <<~DESC\n      Build the SIMP non-module RPMs.\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n    DESC\n    task :aux => [:prep]  do |t,args|\n      build(@build_dirs[:aux],t)\n    end\n\n    desc <<~DESC\n      Build the SIMP documentation.\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n    DESC\n    task :doc => [:prep] do |t,args|\n      # Need to make sure that the docs have the version updated\n      # appropriately prior to building\n\n      Dir.chdir(@build_dirs[:doc]) do\n        sh %{rake munge:prep}\n      end\n\n      build(@build_dirs[:doc],t)\n    end\n\n    desc <<~DESC\n      Sign a set of RPMs.\n\n        Signs any unsigned RPMs in the specified directory\n          * :key - The key directory to use under the build keys directory\n            * key defaults to 'dev'\n            * build keys directory defaults to\n              `\#{@build_keys_dir}`\n          * :rpm_dir - A directory containing RPM files to sign. Will recurse!\n            * Defaults to \#{File.join(File.dirname(@rpm_dir), '*RPMS')}\n          * :force - Force rpms that are already signed to be resigned\n            * Defaults to 'false', can be enabled with 'true'\n          * :digest_algo - Digest algorithm to be used when signing the RPMs\n            * Defaults to 'sha256'\n\n      ENV vars:\n        * Set `SIMP_RPM_verbose=yes` to report RPM operations as they happen.\n        * Set `SIMP_PKG_build_keys_dir` to override the default build keys path.\n        * Set `SIMP_PKG_rpmsign_timeout` to override the maximum time in seconds\n          to wait for an individual RPM signing operation to complete.\n          - Defaults to 60 seconds.\n    DESC\n    task :signrpms,[:key,:rpm_dir,:force,:digest_algo] => [:prep,:key_prep] do |t,args|\n      require 'simp/rpm_signer'\n\n      args.with_defaults(:key => 'dev')\n      args.with_defaults(:rpm_dir => File.join(File.dirname(@rpm_dir), '*RPMS'))\n      args.with_defaults(:force => 'false')\n      args.with_defaults(:digest_algo => 'sha256')\n\n      force = (args[:force].to_s == 'false' ? false : true)\n      timeout = ENV['SIMP_PKG_rpmsign_timeout'] ? ENV['SIMP_PKG_rpmsign_timeout'].to_i : 60\n\n      opts = {\n        :digest_algo        => args[:digest_algo],\n        :force              => force,\n        :max_concurrent     => @cpu_limit,\n        :progress_bar_title => t.name,\n        :timeout_seconds    => timeout,\n        :verbose            => @verbose\n      }\n\n      results = nil\n      begin\n        results = Simp::RpmSigner.sign_rpms(\n          args[:rpm_dir],\n          File.join(@build_keys_dir, args[:key]),\n          opts\n        )\n      rescue Exception => e\n        raise(\"\#{e.message}\\n\\n\#{@long_gpg_socket_err_msg}\")\n      end\n\n      if results\n        successes = results.select { |rpm,status| status == :signed }\n        failures = results.select { |rpm,status| status == :unsigned }\n        already_signed = results.select { |rpm,status| status == :skipped_already_signed }\n\n        if opts[:verbose]\n          puts\n          puts 'Summary'\n          puts '======='\n          puts \"# RPMs already signed:      \#{already_signed.size}\"\n          puts \"# RPMs successfully signed: \#{successes.size}\"\n          puts \"# RPM signing failures:     \#{failures.size}\"\n          puts\n        end\n\n        if !failures.empty?\n          if ((results.size - already_signed.size) == (failures.size))\n            detail = already_signed.empty? ? '' : 'unsigned '\n            raise(\"ERROR: Failed to sign all \#{detail}RPMs in \#{args[:rpm_dir]}\")\n          else\n            err_msg = \"ERROR: Failed to sign some RPMs in \#{args[:rpm_dir]}:\\n\"\n            err_msg += \"  \#{failures.keys.join(\"\\n  \")}\"\n            raise(err_msg)\n          end\n        end\n      end\n    end\n\n=begin\n    desc <<~DESC\n      Check that RPMs are signed.\n\n        Checks all RPM files in a directory to see if they are trusted.\n          * :rpm_dir - A directory containing RPM files to check. Default \#{@build_dir}/SIMP\n          * :key_dir - The path to the GPG keys you want to check the packages against. Default \#{@src_dir}/assets/gpgkeys/\n    DESC\n=end\n    task :checksig,[:rpm_dir,:key_dir] => [:prep] do |t,args|\n      begin\n\n        default_key_dir = File.join(@src_dir, 'assets', 'gpgkeys', 'GPGKEYS')\n        args.with_defaults(:rpm_dir => @pkg_dirs[:simp])\n        args.with_defaults(:key_dir => default_key_dir)\n\n        rpm_dirs = Dir.glob(args[:rpm_dir])\n\n        fail(\"Could not find files at \#{args[:rpm_dir]}!\") if rpm_dirs.empty?\n\n        temp_gpg_dir = Dir.mktmpdir\n        at_exit { FileUtils.remove_entry(temp_gpg_dir) if File.exist?(temp_gpg_dir) }\n\n        rpm_cmd = %{rpm --dbpath \#{temp_gpg_dir}}\n\n        %x{\#{rpm_cmd} --initdb}\n\n        public_keys = Dir.glob(File.join(args[:key_dir], '*'))\n\n        if public_keys.empty?\n          key_dirs_tried = [ args[:key_dir] ]\n\n          # try path to GPG keys for SIMP 6.1+\n          if (args[:key_dir] != default_key_dir) and File.exist?(default_key_dir)\n            key_dirs_tried << default_key_dir\n            public_keys = Dir.glob(File.join(default_key_dir, '*'))\n          end\n\n          if public_keys.empty?\n            # try path to GPG keys for SIMP 6.0\n            old_key_dir = File.join(@src_dir, 'assets', 'simp-gpgkeys', 'GPGKEYS')\n            if File.exist?(old_key_dir)\n              key_dirs_tried << old_key_dir\n              public_keys = Dir.glob(File.join(old_key_dir, '*'))\n            end\n          end\n\n          if public_keys.empty?\n            $stderr.puts \"pkg:checksig: Warning no GPG keys found in \#{key_dirs_tried}\"\n          end\n        end\n\n        # be sure to include any development keys packaged with the DVD\n        public_keys += Dir.glob(File.join(@dvd_src, 'RPM-GPG-KEY*'))\n\n        # Only import thngs that look like GPG keys...\n        public_keys.each do |key|\n          next if File.directory?(key) or !File.readable?(key)\n\n          File.read(key).each_line do |line|\n            if line =~ /-----BEGIN PGP PUBLIC KEY BLOCK-----/\n              %x{\#{rpm_cmd} --import \#{key}}\n              break\n            end\n          end\n        end\n\n        bad_rpms = []\n        rpm_dirs.each do |rpm_dir|\n          Find.find(rpm_dir) do |path|\n            if (path =~ /.*\\.rpm$/)\n              %x{\#{rpm_cmd} --checksig \#{path}}.strip\n              result = $?\n              unless result && (result.exitstatus == 0)\n                bad_rpms << path.split(/\\s/).first\n              end\n            end\n          end\n        end\n\n        unless bad_rpms.empty?\n          bad_rpms.map!{|x| x = \"  * \#{x}\"}\n          bad_rpms.unshift(\"ERROR: Untrusted RPMs found in the repository:\")\n\n          fail(bad_rpms.join(\"\\n\"))\n        else\n          puts \"Checksig succeeded\"\n        end\n      ensure\n        remove_entry_secure temp_gpg_dir if (temp_gpg_dir && File.exist?(temp_gpg_dir))\n      end\n    end\n\n    desc <<~DESC\n      Run repoclosure on RPM files.\n\n        Finds all rpm files in the target dir and all of its subdirectories, then\n        reports which packages have unresolved dependencies. This needs to be run\n        after rake tasks tar:build and unpack if operating on the basetest SIMP repo.\n          * :target_dir  - The directory to assess. Default \#{@build_dir}/SIMP.\n          * :aux_dir     - Auxillary repo glob to use when assessing. Default \#{@build_dir}/Ext_*.\n                          Defaults to ''(empty) if :target_dir is not the system default.\n\n        ENV vars:\n          - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n          - Set `SIMP_PKG_repoclose_pe=yes` to enable repoclosure on PE-related RPMs.\n\n    DESC\n    task :repoclosure,[:target_dir,:aux_dir] => [:prep] do |t,args|\n      default_target = @pkg_dirs[:simp]\n      args.with_defaults(:target_dir => File.expand_path(default_target))\n\n      if args[:aux_dir]\n        args[:aux_dir] = File.expand_path(args[:aux_dir])\n      end\n\n      _repoclose_pe = ENV.fetch('SIMP_PKG_repoclose_pe','no') == 'yes'\n\n      yum_conf_template = <<~YUM_CONF\n        [main]\n        keepcache=0\n        exactarch=1\n        obsoletes=1\n        gpgcheck=0\n        plugins=1\n        installonly_limit=5\n        <% unless \#{_repoclose_pe} -%>\n        exclude=*-pe-*\n        <% end -%>\n\n        <% repo_files.each do |repo| -%>\n        include=file://<%= repo %>\n        <% end -%>\n      YUM_CONF\n\n      yum_repo_template = <<~YUM_REPO\n        [<%= repo_name %>]\n        name=<%= repo_name %>\n        baseurl=file://<%= repo_path %>\n        enabled=1\n        gpgcheck=0\n        protect=1\n      YUM_REPO\n\n      fail(\"\#{args[:target_dir]} does not exist!\") unless File.directory?(args[:target_dir])\n\n      Dir.mktmpdir do |temp_pkg_dir|\n        Dir.chdir(temp_pkg_dir) do\n          mkdir_p('repos/basetest')\n          mkdir_p('repos/lookaside')\n          mkdir_p('repodata')\n\n          Dir.glob(File.join(args[:target_dir], '**', '*.rpm'))\n            .delete_if{|x| x =~ /\\.src\\.rpm$/}\n            .each do |path|\n              sym_path = \"repos/basetest/\#{File.basename(path)}\"\n              ln_sf(path,sym_path, :verbose => @verbose) unless File.exist?(sym_path)\n          end\n\n          if args[:aux_dir]\n            Dir.glob(File.join(args[:aux_dir], '**', '*.rpm'))\n              .delete_if{|x| x =~ /\\.src\\.rpm$/}\n              .each do |path|\n                sym_path = \"repos/lookaside/\#{File.basename(path)}\"\n                ln_sf(path,sym_path, :verbose => @verbose) unless File.exist?(sym_path)\n            end\n          end\n\n          repo_files = []\n          Dir.glob('repos/*').each do |repo|\n            if File.directory?(repo)\n              Dir.chdir(repo) { sh %{createrepo .} }\n\n              repo_name = File.basename(repo)\n              repo_path = File.expand_path(repo)\n              conf_file = \"\#{temp_pkg_dir}/\#{repo_name}.conf\"\n\n              File.open(conf_file,'w') do |file|\n                file.write(ERB.new(yum_repo_template,nil,'-').result(binding))\n              end\n\n              repo_files << conf_file\n            end\n          end\n\n          File.open('yum.conf', 'w') do |file|\n            file.write(ERB.new(yum_conf_template,nil,'-').result(binding))\n          end\n\n          dnf_system = which('dnf')\n          if dnf_system\n            cmd = 'repoclosure -c basetest.conf --disablerepo=* --enablerepo=basetest'\n          else\n            cmd = 'repoclosure -c repodata -n -t -r basetest -l lookaside -c yum.conf'\n          end\n\n          if ENV['SIMP_BUILD_verbose'] == 'yes'\n            puts\n            puts '-'*80\n            puts \"#### RUNNING: `\#{cmd}`\"\n            puts \"     in path '\#{Dir.pwd}'\"\n            puts '-'*80\n          end\n          repoclosure_output = %x(\#{cmd})\n\n          if (!$?.success? || (repoclosure_output =~ /nresolved/))\n            errmsg = ['Error: REPOCLOSURE FAILED:']\n            errmsg << [repoclosure_output]\n            puts(errmsg.join(\"\\n\"))\n\n            if dnf_system\n              if ENV.fetch('SIMP_BUILD_prompt', 'yes') != 'no'\n                puts('- Press any key to continue or ^C to abort -')\n                $stdin.gets\n              end\n            else\n              fail('Repoclosure Failed')\n            end\n          end\n        end\n      end\n    end\n\n    desc <<~DESC\n      Print published status of all project RPMs\n    DESC\n    task :check_published => [:prep] do |t,args|\n      begin\n        yum_helper = Simp::YUM.new(\n          Simp::YUM.generate_yum_conf(File.join(@distro_build_dir, 'yum_data')),\n          ENV.fetch('SIMP_YUM_makecache','yes') == 'yes')\n      rescue Simp::YUM::Error\n      end\n\n      errmsg = Parallel.map(\n        # Allow for shell globs\n        Array(@build_dirs.values).flatten.sort,\n        :in_processes => 1\n      ) do |dir|\n        _errmsg = nil\n\n        if Dir.exist?(dir)\n          begin\n            require_rebuild?(dir, yum_helper, {\n              fetch:      false,\n              verbose:    true,\n              check_git:  true,\n              prefix:     ''\n            })\n          rescue => e\n            _errmsg = \"Error: require_rebuild?(): Status check failed on '\#{dir}' => \#{e}\"\n          end\n        else\n          _errmsg = \"Error: Cound not find specified build directory '\#{dir}'\"\n        end\n\n        _errmsg\n      end.compact\n\n      unless errmsg.empty?\n        fail(errmsg.join(\"\\n\"))\n      end\n    end\n\n    ##############################################################################\n    # Helper methods\n    ##############################################################################\n\n    # Generate a random string suitable for a rake task namespace\n    #\n    # This is used as a workaround for Parallelization\n    def generate_namespace\n      return (0...24).map{ (65 + rand(26)).chr }.join.downcase\n    end\n\n    # Return a SIMP::YUM object configured for the local build dir or nil\n    #\n    # ENV vars:\n    #   - Set `SIMP_PKG_verbose=yes` to report file operations as they happen.\n    #   - Set `SIMP_YUM_makecache=no` if you do NOT want to rebuild the\n    #     build-specific YUM cache\n    def get_yum_helper( makecache = (ENV.fetch('SIMP_YUM_makecache','yes') == 'yes') )\n      begin\n        build_yum_data = File.join(@distro_build_dir, 'yum_data')\n        return Simp::YUM.new(Simp::YUM.generate_yum_conf(build_yum_data), makecache)\n      rescue Simp::YUM::Error => e\n        $stderr.puts \"Simp::YUM::Error: \#{e}\" if @verbose\n      end\n    end\n\n    # Check and see if 'dir' requires a rebuild based on published packages\n    #\n    # If 'fetch' is true => Download the published RPM\n    # If 'verbose' is true => Print helpful information to stderr\n    # If 'check_git' is true => Print the git tag status if 'verbose' is true\n    # 'prefix' is used to prepend verbose messages\n    #\n    # FIXME\n    # - Method is too long\n    # - Method needs to be passed in class variables (@xxx) so that it\n    #   can be pulled out into a library that is easily unit-testable\n    def require_rebuild?(dir, yum_helper, opts={\n      unique_namespace:  generate_namespace,\n      fetch:             false,\n      verbose:           @verbose,\n      check_git:         false,\n      prefix:            ''\n    })\n      always_require_rebuild = ENV.select{|x| x =~ /SIMP_BUILD_PKG_require_rebuild/i }\n      unless always_require_rebuild.empty?\n        return true if always_require_rebuild =~ /\\A(yes|always)\\Z/i\n      end\n      result = false\n      rpm_metadata = File.exist?(@rpm_dependency_file) ? YAML.load(File.read(@rpm_dependency_file)) : {}\n      dir_relpath = Pathname.new(dir).relative_path_from(Pathname.new(Dir.pwd)).to_path\n      $stderr.puts \"\\n  require_rebuild? (\#{dir_relpath}):\" if @verbose\n\n      Dir.chdir(dir) do\n        if File.exist?('metadata.json')\n          # Generate RPM metadata files\n          # - 'build/rpm_metadata/requires' file containing RPM\n          #   dependency/obsoletes information from the\n          #   'dependencies.yaml' and the module's\n          #   'metadata.json'; always created\n          # - 'build/rpm_metadata/release' file containing RPM\n          #   release qualifier from the 'dependencies.yaml';\n          #   only created if release qualifier if specified in\n          #   the 'dependencies.yaml'\n          Simp::Rake::Build::RpmDeps::generate_rpm_meta_files(dir, rpm_metadata)\n\n          new_rpm = Simp::Rake::Pkg.new(Dir.pwd, opts[:unique_namespace], @simp_version)\n          new_rpm_info = Simp::RPM.new(new_rpm.spec_file)\n        else\n          spec_file = Dir.glob(File.join('build', '*.spec'))\n          fail(\"No spec file found in \#{dir}/build\") if spec_file.empty?\n          $stderr.puts \"    Found spec file: \#{File.expand_path(spec_file.first)}\" if @verbose\n          new_rpm_info = Simp::RPM.new(spec_file.first)\n        end\n\n        if @verbose\n          $stderr.puts '    Details:'\n          $stderr.puts \"        Puppetfile name: \#{File.basename(dir)}\"\n          $stderr.puts \"        RPM name:        \#{new_rpm_info.name}\"\n          $stderr.puts \"        Local directory: \#{dir}\"\n        end\n\n        if opts[:check_git]\n          git_origin_url = nil\n          ['origin','upstream'].each do |r|\n            git_origin_url = %x(git config --get remote.\#{r}.url).strip if git_origin_url.to_s.empty?\n          end\n          $stderr.puts \"        Git origin URL:  \#{git_origin_url}\" if @verbose\n          require_tag = false\n\n          #FIXME The check below is insufficient. See logic in compare_latest_tag,\n          # which does a git diff between files checked out and latest tag to see\n          # if any changes to mission-relevant files have been made and if the\n          # version has been bumped, when such changes have been made.\n          #\n          # We remove any leading 'v' chars since some external projects use them\n          latest_tag = %x(git describe --abbrev=0 --tags 2>/dev/null).strip.gsub(/^v/,'')\n\n          # Legacy munge\n          # We remove any leading 'simp-', leading 'simp6.0.0-', or trailing\n          # '-post1' strings used previously for some projects.  This munge\n          # logic can be remove in SIMP 7.\n          latest_tag.gsub!(/^simp-|^simp6.0.0-|-post1$/,'')\n\n          begin\n            rpm_version = Gem::Version.new(new_rpm_info.version)\n            rpm_release = new_rpm_info.release.match(/^(\\d+)[.-_]?/) ? new_rpm_info.release.match(/^(\\d+)[.-_]?/)[1] : nil\n            if @verbose\n              $stderr.puts '        ' + [\n                \"RPM version-rel: \#{ \"\#{rpm_version}-\#{rpm_release}\".ljust(10) }  \",\n                \"(semver: \#{rpm_version}, relver: \#{rpm_release})\",\n              ].join\n            end\n          rescue ArgumentError\n            $stderr.puts \">>\#{new_rpm_info.basename}: Could not determine RPM version from '\#{new_rpm_info.version}'\"\n          end\n\n          begin\n            if latest_tag.empty?\n              require_tag = true\n              $stderr.puts \"        Latest Git tag semver:   (none)\" if @verbose\n            else\n              # Gem::Version interprets an RPM-style release suffix like\n              # `1.2.3-4` as `1.2.3.pre.4`, which is *less* than `1.2.3`.\n              # So we compare SemVer first, then relver numbers if needed\n              latest_tag_version = Gem::Version.new(latest_tag.sub(/-\\d+$/,''))\n              latest_tag_release = latest_tag.match(/-(\\d+)$/) ? latest_tag.match(/-(\\d+)$/)[1].to_i : nil\n              if @verbose\n                $stderr.puts '        ' + [\n                  \"Latest Git tag:  \#{latest_tag.ljust(10)}  \",\n                  \"(semver: \#{latest_tag_version}\#{latest_tag_release ? \", relver: \#{latest_tag_release}\" : nil})\",\n                ].join\n              end\n            end\n          rescue ArgumentError\n            $stderr.puts \">>\#{git_origin_url}: Invalid git tag version '\#{latest_tag}' \"\n          end\n\n          if rpm_version && latest_tag_version\n            # undefined behavior, so far (this current logic skips it):\n            #   what to do if rpm_release is set and latest_tag_release is nil?\n            if latest_tag_release &&\n               rpm_release &&\n               (rpm_version == latest_tag_version) &&\n               (rpm_release > latest_tag_release)\n              require_tag = true\n            elsif rpm_version > latest_tag_version\n              require_tag = true\n            end\n          end\n\n          if opts[:verbose] && require_tag\n            $stderr.puts [\n              \"\#{opts[:prefix]}Git Release Tag Required: \",\n              \"[\#{git_origin_url || dir_relpath }] \",\n              \"tag: \#{latest_tag} => \",\n              \"rpm: \#{new_rpm_info.version}\#{latest_tag_release ? \"-\#{rpm_release}\" : nil} \",\n              \"[\#{new_rpm_info.basename}]\",\n            ].join\n          end\n        end\n\n        # Pull down any newer versions of the target RPM if we've been\n        # given a yum_helper\n        #\n        # Just build from scratch if something goes wrong\n        if yum_helper\n          # Most RPM spec files generate a single package, but we have\n          # a handful that generate multiple (sub-)packages\n          new_rpm_info.packages.each do |package|\n            begin\n              published_rpm = yum_helper.available_package(package)\n\n              if published_rpm\n                if new_rpm_info.package_newer?(package, published_rpm)\n                  if opts[:verbose]\n                    $stderr.puts \"\#{opts[:prefix]}RPM Publish Required: \#{published_rpm} => \#{new_rpm_info.rpm_name(package)}\"\n                  end\n                  result = true\n                else\n                  $stderr.puts \"\#{opts[:prefix]}Found Existing Remote RPM: \#{published_rpm}\" if opts[:verbose]\n                  if opts[:fetch]\n                    # Download published RPM, unless it's already been downloaded.\n                    # TODO Unhandled edge case: Validate that downloaded RPM is valid\n                    if File.exist?(File.join('dist', published_rpm))\n                      $stderr.puts \"\#{opts[:prefix]}\#{published_rpm} previously downloaded\" if opts[:verbose]\n                    else\n                      # We know the package exists. So in a brute-force fashion,\n                      # we're going to retry a couple of times.\n                      # (Real fix is for user to update retry and timeout parameters\n                      # in their yum config).\n                      tries = ENV.fetch('SIMP_YUM_retries','3').to_i\n                      begin\n                        yum_helper.download(\"\#{package}\", :target_dir => 'dist')\n                        $stderr.puts \"\#{opts[:prefix]}Downloaded \#{published_rpm}\" if opts[:verbose]\n                      rescue Simp::YUM::Error\n                        tries -= 1\n                        if tries > 0\n                          retry\n                        else\n                          $stderr.puts \">>Failed to download existing remote RPM: \#{published_rpm}. RPM will be locally rebuilt\"\n                          result = true\n                        end\n                      end\n                    end\n                  end\n                end\n              else\n                if opts[:verbose]\n                  $stderr.puts \"\#{opts[:prefix]}RPM Publish Required (new RPM): \#{new_rpm_info.rpm_name(package)}\"\n                end\n                result = true\n              end\n            rescue Simp::YUM::Error => e\n              $stderr.puts e if opts[:verbose]\n            end\n          end\n        else\n          $stderr.puts '>>Issue creating YUM configuration. Packages will be locally generated.' if opts[:verbose]\n\n          result = true\n        end\n      end\n\n      return result\n    end\n\n    def build_pupmod_rpm(dir, yum_helper, dbg_prefix = '  ')\n      unique_namespace = generate_namespace\n      if require_rebuild?(dir, yum_helper, {\n        unique_namespace:  unique_namespace,\n        fetch:             @fetch_published_rpm.nil? ? true : @fetch_published_rpm,\n        verbose:           @verbose,\n        prefix:            dbg_prefix,\n      })\n        $stderr.puts(\"\#{dbg_prefix}Running 'rake pkg:rpm' on \#{File.basename(dir)}\") if @verbose\n        Rake::Task[\"\#{unique_namespace}:pkg:rpm\"].invoke\n      else\n        # Record metadata for the downloaded RPM\n        Simp::RPM::create_rpm_build_metadata(File.expand_path(dir))\n      end\n      true\n    end\n\n\n    def build_rakefile_rpm(dir, yum_helper, dbg_prefix = '  ')\n      if require_rebuild?(dir, yum_helper, {\n        fetch:    @fetch_published_rpm.nil? ? true : @fetch_published_rpm,\n        verbose:  @verbose,\n        prefix:   dbg_prefix\n      })\n        $stderr.puts(\"\#{dbg_prefix}Running 'rake pkg:rpm' in \#{File.basename(dir)}\") if @verbose\n        rake_flags = Rake.application.options.trace ? '--trace' : ''\n        cmd = %{SIMP_BUILD_version=\#{@simp_version} rake pkg:rpm \#{rake_flags} 2>&1}\n\n        build_success = true\n        begin\n          %x{\#{cmd}}\n          build_success = $?.success?\n\n          built_rpm = true\n        rescue\n          build_success = false\n        end\n\n        unless build_success\n          if @verbose\n            $stderr.puts(\"First 'rake pkg:rpm' attempt for \#{dir} failed, running bundle and trying again.\")\n          end\n\n          if Bundler.respond_to?(:with_unbundled_env)\n            # Bundler 2.1+\n            clean_env_method = :with_unbundled_env\n            bundle_install_cmd = %{bundle config set with 'development' && bundle install}\n          else\n            # Old Bundler\n            clean_env_method = :with_clean_env\n            bundle_install_cmd = %{bundle install --with development}\n          end\n\n          ::Bundler.send(clean_env_method) do\n            %x{\#{bundle_install_cmd}}\n\n            output = %x{\#{cmd} 2>&1}\n\n            unless $?.success?\n              raise(\"Error in \#{dir} running \#{cmd}\\n\#{output}\")\n            end\n          end\n        end\n      else\n        # Record metadata for the downloaded RPM\n        Simp::RPM::create_rpm_build_metadata(File.expand_path(dir))\n        built_rpm = true\n      end\n    end\n\n\n    # Takes a list of directories to hop into and perform builds within\n    #\n    # The task must be passed so that we can output the calling name in the\n    # status bar.\n    def build(dirs, task, rebuild_for_arch=false, remake_yum_cache = false)\n      fail(\"Could not find RPM dependency file '\#{@rpm_dependency_file}'\") unless File.exist?(@rpm_dependency_file)\n      yum_helper = get_yum_helper( remake_yum_cache )\n\n      Parallel.map(\n        # Allow for shell globs\n        Array(dirs), {\n          in_processes:  @cpu_limit,\n          progress:      (ENV.fetch('SIMP_PKG_progress_bar','yes') == 'yes') ? task.name : nil,\n        }\n      ) do |dir|\n        fail(\"Could not find directory \#{dir}\") unless Dir.exist?(dir)\n\n        Dir.chdir(dir) do\n          built_rpm = false\n          $stderr.puts(\"\\nPackaging \#{File.basename(dir)}\") if @verbose\n\n          if File.exist?('metadata.json')\n            # We're building a module, override anything down there\n            built_rpm = build_pupmod_rpm(dir, yum_helper)\n          elsif File.exist?('Rakefile')\n            # We're building one of the extra assets and should honor its Rakefile\n            # and RPM spec file.\n            built_rpm = build_rakefile_rpm(dir, yum_helper)\n          else\n            puts \"Warning: '\#{dir}' could not be built (not a pupmod & no Rakefile!)\"\n          end\n\n          if built_rpm\n            tarballs = Dir.glob('dist/*.tar.gz')\n            rpms = Dir.glob('dist/*.rpm').delete_if{|x| x =~ %r(\\.src\\.rpm$)}\n\n            # Not all items generate tarballs\n            tarballs.each do |pkg|\n              if (File.stat(pkg).size == 0)\n                raise(\"Empty Tarball '\#{pkg}' generated for \#{dir}\")\n              end\n            end\n\n            raise(\"No RPMs generated for \#{dir}\") if rpms.empty?\n          end\n          $stderr.puts(\"Finished  \#{File.basename(dir)}\") if @verbose\n        end\n      end\n    end\n\n    #desc \"Checks the environment for building the DVD tarball\n    def check_dvd_env\n      [\"\#{@dvd_src}/isolinux\",\"\#{@dvd_src}/ks\"].each do |dir|\n        File.directory?(dir) or raise \"Environment not suitable: Unable to find directory '\#{dir}'\"\n      end\n    end\n\n    # Return an Array of all puppet module directories\n    def get_module_dirs(method='tracking')\n      load_puppetfile(method)\n      module_paths.select{|x| File.basename(File.dirname(x)) == 'modules'}.sort\n    end\n  end\nend\n"