-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel
executable file
·13744 lines (12990 loc) · 400 KB
/
parallel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
# Copyright (C) 2007-2021 Ole Tange, http://ole.tange.dk and Free
# Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
# or write to the Free Software Foundation, Inc., 51 Franklin St,
# Fifth Floor, Boston, MA 02110-1301 USA
#
# SPDX-FileCopyrightText: 2021 Ole Tange, http://ole.tange.dk and Free Software and Foundation, Inc.
# SPDX-License-Identifier: GPL-3.0-or-later
# open3 used in Job::start
use IPC::Open3;
use POSIX;
# gensym used in Job::start
use Symbol qw(gensym);
# tempfile used in Job::start
use File::Temp qw(tempfile tempdir);
# mkpath used in openresultsfile
use File::Path;
# GetOptions used in get_options_from_array
use Getopt::Long;
# Used to ensure code quality
use strict;
use File::Basename;
sub set_input_source_header($$) {
my ($command_ref,$input_source_fh_ref) = @_;
if($opt::header and not $opt::pipe) {
# split with colsep or \t
# $header force $colsep = \t if undef?
my $delimiter = defined $opt::colsep ? $opt::colsep : "\t";
# regexp for {=
my $left = "\Q$Global::parensleft\E";
my $l = $Global::parensleft;
# regexp for =}
my $right = "\Q$Global::parensright\E";
my $r = $Global::parensright;
my $id = 1;
for my $fh (@$input_source_fh_ref) {
my $line = <$fh>;
chomp($line);
$line =~ s/\r$//;
::debug("init", "Delimiter: '$delimiter'");
for my $s (split /$delimiter/o, $line) {
::debug("init", "Colname: '$s'");
# Replace {colname} with {2}
for(@$command_ref, @Global::ret_files,
@Global::transfer_files, $opt::tagstring,
$opt::workdir, $opt::results, $opt::retries,
@Global::template_contents, @Global::template_names,
@opt::filter) {
# Skip if undefined
$_ or next;
s:\{$s(|/|//|\.|/\.)\}:\{$id$1\}:g;
# {=header1 ... =} => {=1 ... =}
s:$left $s (.*?) $right:$l$id$1$r:gx;
}
$Global::input_source_header{$id} = $s;
$id++;
}
}
} else {
my $id = 1;
for my $fh (@$input_source_fh_ref) {
$Global::input_source_header{$id} = $id;
$id++;
}
}
}
sub max_jobs_running() {
# Compute $Global::max_jobs_running as the max number of jobs
# running on each sshlogin.
# Returns:
# $Global::max_jobs_running
if(not $Global::max_jobs_running) {
for my $sshlogin (values %Global::host) {
$sshlogin->max_jobs_running();
}
}
if(not $Global::max_jobs_running) {
::error("Cannot run any jobs.");
wait_and_exit(255);
}
return $Global::max_jobs_running;
}
sub halt() {
# Compute exit value,
# wait for children to complete
# and exit
if($opt::halt and $Global::halt_when ne "never") {
if(not defined $Global::halt_exitstatus) {
if($Global::halt_pct) {
$Global::halt_exitstatus =
::ceil($Global::total_failed /
($Global::total_started || 1) * 100);
} elsif($Global::halt_count) {
$Global::halt_exitstatus =
::min(undef_as_zero($Global::total_failed),101);
}
}
wait_and_exit($Global::halt_exitstatus);
} else {
wait_and_exit(min(undef_as_zero($Global::exitstatus),101));
}
}
sub __PIPE_MODE__() {}
sub pipepart_setup() {
# Compute the blocksize
# Generate the commands to extract the blocks
# Push the commands on queue
# Changes:
# @Global::cat_prepends
# $Global::JobQueue
if($opt::tee) {
# Prepend each command with
# < file
my $cat_string = "< ".Q($opt::a[0]);
for(1..$Global::JobQueue->total_jobs()) {
push @Global::cat_appends, $cat_string;
push @Global::cat_prepends, "";
}
} else {
if(not $opt::blocksize) {
# --blocksize with 10 jobs per jobslot
$opt::blocksize = -10;
}
if($opt::roundrobin) {
# --blocksize with 1 job per jobslot
$opt::blocksize = -1;
}
if($opt::blocksize < 0) {
my $size = 0;
# Compute size of -a
for(@opt::a) {
if(-f $_) {
$size += -s $_;
} elsif(-b $_) {
$size += size_of_block_dev($_);
} elsif(-e $_) {
::error("$_ is neither a file nor a block device");
wait_and_exit(255);
} else {
::error("File not found: $_");
wait_and_exit(255);
}
}
# Run in total $job_slots*(- $blocksize) jobs
# Set --blocksize = size / no of proc / (- $blocksize)
$Global::dummy_jobs = 1;
$Global::blocksize = 1 +
int($size / max_jobs_running() /
-multiply_binary_prefix($opt::blocksize));
}
@Global::cat_prepends = map { pipe_part_files($_) } @opt::a;
# Unget the empty arg as many times as there are parts
$Global::JobQueue->{'commandlinequeue'}{'arg_queue'}->unget(
map { [Arg->new("\0noarg")] } @Global::cat_prepends
);
}
}
sub pipe_tee_setup() {
# Create temporary fifos
# Run 'tee fifo1 fifo2 fifo3 ... fifoN' in the background
# This will spread the input to fifos
# Generate commands that reads from fifo1..N:
# cat fifo | user_command
# Changes:
# @Global::cat_prepends
my @fifos;
for(1..$Global::JobQueue->total_jobs()) {
push @fifos, tmpfifo();
}
# cat foo | tee fifo1 fifo2 fifo3 fifo4 fifo5 > /dev/null
if(not fork()){
# Test if tee supports --output-error=warn-nopipe
`echo | tee --output-error=warn-nopipe /dev/null >/dev/null 2>/dev/null`;
my $opt = $? ? "" : "--output-error=warn-nopipe";
::debug("init","tee $opt");
# Let tee inherit our stdin
# and redirect stdout to null
open STDOUT, ">","/dev/null";
if($opt) {
exec "tee", $opt, @fifos;
} else {
exec "tee", @fifos;
}
}
# For each fifo
# (rm fifo1; grep 1) < fifo1
# (rm fifo2; grep 2) < fifo2
# (rm fifo3; grep 3) < fifo3
# Remove the tmpfifo as soon as it is open
@Global::cat_prepends = map { "(rm $_;" } @fifos;
@Global::cat_appends = map { ") < $_" } @fifos;
}
sub parcat_script() {
# TODO if script fails: Use parallel -j0 --plain --lb cat ::: fifos
my $script = q'{
use POSIX qw(:errno_h);
use IO::Select;
use strict;
use threads;
use Thread::Queue;
use Fcntl qw(:DEFAULT :flock);
my $opened :shared;
my $q = Thread::Queue->new();
my $okq = Thread::Queue->new();
my @producers;
if(not @ARGV) {
if(-t *STDIN) {
print "Usage:\n";
print " parcat file(s)\n";
print " cat argfile | parcat\n";
} else {
# Read arguments from stdin
chomp(@ARGV = <STDIN>);
}
}
my $files_to_open = 0;
# Default: fd = stdout
my $fd = 1;
for (@ARGV) {
# --rm = remove file when opened
/^--rm$/ and do { $opt::rm = 1; next; };
# -1 = output to fd 1, -2 = output to fd 2
/^-(\d+)$/ and do { $fd = $1; next; };
push @producers, threads->create("producer", $_, $fd);
$files_to_open++;
}
sub producer {
# Open a file/fifo, set non blocking, enqueue fileno of the file handle
my $file = shift;
my $output_fd = shift;
open(my $fh, "<", $file) || do {
print STDERR "parcat: Cannot open $file\n";
exit(1);
};
# Remove file when it has been opened
if($opt::rm) {
unlink $file;
}
set_fh_non_blocking($fh);
$opened++;
# Pass the fileno to parent
$q->enqueue(fileno($fh),$output_fd);
# Get an OK that the $fh is opened and we can release the $fh
while(1) {
my $ok = $okq->dequeue();
if($ok == fileno($fh)) { last; }
# Not ours - very unlikely to happen
$okq->enqueue($ok);
}
return;
}
my $s = IO::Select->new();
my %buffer;
sub add_file {
my $infd = shift;
my $outfd = shift;
open(my $infh, "<&=", $infd) || die;
open(my $outfh, ">&=", $outfd) || die;
$s->add($infh);
# Tell the producer now opened here and can be released
$okq->enqueue($infd);
# Initialize the buffer
@{$buffer{$infh}{$outfd}} = ();
$Global::fh{$outfd} = $outfh;
}
sub add_files {
# Non-blocking dequeue
my ($infd,$outfd);
do {
($infd,$outfd) = $q->dequeue_nb(2);
if(defined($outfd)) {
add_file($infd,$outfd);
}
} while(defined($outfd));
}
sub add_files_block {
# Blocking dequeue
my ($infd,$outfd) = $q->dequeue(2);
add_file($infd,$outfd);
}
my $fd;
my (@ready,$infh,$rv,$buf);
do {
# Wait until at least one file is opened
add_files_block();
while($q->pending or keys %buffer) {
add_files();
while(keys %buffer) {
@ready = $s->can_read(0.01);
if(not @ready) {
add_files();
}
for $infh (@ready) {
# There is only one key, namely the output file descriptor
for my $outfd (keys %{$buffer{$infh}}) {
# TODO test if 65536 is optimal (2^17 is used elsewhere)
$rv = sysread($infh, $buf, 65536);
if (!$rv) {
if($! == EAGAIN) {
# Would block: Nothing read
next;
} else {
# Nothing read, but would not block:
# This file is done
$s->remove($infh);
for(@{$buffer{$infh}{$outfd}}) {
syswrite($Global::fh{$outfd},$_);
}
delete $buffer{$infh};
# Closing the $infh causes it to block
# close $infh;
add_files();
next;
}
}
# Something read.
# Find \n or \r for full line
my $i = (rindex($buf,"\n")+1);
if($i) {
# Print full line
for(@{$buffer{$infh}{$outfd}}, substr($buf,0,$i)) {
syswrite($Global::fh{$outfd},$_);
}
# @buffer = remaining half line
$buffer{$infh}{$outfd} = [substr($buf,$i,$rv-$i)];
} else {
# Something read, but not a full line
push @{$buffer{$infh}{$outfd}}, $buf;
}
redo;
}
}
}
}
} while($opened < $files_to_open);
for (@producers) {
$_->join();
}
sub set_fh_non_blocking {
# Set filehandle as non-blocking
# Inputs:
# $fh = filehandle to be blocking
# Returns:
# N/A
my $fh = shift;
my $flags;
fcntl($fh, &F_GETFL, $flags) || die $!; # Get the current flags on the filehandle
$flags |= &O_NONBLOCK; # Add non-blocking to the flags
fcntl($fh, &F_SETFL, $flags) || die $!; # Set the flags on the filehandle
}
}';
return ::spacefree(3, $script);
}
sub sharder_script() {
my $script = q{
use B;
# Column separator
my $sep = shift;
# Which columns to shard on (count from 1)
my $col = shift;
# Which columns to shard on (count from 0)
my $col0 = $col - 1;
# Perl expression
my $perlexpr = shift;
my $bins = @ARGV;
# Open fifos for writing, fh{0..$bins}
my $t = 0;
my %fh;
for(@ARGV) {
open $fh{$t++}, ">", $_;
# open blocks until it is opened by reader
# so unlink only happens when it is ready
unlink $_;
}
if($perlexpr) {
my $subref = eval("sub { no strict; no warnings; $perlexpr }");
while(<STDIN>) {
# Split into $col columns (no need to split into more)
@F = split $sep, $_, $col+1;
{
local $_ = $F[$col0];
&$subref();
$fh = $fh{ hex(B::hash($_))%$bins };
}
print $fh $_;
}
} else {
while(<STDIN>) {
# Split into $col columns (no need to split into more)
@F = split $sep, $_, $col+1;
$fh = $fh{ hex(B::hash($F[$col0]))%$bins };
print $fh $_;
}
}
# Close all open fifos
close values %fh;
};
return ::spacefree(1, $script);
}
sub binner_script() {
my $script = q{
use B;
# Column separator
my $sep = shift;
# Which columns to shard on (count from 1)
my $col = shift;
# Which columns to shard on (count from 0)
my $col0 = $col - 1;
# Perl expression
my $perlexpr = shift;
my $bins = @ARGV;
# Open fifos for writing, fh{0..$bins}
my $t = 0;
my %fh;
# Let the last output fifo be the 0'th
open $fh{$t++}, ">", pop @ARGV;
for(@ARGV) {
open $fh{$t++}, ">", $_;
# open blocks until it is opened by reader
# so unlink only happens when it is ready
unlink $_;
}
if($perlexpr) {
my $subref = eval("sub { no strict; no warnings; $perlexpr }");
while(<STDIN>) {
# Split into $col columns (no need to split into more)
@F = split $sep, $_, $col+1;
{
local $_ = $F[$col0];
&$subref();
$fh = $fh{ $_%$bins };
}
print $fh $_;
}
} else {
while(<STDIN>) {
# Split into $col columns (no need to split into more)
@F = split $sep, $_, $col+1;
$fh = $fh{ $F[$col0]%$bins };
print $fh $_;
}
}
# Close all open fifos
close values %fh;
};
return ::spacefree(1, $script);
}
sub pipe_shard_setup() {
# Create temporary fifos
# Run 'shard.pl sep col fifo1 fifo2 fifo3 ... fifoN' in the background
# This will spread the input to fifos
# Generate commands that reads from fifo1..N:
# cat fifo | user_command
# Changes:
# @Global::cat_prepends
my @shardfifos;
my @parcatfifos;
# TODO $opt::jobs should be evaluated (100%)
# TODO $opt::jobs should be number of total_jobs if there are argugemts
my $njobs = $opt::jobs;
for my $m (0..$njobs-1) {
for my $n (0..$njobs-1) {
# sharding to A B C D
# parcatting all As together
$parcatfifos[$n][$m] = $shardfifos[$m][$n] = tmpfifo();
}
}
my $shardbin = ($opt::shard || $opt::bin);
my $script;
if($opt::bin) {
$script = binner_script();
} else {
$script = sharder_script();
}
# cat foo | sharder sep col fifo1 fifo2 fifo3 ... fifoN
if($shardbin =~ /^[a-z_][a-z_0-9]*(\s|$)/i) {
# Group by column name
# (Yes, this will also wrongly match a perlexpr like: chop)
my($read,$char,@line);
# A full line, but nothing more (the rest must be read by the child)
# $Global::header used to prepend block to each job
do {
$read = sysread(STDIN,$char,1);
push @line, $char;
} while($read and $char ne "\n");
$Global::header = join "", @line;
}
my ($col, $perlexpr, $subref) =
column_perlexpr($shardbin, $Global::header, $opt::colsep);
if(not fork()) {
# Let the sharder inherit our stdin
# and redirect stdout to null
open STDOUT, ">","/dev/null";
# The PERL_HASH_SEED must be the same for all sharders
# so B::hash will return the same value for any given input
$ENV{'PERL_HASH_SEED'} = $$;
exec qw(parallel --block 100k -q --pipe -j), $njobs,
qw(--roundrobin -u perl -e), $script, ($opt::colsep || ","),
$col, $perlexpr, '{}', (map { (':::+', @{$_}) } @parcatfifos);
}
# For each fifo
# (rm fifo1; grep 1) < fifo1
# (rm fifo2; grep 2) < fifo2
# (rm fifo3; grep 3) < fifo3
my $parcat = Q(parcat_script());
if(not $parcat) {
::error("'parcat' must be in path.");
::wait_and_exit(255);
}
@Global::cat_prepends = map { "perl -e $parcat @$_ | " } @parcatfifos;
}
sub pipe_part_files(@) {
# Given the bigfile
# find header and split positions
# make commands that 'cat's the partial file
# Input:
# $file = the file to read
# Returns:
# @commands that will cat_partial each part
my ($file) = @_;
my $buf = "";
if(not -f $file and not -b $file) {
::error("$file is not a seekable file.");
::wait_and_exit(255);
}
my $header = find_header(\$buf,open_or_exit($file));
# find positions
my @pos = find_split_positions($file,int($Global::blocksize),$header);
# Make @cat_prepends
my @cat_prepends = ();
for(my $i=0; $i<$#pos; $i++) {
push(@cat_prepends,
cat_partial($file, 0, length($header), $pos[$i], $pos[$i+1]));
}
return @cat_prepends;
}
sub find_header($$) {
# Compute the header based on $opt::header
# Input:
# $buf_ref = reference to read-in buffer
# $fh = filehandle to read from
# Uses:
# $opt::header
# $Global::blocksize
# $Global::header
# Returns:
# $header string
my ($buf_ref, $fh) = @_;
my $header = "";
# $Global::header may be set in group_by_loop()
if($Global::header) { return $Global::header }
if($opt::header) {
if($opt::header eq ":") { $opt::header = "(.*\n)"; }
# Number = number of lines
$opt::header =~ s/^(\d+)$/"(.*\n)"x$1/e;
while(sysread($fh,$$buf_ref,int($Global::blocksize),length $$buf_ref)) {
if($$buf_ref =~ s/^($opt::header)//) {
$header = $1;
last;
}
}
}
return $header;
}
sub find_split_positions($$$) {
# Find positions in bigfile where recend is followed by recstart
# Input:
# $file = the file to read
# $block = (minimal) --block-size of each chunk
# $header = header to be skipped
# Uses:
# $opt::recstart
# $opt::recend
# Returns:
# @positions of block start/end
my($file, $block, $header) = @_;
my $headerlen = length $header;
my $size = -s $file;
if(-b $file) {
# $file is a blockdevice
$size = size_of_block_dev($file);
}
$block = int $block;
if($opt::groupby) {
return split_positions_for_group_by($file,$size,$block,$header);
}
# The optimal dd blocksize for mint, redhat, solaris, openbsd = 2^17..2^20
# The optimal dd blocksize for freebsd = 2^15..2^17
# The optimal dd blocksize for ubuntu (AMD6376) = 2^16
my $dd_block_size = 131072; # 2^17
my @pos;
my ($recstart,$recend) = recstartrecend();
my $recendrecstart = $recend.$recstart;
my $fh = ::open_or_exit($file);
push(@pos,$headerlen);
for(my $pos = $block+$headerlen; $pos < $size; $pos += $block) {
my $buf;
if($recendrecstart eq "") {
# records ends anywhere
push(@pos,$pos);
} else {
# Seek the the block start
if(not sysseek($fh, $pos, 0)) {
::error("Cannot seek to $pos in $file");
edit(255);
}
while(sysread($fh,$buf,$dd_block_size,length $buf)) {
if($opt::regexp) {
# If match /$recend$recstart/ => Record position
if($buf =~ m:^(.*$recend)$recstart:os) {
# Start looking for next record _after_ this match
$pos += length($1);
push(@pos,$pos);
last;
}
} else {
# If match $recend$recstart => Record position
# TODO optimize to only look at the appended
# $dd_block_size + len $recendrecstart
# TODO increase $dd_block_size to optimize for longer records
my $i = index64(\$buf,$recendrecstart);
if($i != -1) {
# Start looking for next record _after_ this match
$pos += $i + length($recend);
push(@pos,$pos);
last;
}
}
}
}
}
if($pos[$#pos] != $size) {
# Last splitpoint was not at end of the file: add $size as the last
push @pos, $size;
}
close $fh;
return @pos;
}
sub split_positions_for_group_by($$$$) {
my($fh);
sub value_at($) {
my $pos = shift;
if($pos != 0) {
seek($fh, $pos-1, 0) || die;
# Read half line
<$fh>;
}
# Read full line
my $linepos = tell($fh);
$_ = <$fh>;
if(defined $_) {
# Not end of file
my @F;
if(defined $group_by::col) {
$opt::colsep ||= "\t";
@F = split /$opt::colsep/, $_;
$_ = $F[$group_by::col];
}
eval $group_by::perlexpr;
}
return ($_,$linepos);
}
sub binary_search_end($$$) {
my ($s,$spos,$epos) = @_;
# value_at($spos) == $s
# value_at($epos) != $s
my $posdif = $epos - $spos;
my ($v,$vpos);
while($posdif) {
($v,$vpos) = value_at($spos+$posdif);
if($v eq $s) {
$spos = $vpos;
$posdif = $epos - $spos;
} else {
$epos = $vpos;
}
$posdif = int($posdif/2);
}
return($v,$vpos);
}
sub binary_search_start($$$) {
my ($s,$spos,$epos) = @_;
# value_at($spos) != $s
# value_at($epos) == $s
my $posdif = $epos - $spos;
my ($v,$vpos);
while($posdif) {
($v,$vpos) = value_at($spos+$posdif);
if($v eq $s) {
$epos = $vpos;
} else {
$spos = $vpos;
$posdif = $epos - $spos;
}
$posdif = int($posdif/2);
}
return($v,$vpos);
}
my ($file,$size,$block,$header) = @_;
my ($a,$b,$c,$apos,$bpos,$cpos);
my @pos;
$fh = open_or_exit($file);
# Set $Global::group_by_column $Global::group_by_perlexpr
group_by_loop($fh,$opt::recsep);
# $xpos = linestart, $x = value at $xpos, $apos < $bpos < $cpos
$apos = length $header;
for(($a,$apos) = value_at($apos); $apos < $size;) {
push @pos, $apos;
$bpos = $apos + $block;
($b,$bpos) = value_at($bpos);
if(eof($fh)) {
push @pos, $size; last;
}
$cpos = $bpos + $block;
($c,$cpos) = value_at($cpos);
if($a eq $b) {
while($b eq $c) {
# Move bpos, cpos a block forward until $a == $b != $c
$bpos = $cpos;
$cpos += $block;
($c,$cpos) = value_at($cpos);
if($cpos >= $size) {
$cpos = $size;
last;
}
}
# $a == $b != $c
# Binary search for $b ending between ($bpos,$cpos)
($b,$bpos) = binary_search_end($b,$bpos,$cpos);
} else {
if($b eq $c) {
# $a != $b == $c
# Binary search for $b starting between ($apos,$bpos)
($b,$bpos) = binary_search_start($b,$apos,$bpos);
} else {
# $a != $b != $c
# Binary search for $b ending between ($bpos,$cpos)
($b,$bpos) = binary_search_end($b,$bpos,$cpos);
}
}
($a,$apos) = ($b,$bpos);
}
if($pos[$#pos] != $size) {
# Last splitpoint was not at end of the file: add it
push @pos, $size;
}
return @pos;
}
sub cat_partial($@) {
# Efficient command to copy from byte X to byte Y
# Input:
# $file = the file to read
# ($start, $end, [$start2, $end2, ...]) = start byte, end byte
# Returns:
# Efficient command to copy $start..$end, $start2..$end2, ... to stdout
my($file, @start_end) = @_;
my($start, $i);
# Convert (start,end) to (start,len)
my @start_len = map {
if(++$i % 2) { $start = $_; } else { $_-$start }
} @start_end;
# This can read 7 GB/s using a single core
my $script = spacefree
(0,
q{
while(@ARGV) {
sysseek(STDIN,shift,0) || die;
$left = shift;
while($read =
sysread(STDIN,$buf, $left > 131072 ? 131072 : $left)){
$left -= $read;
syswrite(STDOUT,$buf);
}
}
});
return "<". Q($file) .
" perl -e '$script' @start_len |";
}
sub column_perlexpr($$$) {
# Compute the column number (if any), perlexpression from combined
# string (such as --shard key, --groupby key, {=n perlexpr=}
# Input:
# $column_perlexpr = string with column and perl expression
# $header = header from input file (if column is column name)
# $colsep = column separator regexp
# Returns:
# $col = column number
# $perlexpr = perl expression
# $subref = compiled perl expression as sub reference
my ($column_perlexpr, $header, $colsep) = @_;
my ($col, $perlexpr, $subref);
if($column_perlexpr =~ /^[-a-z0-9_]+(\s|$)/i) {
# Column name/number (possibly prefix)
if($column_perlexpr =~ s/^(-?\d+)(\s|$)//) {
# Column number (possibly prefix)
$col = $1;
} elsif($column_perlexpr =~ s/^([a-z0-9_]+)(\s+|$)//i) {
# Column name (possibly prefix)
my $colname = $1;
# Split on --copsep pattern
my @headers = split /$colsep/, $header;
my %headers;
@headers{@headers} = (1..($#headers+1));
$col = $headers{$colname};
if(not defined $col) {
::error("Column '$colname' $colsep not found in header",keys %headers);
::wait_and_exit(255);
}
}
}
# What is left of $column_perlexpr is $perlexpr (possibly empty)
$perlexpr = $column_perlexpr;
$subref = eval("sub { no strict; no warnings; $perlexpr }");
return($col, $perlexpr, $subref);
}
sub group_by_loop($$) {
# Generate perl code for group-by loop
# Insert a $recsep when the column value changes
# The column value can be computed with $perlexpr
my($fh,$recsep) = @_;
my $groupby = $opt::groupby;
if($groupby =~ /^[a-z_][a-z_0-9]*(\s|$)/i) {
# Group by column name
# (Yes, this will also wrongly match a perlexpr like: chop)
my($read,$char,@line);
# Read a full line, but nothing more
# (the rest must be read by the child)
# $Global::header used to prepend block to each job
do {
$read = sysread($fh,$char,1);
push @line, $char;
} while($read and $char ne "\n");
$Global::header = join "", @line;
}
$opt::colsep ||= "\t";
($group_by::col, $group_by::perlexpr, $group_by::subref) =
column_perlexpr($groupby, $Global::header, $opt::colsep);
# Numbered 0..n-1 due to being used by $F[n]
if($group_by::col) { $group_by::col--; }
my $loop = ::spacefree(0,q{
BEGIN{ $last = "RECSEP"; }
{
local $_=COLVALUE;
PERLEXPR;
if(($last) ne $_) {
print "RECSEP";
$last = $_;
}
}
});
if(defined $group_by::col) {
$loop =~ s/COLVALUE/\$F[$group_by::col]/g;
} else {
$loop =~ s/COLVALUE/\$_/g;
}
$loop =~ s/PERLEXPR/$group_by::perlexpr/g;
$loop =~ s/RECSEP/$recsep/g;
return $loop;
}
sub group_by_stdin_filter() {
# Record separator with 119 bit random value
$opt::recend = '';
$opt::recstart =
join "", map { (0..9,"a".."z","A".."Z")[rand(62)] } (1..20);
$opt::remove_rec_sep = 1;
my @filter;
push @filter, "perl";
if($opt::groupby =~ /^[a-z0-9_]+(\s|$)/i) {
# This is column number/name
# Use -a (auto-split)
push @filter, "-a";
$opt::colsep ||= "\t";
my $sep = $opt::colsep;
$sep =~ s/\t/\\t/g;
$sep =~ s/\"/\\"/g;
# man perlrun: -Fpattern [...] You can't use literal whitespace
$sep =~ s/ /\\040{1}/g;
push @filter, "-F$sep";
}
push @filter, "-pe";
push @filter, group_by_loop(*STDIN,$opt::recstart);
::debug("init", "@filter\n");
open(STDIN, '-|', @filter) || die ("Cannot start @filter");
if(which("mbuffer")) {
# You get a speed up of 30% by going through mbuffer
open(STDIN, '-|', "mbuffer", "-q","-m6M","-b5") ||
die ("Cannot start mbuffer");
}
}
sub spreadstdin() {
# read a record
# Spawn a job and print the record to it.
# Uses:
# $Global::blocksize
# STDIN
# $opt::r
# $Global::max_lines
# $Global::max_number_of_args
# $opt::regexp
# $Global::start_no_new_jobs
# $opt::roundrobin
# %Global::running
# Returns: N/A
my $buf = "";
my ($recstart,$recend) = recstartrecend();
my $recendrecstart = $recend.$recstart;
my $chunk_number = 1;
my $one_time_through;
my $two_gb = 2**31-1;
my $blocksize = int($Global::blocksize);
my $in = *STDIN;
my $timeout = $Global::blocktimeout;
my $header = find_header(\$buf,$in);
my $anything_written;
my $eof;
sub read_block() {
# Read a --blocksize from STDIN
# possibly interrupted by --blocktimeout
# Add up to the next full block
my $readsize = $blocksize - (length $buf) % $blocksize;
my ($nread,$alarm);
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
# --blocktimeout (or 0 if not set)
alarm $timeout;
if($] >= 5.026) {
do {
$nread = sysread $in, $buf, $readsize, length $buf;
$readsize -= $nread;
} while($readsize and $nread);
} else {
# Less efficient reading, but 32-bit sysread compatible
do {
$nread = sysread($in,substr($buf,length $buf,0),$readsize,0);
$readsize -= $nread;
} while($readsize and $nread);
}
alarm 0;
};
if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
$alarm = 1;
} else {