2 # -*- mode: perl; perl-indent-level: 2; indent-tabs-mode: nil; -*-
6 crunch-job: Execute job steps, save snapshots as requested, collate output.
10 Obtain job details from Arvados, run tasks on compute nodes (typically
11 invoked by scheduler on controller):
13 crunch-job --job x-y-z --git-dir /path/to/repo/.git
15 Obtain job details from command line, run tasks on local machine
16 (typically invoked by application or developer on VM):
18 crunch-job --job '{"script_version":"/path/to/working/tree","script":"scriptname",...}'
20 crunch-job --job '{"repository":"https://github.com/curoverse/arvados.git","script_version":"master","script":"scriptname",...}'
28 If the job is already locked, steal the lock and run it anyway.
32 Path to a .git directory (or a git URL) where the commit given in the
33 job's C<script_version> attribute is to be found. If this is I<not>
34 given, the job's C<repository> attribute will be used.
38 Arvados API authorization token to use during the course of the job.
42 Do not clear per-job/task temporary directories during initial job
43 setup. This can speed up development and debugging when running jobs
48 UUID of the job to run, or a JSON-encoded job resource without a
49 UUID. If the latter is given, a new job object will be created.
53 =head1 RUNNING JOBS LOCALLY
55 crunch-job's log messages appear on stderr along with the job tasks'
56 stderr streams. The log is saved in Keep at each checkpoint and when
59 If the job succeeds, the job's output locator is printed on stdout.
61 While the job is running, the following signals are accepted:
65 =item control-C, SIGINT, SIGQUIT
67 Save a checkpoint, terminate any job tasks that are running, and stop.
71 Save a checkpoint and continue.
75 Refresh node allocation (i.e., check whether any nodes have been added
76 or unallocated) and attributes of the Job record that should affect
77 behavior (e.g., cancel job if cancelled_at becomes non-nil).
85 use POSIX ':sys_wait_h';
86 use POSIX qw(strftime);
87 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
89 use Digest::MD5 qw(md5_hex);
95 use File::Path qw( make_path remove_tree );
97 use constant EX_TEMPFAIL => 75;
99 $ENV{"TMPDIR"} ||= "/tmp";
100 unless (defined $ENV{"CRUNCH_TMP"}) {
101 $ENV{"CRUNCH_TMP"} = $ENV{"TMPDIR"} . "/crunch-job";
102 if ($ENV{"USER"} ne "crunch" && $< != 0) {
103 # use a tmp dir unique for my uid
104 $ENV{"CRUNCH_TMP"} .= "-$<";
108 # Create the tmp directory if it does not exist
109 if ( ! -d $ENV{"CRUNCH_TMP"} ) {
110 make_path $ENV{"CRUNCH_TMP"} or die "Failed to create temporary working directory: " . $ENV{"CRUNCH_TMP"};
113 $ENV{"JOB_WORK"} = $ENV{"CRUNCH_TMP"} . "/work";
114 $ENV{"CRUNCH_INSTALL"} = "$ENV{CRUNCH_TMP}/opt";
115 $ENV{"CRUNCH_WORK"} = $ENV{"JOB_WORK"}; # deprecated
116 mkdir ($ENV{"JOB_WORK"});
124 GetOptions('force-unlock' => \$force_unlock,
125 'git-dir=s' => \$git_dir,
126 'job=s' => \$jobspec,
127 'job-api-token=s' => \$job_api_token,
128 'no-clear-tmp' => \$no_clear_tmp,
129 'resume-stash=s' => \$resume_stash,
132 if (defined $job_api_token) {
133 $ENV{ARVADOS_API_TOKEN} = $job_api_token;
136 my $have_slurm = exists $ENV{SLURM_JOBID} && exists $ENV{SLURM_NODELIST};
142 $main::ENV{CRUNCH_DEBUG} = 1;
146 $main::ENV{CRUNCH_DEBUG} = 0;
151 my $arv = Arvados->new('apiVersion' => 'v1');
159 my $User = retry_op(sub { $arv->{'users'}->{'current'}->execute; });
161 if ($jobspec =~ /^[-a-z\d]+$/)
163 # $jobspec is an Arvados UUID, not a JSON job specification
164 $Job = retry_op(sub {
165 $arv->{'jobs'}->{'get'}->execute('uuid' => $jobspec);
167 if (!$force_unlock) {
168 # Claim this job, and make sure nobody else does
169 eval { retry_op(sub {
170 # lock() sets is_locked_by_uuid and changes state to Running.
171 $arv->{'jobs'}->{'lock'}->execute('uuid' => $Job->{'uuid'})
174 Log(undef, "Error while locking job, exiting ".EX_TEMPFAIL);
181 $Job = JSON::decode_json($jobspec);
185 map { croak ("No $_ specified") unless $Job->{$_} }
186 qw(script script_version script_parameters);
189 $Job->{'is_locked_by_uuid'} = $User->{'uuid'};
190 $Job->{'started_at'} = gmtime;
191 $Job->{'state'} = 'Running';
193 $Job = retry_op(sub { $arv->{'jobs'}->{'create'}->execute('job' => $Job); });
195 $job_id = $Job->{'uuid'};
197 my $keep_logfile = $job_id . '.log.txt';
198 log_writer_start($keep_logfile);
200 $Job->{'runtime_constraints'} ||= {};
201 $Job->{'runtime_constraints'}->{'max_tasks_per_node'} ||= 0;
202 my $max_ncpus = $Job->{'runtime_constraints'}->{'max_tasks_per_node'};
205 Log (undef, "check slurm allocation");
208 # Should use $ENV{SLURM_TASKS_PER_NODE} instead of sinfo? (eg. "4(x3),2,4(x2)")
212 my $localcpus = 0 + `grep -cw ^processor /proc/cpuinfo` || 1;
213 push @sinfo, "$localcpus localhost";
215 if (exists $ENV{SLURM_NODELIST})
217 push @sinfo, `sinfo -h --format='%c %N' --nodes=\Q$ENV{SLURM_NODELIST}\E`;
221 my ($ncpus, $slurm_nodelist) = split;
222 $ncpus = $max_ncpus if $max_ncpus && $ncpus > $max_ncpus;
225 while ($slurm_nodelist =~ s/^([^\[,]+?(\[.*?\])?)(,|$)//)
228 if ($nodelist =~ /\[((\d+)(-(\d+))?(,(\d+)(-(\d+))?)*)\]/)
231 foreach (split (",", $ranges))
244 push @nodelist, map {
246 $n =~ s/\[[-,\d]+\]/$_/;
253 push @nodelist, $nodelist;
256 foreach my $nodename (@nodelist)
258 Log (undef, "node $nodename - $ncpus slots");
259 my $node = { name => $nodename,
263 foreach my $cpu (1..$ncpus)
265 push @slot, { node => $node,
269 push @node, @nodelist;
274 # Ensure that we get one jobstep running on each allocated node before
275 # we start overloading nodes with concurrent steps
277 @slot = sort { $a->{cpu} <=> $b->{cpu} } @slot;
280 $Job->update_attributes(
281 'tasks_summary' => { 'failed' => 0,
286 Log (undef, "start");
287 $SIG{'INT'} = sub { $main::please_freeze = 1; };
288 $SIG{'QUIT'} = sub { $main::please_freeze = 1; };
289 $SIG{'TERM'} = \&croak;
290 $SIG{'TSTP'} = sub { $main::please_freeze = 1; };
291 $SIG{'ALRM'} = sub { $main::please_info = 1; };
292 $SIG{'CONT'} = sub { $main::please_continue = 1; };
293 $SIG{'HUP'} = sub { $main::please_refresh = 1; };
295 $main::please_freeze = 0;
296 $main::please_info = 0;
297 $main::please_continue = 0;
298 $main::please_refresh = 0;
299 my $jobsteps_must_output_keys = 0; # becomes 1 when any task outputs a key
301 grep { $ENV{$1} = $2 if /^(NOCACHE.*?)=(.*)/ } split ("\n", $$Job{knobs});
302 $ENV{"CRUNCH_JOB_UUID"} = $job_id;
303 $ENV{"JOB_UUID"} = $job_id;
306 my @jobstep_todo = ();
307 my @jobstep_done = ();
308 my @jobstep_tomerge = ();
309 my $jobstep_tomerge_level = 0;
311 my $squeue_kill_checked;
312 my $output_in_keep = 0;
313 my $latest_refresh = scalar time;
317 if (defined $Job->{thawedfromkey})
319 thaw ($Job->{thawedfromkey});
323 my $first_task = retry_op(sub {
324 $arv->{'job_tasks'}->{'create'}->execute('job_task' => {
325 'job_uuid' => $Job->{'uuid'},
331 push @jobstep, { 'level' => 0,
333 'arvados_task' => $first_task,
335 push @jobstep_todo, 0;
341 must_lock_now("$ENV{CRUNCH_TMP}/.lock", "a job is already running here.");
348 $build_script = <DATA>;
350 my $nodelist = join(",", @node);
352 if (!defined $no_clear_tmp) {
353 # Clean out crunch_tmp/work, crunch_tmp/opt, crunch_tmp/src*
354 Log (undef, "Clean work dirs");
356 my $cleanpid = fork();
359 srun (["srun", "--nodelist=$nodelist", "-D", $ENV{'TMPDIR'}],
360 ['bash', '-c', 'if mount | grep -q $JOB_WORK/; then for i in $JOB_WORK/*keep $CRUNCH_TMP/task/*.keep; do /bin/fusermount -z -u $i; done; fi; sleep 1; rm -rf $JOB_WORK $CRUNCH_INSTALL $CRUNCH_TMP/task $CRUNCH_TMP/src*']);
365 last if $cleanpid == waitpid (-1, WNOHANG);
366 freeze_if_want_freeze ($cleanpid);
367 select (undef, undef, undef, 0.1);
369 Log (undef, "Cleanup command exited ".exit_status_s($?));
374 if (!defined $git_dir && $Job->{'script_version'} =~ m{^/}) {
375 # If script_version looks like an absolute path, *and* the --git-dir
376 # argument was not given -- which implies we were not invoked by
377 # crunch-dispatch -- we will use the given path as a working
378 # directory instead of resolving script_version to a git commit (or
379 # doing anything else with git).
380 $ENV{"CRUNCH_SRC_COMMIT"} = $Job->{'script_version'};
381 $ENV{"CRUNCH_SRC"} = $Job->{'script_version'};
384 # Resolve the given script_version to a git commit sha1. Also, if
385 # the repository is remote, clone it into our local filesystem: this
386 # ensures "git archive" will work, and is necessary to reliably
387 # resolve a symbolic script_version like "master^".
388 $ENV{"CRUNCH_SRC"} = "$ENV{CRUNCH_TMP}/src";
390 Log (undef, "Looking for version ".$Job->{script_version}." from repository ".$Job->{repository});
392 $ENV{"CRUNCH_SRC_COMMIT"} = $Job->{script_version};
394 # If we're running under crunch-dispatch, it will have already
395 # pulled the appropriate source tree into its own repository, and
396 # given us that repo's path as $git_dir.
398 # If we're running a "local" job, we might have to fetch content
399 # from a remote repository.
401 # (Currently crunch-dispatch gives a local path with --git-dir, but
402 # we might as well accept URLs there too in case it changes its
404 my $repo = $git_dir || $Job->{'repository'};
406 # Repository can be remote or local. If remote, we'll need to fetch it
407 # to a local dir before doing `git log` et al.
410 if ($repo =~ m{://|^[^/]*:}) {
411 # $repo is a git url we can clone, like git:// or https:// or
412 # file:/// or [user@]host:repo.git. Note "user/name@host:foo" is
413 # not recognized here because distinguishing that from a local
414 # path is too fragile. If you really need something strange here,
415 # use the ssh:// form.
416 $repo_location = 'remote';
417 } elsif ($repo =~ m{^\.*/}) {
418 # $repo is a local path to a git index. We'll also resolve ../foo
419 # to ../foo/.git if the latter is a directory. To help
420 # disambiguate local paths from named hosted repositories, this
421 # form must be given as ./ or ../ if it's a relative path.
422 if (-d "$repo/.git") {
423 $repo = "$repo/.git";
425 $repo_location = 'local';
427 # $repo is none of the above. It must be the name of a hosted
429 my $arv_repo_list = retry_op(sub {
430 $arv->{'repositories'}->{'list'}->execute(
431 'filters' => [['name','=',$repo]]);
433 my @repos_found = @{$arv_repo_list->{'items'}};
434 my $n_found = $arv_repo_list->{'serverResponse'}->{'items_available'};
436 Log(undef, "Repository '$repo' -> "
437 . join(", ", map { $_->{'uuid'} } @repos_found));
440 croak("Error: Found $n_found repositories with name '$repo'.");
442 $repo = $repos_found[0]->{'fetch_url'};
443 $repo_location = 'remote';
445 Log(undef, "Using $repo_location repository '$repo'");
446 $ENV{"CRUNCH_SRC_URL"} = $repo;
448 # Resolve given script_version (we'll call that $treeish here) to a
449 # commit sha1 ($commit).
450 my $treeish = $Job->{'script_version'};
452 if ($repo_location eq 'remote') {
453 # We minimize excess object-fetching by re-using the same bare
454 # repository in CRUNCH_TMP/.git for multiple crunch-jobs -- we
455 # just keep adding remotes to it as needed.
456 my $local_repo = $ENV{'CRUNCH_TMP'}."/.git";
457 my $gitcmd = "git --git-dir=\Q$local_repo\E";
459 # Set up our local repo for caching remote objects, making
461 if (!-d $local_repo) {
462 make_path($local_repo) or croak("Error: could not create $local_repo");
464 # This works (exits 0 and doesn't delete fetched objects) even
465 # if $local_repo is already initialized:
466 `$gitcmd init --bare`;
468 croak("Error: $gitcmd init --bare exited ".exit_status_s($?));
471 # If $treeish looks like a hash (or abbrev hash) we look it up in
472 # our local cache first, since that's cheaper. (We don't want to
473 # do that with tags/branches though -- those change over time, so
474 # they should always be resolved by the remote repo.)
475 if ($treeish =~ /^[0-9a-f]{7,40}$/s) {
476 # Hide stderr because it's normal for this to fail:
477 my $sha1 = `$gitcmd rev-list -n1 ''\Q$treeish\E 2>/dev/null`;
479 # Careful not to resolve a branch named abcdeff to commit 1234567:
480 $sha1 =~ /^$treeish/ &&
481 $sha1 =~ /^([0-9a-f]{40})$/s) {
483 Log(undef, "Commit $commit already present in $local_repo");
487 if (!defined $commit) {
488 # If $treeish isn't just a hash or abbrev hash, or isn't here
489 # yet, we need to fetch the remote to resolve it correctly.
491 # First, remove all local heads. This prevents a name that does
492 # not exist on the remote from resolving to (or colliding with)
493 # a previously fetched branch or tag (possibly from a different
495 remove_tree("$local_repo/refs/heads", {keep_root => 1});
497 Log(undef, "Fetching objects from $repo to $local_repo");
498 `$gitcmd fetch --no-progress --tags ''\Q$repo\E \Q+refs/heads/*:refs/heads/*\E`;
500 croak("Error: `$gitcmd fetch` exited ".exit_status_s($?));
504 # Now that the data is all here, we will use our local repo for
505 # the rest of our git activities.
509 my $gitcmd = "git --git-dir=\Q$repo\E";
510 my $sha1 = `$gitcmd rev-list -n1 ''\Q$treeish\E`;
511 unless ($? == 0 && $sha1 =~ /^([0-9a-f]{40})$/) {
512 croak("`$gitcmd rev-list` exited "
514 .", '$treeish' not found. Giving up.");
517 Log(undef, "Version $treeish is commit $commit");
519 if ($commit ne $Job->{'script_version'}) {
520 # Record the real commit id in the database, frozentokey, logs,
521 # etc. -- instead of an abbreviation or a branch name which can
522 # become ambiguous or point to a different commit in the future.
523 if (!$Job->update_attributes('script_version' => $commit)) {
524 croak("Error: failed to update job's script_version attribute");
528 $ENV{"CRUNCH_SRC_COMMIT"} = $commit;
529 $git_archive = `$gitcmd archive ''\Q$commit\E`;
531 croak("Error: $gitcmd archive exited ".exit_status_s($?));
535 if (!defined $git_archive) {
536 Log(undef, "Skip install phase (no git archive)");
538 Log(undef, "Warning: This probably means workers have no source tree!");
542 Log(undef, "Run install script on all workers");
544 my @srunargs = ("srun",
545 "--nodelist=$nodelist",
546 "-D", $ENV{'TMPDIR'}, "--job-name=$job_id");
547 my @execargs = ("sh", "-c",
548 "mkdir -p $ENV{CRUNCH_INSTALL} && cd $ENV{CRUNCH_TMP} && perl -");
550 my $installpid = fork();
551 if ($installpid == 0)
553 srun (\@srunargs, \@execargs, {}, $build_script . $git_archive);
558 last if $installpid == waitpid (-1, WNOHANG);
559 freeze_if_want_freeze ($installpid);
560 select (undef, undef, undef, 0.1);
562 Log (undef, "Install script exited ".exit_status_s($?));
567 # Grab our lock again (we might have deleted and re-created CRUNCH_TMP above)
568 must_lock_now("$ENV{CRUNCH_TMP}/.lock", "a job is already running here.");
571 # If this job requires a Docker image, install that.
572 my $docker_bin = "/usr/bin/docker.io";
573 my ($docker_locator, $docker_stream, $docker_hash);
574 if ($docker_locator = $Job->{docker_image_locator}) {
575 ($docker_stream, $docker_hash) = find_docker_image($docker_locator);
578 croak("No Docker image hash found from locator $docker_locator");
580 $docker_stream =~ s/^\.//;
581 my $docker_install_script = qq{
582 if ! $docker_bin images -q --no-trunc | grep -qxF \Q$docker_hash\E; then
583 arv-get \Q$docker_locator$docker_stream/$docker_hash.tar\E | $docker_bin load
586 my $docker_pid = fork();
587 if ($docker_pid == 0)
589 srun (["srun", "--nodelist=" . join(',', @node)],
590 ["/bin/sh", "-ec", $docker_install_script]);
595 last if $docker_pid == waitpid (-1, WNOHANG);
596 freeze_if_want_freeze ($docker_pid);
597 select (undef, undef, undef, 0.1);
601 croak("Installing Docker image from $docker_locator exited "
606 foreach (qw (script script_version script_parameters runtime_constraints))
610 (ref($Job->{$_}) ? JSON::encode_json($Job->{$_}) : $Job->{$_}));
612 foreach (split (/\n/, $Job->{knobs}))
614 Log (undef, "knob " . $_);
619 $main::success = undef;
625 my $thisround_succeeded = 0;
626 my $thisround_failed = 0;
627 my $thisround_failed_multiple = 0;
629 @jobstep_todo = sort { $jobstep[$a]->{level} <=> $jobstep[$b]->{level}
630 or $a <=> $b } @jobstep_todo;
631 my $level = $jobstep[$jobstep_todo[0]]->{level};
632 Log (undef, "start level $level");
637 my @freeslot = (0..$#slot);
640 my $progress_is_dirty = 1;
641 my $progress_stats_updated = 0;
643 update_progress_stats();
648 for (my $todo_ptr = 0; $todo_ptr <= $#jobstep_todo; $todo_ptr ++)
650 my $id = $jobstep_todo[$todo_ptr];
651 my $Jobstep = $jobstep[$id];
652 if ($Jobstep->{level} != $level)
657 pipe $reader{$id}, "writer" or croak ($!);
658 my $flags = fcntl ($reader{$id}, F_GETFL, 0) or croak ($!);
659 fcntl ($reader{$id}, F_SETFL, $flags | O_NONBLOCK) or croak ($!);
661 my $childslot = $freeslot[0];
662 my $childnode = $slot[$childslot]->{node};
663 my $childslotname = join (".",
664 $slot[$childslot]->{node}->{name},
665 $slot[$childslot]->{cpu});
666 my $childpid = fork();
669 $SIG{'INT'} = 'DEFAULT';
670 $SIG{'QUIT'} = 'DEFAULT';
671 $SIG{'TERM'} = 'DEFAULT';
673 foreach (values (%reader))
677 fcntl ("writer", F_SETFL, 0) or croak ($!); # no close-on-exec
678 open(STDOUT,">&writer");
679 open(STDERR,">&writer");
684 delete $ENV{"GNUPGHOME"};
685 $ENV{"TASK_UUID"} = $Jobstep->{'arvados_task'}->{'uuid'};
686 $ENV{"TASK_QSEQUENCE"} = $id;
687 $ENV{"TASK_SEQUENCE"} = $level;
688 $ENV{"JOB_SCRIPT"} = $Job->{script};
689 while (my ($param, $value) = each %{$Job->{script_parameters}}) {
690 $param =~ tr/a-z/A-Z/;
691 $ENV{"JOB_PARAMETER_$param"} = $value;
693 $ENV{"TASK_SLOT_NODE"} = $slot[$childslot]->{node}->{name};
694 $ENV{"TASK_SLOT_NUMBER"} = $slot[$childslot]->{cpu};
695 $ENV{"TASK_WORK"} = $ENV{"CRUNCH_TMP"}."/task/$childslotname";
696 $ENV{"HOME"} = $ENV{"TASK_WORK"};
697 $ENV{"TASK_KEEPMOUNT"} = $ENV{"TASK_WORK"}.".keep";
698 $ENV{"TASK_TMPDIR"} = $ENV{"TASK_WORK"}; # deprecated
699 $ENV{"CRUNCH_NODE_SLOTS"} = $slot[$childslot]->{node}->{ncpus};
700 $ENV{"PATH"} = $ENV{"CRUNCH_INSTALL"} . "/bin:" . $ENV{"PATH"};
706 "--nodelist=".$childnode->{name},
707 qw(-n1 -c1 -N1 -D), $ENV{'TMPDIR'},
708 "--job-name=$job_id.$id.$$",
710 my $build_script_to_send = "";
712 "if [ -e $ENV{TASK_WORK} ]; then rm -rf $ENV{TASK_WORK}; fi; "
713 ."mkdir -p $ENV{CRUNCH_TMP} $ENV{JOB_WORK} $ENV{TASK_WORK} $ENV{TASK_KEEPMOUNT} "
714 ."&& cd $ENV{CRUNCH_TMP} ";
717 $build_script_to_send = $build_script;
721 $command .= "&& exec arv-mount --by-id --allow-other $ENV{TASK_KEEPMOUNT} --exec ";
724 my $cidfile = "$ENV{CRUNCH_TMP}/$ENV{TASK_UUID}.cid";
725 $command .= "crunchstat -cgroup-root=/sys/fs/cgroup -cgroup-parent=docker -cgroup-cid=$cidfile -poll=10000 ";
726 $command .= "$docker_bin run --rm=true --attach=stdout --attach=stderr --attach=stdin -i --user=crunch --cidfile=$cidfile --sig-proxy ";
728 # Dynamically configure the container to use the host system as its
729 # DNS server. Get the host's global addresses from the ip command,
730 # and turn them into docker --dns options using gawk.
732 q{$(ip -o address show scope global |
733 gawk 'match($4, /^([0-9\.:]+)\//, x){print "--dns", x[1]}') };
735 # The source tree and $destdir directory (which we have
736 # installed on the worker host) are available in the container,
737 # under the same path.
738 $command .= "--volume=\Q$ENV{CRUNCH_SRC}:$ENV{CRUNCH_SRC}:ro\E ";
739 $command .= "--volume=\Q$ENV{CRUNCH_INSTALL}:$ENV{CRUNCH_INSTALL}:ro\E ";
741 # For some reason we make arv-mount's mount point appear at
742 # /keep inside the container, instead of using the same path as
743 # the host and expecting the task to pay attention to
744 # $TASK_KEEPMOUNT like we do with everything else.
745 $command .= "--volume=\Q$ENV{TASK_KEEPMOUNT}:/keep:ro\E ";
746 $ENV{TASK_KEEPMOUNT} = "/keep";
748 # TASK_WORK is a plain docker data volume: it starts out empty,
749 # is writable, and persists until no containers use it any
750 # more. We don't use --volumes-from to share it with other
751 # containers: it is only accessible to this task, and it goes
752 # away when this task stops.
753 $command .= "--volume=\Q$ENV{TASK_WORK}\E ";
755 # JOB_WORK is also a plain docker data volume for now. TODO:
756 # Share a single JOB_WORK volume across all task containers on a
757 # given worker node, and delete it when the job ends (and, in
758 # case that doesn't work, when the next job starts).
759 $command .= "--volume=\Q$ENV{JOB_WORK}\E ";
761 while (my ($env_key, $env_val) = each %ENV)
763 if ($env_key =~ /^(ARVADOS|CRUNCH|JOB|TASK)_/) {
764 $command .= "--env=\Q$env_key=$env_val\E ";
767 $command .= "--env=\QHOME=$ENV{HOME}\E ";
768 $command .= "\Q$docker_hash\E ";
769 $command .= "stdbuf --output=0 --error=0 ";
770 $command .= "$ENV{CRUNCH_SRC}/crunch_scripts/" . $Job->{"script"};
773 $command .= "crunchstat -cgroup-root=/sys/fs/cgroup -poll=10000 ";
774 $command .= "stdbuf --output=0 --error=0 ";
775 $command .= "$ENV{CRUNCH_SRC}/crunch_scripts/" . $Job->{"script"};
778 my @execargs = ('bash', '-c', $command);
779 srun (\@srunargs, \@execargs, undef, $build_script_to_send);
780 # exec() failed, we assume nothing happened.
781 die "srun() failed on build script\n";
784 if (!defined $childpid)
791 $proc{$childpid} = { jobstep => $id,
794 jobstepname => "$job_id.$id.$childpid",
796 croak ("assert failed: \$slot[$childslot]->{'pid'} exists") if exists $slot[$childslot]->{pid};
797 $slot[$childslot]->{pid} = $childpid;
799 Log ($id, "job_task ".$Jobstep->{'arvados_task'}->{'uuid'});
800 Log ($id, "child $childpid started on $childslotname");
801 $Jobstep->{starttime} = time;
802 $Jobstep->{node} = $childnode->{name};
803 $Jobstep->{slotindex} = $childslot;
804 delete $Jobstep->{stderr};
805 delete $Jobstep->{finishtime};
807 $Jobstep->{'arvados_task'}->{started_at} = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime($Jobstep->{starttime});
808 $Jobstep->{'arvados_task'}->save;
810 splice @jobstep_todo, $todo_ptr, 1;
813 $progress_is_dirty = 1;
817 (@slot > @freeslot && $todo_ptr+1 > $#jobstep_todo))
819 last THISROUND if $main::please_freeze;
820 if ($main::please_info)
822 $main::please_info = 0;
826 update_progress_stats();
833 check_refresh_wanted();
835 update_progress_stats();
836 select (undef, undef, undef, 0.1);
838 elsif (time - $progress_stats_updated >= 30)
840 update_progress_stats();
842 if (($thisround_failed_multiple >= 8 && $thisround_succeeded == 0) ||
843 ($thisround_failed_multiple >= 16 && $thisround_failed_multiple > $thisround_succeeded))
845 my $message = "Repeated failure rate too high ($thisround_failed_multiple/"
846 .($thisround_failed+$thisround_succeeded)
847 .") -- giving up on this round";
848 Log (undef, $message);
852 # move slots from freeslot to holdslot (or back to freeslot) if necessary
853 for (my $i=$#freeslot; $i>=0; $i--) {
854 if ($slot[$freeslot[$i]]->{node}->{hold_until} > scalar time) {
855 push @holdslot, (splice @freeslot, $i, 1);
858 for (my $i=$#holdslot; $i>=0; $i--) {
859 if ($slot[$holdslot[$i]]->{node}->{hold_until} <= scalar time) {
860 push @freeslot, (splice @holdslot, $i, 1);
864 # give up if no nodes are succeeding
865 if (!grep { $_->{node}->{losing_streak} == 0 &&
866 $_->{node}->{hold_count} < 4 } @slot) {
867 my $message = "Every node has failed -- giving up on this round";
868 Log (undef, $message);
875 push @freeslot, splice @holdslot;
876 map { $slot[$freeslot[$_]]->{node}->{losing_streak} = 0 } (0..$#freeslot);
879 Log (undef, "wait for last ".(scalar keys %proc)." children to finish");
882 if ($main::please_continue) {
883 $main::please_continue = 0;
886 $main::please_info = 0, freeze(), collate_output(), save_meta(1) if $main::please_info;
890 check_refresh_wanted();
892 update_progress_stats();
893 select (undef, undef, undef, 0.1);
894 killem (keys %proc) if $main::please_freeze;
898 update_progress_stats();
899 freeze_if_want_freeze();
902 if (!defined $main::success)
905 $thisround_succeeded == 0 &&
906 ($thisround_failed == 0 || $thisround_failed > 4))
908 my $message = "stop because $thisround_failed tasks failed and none succeeded";
909 Log (undef, $message);
918 goto ONELEVEL if !defined $main::success;
921 release_allocation();
923 my $collated_output = &collate_output();
925 if (!$collated_output) {
926 Log(undef, "output undef");
930 open(my $orig_manifest, '-|', 'arv-get', $collated_output)
931 or die "failed to get collated manifest: $!";
932 my $orig_manifest_text = '';
933 while (my $manifest_line = <$orig_manifest>) {
934 $orig_manifest_text .= $manifest_line;
936 my $output = retry_op(sub {
937 $arv->{'collections'}->{'create'}->execute(
938 'collection' => {'manifest_text' => $orig_manifest_text});
940 Log(undef, "output uuid " . $output->{uuid});
941 Log(undef, "output hash " . $output->{portable_data_hash});
942 $Job->update_attributes('output' => $output->{portable_data_hash});
945 Log (undef, "Failed to register output manifest: $@");
949 Log (undef, "finish");
954 if ($collated_output && $main::success) {
955 $final_state = 'Complete';
957 $final_state = 'Failed';
959 $Job->update_attributes('state' => $final_state);
961 exit (($final_state eq 'Complete') ? 0 : 1);
965 sub update_progress_stats
967 $progress_stats_updated = time;
968 return if !$progress_is_dirty;
969 my ($todo, $done, $running) = (scalar @jobstep_todo,
970 scalar @jobstep_done,
971 scalar @slot - scalar @freeslot - scalar @holdslot);
972 $Job->{'tasks_summary'} ||= {};
973 $Job->{'tasks_summary'}->{'todo'} = $todo;
974 $Job->{'tasks_summary'}->{'done'} = $done;
975 $Job->{'tasks_summary'}->{'running'} = $running;
976 $Job->update_attributes('tasks_summary' => $Job->{'tasks_summary'});
977 Log (undef, "status: $done done, $running running, $todo todo");
978 $progress_is_dirty = 0;
985 my $pid = waitpid (-1, WNOHANG);
986 return 0 if $pid <= 0;
988 my $whatslot = ($slot[$proc{$pid}->{slot}]->{node}->{name}
990 . $slot[$proc{$pid}->{slot}]->{cpu});
991 my $jobstepid = $proc{$pid}->{jobstep};
992 my $elapsed = time - $proc{$pid}->{time};
993 my $Jobstep = $jobstep[$jobstepid];
995 my $childstatus = $?;
996 my $exitvalue = $childstatus >> 8;
997 my $exitinfo = "exit ".exit_status_s($childstatus);
998 $Jobstep->{'arvados_task'}->reload;
999 my $task_success = $Jobstep->{'arvados_task'}->{success};
1001 Log ($jobstepid, "child $pid on $whatslot $exitinfo success=$task_success");
1003 if (!defined $task_success) {
1004 # task did not indicate one way or the other --> fail
1005 $Jobstep->{'arvados_task'}->{success} = 0;
1006 $Jobstep->{'arvados_task'}->save;
1013 $temporary_fail ||= $Jobstep->{node_fail};
1014 $temporary_fail ||= ($exitvalue == 111);
1016 ++$thisround_failed;
1017 ++$thisround_failed_multiple if $Jobstep->{'failures'} >= 1;
1019 # Check for signs of a failed or misconfigured node
1020 if (++$slot[$proc{$pid}->{slot}]->{node}->{losing_streak} >=
1021 2+$slot[$proc{$pid}->{slot}]->{node}->{ncpus}) {
1022 # Don't count this against jobstep failure thresholds if this
1023 # node is already suspected faulty and srun exited quickly
1024 if ($slot[$proc{$pid}->{slot}]->{node}->{hold_until} &&
1026 Log ($jobstepid, "blaming failure on suspect node " .
1027 $slot[$proc{$pid}->{slot}]->{node}->{name});
1028 $temporary_fail ||= 1;
1030 ban_node_by_slot($proc{$pid}->{slot});
1033 Log ($jobstepid, sprintf('failure (#%d, %s) after %d seconds',
1034 ++$Jobstep->{'failures'},
1035 $temporary_fail ? 'temporary ' : 'permanent',
1038 if (!$temporary_fail || $Jobstep->{'failures'} >= 3) {
1039 # Give up on this task, and the whole job
1041 $main::please_freeze = 1;
1043 # Put this task back on the todo queue
1044 push @jobstep_todo, $jobstepid;
1045 $Job->{'tasks_summary'}->{'failed'}++;
1049 ++$thisround_succeeded;
1050 $slot[$proc{$pid}->{slot}]->{node}->{losing_streak} = 0;
1051 $slot[$proc{$pid}->{slot}]->{node}->{hold_until} = 0;
1052 push @jobstep_done, $jobstepid;
1053 Log ($jobstepid, "success in $elapsed seconds");
1055 $Jobstep->{exitcode} = $childstatus;
1056 $Jobstep->{finishtime} = time;
1057 $Jobstep->{'arvados_task'}->{finished_at} = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime($Jobstep->{finishtime});
1058 $Jobstep->{'arvados_task'}->save;
1059 process_stderr ($jobstepid, $task_success);
1060 Log ($jobstepid, "output " . $Jobstep->{'arvados_task'}->{output});
1062 close $reader{$jobstepid};
1063 delete $reader{$jobstepid};
1064 delete $slot[$proc{$pid}->{slot}]->{pid};
1065 push @freeslot, $proc{$pid}->{slot};
1068 if ($task_success) {
1070 my $newtask_list = [];
1071 my $newtask_results;
1073 $newtask_results = retry_op(sub {
1074 $arv->{'job_tasks'}->{'list'}->execute(
1076 'created_by_job_task_uuid' => $Jobstep->{'arvados_task'}->{uuid}
1078 'order' => 'qsequence',
1079 'offset' => scalar(@$newtask_list),
1082 push(@$newtask_list, @{$newtask_results->{items}});
1083 } while (@{$newtask_results->{items}});
1084 foreach my $arvados_task (@$newtask_list) {
1086 'level' => $arvados_task->{'sequence'},
1088 'arvados_task' => $arvados_task
1090 push @jobstep, $jobstep;
1091 push @jobstep_todo, $#jobstep;
1095 $progress_is_dirty = 1;
1099 sub check_refresh_wanted
1101 my @stat = stat $ENV{"CRUNCH_REFRESH_TRIGGER"};
1102 if (@stat && $stat[9] > $latest_refresh) {
1103 $latest_refresh = scalar time;
1104 my $Job2 = retry_op(sub {
1105 $arv->{'jobs'}->{'get'}->execute('uuid' => $jobspec);
1107 for my $attr ('cancelled_at',
1108 'cancelled_by_user_uuid',
1109 'cancelled_by_client_uuid',
1111 $Job->{$attr} = $Job2->{$attr};
1113 if ($Job->{'state'} ne "Running") {
1114 if ($Job->{'state'} eq "Cancelled") {
1115 Log (undef, "Job cancelled at " . $Job->{'cancelled_at'} . " by user " . $Job->{'cancelled_by_user_uuid'});
1117 Log (undef, "Job state unexpectedly changed to " . $Job->{'state'});
1120 $main::please_freeze = 1;
1127 # return if the kill list was checked <4 seconds ago
1128 if (defined $squeue_kill_checked && $squeue_kill_checked > time - 4)
1132 $squeue_kill_checked = time;
1134 # use killem() on procs whose killtime is reached
1137 if (exists $proc{$_}->{killtime}
1138 && $proc{$_}->{killtime} <= time)
1144 # return if the squeue was checked <60 seconds ago
1145 if (defined $squeue_checked && $squeue_checked > time - 60)
1149 $squeue_checked = time;
1153 # here is an opportunity to check for mysterious problems with local procs
1157 # get a list of steps still running
1158 my @squeue = `squeue -s -h -o '%i %j' && echo ok`;
1160 if ($squeue[-1] ne "ok")
1166 # which of my jobsteps are running, according to squeue?
1170 if (/^(\d+)\.(\d+) (\S+)/)
1172 if ($1 eq $ENV{SLURM_JOBID})
1179 # which of my active child procs (>60s old) were not mentioned by squeue?
1180 foreach (keys %proc)
1182 if ($proc{$_}->{time} < time - 60
1183 && !exists $ok{$proc{$_}->{jobstepname}}
1184 && !exists $proc{$_}->{killtime})
1186 # kill this proc if it hasn't exited in 30 seconds
1187 $proc{$_}->{killtime} = time + 30;
1193 sub release_allocation
1197 Log (undef, "release job allocation");
1198 system "scancel $ENV{SLURM_JOBID}";
1206 foreach my $job (keys %reader)
1209 while (0 < sysread ($reader{$job}, $buf, 8192))
1211 print STDERR $buf if $ENV{CRUNCH_DEBUG};
1212 $jobstep[$job]->{stderr} .= $buf;
1213 preprocess_stderr ($job);
1214 if (length ($jobstep[$job]->{stderr}) > 16384)
1216 substr ($jobstep[$job]->{stderr}, 0, 8192) = "";
1225 sub preprocess_stderr
1229 while ($jobstep[$job]->{stderr} =~ /^(.*?)\n/) {
1231 substr $jobstep[$job]->{stderr}, 0, 1+length($line), "";
1232 Log ($job, "stderr $line");
1233 if ($line =~ /srun: error: (SLURM job $ENV{SLURM_JOB_ID} has expired|Unable to confirm allocation for job $ENV{SLURM_JOB_ID})/) {
1235 $main::please_freeze = 1;
1237 elsif ($line =~ /srun: error: (Node failure on|Unable to create job step) /) {
1238 $jobstep[$job]->{node_fail} = 1;
1239 ban_node_by_slot($jobstep[$job]->{slotindex});
1248 my $task_success = shift;
1249 preprocess_stderr ($job);
1252 Log ($job, "stderr $_");
1253 } split ("\n", $jobstep[$job]->{stderr});
1259 my ($keep, $child_out, $output_block);
1261 my $cmd = "arv-get \Q$hash\E";
1262 open($keep, '-|', $cmd) or die "fetch_block: $cmd: $!";
1266 my $bytes = sysread($keep, $buf, 1024 * 1024);
1267 if (!defined $bytes) {
1268 die "reading from arv-get: $!";
1269 } elsif ($bytes == 0) {
1270 # sysread returns 0 at the end of the pipe.
1273 # some bytes were read into buf.
1274 $output_block .= $buf;
1278 return $output_block;
1283 Log (undef, "collate");
1285 my ($child_out, $child_in);
1286 my $pid = open2($child_out, $child_in, 'arv-put', '--raw',
1287 '--retries', retry_count());
1291 next if (!exists $_->{'arvados_task'}->{'output'} ||
1292 !$_->{'arvados_task'}->{'success'});
1293 my $output = $_->{'arvados_task'}->{output};
1294 if ($output !~ /^[0-9a-f]{32}(\+\S+)*$/)
1296 $output_in_keep ||= $output =~ / [0-9a-f]{32}\S*\+K/;
1297 print $child_in $output;
1299 elsif (@jobstep == 1)
1301 $joboutput = $output;
1304 elsif (defined (my $outblock = fetch_block ($output)))
1306 $output_in_keep ||= $outblock =~ / [0-9a-f]{32}\S*\+K/;
1307 print $child_in $outblock;
1311 Log (undef, "XXX fetch_block($output) failed XXX");
1317 if (!defined $joboutput) {
1318 my $s = IO::Select->new($child_out);
1319 if ($s->can_read(120)) {
1320 sysread($child_out, $joboutput, 64 * 1024 * 1024);
1322 # TODO: Ensure exit status == 0.
1324 Log (undef, "timed out reading from 'arv-put'");
1327 # TODO: kill $pid instead of waiting, now that we've decided to
1328 # ignore further output.
1339 my $sig = 2; # SIGINT first
1340 if (exists $proc{$_}->{"sent_$sig"} &&
1341 time - $proc{$_}->{"sent_$sig"} > 4)
1343 $sig = 15; # SIGTERM if SIGINT doesn't work
1345 if (exists $proc{$_}->{"sent_$sig"} &&
1346 time - $proc{$_}->{"sent_$sig"} > 4)
1348 $sig = 9; # SIGKILL if SIGTERM doesn't work
1350 if (!exists $proc{$_}->{"sent_$sig"})
1352 Log ($proc{$_}->{jobstep}, "sending 2x signal $sig to pid $_");
1354 select (undef, undef, undef, 0.1);
1357 kill $sig, $_; # srun wants two SIGINT to really interrupt
1359 $proc{$_}->{"sent_$sig"} = time;
1360 $proc{$_}->{"killedafter"} = time - $proc{$_}->{"time"};
1370 vec($bits,fileno($_),1) = 1;
1376 # Send log output to Keep via arv-put.
1378 # $log_pipe_in and $log_pipe_out are the input and output filehandles to the arv-put pipe.
1379 # $log_pipe_pid is the pid of the arv-put subprocess.
1381 # The only functions that should access these variables directly are:
1383 # log_writer_start($logfilename)
1384 # Starts an arv-put pipe, reading data on stdin and writing it to
1385 # a $logfilename file in an output collection.
1387 # log_writer_send($txt)
1388 # Writes $txt to the output log collection.
1390 # log_writer_finish()
1391 # Closes the arv-put pipe and returns the output that it produces.
1393 # log_writer_is_active()
1394 # Returns a true value if there is currently a live arv-put
1395 # process, false otherwise.
1397 my ($log_pipe_in, $log_pipe_out, $log_pipe_pid);
1399 sub log_writer_start($)
1401 my $logfilename = shift;
1402 $log_pipe_pid = open2($log_pipe_out, $log_pipe_in,
1403 'arv-put', '--portable-data-hash',
1405 '--filename', $logfilename,
1409 sub log_writer_send($)
1412 print $log_pipe_in $txt;
1415 sub log_writer_finish()
1417 return unless $log_pipe_pid;
1419 close($log_pipe_in);
1422 my $s = IO::Select->new($log_pipe_out);
1423 if ($s->can_read(120)) {
1424 sysread($log_pipe_out, $arv_put_output, 1024);
1425 chomp($arv_put_output);
1427 Log (undef, "timed out reading from 'arv-put'");
1430 waitpid($log_pipe_pid, 0);
1431 $log_pipe_pid = $log_pipe_in = $log_pipe_out = undef;
1433 Log("log_writer_finish: arv-put exited ".exit_status_s($?))
1436 return $arv_put_output;
1439 sub log_writer_is_active() {
1440 return $log_pipe_pid;
1443 sub Log # ($jobstep_id, $logmessage)
1445 if ($_[1] =~ /\n/) {
1446 for my $line (split (/\n/, $_[1])) {
1451 my $fh = select STDERR; $|=1; select $fh;
1452 my $message = sprintf ("%s %d %s %s", $job_id, $$, @_);
1453 $message =~ s{([^ -\176])}{"\\" . sprintf ("%03o", ord($1))}ge;
1456 if (log_writer_is_active() || -t STDERR) {
1457 my @gmtime = gmtime;
1458 $datetime = sprintf ("%04d-%02d-%02d_%02d:%02d:%02d",
1459 $gmtime[5]+1900, $gmtime[4]+1, @gmtime[3,2,1,0]);
1461 print STDERR ((-t STDERR) ? ($datetime." ".$message) : $message);
1463 if (log_writer_is_active()) {
1464 log_writer_send($datetime . " " . $message);
1471 my ($package, $file, $line) = caller;
1472 my $message = "@_ at $file line $line\n";
1473 Log (undef, $message);
1474 freeze() if @jobstep_todo;
1475 collate_output() if @jobstep_todo;
1485 if ($Job->{'state'} eq 'Cancelled') {
1486 $Job->update_attributes('finished_at' => scalar gmtime);
1488 $Job->update_attributes('state' => 'Failed');
1495 my $justcheckpoint = shift; # false if this will be the last meta saved
1496 return if $justcheckpoint; # checkpointing is not relevant post-Warehouse.pm
1497 return unless log_writer_is_active();
1499 my $loglocator = log_writer_finish();
1500 Log (undef, "log manifest is $loglocator");
1501 $Job->{'log'} = $loglocator;
1502 $Job->update_attributes('log', $loglocator);
1506 sub freeze_if_want_freeze
1508 if ($main::please_freeze)
1510 release_allocation();
1513 # kill some srun procs before freeze+stop
1514 map { $proc{$_} = {} } @_;
1517 killem (keys %proc);
1518 select (undef, undef, undef, 0.1);
1520 while (($died = waitpid (-1, WNOHANG)) > 0)
1522 delete $proc{$died};
1537 Log (undef, "Freeze not implemented");
1544 croak ("Thaw not implemented");
1560 $s =~ s{\\(.)}{$1 eq "n" ? "\n" : $1}ge;
1567 my $srunargs = shift;
1568 my $execargs = shift;
1569 my $opts = shift || {};
1571 my $args = $have_slurm ? [@$srunargs, @$execargs] : $execargs;
1573 my $show_cmd = "@{$args}";
1574 $show_cmd =~ s/(TOKEN\\*=)\S+/${1}[...]/g;
1575 $show_cmd =~ s/\n/ /g;
1576 warn "starting: $show_cmd\n";
1578 if (defined $stdin) {
1579 my $child = open STDIN, "-|";
1580 defined $child or die "no fork: $!";
1582 print $stdin or die $!;
1583 close STDOUT or die $!;
1588 return system (@$args) if $opts->{fork};
1591 warn "ENV size is ".length(join(" ",%ENV));
1592 die "exec failed: $!: @$args";
1596 sub ban_node_by_slot {
1597 # Don't start any new jobsteps on this node for 60 seconds
1599 $slot[$slotid]->{node}->{hold_until} = 60 + scalar time;
1600 $slot[$slotid]->{node}->{hold_count}++;
1601 Log (undef, "backing off node " . $slot[$slotid]->{node}->{name} . " for 60 seconds");
1606 my ($lockfile, $error_message) = @_;
1607 open L, ">", $lockfile or croak("$lockfile: $!");
1608 if (!flock L, LOCK_EX|LOCK_NB) {
1609 croak("Can't lock $lockfile: $error_message\n");
1613 sub find_docker_image {
1614 # Given a Keep locator, check to see if it contains a Docker image.
1615 # If so, return its stream name and Docker hash.
1616 # If not, return undef for both values.
1617 my $locator = shift;
1618 my ($streamname, $filename);
1619 my $image = retry_op(sub {
1620 $arv->{collections}->{get}->execute(uuid => $locator);
1623 foreach my $line (split(/\n/, $image->{manifest_text})) {
1624 my @tokens = split(/\s+/, $line);
1626 $streamname = shift(@tokens);
1627 foreach my $filedata (grep(/^\d+:\d+:/, @tokens)) {
1628 if (defined($filename)) {
1629 return (undef, undef); # More than one file in the Collection.
1631 $filename = (split(/:/, $filedata, 3))[2];
1636 if (defined($filename) and ($filename =~ /^([0-9A-Fa-f]{64})\.tar$/)) {
1637 return ($streamname, $1);
1639 return (undef, undef);
1644 # Calculate the number of times an operation should be retried,
1645 # assuming exponential backoff, and that we're willing to retry as
1646 # long as tasks have been running. Enforce a minimum of 3 retries.
1647 my ($starttime, $endtime, $timediff, $retries);
1649 $starttime = $jobstep[0]->{starttime};
1650 $endtime = $jobstep[-1]->{finishtime};
1652 if (!defined($starttime)) {
1654 } elsif (!defined($endtime)) {
1655 $timediff = time - $starttime;
1657 $timediff = ($endtime - $starttime) - (time - $endtime);
1659 if ($timediff > 0) {
1660 $retries = int(log($timediff) / log(2));
1662 $retries = 1; # Use the minimum.
1664 return ($retries > 3) ? $retries : 3;
1668 # Given a function reference, call it with the remaining arguments. If
1669 # it dies, retry it with exponential backoff until it succeeds, or until
1670 # the current retry_count is exhausted.
1671 my $operation = shift;
1672 my $retries = retry_count();
1673 foreach my $try_count (0..$retries) {
1674 my $next_try = time + (2 ** $try_count);
1675 my $result = eval { $operation->(@_); };
1678 } elsif ($try_count < $retries) {
1679 my $sleep_time = $next_try - time;
1680 sleep($sleep_time) if ($sleep_time > 0);
1683 # Ensure the error message ends in a newline, so Perl doesn't add
1684 # retry_op's line number to it.
1690 # Given a $?, return a human-readable exit code string like "0" or
1691 # "1" or "0 with signal 1" or "1 with signal 11".
1692 my $exitcode = shift;
1693 my $s = $exitcode >> 8;
1694 if ($exitcode & 0x7f) {
1695 $s .= " with signal " . ($exitcode & 0x7f);
1697 if ($exitcode & 0x80) {
1698 $s .= " with core dump";
1706 # checkout-and-build
1709 use File::Path qw( make_path remove_tree );
1711 my $destdir = $ENV{"CRUNCH_SRC"};
1712 my $commit = $ENV{"CRUNCH_SRC_COMMIT"};
1713 my $repo = $ENV{"CRUNCH_SRC_URL"};
1714 my $task_work = $ENV{"TASK_WORK"};
1716 for my $dir ($destdir, $task_work) {
1719 -e $dir or die "Failed to create temporary directory ($dir): $!";
1724 remove_tree($task_work, {keep_root => 1});
1728 open L, ">", "$destdir.lock" or die "$destdir.lock: $!";
1730 if (readlink ("$destdir.commit") eq $commit && -d $destdir) {
1733 die "Cannot exec `@ARGV`: $!";
1739 unlink "$destdir.commit";
1740 open STDERR_ORIG, ">&STDERR";
1741 open STDOUT, ">", "$destdir.log";
1742 open STDERR, ">&STDOUT";
1745 my @git_archive_data = <DATA>;
1746 if (@git_archive_data) {
1747 open TARX, "|-", "tar", "-C", $destdir, "-xf", "-";
1748 print TARX @git_archive_data;
1750 die "'tar -C $destdir -xf -' exited $?: $!";
1755 chomp ($pwd = `pwd`);
1756 my $install_dir = $ENV{"CRUNCH_INSTALL"} || "$pwd/opt";
1759 for my $src_path ("$destdir/arvados/sdk/python") {
1761 shell_or_die ("virtualenv", $install_dir);
1762 shell_or_die ("cd $src_path && ./build.sh && $install_dir/bin/python setup.py install");
1766 if (-e "$destdir/crunch_scripts/install") {
1767 shell_or_die ("$destdir/crunch_scripts/install", $install_dir);
1768 } elsif (!-e "./install.sh" && -e "./tests/autotests.sh") {
1770 shell_or_die ("./tests/autotests.sh", $install_dir);
1771 } elsif (-e "./install.sh") {
1772 shell_or_die ("./install.sh", $install_dir);
1776 unlink "$destdir.commit.new";
1777 symlink ($commit, "$destdir.commit.new") or die "$destdir.commit.new: $!";
1778 rename ("$destdir.commit.new", "$destdir.commit") or die "$destdir.commit: $!";
1785 die "Cannot exec `@ARGV`: $!";
1792 if ($ENV{"DEBUG"}) {
1793 print STDERR "@_\n";
1795 if (system (@_) != 0) {
1796 my $exitstatus = sprintf("exit %d signal %d", $? >> 8, $? & 0x7f);
1797 open STDERR, ">&STDERR_ORIG";
1798 system ("cat $destdir.log >&2");
1799 die "@_ failed ($!): $exitstatus";