-
Notifications
You must be signed in to change notification settings - Fork 5
/
Grun.pm
114 lines (95 loc) · 2.51 KB
/
Grun.pm
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
package Grun;
use Exporter;
use JSON::XS;
use File::Temp qw(tempfile);
use Carp;
our @ISA=qw(Exporter);
our @EXPORT=qw(grun grun_wait grun_kill);
my %JTMP;
sub grun_wait {
my ($jid) = @_;
my $ret = system("grun -q wait $jid 2>&1");
if ($ret) {
$ret =(($ret<<8)&255) if $ret > 255;
$ret = 1 if !$ret;
}
open (my $fh, '<', $JTMP{$jid} . ".out");
local $/=undef;
my $out=<$fh>;
close $fh;
# copy pasted from below... make a function!
$out=decode_json($out);
if ($out->{err}) {
# remote eval died... so we do too
die $out->{err};
};
if (wantarray) {
# return array
return @{$out->{ret}};
} else {
# return single value
return $out->{ret}->[0];
}
}
sub grun {
# this is only required on the execution node....so don't use it everywhere if not needed
require B::RecDeparse;
# at most 9 levels deep
my $deparse=B::RecDeparse->new(level=>9);
my ($op, $func, @args) = @_;
croak("usage: grun({options}, \\\&function, \@args)") unless ref($func) eq 'CODE' && defined(wantarray);
($fh, $filename) = tempfile(".grun.XXXXXX", DIR=>".");
my $code=$deparse->coderef2text($func);
my $def=encode_json({code=>$code, args=>\@args, wantarray=>wantarray});
print $fh $def;
close $fh;
my $opts;
if ($op->{nowait}) {
$opts = "-o $filename.out -nowait";
}
my $cmd = "grun $opts $^X -MGrun -e \"\\\"Grun::exec('$filename')\\\"\"";
# get output (json string)
my $out = `$cmd`;
if ($op->{nowait}) {
my ($jid) = $out =~ /job_id.*:\s*(\d+)/i;
$JTMP{$jid}=$filename;
return $jid;
}
$out=decode_json($out);
if ($out->{err}) {
# remote eval died... so we do too
die $out->{err};
};
if (wantarray) {
# return array
return @{$out->{ret}};
} else {
# return single value
return $out->{ret}->[0];
}
}
sub exec {
my ($fil) = @_;
local $/ = undef;
open( my $fh, '<', $fil );
my $json = <$fh>;
close $fh;
my $hash=decode_json($json);
my $sub = "sub " . $hash->{code};
$sub = eval($sub);
my (@ret, $ret, $err);
eval {
if ($hash->{wantarray}) {
@ret=&{$sub}(@{$hash->{args}});
} else {
# scalar context
$ret=&{$sub}(@{$hash->{args}});
@ret=(($ret));
}
};
my $err=$@;
my $out=encode_json({ret=>\@ret, err=>$err});
# return output via STDOUT
print $out;
}
1;