-
Notifications
You must be signed in to change notification settings - Fork 5
/
grun
executable file
·3952 lines (3457 loc) · 118 KB
/
grun
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# grun - lightweight jobs queueing system
# Copyright (C) 2011 Erik Aronesty
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
use strict;
use Carp qw(carp croak confess cluck);
use Getopt::Long qw(GetOptions);
use Data::UUID;
use ZMQ::LibZMQ3;
use ZMQ::Constants ':all';
use JSON::XS;
use Time::HiRes;
use BSD::Resource;
use IO::File;
use POSIX qw(:sys_wait_h strftime);
use Socket qw(IPPROTO_TCP TCP_NODELAY TCP_KEEPIDLE TCP_KEEPINTVL TCP_KEEPCNT);
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use Safe;
use Cwd qw(abs_path cwd);
use List::Util qw(min max);
use File::Basename qw(dirname);
sub pretty_encode;
our ($REVISION) = (q$LastChangedRevision: 15872 $ =~ /(\d+)/);
our $VERSION = "0.9.$REVISION"; # 0.10 wil be feature lock, after sql impl. 0.9.X is zmq & json::xs
my $STATUS_NEVERRUN=199;
my $STATUS_ORPHAN=-8;
my $STATUS_UNKNOWN=-9;
my $STATUS_EXECERR=-10;
my $PPID=$$;
my $WIN32 = ($^O =~ /Win32/);
my $TIMEFMT = 'command:%C\ncpu-real:%E\ncpu-user:%U\ncpu-sys:%S\nmem-max:%M\nmem-avg:%t\nctx-wait:%w\nfs-in:%I\nfs-out:%O';
my ($daemon, $killjob, $editjob);
my (%conf, %def, @metrics, @labels);
# defaults just run things locally, no master
$def{config} = "/etc/grun.conf"; # config file
$def{spool} = "/var/spool/grun"; # dir to place jobs
$def{port} = 5184; # listen/connect port
$def{bind} = '0.0.0.0'; # listen addr
$def{env} = ['PATH']; # list of environment vars to copy from submit through to exec
$def{default_memory} = 1000 * 1000; # default job memory
$def{default_priority} = 20; # default job priority (20 = always run)
$def{ping_secs} = 30; # how often to tell about load/mem/stats
$def{remove_secs} = '$ping_secs * 1000'; # don't even try kickstarting if the node is this old
$def{idle_load} = .3; # how often to tell about load/mem/stats
$def{retry_secs} = 10; # how often to retry notifications
$def{bench_secs} = 86400; # how often to re-benchmark
$def{max_buf} = 1000000; # how often to retry notifications
$def{expire_secs} = 14400; # remove jobs whose execution nodes haven't reported back in this amount of time
$def{io_keep} = 3600; # keep io for this long after a job with i/o is finished in a detached session
#$def{hard_factor} = 1.5; # hard limit factor
$def{max_sched} = 50; # how many different jobs to try and match before giving up on the rest (queue busy)
$def{spread_pct} = 5; # how often to "distribute jobs", versus "clump" them
$def{master} = 'localhost:5184'; # central scheduler
$def{services} = "queue exec"; # all can run
$def{pid_file} = "/var/run/grun.pid"; # pid file
$def{log_file} = "/var/log/grun.log"; # pid file
$def{hostname} = $ENV{HOSTNAME} ? $ENV{HOSTNAME} : $ENV{COMPUTERNAME} ? $ENV{COMPUTERNAME} : `hostname`;
$def{log_types} = "note error warn"; # log all
$def{nfs_sync} = 1; # enable nfs sync support
chomp $def{hostname};
sub debugging;
my $GRUN_PATH=abs_path($0);
my ($qinfo, $help, $config, $ver);
Getopt::Long::Configure qw(require_order no_ignore_case passthrough);
my $context = zmq_init();
my @ORIG_ARGV= @ARGV;
GetOptions("daemon"=>\$daemon, "CONF:s"=>\$config, "trace"=>\$def{trace}, "query"=>\$qinfo, "V"=>\$ver, "help"=>\$help) ||
die usage();
(print "grun $VERSION\n") && exit(0) if $ver;
my @send_files; # files to send
my $safe = new Safe;
$def{config} = $config if $config;
init();
# this fixes issues on some systems, probably a tty thing
system("echo . >> /dev/null")
my $stream_quit = 0;
if ($ARGV[0] eq '-X') {
do_stream();
exit(0);
}
if ($ARGV[0] eq '-Y') {
do_execute();
exit(0);
}
if ($ARGV[0] eq '-?') {
shift @ARGV;
$help = 1;
}
$help = 1 if defined $config && !$config;
if ($help) {
print usage();
exit 0;
}
if (!$daemon) {
# -k <id> works as long as -d wasn't specified
GetOptions("kill"=>\$killjob, "trace"=>\$def{trace}, "edit|e"=>\$editjob) ||
die usage();
}
if ($conf{debug_memory}) {
eval {require Devel::Gladiator;};
die $@ if $@;
}
my $gjobid = slurp("$conf{spool}/nextid");
my $log_to_stderr = 0;
if ($qinfo) {
# this is the code for grun -q
Getopt::Long::Configure qw(no_require_order no_ignore_case passthrough);
my %opt;
GetOptions(\%opt, "silent", "inplace", "hosts=s", "debug") || die usage();
my $cmd = shift @ARGV;
die usage() if !$cmd;
$log_to_stderr = 1 if $opt{debug};
my @arg = @ARGV;
$cmd =~ s/^-//;
my $tmp = substr bestunique($cmd, qw(config status jobs file history wait memory)), 0, 4;
if (!$tmp) {
die "Command $cmd is not available, for help type grun -query -?\n";
}
$cmd = $tmp;
# some commands default to localhost, others default to queue host... this is confusing... fix?
my @dest = $opt{hosts} ? expandnodes($opt{hosts}) :
$cmd eq 'conf' ? [$conf{bind}, $conf{port}] :
[$conf{master},$conf{master_port}];
if ($cmd eq 'file' && @dest > 1) {
die "Command $cmd cannot be run on multiple hosts";
}
my $ok=0;
for my $d (@dest) {
my ($host, $port) = @$d;
if ($cmd eq 'wait') {
my $st = 0;
for (@arg) {
my ($res) = waitmsg($host, $port, "jwait", $_);
if ($res && defined $res->{status}) {
print "Job $_ status $res->{status}\n";
$st = $res->{status} if $res->{status};
} else {
print "Job $_ status $STATUS_UNKNOWN\n";
$st = $STATUS_UNKNOWN;
}
}
exit $st;
} elsif ($cmd eq 'file') {
my $cwd = cwd;
my @need;
for (@arg) {
next if -e $_;
if ($_ !~ /^\//) {
$_ = "$cwd/$_";
}
push @need, $_;
}
die "not supported yet\n";
# if (@need) {
# my ($res, $error) = waitio({inplace=>$opt{inplace}}, $host, $port, "xcmd", 'file', @need);
# die $error, "\n" if $error && !$opt{silent};
# exit 1 if $error;
# }
} elsif ((!samehost($host,$conf{hostname}) || (!$ENV{_GRUN} && (!$conf{services}->{queue} || $cmd !~ /^stat|jobs|hist$/)))) {
# this could get ugly, if called a lot, may want to make more efficient
warn ("waitmsg($host, $port, 'xcmd', $cmd, @arg, @{[%opt]})\n") if $opt{debug};
my ($ret) = waitmsg($host, $port, "xcmd", $cmd, @arg, %opt);
print $ret;
$ok=1 if $ret;
} else {
warn ("Using local queue status, host $host is $conf{bind}/$conf{hostip}, name is $conf{hostname} \n") if $opt{debug};
my $ret;
if ($cmd eq 'stat') {
$ret = shownodes(@arg);
} elsif ($cmd eq 'jobs') {
$ret = showjobs(@arg);
} elsif ($cmd eq 'hist') {
$ret = showhist(@arg);
}
print $ret;
$ok=1 if $ret;
}
}
exit($ok ? 0 : 1);
}
my $gpid; # daemon pid
if (open(IN, $conf{pid_file})) {
$gpid = <IN>;
close IN;
}
if ($killjob) {
# grun -k code
my $sig = 15;
my $kforce = 0;
Getopt::Long::Configure qw(no_require_order no_ignore_case);
GetOptions("signal|n=i"=>\$sig, "force"=>\$kforce) || die usage();
my $exit = 0;
for my $job (@ARGV) {
my @id;
if ($job !~ /^\d/) {
@id=(guid=>"$job");
} else {
@id=(jid=>$job);
}
my $err = kill_job(@id, sig=>$sig, force=>$kforce);
if (!defined($err) && $@) {
warn $@,"\n";
$exit=-1;
} else {
my $ok = ($err =~ /^Job.*(aborted|kill requested)/);
$err =~ s/\n$//;
warn "$err\n" if $ok;
$err = 'No remote response to jkill' if !$ok && !$err;
warn "Error: $err\n" if !$ok;
$exit=-1 if !$ok;
}
}
exit 0;
}
if ($editjob) {
my %ed;
while (@ARGV) {
$_=$ARGV[0];
for (split /,/, $_) {
my ($key, $val) = $_ =~ /^([^=]+)(?:=(.*))?$/;
my $nk = bestunique($key, qw(hold resume memory cpus state hosts), @metrics, @labels);
$key = $nk if $nk;
$key = 'state', $val = 'hold' if ($key eq 'hold');
$key = 'state', $val = 'resume' if ($key eq 'resume');
if ($key eq 'state') {
$val = substr bestunique($val, qw(hold resume)), 0, 4;
die "' must be one of: h(old) r(esume)\n" unless $val;
}
$ed{$key}=$val;
}
shift;
last unless $ARGV[0] =~ /=/;
}
my @jids = @ARGV;
die usage() if !%ed || !@jids;
my $ex = 0;
for my $jid (@jids) {
warn "Edit " . packdump(\%ed) . "\n";
my ($err) = waitmsg($conf{master}, $conf{master_port}, 'jedit', $jid, %ed);
my $ok = ($err =~ /^Job.*edited/);
$err=~ s/\n$//;
warn "$err\n" if $ok;
$err = 'No remote response to jedit' if !$ok && !$err;
warn "Error: $err\n" if !$ok;
$ex = 1 if !$ok;
}
exit $ex;
}
my ($router, $read_set, $write_set, $quit, %pid_jobs, %j_wait, %io_wait, %start_wait); # daemon globals
my %ZMQS; # hash of open sockets
my %nodes; # hash of registered nodes
if ($daemon) {
startdaemon();
} else {
grun_client();
}
####################
# client mode
my $make;
my %sync_after;
my %sync_before;
my %sync_already;
sub grun_client {
my %jobs;
my %opt;
$opt{wait} = 1; # keep socket open until job is finished
$opt{io} = 1; # copy io back on the socket, implies wait
Getopt::Long::Configure qw(require_order no_ignore_case passthrough);
GetOptions(\%opt, "file=s", "int|I", "memory|m=i", "hosts|h=s", "cpus|c=f", "io!", "wait!", "err_a|err-append|ea=s", "err|e=s", "out|o=s", "out_a|out-append|oa=s", "ouer|out-err|oe=s", "ouer_a|out-err-append|oea=s", "jobx|jobid|j=s", "verbose", "make|M", "debug|D", "env|E=s", "alert=s", "param|p=s@", "wait-exists|W", "priority|r=i");
if ((!!$opt{out} + !!$opt{out_a} + !!$opt{ouer} + !!$opt{ouer_a})>1) {
$config=undef;
die "ERROR: Specify only one of --out, --out-append, --out-err or --out-err-append\n\n" . usage()
}
if ((!!$opt{err} + !!$opt{err_a} + !!$opt{ouer} + !!$opt{ouer_a})>1) {
$config=undef;
die "ERROR: Specify only one of --err, --err-append, --out-err or --out-err-append\n\n" . usage()
}
if (my $t=$opt{out_a}?$opt{out_a}:$opt{ouer_a}) {
$opt{out}=$t;
$opt{out_a}=1;
delete $opt{ouer_a};
}
if (my $t=$opt{err_a}?$opt{err_a}:$opt{ouer_a}) {
$opt{err}=$t;
$opt{err_a}=1;
delete $opt{ouer_a};
}
if ($opt{ouer}) {
$opt{out}=$opt{err}=$opt{ouer}; delete $opt{ouer};
}
my $verbose = $opt{verbose}; delete $opt{verbose};
my $env = $opt{env}; delete $opt{env};
$make = $opt{make}; delete $opt{make};
$log_to_stderr = 1 if $opt{debug};
if ($< == 0) {
die "Won't run a job as root\n";
}
if ($opt{err} && $opt{out}) {
$opt{io} = 0;
}
while ($ARGV[0] =~ /^--([\w-]+)=([\w=]+)/) {
# allow arbitrary job options, that jan later be referred to in match expressions
# or in execution wrappers, etc
$opt{$1} = $2;
shift @ARGV;
}
if ($make || $verbose) {
GetOptions(\%opt, "noexec");
}
my @cmd = @ARGV;
if ($opt{file}) {
# read options from a file
funpack($opt{file}, \%opt);
if ($opt{cmd}) {
if (@ARGV) {
die "Can't supply cmd: in the file and '@cmd' on the command line\n";
}
if ($opt{cmd} !~ /^[\w0-9:\/\t -]+$/) {
# not simple: let bash handle it
@cmd = ('bash', '-c', $opt{cmd});
} else {
# simple: split, pass as is to exec
$opt{cmd} =~ s/^\s+//;
$opt{cmd} =~ s/\s+$//;
@cmd = split /\s+/, $opt{cmd};
}
}
}
# force exec in "same as current dir"
$opt{cwd} = cwd;
if (!$opt{cwd}) {
die "Can't get current working directory, not executing unanchored remote command.\n";
}
if ($make) {
# %i:input %o:output
my (@i, @o);
for (@cmd) {
my @t = m/[#%]([io]):(\S+)/g;
if (@t) {
for (my $i=0;$i<@t;++$i) {
push @o, $t[$i+1] if $t[$i] eq 'o';
push @i, $t[$i+1] if $t[$i] eq 'i';
}
s/%[io]:(\S+)/$1/g;
s/#[io]:\S+//g;
}
my @t = m/([<>])\s*(\S+)/g;
if (@t) {
for (my $i=0;$i<@t;$i+=2) {
push @i, $t[$i+1] if $t[$i] eq '<' && $t[$i+1]=~/^\s*\w/;
push @o, $t[$i+1] if $t[$i] eq '>' && $t[$i+1]=~/^\s*\w/;
}
}
s/\%\!\>(>?\s*\S+)/>$1/g;
}
die "Unable to determine i/o for -M (make) semantics\n\n" . usage()
if !@i || !@o;
my $need=0;
for my $i (@i) {
syncfile($i);
add_syncfile_before($i);
for my $o (@o) {
syncfile($o);
if (! (-s $o) || (fmodtime($i) > fmodtime($o))) {
warn "# need $o\n" if $opt{noexec} || $verbose;
$need=1;
}
}
}
if (!$need) {
warn "Skipping: @cmd\n";
exit 0;
}
for (@o) {
add_syncfile_after($_);
}
warn "+@cmd\n" if $opt{noexec} || $verbose;
} else {
for (@cmd) {
if (m{([^\s,:]+)/([^\s,:]+)}) {
add_syncfile_after($_);
add_syncfile_before($_);
}
}
add_syncdir_after($opt{cwd});
add_syncdir_before($opt{cwd});
}
if ($ARGV[0] =~ /^-/) {
die "Unknown option $ARGV[0]\n";
}
#die pretty_encode \@cmd if $opt{debug};
if (!@cmd) {
die usage();
}
if ($cmd[$#cmd] =~ /\&$/) {
# TODO: grun should wait for all kids, and disallow detaching, not just get rude here
die "Not running background-only job. You might mean: grun \"command\" &.\n";
}
if ($conf{auto_profile}) {
if (-e ($conf{auto_profile})) {
my $cmd = join ' ', @cmd;
# safe'ish eval, just so there aren't weird side effects
my ($cpu, $mem, $prof) = evalctx(slurp($conf{auto_profile}) . ";\nreturn (\$cpu, \$mem, \%prof);", cmd=>$cmd, cmd=>\@cmd);
$prof = $cpu if ref($cpu) eq 'HASH';
# alias names
$prof->{cpus}=$prof->{cpu} if !$prof->{cpus} && $prof->{cpu};
$prof->{memory}=$prof->{mem} if !$prof->{memory} && $prof->{mem};
if ($prof && ref($prof) eq 'HASH') {
$prof->{memory} = $mem if defined($mem) && !ref($mem) && !$prof->{memory};
$prof->{cpus} = $cpu if defined($cpu) && !ref($cpu) && !$prof->{cpus};
$opt{memory}=$prof->{memory} if $prof->{memory} && !$opt{memory};
$opt{cpus}=$prof->{cpus} if $prof->{cpus} && !$opt{cpus};
$opt{hosts}=$prof->{hosts} if $prof->{hosts} && !$opt{hosts};
$opt{priority}=$prof->{priority} if $prof->{priority} && !$opt{priority};
for ((@metrics,@labels)) {
# as if the user entered it
next if !$_;
push @{$opt{"param"}}, "$_=" . $prof->{$_} if defined($prof->{$_});
}
} else {
$opt{memory}=$mem if ($mem > $opt{memory});
$opt{cpus}=$cpu if ($cpu > $opt{cpus});
}
if ($@) {
die "Can't run $conf{auto_profile}: $@\n";
}
} else {
die "Can't find $conf{auto_profile}: $!\n";
}
}
my %param;
if ($opt{param}) {
for (@{$opt{param}}) {
if (/^([^=]+)=(.*)/) {
$param{$1} = $2;
} else {
die "Parameter $_: should be name=value\n";
}
}
}
$opt{param} = \%param;
$opt{priority} = $ENV{GRUN_PRIORITY}+0 if !$opt{priority} && $ENV{GRUN_PRIORITY} >= 1;
$opt{priority} = $conf{default_priority} if !$opt{priority};
# convert memory to kB
if ($opt{memory}) {
if ($opt{memory} =~ /kb?$/i) {
# internal memory unit is kB
} elsif ($opt{memory} =~ /gb?$/i) {
# convert gB to kB
$opt{memory} *= 1000000;
} else {
# convert mB to kB
$opt{memory} *= 1000;
}
} else {
$opt{memory} = $conf{default_memory};
}
# no socket io unless waiting
if (!$opt{wait}) {
delete $opt{io};
}
# copy env
if ($env eq '*' || ($conf{env} && ($conf{env}->[0] eq '*')) ) {
for (keys %ENV) {
if (! /^_|LS_COLORS/) {
$opt{env}->{$_} = $ENV{$_};
}
}
} else {
for (@{$conf{env}}) {
$opt{env}->{$_} = $ENV{$_} if defined $ENV{$_};
}
for (split /\s+/, $env) {
$opt{env}->{$_} = $ENV{$_} if defined $ENV{$_};
}
}
$opt{user} = getpwuid($>);
$opt{group}=$);
$opt{umask} = umask();
$opt{env}->{USER} = $opt{user};
if (!$opt{wait}) {
open STDERR, ">&STDOUT";
}
$opt{memory} = $opt{memory} ? $opt{memory} : $conf{default_memory};
$opt{cpus} = $opt{cpus} ? $opt{cpus} : 1;
for (@metrics) {
if ($conf{"default_$_"}) {
$opt{$_} = $opt{$_} ? $opt{$_} : $conf{"default_$_"};
}
}
if ($verbose) {
printf STDERR "Memory: %d\n", $opt{memory};
printf STDERR "CPUs: %d\n", $opt{cpus};
printf STDERR "Hosts: %s\n", $opt{hosts} if $opt{hosts};
for ((@metrics,@labels)) {
printf STDERR proper($_) . ": %s\n", $opt{param}->{$_} ? $opt{param}->{$_} : 1;
}
}
if ($opt{jobx}) {
if ($opt{jobx} =~ /^\d/) {
die "External job id's should start with a non-numeric\n";
}
}
my %info;
sub client_sigh {
my $signame = shift;
$SIG{INT} = undef;
$SIG{TERM} = undef;
$SIG{PIPE} = undef;
if ($info{jid}||$info{guid}) {
if (!($signame eq 'PIPE')) {
print STDERR "Aborting command, sending jkill for $info{jid}\n";
}
my $code = $signame eq 'INT' ? 2 : $signame eq 'PIPE' ? 13 : 15;
my $err = kill_job(jid=>$info{jid}, guid=>$opt{guid}, sig=>$code, termio=>1);
if (!($signame eq 'PIPE')) {
if (!defined($err) && $@) {
warn $@,"\n";
}
}
exit 128+$code;
} else {
die "Interrupted before job sent\n";
}
};
# for testing -M make
exit 0 if $opt{noexec};
$SIG{INT} = \&client_sigh;
$SIG{TERM} = \&client_sigh;
$SIG{PIPE} = \&client_sigh;
$opt{cmd} = \@cmd;
$opt{hard_factor} = $conf{hard_factor};
$opt{frompid} = $$;
$opt{guid} = $opt{jobx} ? $opt{jobx} : create_guid();
$opt{syncdirs} = [keys(%sync_before)];
%info = waitmsg($conf{master}, $conf{master_port}, 'run', \%opt);
if (!%info) {
die ($@ ? $@ : "No response to 'run'") . "\n";
}
if ($info{error}) {
print STDERR $info{error}, "\n";
exit -1;
}
if (!$info{jid}) {
print STDERR "Failed to submit job", "\n";
exit -1;
}
my $save_jid = $info{jid};
$0 = "GRUN:$save_jid";
if ($verbose) {
printf STDERR "Job_ID: $info{jid}\n";
}
if ($info{already}) {
if ($opt{"wait-exists"}) {
my ($res) = waitmsg($conf{master},$conf{master_port}, "jwait", $info{jid});
my $st;
if ($res && defined $res->{status}) {
print "Job $_ status $res->{status}\n";
$st = $res->{status} if $res->{status};
} else {
print "Job $_ status $STATUS_UNKNOWN\n";
$st = $STATUS_UNKNOWN;
}
exit $st;
} else {
print STDOUT "Job_ID: $info{jid} \n" if !$verbose;
printf STDERR "Already running job named $opt{jobx}, try grun -q wait JOB\n";
exit -1;
}
}
if ($opt{wait}) {
# wait for a job ip
while (!defined($info{ip})) {
my %tmp = waitmsg_retry($conf{retry_secs}*1000, $conf{master}, $conf{master_port}, 'jinfo', $info{jid});
if ($tmp{error}) {
print STDERR $tmp{error}, "\n";
exit $tmp{status} != 0 ? $tmp{status} : -1;
}
if (!defined($tmp{ip})) {
xlog("error","Had to retry after a retry... BUG in job $save_jid\n");
sleep(5);
} else {
%info=%tmp;
}
}
my $host = $info{hostname} ? $info{hostname} : $info{ip}; # support old ver which didn't have hostname
if ($verbose) {
printf STDERR "Host: %s\n", $host;
}
# look at all the work you can avoid if you don't wait
my ($stat, $err, $diderr);
# connect to executing node directly and ask for stderr, stdout, and status based on job id
if (defined $info{status}) {
$stat=$info{status};
$err=$info{error};
}
while (!defined $stat && !defined $err) {
# shadow watcher....
if ($info{ip}=~/^\d/) {
if ($opt{io} && !($opt{err} && $opt{out}) ) {
($stat, $err, $diderr) = waitio($info{ip}, $info{port}, $info{jid}, \%opt);
} else {
my ($key, $dat) = waitmsg_retry($conf{retry_secs}*1000, $info{ip}, $info{port}, 'xstat', $info{jid});
$stat=$dat->{status};
$err=$dat->{error};
}
if ($stat == 65280 && !$err) {
print STDERR "Error: [$host] Command returned -1\n";
}
} else {
$stat=$STATUS_UNKNOWN;
$err="Error in grun protocol (ip=$info{ip}), unknown status!\n";
}
sleep 5 if (!defined $stat && !defined $err);
}
# send this command into the ether...if exec doesn't get it, clean up after timeout
if ($opt{io}||$opt{wait}) {
if ($info{ip}=~/^\d/) {
sendcmd($info{ip}, $info{port}, 'xclean', $info{jid});
}
}
if ($stat == 11) {
$err = 'Segmentation fault';
}
if ($stat > 127) {
# shift... but if that doesn't get you anything, set to -1 (unknown error)
$stat = $stat>>8;
$stat = -1 if !$stat;
}
syncafter();
if ($err) {
print STDERR "[$host] $err", "\n";
$stat = -1 if !$stat; # unknown error if undefined
} else {
if ($stat != 0 && ! $diderr) {
print STDERR "Error: [$host] Command returned $stat\n";
}
}
unlink("$ENV{HOME}/.grun/jobx/$opt{jobx}") if $opt{jobx};
exit($stat);
} else {
# aah... nicer
print STDOUT "Job_ID: $info{jid} \n" if !$verbose;
}
}
### nfs sync support
sub syncdirs {
for (@_) {
syncdir($_);
}
}
sub syncafter {
%sync_already = ();
return unless $conf{nfs_sync};
syncdirs(keys(%sync_after));
}
sub add_syncdir_after {
my ($d) = @_;
return unless $conf{nfs_sync};
$sync_after{abs_path($d)}=1;
}
sub add_syncdir_before {
my ($d) = @_;
return unless $conf{nfs_sync};
$sync_before{abs_path($d)}=1;
}
sub add_syncfile_before {
my ($f) = @_;
return unless $conf{nfs_sync};
add_syncdir_before(-d $f ? $f : dirname($f));
}
sub add_syncfile_after {
my ($f) = @_;
return unless $conf{nfs_sync};
add_syncdir_after(-d $f ? $f : dirname($f));
}
sub syncfile {
my ($f) = @_;
return unless $conf{nfs_sync};
syncdir(-d $f ? $f : dirname($f));
}
# this refreshes the lookupcasche, which is an issue when running scripts back to back on multiple nodes using NFS
sub syncdir {
my ($d) = @_;
my $tmp;
return if $sync_already{$d};
opendir($tmp,$d);
closedir($tmp);
}
sub readsocks {
my $did;
# identity & data received
my $cnt;
if (!$router) {
xlog("debug", "Readsocks called with no router: " . Carp::longmess() );
return;
}
while (my $id= zmq_recvmsg($router,ZMQ_NOBLOCK)) {
++$cnt;
$did=1;
$id = zmq_msg_data($id);
if (zmq_getsockopt($router,ZMQ_RCVMORE)) {
# print "getting sep\n";
my $sep = zmq_recvmsg($router);
}
if (zmq_getsockopt($router,ZMQ_RCVMORE)) {
# print "getting data\n";
my $msg = zmq_recvmsg($router);
my $data = zmq_msg_data($msg);
my @resp = process_message($data, $id);
if (@resp) {
print("Got resp: @resp\n");
replymsg($id, @resp);
} else {
# warn("No resp for $data\n");
}
}
while (zmq_getsockopt($router,ZMQ_RCVMORE)) {
print("Discarding excess multipart data!\n");
}
if ($cnt > 100000) {
xlog("error", "Getting flooded with messages");
last;
}
}
return $did;
}
sub jhiststat {
my ($jid) = @_;
my $jhistfile=jhistpath($jid);
if (-e $jhistfile) {
# job is toast... but maybe some streams are waiting
my $job=unpack_file($jhistfile);
delete $job->{env};
$job->{host}="n/a" if !$job->{host} && !defined $job->{status};
$job->{ip}=host2ip($job->{host}) if !$job->{ip} && ! defined $job->{status};
# needs ip!
$job->{ip}="n/a" if defined $job->{status} && ! $job->{ip};
$job->{hostname}=$job->{host};
return $job;
}
return undef;
}
sub replymsg {
my ($id, @resp) = @_;
if (debugging) {
my $hid=unpack("h*",$id);
xlog("debug", "Reply ($hid) " . packdump(\@resp) . "\n") if $conf{trace};
}
zmq_send($router, $id, length($id), ZMQ_SNDMORE);
zmq_send($router, "", 0, ZMQ_SNDMORE);
zmq_send($router, packref(\@resp));
}
sub selfcmd {
my $cmd = packcmd(@_);
process_message($cmd, undef);
}
my $debugzid;
sub process_message {
my ($src_data, $zid) = @_;
my ($ip, $trace, $cmd, @args) = unpackcmd($src_data);
$trace=$conf{trace} if !$trace;
if (debugging|$trace) {
my $hid=defined($zid) ? unpack("h*",$zid) : "";
xlog($trace ? "trace" : "debug", "Received command ($hid) '$cmd' : $src_data\n") if $trace;
}
return ('error'=>$@) if ($@);
if ($cmd eq 'xcmd') {
# these commands 'query or interfere' with normal running of the server
# they are initiated by a user
# they are limped together like this for basically no reason
if ($args[0] eq 'relo') {
# reread config... maybe rebind stuff too
xlog("note", "Reload from remote command (ARGS: @ORIG_ARGV)");
eval{init();};
if ($@) {
return "Error: $conf{config}, $@";
} else {
return "Ok, reloaded from $conf{config}";
}
} elsif ($args[0] eq 'term') {
xlog("note", "Shutdown from remote command");
$quit = 1;
return 'Ok, shutdown initiated';
} elsif ($args[0] eq 'rest') {
xlog("note", "Restarting from remote command ($GRUN_PATH @ORIG_ARGV)");
$quit = 1;
zmq_unbind($router, "tcp://$conf{bind}:$conf{port}");
if (!fork) {
zmq_fork_undef();
exec($GRUN_PATH, @ORIG_ARGV);
}
return "Ok, restart initiated";
} elsif ($args[0] eq 'stat') {
shift @args;
return shownodes(@args);
} elsif ($args[0] eq 'hist') {
shift @args;
# if (@args && (@args > 1 || $args[0] !~ /^\d+$/)) {
# fork... do it in parallel
# forkandgo($zid, \&showhist, @args);
# return();
# } else {
# inline... do it now, less expensive than fork!
return showhist(@args);
# }
} elsif ($args[0] eq 'conf') {
return showconf();
} elsif ($args[0] eq 'memo') {
return showmem();
} elsif ($args[0] eq 'jobs') {
shift @args;
return showjobs(@args);
# } elsif ($args[0] eq 'file') {
# shift @args;
# xlog("note", "Sending file [@args] to remote");
# return ($SOCK_FILE, @args);
} else {
return "Error: unknown xcmd '$args[0]'";
}
} elsif ($cmd eq 'frep') {
# warn("router is $router, zid is $debugzid\n");
my ($dat) = @args;
if ($dat->{zid}) {
xlog("debug", "Sending response to $dat->{zid}");
replymsg(pack("h*",$dat->{zid}),$dat->{out},$dat->{more});
#replymsg($debugzid,$dat->{out});
}
} elsif ($cmd eq 'node') {
# this is the 'node ping'
if (ref($args[0]) eq 'HASH') { # bit of validation
my $node = $args[0];
$node->{ip}=$ip unless $node->{ip};
$ip=$node->{ip};
if ($ip) {
my $file = "$conf{spool}/nodes/$ip.reg";
open(F, ">$file") || return("Error: can't create $file : $!");
print F packfile($node);
close F;
# also stick in memory
if (!$nodes{$ip}) {
xlog("note", "Registering node $ip:$node->{port} $node->{hostname}");
}
$node->{ping} = time();
$node->{ex_ping} = $nodes{$ip}->{ping};