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);
91 use Digest::MD5 qw(md5_hex);
97 use File::Path qw( make_path remove_tree );
99 use constant TASK_TEMPFAIL => 111;
100 use constant EX_TEMPFAIL => 75;
102 $ENV{"TMPDIR"} ||= "/tmp";
103 unless (defined $ENV{"CRUNCH_TMP"}) {
104 $ENV{"CRUNCH_TMP"} = $ENV{"TMPDIR"} . "/crunch-job";
105 if ($ENV{"USER"} ne "crunch" && $< != 0) {
106 # use a tmp dir unique for my uid
107 $ENV{"CRUNCH_TMP"} .= "-$<";
111 # Create the tmp directory if it does not exist
112 if ( ! -d $ENV{"CRUNCH_TMP"} ) {
113 make_path $ENV{"CRUNCH_TMP"} or die "Failed to create temporary working directory: " . $ENV{"CRUNCH_TMP"};
116 $ENV{"JOB_WORK"} = $ENV{"CRUNCH_TMP"} . "/work";
117 $ENV{"CRUNCH_INSTALL"} = "$ENV{CRUNCH_TMP}/opt";
118 $ENV{"CRUNCH_WORK"} = $ENV{"JOB_WORK"}; # deprecated
119 mkdir ($ENV{"JOB_WORK"});
127 GetOptions('force-unlock' => \$force_unlock,
128 'git-dir=s' => \$git_dir,
129 'job=s' => \$jobspec,
130 'job-api-token=s' => \$job_api_token,
131 'no-clear-tmp' => \$no_clear_tmp,
132 'resume-stash=s' => \$resume_stash,
135 if (defined $job_api_token) {
136 $ENV{ARVADOS_API_TOKEN} = $job_api_token;
139 my $have_slurm = exists $ENV{SLURM_JOBID} && exists $ENV{SLURM_NODELIST};
145 $main::ENV{CRUNCH_DEBUG} = 1;
149 $main::ENV{CRUNCH_DEBUG} = 0;
154 my $arv = Arvados->new('apiVersion' => 'v1');
162 my $User = api_call("users/current");
164 if ($jobspec =~ /^[-a-z\d]+$/)
166 # $jobspec is an Arvados UUID, not a JSON job specification
167 $Job = api_call("jobs/get", uuid => $jobspec);
168 if (!$force_unlock) {
169 # Claim this job, and make sure nobody else does
170 eval { api_call("jobs/lock", uuid => $Job->{uuid}); };
172 Log(undef, "Error while locking job, exiting ".EX_TEMPFAIL);
179 $Job = JSON::decode_json($jobspec);
183 map { croak ("No $_ specified") unless $Job->{$_} }
184 qw(script script_version script_parameters);
187 $Job->{'is_locked_by_uuid'} = $User->{'uuid'};
188 $Job->{'started_at'} = gmtime;
189 $Job->{'state'} = 'Running';
191 $Job = api_call("jobs/create", job => $Job);
193 $job_id = $Job->{'uuid'};
195 my $keep_logfile = $job_id . '.log.txt';
196 log_writer_start($keep_logfile);
198 $Job->{'runtime_constraints'} ||= {};
199 $Job->{'runtime_constraints'}->{'max_tasks_per_node'} ||= 0;
200 my $max_ncpus = $Job->{'runtime_constraints'}->{'max_tasks_per_node'};
202 my $gem_versions = `gem list --quiet arvados-cli 2>/dev/null`;
204 $gem_versions =~ s/^arvados-cli \(/ with arvados-cli Gem version(s) /;
205 chomp($gem_versions);
206 chop($gem_versions); # Closing parentheses
211 "running from " . ((-e $0) ? realpath($0) : "stdin") . $gem_versions);
213 Log (undef, "check slurm allocation");
216 # Should use $ENV{SLURM_TASKS_PER_NODE} instead of sinfo? (eg. "4(x3),2,4(x2)")
220 my $localcpus = 0 + `grep -cw ^processor /proc/cpuinfo` || 1;
221 push @sinfo, "$localcpus localhost";
223 if (exists $ENV{SLURM_NODELIST})
225 push @sinfo, `sinfo -h --format='%c %N' --nodes=\Q$ENV{SLURM_NODELIST}\E`;
229 my ($ncpus, $slurm_nodelist) = split;
230 $ncpus = $max_ncpus if $max_ncpus && $ncpus > $max_ncpus;
233 while ($slurm_nodelist =~ s/^([^\[,]+?(\[.*?\])?)(,|$)//)
236 if ($nodelist =~ /\[((\d+)(-(\d+))?(,(\d+)(-(\d+))?)*)\]/)
239 foreach (split (",", $ranges))
252 push @nodelist, map {
254 $n =~ s/\[[-,\d]+\]/$_/;
261 push @nodelist, $nodelist;
264 foreach my $nodename (@nodelist)
266 Log (undef, "node $nodename - $ncpus slots");
267 my $node = { name => $nodename,
271 foreach my $cpu (1..$ncpus)
273 push @slot, { node => $node,
277 push @node, @nodelist;
282 # Ensure that we get one jobstep running on each allocated node before
283 # we start overloading nodes with concurrent steps
285 @slot = sort { $a->{cpu} <=> $b->{cpu} } @slot;
288 $Job->update_attributes(
289 'tasks_summary' => { 'failed' => 0,
294 Log (undef, "start");
295 $SIG{'INT'} = sub { $main::please_freeze = 1; };
296 $SIG{'QUIT'} = sub { $main::please_freeze = 1; };
297 $SIG{'TERM'} = \&croak;
298 $SIG{'TSTP'} = sub { $main::please_freeze = 1; };
299 $SIG{'ALRM'} = sub { $main::please_info = 1; };
300 $SIG{'CONT'} = sub { $main::please_continue = 1; };
301 $SIG{'HUP'} = sub { $main::please_refresh = 1; };
303 $main::please_freeze = 0;
304 $main::please_info = 0;
305 $main::please_continue = 0;
306 $main::please_refresh = 0;
307 my $jobsteps_must_output_keys = 0; # becomes 1 when any task outputs a key
309 grep { $ENV{$1} = $2 if /^(NOCACHE.*?)=(.*)/ } split ("\n", $$Job{knobs});
310 $ENV{"CRUNCH_JOB_UUID"} = $job_id;
311 $ENV{"JOB_UUID"} = $job_id;
314 my @jobstep_todo = ();
315 my @jobstep_done = ();
316 my @jobstep_tomerge = ();
317 my $jobstep_tomerge_level = 0;
319 my $squeue_kill_checked;
320 my $latest_refresh = scalar time;
324 if (defined $Job->{thawedfromkey})
326 thaw ($Job->{thawedfromkey});
330 my $first_task = api_call("job_tasks/create", job_task => {
331 'job_uuid' => $Job->{'uuid'},
336 push @jobstep, { 'level' => 0,
338 'arvados_task' => $first_task,
340 push @jobstep_todo, 0;
346 must_lock_now("$ENV{CRUNCH_TMP}/.lock", "a job is already running here.");
349 my $build_script = handle_readall(\*DATA);
350 my $nodelist = join(",", @node);
351 my $git_tar_count = 0;
353 if (!defined $no_clear_tmp) {
354 # Clean out crunch_tmp/work, crunch_tmp/opt, crunch_tmp/src*
355 Log (undef, "Clean work dirs");
357 my $cleanpid = fork();
360 # Find FUSE mounts that look like Keep mounts (the mount path has the
361 # word "keep") and unmount them. Then clean up work directories.
362 # TODO: When #5036 is done and widely deployed, we can get rid of the
363 # regular expression and just unmount everything with type fuse.keep.
364 srun (["srun", "--nodelist=$nodelist", "-D", $ENV{'TMPDIR'}],
365 ['bash', '-ec', 'mount -t fuse,fuse.keep | awk \'($3 ~ /\ykeep\y/){print $3}\' | xargs -r -n 1 fusermount -u -z; sleep 1; rm -rf $JOB_WORK $CRUNCH_INSTALL $CRUNCH_TMP/task $CRUNCH_TMP/src* $CRUNCH_TMP/*.cid']);
370 last if $cleanpid == waitpid (-1, WNOHANG);
371 freeze_if_want_freeze ($cleanpid);
372 select (undef, undef, undef, 0.1);
374 Log (undef, "Cleanup command exited ".exit_status_s($?));
377 # If this job requires a Docker image, install that.
378 my $docker_bin = "/usr/bin/docker.io";
379 my ($docker_locator, $docker_stream, $docker_hash, $docker_limitmem);
380 if ($docker_locator = $Job->{docker_image_locator}) {
381 ($docker_stream, $docker_hash) = find_docker_image($docker_locator);
384 croak("No Docker image hash found from locator $docker_locator");
386 $docker_stream =~ s/^\.//;
387 my $docker_install_script = qq{
388 if ! $docker_bin images -q --no-trunc --all | grep -qxF \Q$docker_hash\E; then
389 arv-get \Q$docker_locator$docker_stream/$docker_hash.tar\E | $docker_bin load
392 my $docker_pid = fork();
393 if ($docker_pid == 0)
395 srun (["srun", "--nodelist=" . join(',', @node)],
396 ["/bin/sh", "-ec", $docker_install_script]);
401 last if $docker_pid == waitpid (-1, WNOHANG);
402 freeze_if_want_freeze ($docker_pid);
403 select (undef, undef, undef, 0.1);
407 croak("Installing Docker image from $docker_locator exited "
411 # Determine whether this version of Docker supports memory+swap limits.
412 srun(["srun", "--nodelist=" . $node[0]],
413 ["/bin/sh", "-ec", "$docker_bin run --help | grep -qe --memory-swap="],
415 $docker_limitmem = ($? == 0);
417 if ($Job->{arvados_sdk_version}) {
418 # The job also specifies an Arvados SDK version. Add the SDKs to the
419 # tar file for the build script to install.
420 Log(undef, sprintf("Packing Arvados SDK version %s for installation",
421 $Job->{arvados_sdk_version}));
422 add_git_archive("git", "--git-dir=$git_dir", "archive",
423 "--prefix=.arvados.sdk/",
424 $Job->{arvados_sdk_version}, "sdk");
428 if (!defined $git_dir && $Job->{'script_version'} =~ m{^/}) {
429 # If script_version looks like an absolute path, *and* the --git-dir
430 # argument was not given -- which implies we were not invoked by
431 # crunch-dispatch -- we will use the given path as a working
432 # directory instead of resolving script_version to a git commit (or
433 # doing anything else with git).
434 $ENV{"CRUNCH_SRC_COMMIT"} = $Job->{'script_version'};
435 $ENV{"CRUNCH_SRC"} = $Job->{'script_version'};
438 # Resolve the given script_version to a git commit sha1. Also, if
439 # the repository is remote, clone it into our local filesystem: this
440 # ensures "git archive" will work, and is necessary to reliably
441 # resolve a symbolic script_version like "master^".
442 $ENV{"CRUNCH_SRC"} = "$ENV{CRUNCH_TMP}/src";
444 Log (undef, "Looking for version ".$Job->{script_version}." from repository ".$Job->{repository});
446 $ENV{"CRUNCH_SRC_COMMIT"} = $Job->{script_version};
448 # If we're running under crunch-dispatch, it will have already
449 # pulled the appropriate source tree into its own repository, and
450 # given us that repo's path as $git_dir.
452 # If we're running a "local" job, we might have to fetch content
453 # from a remote repository.
455 # (Currently crunch-dispatch gives a local path with --git-dir, but
456 # we might as well accept URLs there too in case it changes its
458 my $repo = $git_dir || $Job->{'repository'};
460 # Repository can be remote or local. If remote, we'll need to fetch it
461 # to a local dir before doing `git log` et al.
464 if ($repo =~ m{://|^[^/]*:}) {
465 # $repo is a git url we can clone, like git:// or https:// or
466 # file:/// or [user@]host:repo.git. Note "user/name@host:foo" is
467 # not recognized here because distinguishing that from a local
468 # path is too fragile. If you really need something strange here,
469 # use the ssh:// form.
470 $repo_location = 'remote';
471 } elsif ($repo =~ m{^\.*/}) {
472 # $repo is a local path to a git index. We'll also resolve ../foo
473 # to ../foo/.git if the latter is a directory. To help
474 # disambiguate local paths from named hosted repositories, this
475 # form must be given as ./ or ../ if it's a relative path.
476 if (-d "$repo/.git") {
477 $repo = "$repo/.git";
479 $repo_location = 'local';
481 # $repo is none of the above. It must be the name of a hosted
483 my $arv_repo_list = api_call("repositories/list",
484 'filters' => [['name','=',$repo]]);
485 my @repos_found = @{$arv_repo_list->{'items'}};
486 my $n_found = $arv_repo_list->{'serverResponse'}->{'items_available'};
488 Log(undef, "Repository '$repo' -> "
489 . join(", ", map { $_->{'uuid'} } @repos_found));
492 croak("Error: Found $n_found repositories with name '$repo'.");
494 $repo = $repos_found[0]->{'fetch_url'};
495 $repo_location = 'remote';
497 Log(undef, "Using $repo_location repository '$repo'");
498 $ENV{"CRUNCH_SRC_URL"} = $repo;
500 # Resolve given script_version (we'll call that $treeish here) to a
501 # commit sha1 ($commit).
502 my $treeish = $Job->{'script_version'};
504 if ($repo_location eq 'remote') {
505 # We minimize excess object-fetching by re-using the same bare
506 # repository in CRUNCH_TMP/.git for multiple crunch-jobs -- we
507 # just keep adding remotes to it as needed.
508 my $local_repo = $ENV{'CRUNCH_TMP'}."/.git";
509 my $gitcmd = "git --git-dir=\Q$local_repo\E";
511 # Set up our local repo for caching remote objects, making
513 if (!-d $local_repo) {
514 make_path($local_repo) or croak("Error: could not create $local_repo");
516 # This works (exits 0 and doesn't delete fetched objects) even
517 # if $local_repo is already initialized:
518 `$gitcmd init --bare`;
520 croak("Error: $gitcmd init --bare exited ".exit_status_s($?));
523 # If $treeish looks like a hash (or abbrev hash) we look it up in
524 # our local cache first, since that's cheaper. (We don't want to
525 # do that with tags/branches though -- those change over time, so
526 # they should always be resolved by the remote repo.)
527 if ($treeish =~ /^[0-9a-f]{7,40}$/s) {
528 # Hide stderr because it's normal for this to fail:
529 my $sha1 = `$gitcmd rev-list -n1 ''\Q$treeish\E 2>/dev/null`;
531 # Careful not to resolve a branch named abcdeff to commit 1234567:
532 $sha1 =~ /^$treeish/ &&
533 $sha1 =~ /^([0-9a-f]{40})$/s) {
535 Log(undef, "Commit $commit already present in $local_repo");
539 if (!defined $commit) {
540 # If $treeish isn't just a hash or abbrev hash, or isn't here
541 # yet, we need to fetch the remote to resolve it correctly.
543 # First, remove all local heads. This prevents a name that does
544 # not exist on the remote from resolving to (or colliding with)
545 # a previously fetched branch or tag (possibly from a different
547 remove_tree("$local_repo/refs/heads", {keep_root => 1});
549 Log(undef, "Fetching objects from $repo to $local_repo");
550 `$gitcmd fetch --no-progress --tags ''\Q$repo\E \Q+refs/heads/*:refs/heads/*\E`;
552 croak("Error: `$gitcmd fetch` exited ".exit_status_s($?));
556 # Now that the data is all here, we will use our local repo for
557 # the rest of our git activities.
561 my $gitcmd = "git --git-dir=\Q$repo\E";
562 my $sha1 = `$gitcmd rev-list -n1 ''\Q$treeish\E`;
563 unless ($? == 0 && $sha1 =~ /^([0-9a-f]{40})$/) {
564 croak("`$gitcmd rev-list` exited "
566 .", '$treeish' not found. Giving up.");
569 Log(undef, "Version $treeish is commit $commit");
571 if ($commit ne $Job->{'script_version'}) {
572 # Record the real commit id in the database, frozentokey, logs,
573 # etc. -- instead of an abbreviation or a branch name which can
574 # become ambiguous or point to a different commit in the future.
575 if (!$Job->update_attributes('script_version' => $commit)) {
576 croak("Error: failed to update job's script_version attribute");
580 $ENV{"CRUNCH_SRC_COMMIT"} = $commit;
581 add_git_archive("$gitcmd archive ''\Q$commit\E");
584 my $git_archive = combined_git_archive();
585 if (!defined $git_archive) {
586 Log(undef, "Skip install phase (no git archive)");
588 Log(undef, "Warning: This probably means workers have no source tree!");
592 Log(undef, "Run install script on all workers");
594 my @srunargs = ("srun",
595 "--nodelist=$nodelist",
596 "-D", $ENV{'TMPDIR'}, "--job-name=$job_id");
597 my @execargs = ("sh", "-c",
598 "mkdir -p $ENV{CRUNCH_INSTALL} && cd $ENV{CRUNCH_TMP} && perl -");
600 my $installpid = fork();
601 if ($installpid == 0)
603 srun (\@srunargs, \@execargs, {}, $build_script . $git_archive);
608 last if $installpid == waitpid (-1, WNOHANG);
609 freeze_if_want_freeze ($installpid);
610 select (undef, undef, undef, 0.1);
612 my $install_exited = $?;
613 Log (undef, "Install script exited ".exit_status_s($install_exited));
614 foreach my $tar_filename (map { tar_filename_n($_); } (1..$git_tar_count)) {
615 unlink($tar_filename);
617 exit (1) if $install_exited != 0;
620 foreach (qw (script script_version script_parameters runtime_constraints))
624 (ref($Job->{$_}) ? JSON::encode_json($Job->{$_}) : $Job->{$_}));
626 foreach (split (/\n/, $Job->{knobs}))
628 Log (undef, "knob " . $_);
633 $main::success = undef;
639 my $thisround_succeeded = 0;
640 my $thisround_failed = 0;
641 my $thisround_failed_multiple = 0;
643 @jobstep_todo = sort { $jobstep[$a]->{level} <=> $jobstep[$b]->{level}
644 or $a <=> $b } @jobstep_todo;
645 my $level = $jobstep[$jobstep_todo[0]]->{level};
646 Log (undef, "start level $level");
651 my @freeslot = (0..$#slot);
654 my $progress_is_dirty = 1;
655 my $progress_stats_updated = 0;
657 update_progress_stats();
662 my $tasks_this_level = 0;
663 foreach my $id (@jobstep_todo) {
664 $tasks_this_level++ if ($jobstep[$id]->{level} == $level);
666 for (my $todo_ptr = 0; $todo_ptr <= $#jobstep_todo; $todo_ptr ++)
668 my $id = $jobstep_todo[$todo_ptr];
669 my $Jobstep = $jobstep[$id];
670 if ($Jobstep->{level} != $level)
675 pipe $reader{$id}, "writer" or croak ($!);
676 my $flags = fcntl ($reader{$id}, F_GETFL, 0) or croak ($!);
677 fcntl ($reader{$id}, F_SETFL, $flags | O_NONBLOCK) or croak ($!);
679 my $childslot = $freeslot[0];
680 my $childnode = $slot[$childslot]->{node};
681 my $childslotname = join (".",
682 $slot[$childslot]->{node}->{name},
683 $slot[$childslot]->{cpu});
685 my $childpid = fork();
688 $SIG{'INT'} = 'DEFAULT';
689 $SIG{'QUIT'} = 'DEFAULT';
690 $SIG{'TERM'} = 'DEFAULT';
692 foreach (values (%reader))
696 fcntl ("writer", F_SETFL, 0) or croak ($!); # no close-on-exec
697 open(STDOUT,">&writer");
698 open(STDERR,">&writer");
703 delete $ENV{"GNUPGHOME"};
704 $ENV{"TASK_UUID"} = $Jobstep->{'arvados_task'}->{'uuid'};
705 $ENV{"TASK_QSEQUENCE"} = $id;
706 $ENV{"TASK_SEQUENCE"} = $level;
707 $ENV{"JOB_SCRIPT"} = $Job->{script};
708 while (my ($param, $value) = each %{$Job->{script_parameters}}) {
709 $param =~ tr/a-z/A-Z/;
710 $ENV{"JOB_PARAMETER_$param"} = $value;
712 $ENV{"TASK_SLOT_NODE"} = $slot[$childslot]->{node}->{name};
713 $ENV{"TASK_SLOT_NUMBER"} = $slot[$childslot]->{cpu};
714 $ENV{"TASK_WORK"} = $ENV{"CRUNCH_TMP"}."/task/$childslotname";
715 $ENV{"HOME"} = $ENV{"TASK_WORK"};
716 $ENV{"TASK_KEEPMOUNT"} = $ENV{"TASK_WORK"}.".keep";
717 $ENV{"TASK_TMPDIR"} = $ENV{"TASK_WORK"}; # deprecated
718 $ENV{"CRUNCH_NODE_SLOTS"} = $slot[$childslot]->{node}->{ncpus};
719 $ENV{"PATH"} = $ENV{"CRUNCH_INSTALL"} . "/bin:" . $ENV{"PATH"};
723 my $max_node_concurrent_tasks = $ENV{CRUNCH_NODE_SLOTS};
724 if ($tasks_this_level < $max_node_concurrent_tasks) {
725 $max_node_concurrent_tasks = $tasks_this_level;
730 "--nodelist=".$childnode->{name},
731 qw(-n1 -c1 -N1 -D), $ENV{'TMPDIR'},
732 "--job-name=$job_id.$id.$$",
735 "if [ -e $ENV{TASK_WORK} ]; then rm -rf $ENV{TASK_WORK}; fi; "
736 ."mkdir -p $ENV{CRUNCH_TMP} $ENV{JOB_WORK} $ENV{TASK_WORK} $ENV{TASK_KEEPMOUNT} "
737 ."&& cd $ENV{CRUNCH_TMP} "
738 # These environment variables get used explicitly later in
739 # $command. No tool is expected to read these values directly.
740 .q{&& MEM=$(awk '($1 == "MemTotal:"){print $2}' </proc/meminfo) }
741 .q{&& SWAP=$(awk '($1 == "SwapTotal:"){print $2}' </proc/meminfo) }
742 ."&& MEMLIMIT=\$(( (\$MEM * 95) / ($max_node_concurrent_tasks * 100) )) "
743 ."&& let SWAPLIMIT=\$MEMLIMIT+\$SWAP ";
744 $command .= "&& exec arv-mount --by-id --allow-other $ENV{TASK_KEEPMOUNT} --exec ";
747 my $cidfile = "$ENV{CRUNCH_TMP}/$Jobstep->{arvados_task}->{uuid}-$Jobstep->{failures}.cid";
748 $command .= "crunchstat -cgroup-root=/sys/fs/cgroup -cgroup-parent=docker -cgroup-cid=$cidfile -poll=10000 ";
749 $command .= "$docker_bin run --rm=true --attach=stdout --attach=stderr --attach=stdin -i --user=crunch --cidfile=$cidfile --sig-proxy ";
750 # We only set memory limits if Docker lets us limit both memory and swap.
751 # Memory limits alone have been supported longer, but subprocesses tend
752 # to get SIGKILL if they exceed that without any swap limit set.
753 # See #5642 for additional background.
754 if ($docker_limitmem) {
755 $command .= "--memory=\${MEMLIMIT}k --memory-swap=\${SWAPLIMIT}k ";
758 # Dynamically configure the container to use the host system as its
759 # DNS server. Get the host's global addresses from the ip command,
760 # and turn them into docker --dns options using gawk.
762 q{$(ip -o address show scope global |
763 gawk 'match($4, /^([0-9\.:]+)\//, x){print "--dns", x[1]}') };
765 # The source tree and $destdir directory (which we have
766 # installed on the worker host) are available in the container,
767 # under the same path.
768 $command .= "--volume=\Q$ENV{CRUNCH_SRC}:$ENV{CRUNCH_SRC}:ro\E ";
769 $command .= "--volume=\Q$ENV{CRUNCH_INSTALL}:$ENV{CRUNCH_INSTALL}:ro\E ";
771 # Currently, we make arv-mount's mount point appear at /keep
772 # inside the container (instead of using the same path as the
773 # host like we do with CRUNCH_SRC and CRUNCH_INSTALL). However,
774 # crunch scripts and utilities must not rely on this. They must
775 # use $TASK_KEEPMOUNT.
776 $command .= "--volume=\Q$ENV{TASK_KEEPMOUNT}:/keep:ro\E ";
777 $ENV{TASK_KEEPMOUNT} = "/keep";
779 # TASK_WORK is almost exactly like a docker data volume: it
780 # starts out empty, is writable, and persists until no
781 # containers use it any more. We don't use --volumes-from to
782 # share it with other containers: it is only accessible to this
783 # task, and it goes away when this task stops.
785 # However, a docker data volume is writable only by root unless
786 # the mount point already happens to exist in the container with
787 # different permissions. Therefore, we [1] assume /tmp already
788 # exists in the image and is writable by the crunch user; [2]
789 # avoid putting TASK_WORK inside CRUNCH_TMP (which won't be
790 # writable if they are created by docker while setting up the
791 # other --volumes); and [3] create $TASK_WORK inside the
792 # container using $build_script.
793 $command .= "--volume=/tmp ";
794 $ENV{"TASK_WORK"} = "/tmp/crunch-job-task-work/$childslotname";
795 $ENV{"HOME"} = $ENV{"TASK_WORK"};
796 $ENV{"TASK_TMPDIR"} = $ENV{"TASK_WORK"}; # deprecated
798 # TODO: Share a single JOB_WORK volume across all task
799 # containers on a given worker node, and delete it when the job
800 # ends (and, in case that doesn't work, when the next job
803 # For now, use the same approach as TASK_WORK above.
804 $ENV{"JOB_WORK"} = "/tmp/crunch-job-work";
806 while (my ($env_key, $env_val) = each %ENV)
808 if ($env_key =~ /^(ARVADOS|CRUNCH|JOB|TASK)_/) {
809 $command .= "--env=\Q$env_key=$env_val\E ";
812 $command .= "--env=\QHOME=$ENV{HOME}\E ";
813 $command .= "\Q$docker_hash\E ";
814 $command .= "stdbuf --output=0 --error=0 ";
815 $command .= "perl - $ENV{CRUNCH_SRC}/crunch_scripts/" . $Job->{"script"};
818 $command .= "crunchstat -cgroup-root=/sys/fs/cgroup -poll=10000 ";
819 $command .= "stdbuf --output=0 --error=0 ";
820 $command .= "perl - $ENV{CRUNCH_SRC}/crunch_scripts/" . $Job->{"script"};
823 my @execargs = ('bash', '-c', $command);
824 srun (\@srunargs, \@execargs, undef, $build_script);
825 # exec() failed, we assume nothing happened.
826 die "srun() failed on build script\n";
829 if (!defined $childpid)
836 $proc{$childpid} = { jobstep => $id,
839 jobstepname => "$job_id.$id.$childpid",
841 croak ("assert failed: \$slot[$childslot]->{'pid'} exists") if exists $slot[$childslot]->{pid};
842 $slot[$childslot]->{pid} = $childpid;
844 Log ($id, "job_task ".$Jobstep->{'arvados_task'}->{'uuid'});
845 Log ($id, "child $childpid started on $childslotname");
846 $Jobstep->{starttime} = time;
847 $Jobstep->{node} = $childnode->{name};
848 $Jobstep->{slotindex} = $childslot;
849 delete $Jobstep->{stderr};
850 delete $Jobstep->{finishtime};
852 $Jobstep->{'arvados_task'}->{started_at} = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime($Jobstep->{starttime});
853 $Jobstep->{'arvados_task'}->save;
855 splice @jobstep_todo, $todo_ptr, 1;
858 $progress_is_dirty = 1;
862 (@slot > @freeslot && $todo_ptr+1 > $#jobstep_todo))
864 last THISROUND if $main::please_freeze || defined($main::success);
865 if ($main::please_info)
867 $main::please_info = 0;
869 create_output_collection();
871 update_progress_stats();
878 check_refresh_wanted();
880 update_progress_stats();
881 select (undef, undef, undef, 0.1);
883 elsif (time - $progress_stats_updated >= 30)
885 update_progress_stats();
887 if (($thisround_failed_multiple >= 8 && $thisround_succeeded == 0) ||
888 ($thisround_failed_multiple >= 16 && $thisround_failed_multiple > $thisround_succeeded))
890 my $message = "Repeated failure rate too high ($thisround_failed_multiple/"
891 .($thisround_failed+$thisround_succeeded)
892 .") -- giving up on this round";
893 Log (undef, $message);
897 # move slots from freeslot to holdslot (or back to freeslot) if necessary
898 for (my $i=$#freeslot; $i>=0; $i--) {
899 if ($slot[$freeslot[$i]]->{node}->{hold_until} > scalar time) {
900 push @holdslot, (splice @freeslot, $i, 1);
903 for (my $i=$#holdslot; $i>=0; $i--) {
904 if ($slot[$holdslot[$i]]->{node}->{hold_until} <= scalar time) {
905 push @freeslot, (splice @holdslot, $i, 1);
909 # give up if no nodes are succeeding
910 if (!grep { $_->{node}->{losing_streak} == 0 &&
911 $_->{node}->{hold_count} < 4 } @slot) {
912 my $message = "Every node has failed -- giving up on this round";
913 Log (undef, $message);
920 push @freeslot, splice @holdslot;
921 map { $slot[$freeslot[$_]]->{node}->{losing_streak} = 0 } (0..$#freeslot);
924 Log (undef, "wait for last ".(scalar keys %proc)." children to finish");
927 if ($main::please_continue) {
928 $main::please_continue = 0;
931 $main::please_info = 0, freeze(), create_output_collection(), save_meta(1) if $main::please_info;
935 check_refresh_wanted();
937 update_progress_stats();
938 select (undef, undef, undef, 0.1);
939 killem (keys %proc) if $main::please_freeze;
943 update_progress_stats();
944 freeze_if_want_freeze();
947 if (!defined $main::success)
950 $thisround_succeeded == 0 &&
951 ($thisround_failed == 0 || $thisround_failed > 4))
953 my $message = "stop because $thisround_failed tasks failed and none succeeded";
954 Log (undef, $message);
963 goto ONELEVEL if !defined $main::success;
966 release_allocation();
968 my $collated_output = &create_output_collection();
970 if (!$collated_output) {
971 Log (undef, "Failed to write output collection");
974 Log(undef, "job output $collated_output");
975 $Job->update_attributes('output' => $collated_output);
978 Log (undef, "finish");
983 if ($collated_output && $main::success) {
984 $final_state = 'Complete';
986 $final_state = 'Failed';
988 $Job->update_attributes('state' => $final_state);
990 exit (($final_state eq 'Complete') ? 0 : 1);
994 sub update_progress_stats
996 $progress_stats_updated = time;
997 return if !$progress_is_dirty;
998 my ($todo, $done, $running) = (scalar @jobstep_todo,
999 scalar @jobstep_done,
1000 scalar @slot - scalar @freeslot - scalar @holdslot);
1001 $Job->{'tasks_summary'} ||= {};
1002 $Job->{'tasks_summary'}->{'todo'} = $todo;
1003 $Job->{'tasks_summary'}->{'done'} = $done;
1004 $Job->{'tasks_summary'}->{'running'} = $running;
1005 $Job->update_attributes('tasks_summary' => $Job->{'tasks_summary'});
1006 Log (undef, "status: $done done, $running running, $todo todo");
1007 $progress_is_dirty = 0;
1014 my $pid = waitpid (-1, WNOHANG);
1015 return 0 if $pid <= 0;
1017 my $whatslot = ($slot[$proc{$pid}->{slot}]->{node}->{name}
1019 . $slot[$proc{$pid}->{slot}]->{cpu});
1020 my $jobstepid = $proc{$pid}->{jobstep};
1021 my $elapsed = time - $proc{$pid}->{time};
1022 my $Jobstep = $jobstep[$jobstepid];
1024 my $childstatus = $?;
1025 my $exitvalue = $childstatus >> 8;
1026 my $exitinfo = "exit ".exit_status_s($childstatus);
1027 $Jobstep->{'arvados_task'}->reload;
1028 my $task_success = $Jobstep->{'arvados_task'}->{success};
1030 Log ($jobstepid, "child $pid on $whatslot $exitinfo success=$task_success");
1032 if (!defined $task_success) {
1033 # task did not indicate one way or the other --> fail
1034 $Jobstep->{'arvados_task'}->{success} = 0;
1035 $Jobstep->{'arvados_task'}->save;
1042 $temporary_fail ||= $Jobstep->{node_fail};
1043 $temporary_fail ||= ($exitvalue == TASK_TEMPFAIL);
1045 ++$thisround_failed;
1046 ++$thisround_failed_multiple if $Jobstep->{'failures'} >= 1;
1048 # Check for signs of a failed or misconfigured node
1049 if (++$slot[$proc{$pid}->{slot}]->{node}->{losing_streak} >=
1050 2+$slot[$proc{$pid}->{slot}]->{node}->{ncpus}) {
1051 # Don't count this against jobstep failure thresholds if this
1052 # node is already suspected faulty and srun exited quickly
1053 if ($slot[$proc{$pid}->{slot}]->{node}->{hold_until} &&
1055 Log ($jobstepid, "blaming failure on suspect node " .
1056 $slot[$proc{$pid}->{slot}]->{node}->{name});
1057 $temporary_fail ||= 1;
1059 ban_node_by_slot($proc{$pid}->{slot});
1062 Log ($jobstepid, sprintf('failure (#%d, %s) after %d seconds',
1063 ++$Jobstep->{'failures'},
1064 $temporary_fail ? 'temporary ' : 'permanent',
1067 if (!$temporary_fail || $Jobstep->{'failures'} >= 3) {
1068 # Give up on this task, and the whole job
1071 # Put this task back on the todo queue
1072 push @jobstep_todo, $jobstepid;
1073 $Job->{'tasks_summary'}->{'failed'}++;
1077 ++$thisround_succeeded;
1078 $slot[$proc{$pid}->{slot}]->{node}->{losing_streak} = 0;
1079 $slot[$proc{$pid}->{slot}]->{node}->{hold_until} = 0;
1080 push @jobstep_done, $jobstepid;
1081 Log ($jobstepid, "success in $elapsed seconds");
1083 $Jobstep->{exitcode} = $childstatus;
1084 $Jobstep->{finishtime} = time;
1085 $Jobstep->{'arvados_task'}->{finished_at} = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime($Jobstep->{finishtime});
1086 $Jobstep->{'arvados_task'}->save;
1087 process_stderr ($jobstepid, $task_success);
1088 Log ($jobstepid, sprintf("task output (%d bytes): %s",
1089 length($Jobstep->{'arvados_task'}->{output}),
1090 $Jobstep->{'arvados_task'}->{output}));
1092 close $reader{$jobstepid};
1093 delete $reader{$jobstepid};
1094 delete $slot[$proc{$pid}->{slot}]->{pid};
1095 push @freeslot, $proc{$pid}->{slot};
1098 if ($task_success) {
1100 my $newtask_list = [];
1101 my $newtask_results;
1103 $newtask_results = api_call(
1106 'created_by_job_task_uuid' => $Jobstep->{'arvados_task'}->{uuid}
1108 'order' => 'qsequence',
1109 'offset' => scalar(@$newtask_list),
1111 push(@$newtask_list, @{$newtask_results->{items}});
1112 } while (@{$newtask_results->{items}});
1113 foreach my $arvados_task (@$newtask_list) {
1115 'level' => $arvados_task->{'sequence'},
1117 'arvados_task' => $arvados_task
1119 push @jobstep, $jobstep;
1120 push @jobstep_todo, $#jobstep;
1124 $progress_is_dirty = 1;
1128 sub check_refresh_wanted
1130 my @stat = stat $ENV{"CRUNCH_REFRESH_TRIGGER"};
1131 if (@stat && $stat[9] > $latest_refresh) {
1132 $latest_refresh = scalar time;
1133 my $Job2 = api_call("jobs/get", uuid => $jobspec);
1134 for my $attr ('cancelled_at',
1135 'cancelled_by_user_uuid',
1136 'cancelled_by_client_uuid',
1138 $Job->{$attr} = $Job2->{$attr};
1140 if ($Job->{'state'} ne "Running") {
1141 if ($Job->{'state'} eq "Cancelled") {
1142 Log (undef, "Job cancelled at " . $Job->{'cancelled_at'} . " by user " . $Job->{'cancelled_by_user_uuid'});
1144 Log (undef, "Job state unexpectedly changed to " . $Job->{'state'});
1147 $main::please_freeze = 1;
1154 # return if the kill list was checked <4 seconds ago
1155 if (defined $squeue_kill_checked && $squeue_kill_checked > time - 4)
1159 $squeue_kill_checked = time;
1161 # use killem() on procs whose killtime is reached
1164 if (exists $proc{$_}->{killtime}
1165 && $proc{$_}->{killtime} <= time)
1171 # return if the squeue was checked <60 seconds ago
1172 if (defined $squeue_checked && $squeue_checked > time - 60)
1176 $squeue_checked = time;
1180 # here is an opportunity to check for mysterious problems with local procs
1184 # get a list of steps still running
1185 my @squeue = `squeue -s -h -o '%i %j' && echo ok`;
1187 if ($squeue[-1] ne "ok")
1193 # which of my jobsteps are running, according to squeue?
1197 if (/^(\d+)\.(\d+) (\S+)/)
1199 if ($1 eq $ENV{SLURM_JOBID})
1206 # which of my active child procs (>60s old) were not mentioned by squeue?
1207 foreach (keys %proc)
1209 if ($proc{$_}->{time} < time - 60
1210 && !exists $ok{$proc{$_}->{jobstepname}}
1211 && !exists $proc{$_}->{killtime})
1213 # kill this proc if it hasn't exited in 30 seconds
1214 $proc{$_}->{killtime} = time + 30;
1220 sub release_allocation
1224 Log (undef, "release job allocation");
1225 system "scancel $ENV{SLURM_JOBID}";
1233 foreach my $job (keys %reader)
1236 while (0 < sysread ($reader{$job}, $buf, 8192))
1238 print STDERR $buf if $ENV{CRUNCH_DEBUG};
1239 $jobstep[$job]->{stderr} .= $buf;
1240 preprocess_stderr ($job);
1241 if (length ($jobstep[$job]->{stderr}) > 16384)
1243 substr ($jobstep[$job]->{stderr}, 0, 8192) = "";
1252 sub preprocess_stderr
1256 while ($jobstep[$job]->{stderr} =~ /^(.*?)\n/) {
1258 substr $jobstep[$job]->{stderr}, 0, 1+length($line), "";
1259 Log ($job, "stderr $line");
1260 if ($line =~ /srun: error: (SLURM job $ENV{SLURM_JOB_ID} has expired|Unable to confirm allocation for job $ENV{SLURM_JOB_ID})/) {
1262 $main::please_freeze = 1;
1264 elsif ($line =~ /(srun: error: (Node failure on|Unable to create job step|.*: Communication connection failure))|arvados.errors.Keep/) {
1265 $jobstep[$job]->{node_fail} = 1;
1266 ban_node_by_slot($jobstep[$job]->{slotindex});
1275 my $task_success = shift;
1276 preprocess_stderr ($job);
1279 Log ($job, "stderr $_");
1280 } split ("\n", $jobstep[$job]->{stderr});
1287 if (!open($keep, "-|", "arv-get", "--retries", retry_count(), $hash)) {
1288 Log(undef, "fetch_block run error from arv-get $hash: $!");
1291 my $output_block = "";
1294 my $bytes = sysread($keep, $buf, 1024 * 1024);
1295 if (!defined $bytes) {
1296 Log(undef, "fetch_block read error from arv-get: $!");
1297 $output_block = undef;
1299 } elsif ($bytes == 0) {
1300 # sysread returns 0 at the end of the pipe.
1303 # some bytes were read into buf.
1304 $output_block .= $buf;
1309 Log(undef, "fetch_block arv-get exited " . exit_status_s($?));
1310 $output_block = undef;
1312 return $output_block;
1315 # Create a collection by concatenating the output of all tasks (each
1316 # task's output is either a manifest fragment, a locator for a
1317 # manifest fragment stored in Keep, or nothing at all). Return the
1318 # portable_data_hash of the new collection.
1319 sub create_output_collection
1321 Log (undef, "collate");
1323 my ($child_out, $child_in);
1324 my $pid = open2($child_out, $child_in, 'python', '-c', q{
1327 print (arvados.api("v1").collections().
1328 create(body={"manifest_text": sys.stdin.read()}).
1329 execute(num_retries=int(sys.argv[1]))["portable_data_hash"])
1333 my $manifest_size = 0;
1337 my $output = $_->{'arvados_task'}->{output};
1338 next if (!defined($output));
1340 if ($output =~ /^[0-9a-f]{32}(\+\S+)*$/) {
1341 $next_write = fetch_block($output);
1343 $next_write = $output;
1345 if (defined($next_write)) {
1346 if (!defined(syswrite($child_in, $next_write))) {
1347 # There's been an error writing. Stop the loop.
1348 # We'll log details about the exit code later.
1351 $manifest_size += length($next_write);
1354 my $uuid = $_->{'arvados_task'}->{'uuid'};
1355 Log (undef, "Error retrieving '$output' output by task $task_idx ($uuid)");
1360 Log(undef, "collated output manifest text to send to API server is $manifest_size bytes with access tokens");
1363 my $s = IO::Select->new($child_out);
1364 if ($s->can_read(120)) {
1365 sysread($child_out, $joboutput, 1024 * 1024);
1368 Log(undef, "output collection creation exited " . exit_status_s($?));
1374 Log (undef, "timed out while creating output collection");
1375 foreach my $signal (2, 2, 2, 15, 15, 9) {
1376 kill($signal, $pid);
1377 last if waitpid($pid, WNOHANG) == -1;
1391 my $sig = 2; # SIGINT first
1392 if (exists $proc{$_}->{"sent_$sig"} &&
1393 time - $proc{$_}->{"sent_$sig"} > 4)
1395 $sig = 15; # SIGTERM if SIGINT doesn't work
1397 if (exists $proc{$_}->{"sent_$sig"} &&
1398 time - $proc{$_}->{"sent_$sig"} > 4)
1400 $sig = 9; # SIGKILL if SIGTERM doesn't work
1402 if (!exists $proc{$_}->{"sent_$sig"})
1404 Log ($proc{$_}->{jobstep}, "sending 2x signal $sig to pid $_");
1406 select (undef, undef, undef, 0.1);
1409 kill $sig, $_; # srun wants two SIGINT to really interrupt
1411 $proc{$_}->{"sent_$sig"} = time;
1412 $proc{$_}->{"killedafter"} = time - $proc{$_}->{"time"};
1422 vec($bits,fileno($_),1) = 1;
1428 # Send log output to Keep via arv-put.
1430 # $log_pipe_in and $log_pipe_out are the input and output filehandles to the arv-put pipe.
1431 # $log_pipe_pid is the pid of the arv-put subprocess.
1433 # The only functions that should access these variables directly are:
1435 # log_writer_start($logfilename)
1436 # Starts an arv-put pipe, reading data on stdin and writing it to
1437 # a $logfilename file in an output collection.
1439 # log_writer_send($txt)
1440 # Writes $txt to the output log collection.
1442 # log_writer_finish()
1443 # Closes the arv-put pipe and returns the output that it produces.
1445 # log_writer_is_active()
1446 # Returns a true value if there is currently a live arv-put
1447 # process, false otherwise.
1449 my ($log_pipe_in, $log_pipe_out, $log_pipe_pid);
1451 sub log_writer_start($)
1453 my $logfilename = shift;
1454 $log_pipe_pid = open2($log_pipe_out, $log_pipe_in,
1456 '--portable-data-hash',
1457 '--project-uuid', $Job->{owner_uuid},
1459 '--name', $logfilename,
1460 '--filename', $logfilename,
1464 sub log_writer_send($)
1467 print $log_pipe_in $txt;
1470 sub log_writer_finish()
1472 return unless $log_pipe_pid;
1474 close($log_pipe_in);
1477 my $s = IO::Select->new($log_pipe_out);
1478 if ($s->can_read(120)) {
1479 sysread($log_pipe_out, $arv_put_output, 1024);
1480 chomp($arv_put_output);
1482 Log (undef, "timed out reading from 'arv-put'");
1485 waitpid($log_pipe_pid, 0);
1486 $log_pipe_pid = $log_pipe_in = $log_pipe_out = undef;
1488 Log("log_writer_finish: arv-put exited ".exit_status_s($?))
1491 return $arv_put_output;
1494 sub log_writer_is_active() {
1495 return $log_pipe_pid;
1498 sub Log # ($jobstep_id, $logmessage)
1500 if ($_[1] =~ /\n/) {
1501 for my $line (split (/\n/, $_[1])) {
1506 my $fh = select STDERR; $|=1; select $fh;
1507 my $message = sprintf ("%s %d %s %s", $job_id, $$, @_);
1508 $message =~ s{([^ -\176])}{"\\" . sprintf ("%03o", ord($1))}ge;
1511 if (log_writer_is_active() || -t STDERR) {
1512 my @gmtime = gmtime;
1513 $datetime = sprintf ("%04d-%02d-%02d_%02d:%02d:%02d",
1514 $gmtime[5]+1900, $gmtime[4]+1, @gmtime[3,2,1,0]);
1516 print STDERR ((-t STDERR) ? ($datetime." ".$message) : $message);
1518 if (log_writer_is_active()) {
1519 log_writer_send($datetime . " " . $message);
1526 my ($package, $file, $line) = caller;
1527 my $message = "@_ at $file line $line\n";
1528 Log (undef, $message);
1529 freeze() if @jobstep_todo;
1530 create_output_collection() if @jobstep_todo;
1540 if ($Job->{'state'} eq 'Cancelled') {
1541 $Job->update_attributes('finished_at' => scalar gmtime);
1543 $Job->update_attributes('state' => 'Failed');
1550 my $justcheckpoint = shift; # false if this will be the last meta saved
1551 return if $justcheckpoint; # checkpointing is not relevant post-Warehouse.pm
1552 return unless log_writer_is_active();
1554 my $loglocator = log_writer_finish();
1555 Log (undef, "log manifest is $loglocator");
1556 $Job->{'log'} = $loglocator;
1557 $Job->update_attributes('log', $loglocator);
1561 sub freeze_if_want_freeze
1563 if ($main::please_freeze)
1565 release_allocation();
1568 # kill some srun procs before freeze+stop
1569 map { $proc{$_} = {} } @_;
1572 killem (keys %proc);
1573 select (undef, undef, undef, 0.1);
1575 while (($died = waitpid (-1, WNOHANG)) > 0)
1577 delete $proc{$died};
1582 create_output_collection();
1592 Log (undef, "Freeze not implemented");
1599 croak ("Thaw not implemented");
1615 $s =~ s{\\(.)}{$1 eq "n" ? "\n" : $1}ge;
1622 my $srunargs = shift;
1623 my $execargs = shift;
1624 my $opts = shift || {};
1626 my $args = $have_slurm ? [@$srunargs, @$execargs] : $execargs;
1628 $Data::Dumper::Terse = 1;
1629 $Data::Dumper::Indent = 0;
1630 my $show_cmd = Dumper($args);
1631 $show_cmd =~ s/(TOKEN\\*=)[^\s\']+/${1}[...]/g;
1632 $show_cmd =~ s/\n/ /g;
1633 warn "starting: $show_cmd\n";
1635 if (defined $stdin) {
1636 my $child = open STDIN, "-|";
1637 defined $child or die "no fork: $!";
1639 print $stdin or die $!;
1640 close STDOUT or die $!;
1645 return system (@$args) if $opts->{fork};
1648 warn "ENV size is ".length(join(" ",%ENV));
1649 die "exec failed: $!: @$args";
1653 sub ban_node_by_slot {
1654 # Don't start any new jobsteps on this node for 60 seconds
1656 $slot[$slotid]->{node}->{hold_until} = 60 + scalar time;
1657 $slot[$slotid]->{node}->{hold_count}++;
1658 Log (undef, "backing off node " . $slot[$slotid]->{node}->{name} . " for 60 seconds");
1663 my ($lockfile, $error_message) = @_;
1664 open L, ">", $lockfile or croak("$lockfile: $!");
1665 if (!flock L, LOCK_EX|LOCK_NB) {
1666 croak("Can't lock $lockfile: $error_message\n");
1670 sub find_docker_image {
1671 # Given a Keep locator, check to see if it contains a Docker image.
1672 # If so, return its stream name and Docker hash.
1673 # If not, return undef for both values.
1674 my $locator = shift;
1675 my ($streamname, $filename);
1676 my $image = api_call("collections/get", uuid => $locator);
1678 foreach my $line (split(/\n/, $image->{manifest_text})) {
1679 my @tokens = split(/\s+/, $line);
1681 $streamname = shift(@tokens);
1682 foreach my $filedata (grep(/^\d+:\d+:/, @tokens)) {
1683 if (defined($filename)) {
1684 return (undef, undef); # More than one file in the Collection.
1686 $filename = (split(/:/, $filedata, 3))[2];
1691 if (defined($filename) and ($filename =~ /^([0-9A-Fa-f]{64})\.tar$/)) {
1692 return ($streamname, $1);
1694 return (undef, undef);
1699 # Calculate the number of times an operation should be retried,
1700 # assuming exponential backoff, and that we're willing to retry as
1701 # long as tasks have been running. Enforce a minimum of 3 retries.
1702 my ($starttime, $endtime, $timediff, $retries);
1704 $starttime = $jobstep[0]->{starttime};
1705 $endtime = $jobstep[-1]->{finishtime};
1707 if (!defined($starttime)) {
1709 } elsif (!defined($endtime)) {
1710 $timediff = time - $starttime;
1712 $timediff = ($endtime - $starttime) - (time - $endtime);
1714 if ($timediff > 0) {
1715 $retries = int(log($timediff) / log(2));
1717 $retries = 1; # Use the minimum.
1719 return ($retries > 3) ? $retries : 3;
1723 # Pass in two function references.
1724 # This method will be called with the remaining arguments.
1725 # If it dies, retry it with exponential backoff until it succeeds,
1726 # or until the current retry_count is exhausted. After each failure
1727 # that can be retried, the second function will be called with
1728 # the current try count (0-based), next try time, and error message.
1729 my $operation = shift;
1730 my $retry_callback = shift;
1731 my $retries = retry_count();
1732 foreach my $try_count (0..$retries) {
1733 my $next_try = time + (2 ** $try_count);
1734 my $result = eval { $operation->(@_); };
1737 } elsif ($try_count < $retries) {
1738 $retry_callback->($try_count, $next_try, $@);
1739 my $sleep_time = $next_try - time;
1740 sleep($sleep_time) if ($sleep_time > 0);
1743 # Ensure the error message ends in a newline, so Perl doesn't add
1744 # retry_op's line number to it.
1750 # Pass in a /-separated API method name, and arguments for it.
1751 # This function will call that method, retrying as needed until
1752 # the current retry_count is exhausted, with a log on the first failure.
1753 my $method_name = shift;
1754 my $log_api_retry = sub {
1755 my ($try_count, $next_try_at, $errmsg) = @_;
1756 $errmsg =~ s/\s*\bat \Q$0\E line \d+\.?\s*//;
1757 $errmsg =~ s/\s/ /g;
1758 $errmsg =~ s/\s+$//;
1760 if ($next_try_at < time) {
1761 $retry_msg = "Retrying.";
1763 my $next_try_fmt = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime($next_try_at);
1764 $retry_msg = "Retrying at $next_try_fmt.";
1766 Log(undef, "API method $method_name failed: $errmsg. $retry_msg");
1769 foreach my $key (split(/\//, $method_name)) {
1770 $method = $method->{$key};
1772 return retry_op(sub { $method->execute(@_); }, $log_api_retry, @_);
1776 # Given a $?, return a human-readable exit code string like "0" or
1777 # "1" or "0 with signal 1" or "1 with signal 11".
1778 my $exitcode = shift;
1779 my $s = $exitcode >> 8;
1780 if ($exitcode & 0x7f) {
1781 $s .= " with signal " . ($exitcode & 0x7f);
1783 if ($exitcode & 0x80) {
1784 $s .= " with core dump";
1789 sub handle_readall {
1790 # Pass in a glob reference to a file handle.
1791 # Read all its contents and return them as a string.
1792 my $fh_glob_ref = shift;
1794 return <$fh_glob_ref>;
1797 sub tar_filename_n {
1799 return sprintf("%s/git.%s.%d.tar", $ENV{CRUNCH_TMP}, $job_id, $n);
1802 sub add_git_archive {
1803 # Pass in a git archive command as a string or list, a la system().
1804 # This method will save its output to be included in the archive sent to the
1808 if (!open(GIT_ARCHIVE, ">", tar_filename_n($git_tar_count))) {
1809 croak("Failed to save git archive: $!");
1811 my $git_pid = open2(">&GIT_ARCHIVE", $git_input, @_);
1813 waitpid($git_pid, 0);
1816 croak("Failed to save git archive: git exited " . exit_status_s($?));
1820 sub combined_git_archive {
1821 # Combine all saved tar archives into a single archive, then return its
1822 # contents in a string. Return undef if no archives have been saved.
1823 if ($git_tar_count < 1) {
1826 my $base_tar_name = tar_filename_n(1);
1827 foreach my $tar_to_append (map { tar_filename_n($_); } (2..$git_tar_count)) {
1828 my $tar_exit = system("tar", "-Af", $base_tar_name, $tar_to_append);
1829 if ($tar_exit != 0) {
1830 croak("Error preparing build archive: tar -A exited " .
1831 exit_status_s($tar_exit));
1834 if (!open(GIT_TAR, "<", $base_tar_name)) {
1835 croak("Could not open build archive: $!");
1837 my $tar_contents = handle_readall(\*GIT_TAR);
1839 return $tar_contents;
1845 # This is crunch-job's internal dispatch script. crunch-job running on the API
1846 # server invokes this script on individual compute nodes, or localhost if we're
1847 # running a job locally. It gets called in two modes:
1849 # * No arguments: Installation mode. Read a tar archive from the DATA
1850 # file handle; it includes the Crunch script's source code, and
1851 # maybe SDKs as well. Those should be installed in the proper
1852 # locations. This runs outside of any Docker container, so don't try to
1853 # introspect Crunch's runtime environment.
1855 # * With arguments: Crunch script run mode. This script should set up the
1856 # environment, then run the command specified in the arguments. This runs
1857 # inside any Docker container.
1860 use File::Path qw( make_path remove_tree );
1861 use POSIX qw(getcwd);
1863 use constant TASK_TEMPFAIL => 111;
1865 # Map SDK subdirectories to the path environments they belong to.
1866 my %SDK_ENVVARS = ("perl/lib" => "PERLLIB", "ruby/lib" => "RUBYLIB");
1868 my $destdir = $ENV{"CRUNCH_SRC"};
1869 my $commit = $ENV{"CRUNCH_SRC_COMMIT"};
1870 my $repo = $ENV{"CRUNCH_SRC_URL"};
1871 my $install_dir = $ENV{"CRUNCH_INSTALL"} || (getcwd() . "/opt");
1872 my $job_work = $ENV{"JOB_WORK"};
1873 my $task_work = $ENV{"TASK_WORK"};
1875 for my $dir ($destdir, $job_work, $task_work) {
1878 -e $dir or die "Failed to create temporary directory ($dir): $!";
1883 remove_tree($task_work, {keep_root => 1});
1886 open(STDOUT_ORIG, ">&", STDOUT);
1887 open(STDERR_ORIG, ">&", STDERR);
1888 open(STDOUT, ">>", "$destdir.log");
1889 open(STDERR, ">&", STDOUT);
1891 ### Crunch script run mode
1893 # We want to do routine logging during task 0 only. This gives the user
1894 # the information they need, but avoids repeating the information for every
1897 if ($ENV{TASK_SEQUENCE} eq "0") {
1900 printf STDERR_ORIG "[Crunch] $msg\n", @_;
1906 my $python_src = "$install_dir/python";
1907 my $venv_dir = "$job_work/.arvados.venv";
1908 my $venv_built = -e "$venv_dir/bin/activate";
1909 if ((!$venv_built) and (-d $python_src) and can_run("virtualenv")) {
1910 shell_or_die(undef, "virtualenv", "--quiet", "--system-site-packages",
1911 "--python=python2.7", $venv_dir);
1912 shell_or_die(TASK_TEMPFAIL, "$venv_dir/bin/pip", "--quiet", "install", "-I", $python_src);
1914 $Log->("Built Python SDK virtualenv");
1917 my $pip_bin = "pip";
1919 $Log->("Running in Python SDK virtualenv");
1920 $pip_bin = "$venv_dir/bin/pip";
1921 my $orig_argv = join(" ", map { quotemeta($_); } @ARGV);
1922 @ARGV = ("/bin/sh", "-ec",
1923 ". \Q$venv_dir/bin/activate\E; exec $orig_argv");
1924 } elsif (-d $python_src) {
1925 $Log->("Warning: virtualenv not found inside Docker container default " .
1926 "\$PATH. Can't install Python SDK.");
1929 my $pkgs = `(\Q$pip_bin\E freeze 2>/dev/null | grep arvados) || dpkg-query --show '*arvados*'`;
1931 $Log->("Using Arvados SDK:");
1932 foreach my $line (split /\n/, $pkgs) {
1936 $Log->("Arvados SDK packages not found");
1939 while (my ($sdk_dir, $sdk_envkey) = each(%SDK_ENVVARS)) {
1940 my $sdk_path = "$install_dir/$sdk_dir";
1942 if ($ENV{$sdk_envkey}) {
1943 $ENV{$sdk_envkey} = "$sdk_path:" . $ENV{$sdk_envkey};
1945 $ENV{$sdk_envkey} = $sdk_path;
1947 $Log->("Arvados SDK added to %s", $sdk_envkey);
1953 open(STDOUT, ">&", STDOUT_ORIG);
1954 open(STDERR, ">&", STDERR_ORIG);
1956 die "Cannot exec `@ARGV`: $!";
1959 ### Installation mode
1960 open L, ">", "$destdir.lock" or die "$destdir.lock: $!";
1962 if (readlink ("$destdir.commit") eq $commit && -d $destdir) {
1963 # This version already installed -> nothing to do.
1967 unlink "$destdir.commit";
1970 if (!open(TARX, "|-", "tar", "-xC", $destdir)) {
1971 die "Error launching 'tar -xC $destdir': $!";
1973 # If we send too much data to tar in one write (> 4-5 MiB), it stops, and we
1974 # get SIGPIPE. We must feed it data incrementally.
1976 while (read(DATA, $tar_input, 65536)) {
1977 print TARX $tar_input;
1980 die "'tar -xC $destdir' exited $?: $!";
1985 my $sdk_root = "$destdir/.arvados.sdk/sdk";
1987 foreach my $sdk_lang (("python",
1988 map { (split /\//, $_, 2)[0]; } keys(%SDK_ENVVARS))) {
1989 if (-d "$sdk_root/$sdk_lang") {
1990 if (!rename("$sdk_root/$sdk_lang", "$install_dir/$sdk_lang")) {
1991 die "Failed to install $sdk_lang SDK: $!";
1997 my $python_dir = "$install_dir/python";
1998 if ((-d $python_dir) and can_run("python2.7") and
1999 (system("python2.7", "$python_dir/setup.py", "--quiet", "egg_info") != 0)) {
2000 # egg_info failed, probably when it asked git for a build tag.
2001 # Specify no build tag.
2002 open(my $pysdk_cfg, ">>", "$python_dir/setup.cfg");
2003 print $pysdk_cfg "\n[egg_info]\ntag_build =\n";
2007 if (-e "$destdir/crunch_scripts/install") {
2008 shell_or_die (undef, "$destdir/crunch_scripts/install", $install_dir);
2009 } elsif (!-e "./install.sh" && -e "./tests/autotests.sh") {
2011 shell_or_die (undef, "./tests/autotests.sh", $install_dir);
2012 } elsif (-e "./install.sh") {
2013 shell_or_die (undef, "./install.sh", $install_dir);
2017 unlink "$destdir.commit.new";
2018 symlink ($commit, "$destdir.commit.new") or die "$destdir.commit.new: $!";
2019 rename ("$destdir.commit.new", "$destdir.commit") or die "$destdir.commit: $!";
2025 my $command_name = shift;
2026 open(my $which, "-|", "which", $command_name);
2027 while (<$which>) { }
2034 my $exitcode = shift;
2036 if ($ENV{"DEBUG"}) {
2037 print STDERR "@_\n";
2039 if (system (@_) != 0) {
2042 my $exitstatus = sprintf("exit %d signal %d", $code >> 8, $code & 0x7f);
2043 open STDERR, ">&STDERR_ORIG";
2044 system ("cat $destdir.log >&2");
2045 warn "@_ failed ($err): $exitstatus";
2046 if (defined($exitcode)) {
2050 exit (($code >> 8) || 1);