Queen.pm 39.9 KB
Newer Older
Jessica Severin's avatar
Jessica Severin committed
1 2 3
=pod 

=head1 NAME
4

5 6 7
    Bio::EnsEMBL::Hive::Queen

=head1 DESCRIPTION
Jessica Severin's avatar
Jessica Severin committed
8

9 10 11 12
    The Queen of the Hive based job control system is responsible to 'birthing' the
    correct number of workers of the right type so that they can find jobs to do.
    It will also free up jobs of Workers that died unexpectantly so that other workers
    can claim them to do.
13

14 15 16 17
    Hive based processing is a concept based on a more controlled version
    of an autonomous agent type system.  Each worker is not told what to do
    (like a centralized control system - like the current pipeline system)
    but rather queries a central database for jobs (give me jobs).
Jessica Severin's avatar
Jessica Severin committed
18

19 20
    Each worker is linked to an analysis_id, registers its self on creation
    into the Hive, creates a RunnableDB instance of the Analysis->module,
21
    gets $analysis->batch_size jobs from the job table, does its work,
22 23 24 25 26 27 28 29 30 31 32 33
    creates the next layer of job entries by interfacing to
    the DataflowRuleAdaptor to determine the analyses it needs to pass its
    output data to and creates jobs on the next analysis database.
    It repeats this cycle until it has lived its lifetime or until there are no
    more jobs left.
    The lifetime limit is just a safety limit to prevent these from 'infecting'
    a system.

    The Queens job is to simply birth Workers of the correct analysis_id to get the
    work down.  The only other thing the Queen does is free up jobs that were
    claimed by Workers that died unexpectantly so that other workers can take
    over the work.
34

35 36 37 38 39 40 41 42
    The Beekeeper is in charge of interfacing between the Queen and a compute resource
    or 'compute farm'.  Its job is to query Queens if they need any workers and to
    send the requested number of workers to open machines via the runWorker.pl script.
    It is also responsible for interfacing with the Queen to identify worker which died
    unexpectantly.

=head1 LICENSE

43
    Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Matthieu Muffato's avatar
Matthieu Muffato committed
44
    Copyright [2016-2017] EMBL-European Bioinformatics Institute
45 46 47 48 49 50 51 52 53

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License
    is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and limitations under the License.
Jessica Severin's avatar
Jessica Severin committed
54 55

=head1 CONTACT
56

57
    Please subscribe to the Hive mailing list:  http://listserver.ebi.ac.uk/mailman/listinfo/ehive-users  to discuss Hive-related questions or to be notified of our updates
Jessica Severin's avatar
Jessica Severin committed
58 59

=head1 APPENDIX
60

61 62
    The rest of the documentation details each of the object methods. 
    Internal methods are usually preceded with a _
Jessica Severin's avatar
Jessica Severin committed
63 64 65

=cut

66

Jessica Severin's avatar
Jessica Severin committed
67 68 69
package Bio::EnsEMBL::Hive::Queen;

use strict;
70
use warnings;
71
use File::Path 'make_path';
72
use List::Util qw(max);
73

74
use Bio::EnsEMBL::Hive::Utils ('destringify', 'dir_revhash');  # NB: needed by invisible code
75
use Bio::EnsEMBL::Hive::Role;
76
use Bio::EnsEMBL::Hive::Scheduler;
77
use Bio::EnsEMBL::Hive::Valley;
78
use Bio::EnsEMBL::Hive::Worker;
Jessica Severin's avatar
Jessica Severin committed
79

80 81 82 83 84 85 86
use base ('Bio::EnsEMBL::Hive::DBSQL::ObjectAdaptor');

sub default_table_name {
    return 'worker';
}


87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
sub default_input_column_mapping {
    my $self    = shift @_;
    my $driver  = $self->dbc->driver();
    return  {
        'when_submitted' => {
                            'mysql'     => "UNIX_TIMESTAMP()-UNIX_TIMESTAMP(when_submitted) seconds_since_when_submitted ",
                            'sqlite'    => "strftime('%s','now')-strftime('%s',when_submitted) seconds_since_when_submitted ",
                            'pgsql'     => "EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - when_submitted) seconds_since_when_submitted ",
        }->{$driver},
    };
}


sub do_not_update_columns {
    return ['when_submitted'];
}



106 107 108
sub object_class {
    return 'Bio::EnsEMBL::Hive::Worker';
}
109

Jessica Severin's avatar
Jessica Severin committed
110

111
############################
Jessica Severin's avatar
Jessica Severin committed
112
#
113
# PUBLIC API
Jessica Severin's avatar
Jessica Severin committed
114
#
115
############################
Jessica Severin's avatar
Jessica Severin committed
116

117

Jessica Severin's avatar
Jessica Severin committed
118 119
=head2 create_new_worker

120 121 122 123
  Description: Creates an entry in the worker table,
               populates some non-storable attributes
               and returns a Worker object based on that insert.
               This guarantees that each worker registered in this Queen's hive is properly registered.
Jessica Severin's avatar
Jessica Severin committed
124
  Returntype : Bio::EnsEMBL::Hive::Worker
125
  Caller     : runWorker.pl
Jessica Severin's avatar
Jessica Severin committed
126 127 128 129

=cut

sub create_new_worker {
130 131
    my $self    = shift @_;
    my %flags   = @_;
132

133
    my ($preregistered, $resource_class_id, $resource_class_name, $beekeeper_id,
134 135
            $no_write, $debug, $worker_log_dir, $hive_log_dir, $job_limit, $life_span, $no_cleanup, $retry_throwing_jobs, $can_respecialize,
            $worker_delay_startup_seconds, $worker_crash_on_startup_prob)
136
     = @flags{qw(-preregistered -resource_class_id -resource_class_name -beekeeper_id
137 138
            -no_write -debug -worker_log_dir -hive_log_dir -job_limit -life_span -no_cleanup -retry_throwing_jobs -can_respecialize
            -worker_delay_startup_seconds -worker_crash_on_startup_prob)};
139 140

    sleep( $worker_delay_startup_seconds // 0 );    # NB: undefined parameter would have caused eternal sleep!
141

142 143 144 145 146 147
    if( defined( $worker_crash_on_startup_prob ) ) {
        if( rand(1) < $worker_crash_on_startup_prob ) {
            die "This is a requested crash of the Worker (with probability=$worker_crash_on_startup_prob)";
        }
    }

148 149 150 151
    my ($meadow, $process_id, $meadow_host, $meadow_user) = Bio::EnsEMBL::Hive::Valley->new()->whereami();
    die "Valley is not fully defined" unless ($meadow && $process_id && $meadow_host && $meadow_user);
    my $meadow_type = $meadow->type;
    my $meadow_name = $meadow->cached_name;
152

153
    foreach my $prev_worker_incarnation (@{ $self->find_previous_worker_incarnations($meadow_type, $meadow_name, $process_id) }) {
154
            # So far 'RELOCATED events' has been detected on LSF 9.0 in response to sending signal #99 or #100
155 156 157 158 159 160 161 162 163 164
            # Since I don't know how to avoid them, I am trying to register them when they happen.
            # The following snippet buries the previous incarnation of the Worker before starting a new one.
            #
            # FIXME: if GarabageCollector (beekeeper -dead) gets to these processes first, it will register them as DEAD/UNKNOWN.
            #       LSF 9.0 does not report "rescheduling" events in the output of 'bacct', but does mention them in 'bhist'.
            #       So parsing 'bhist' output would probably yield the most accurate & confident registration of these events.
        $prev_worker_incarnation->cause_of_death( 'RELOCATED' );
        $self->register_worker_death( $prev_worker_incarnation );
    }

165
    my $worker;
166

167
    if($preregistered) {
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        my $sec = 1;
        until( $worker = $self->fetch_preregistered_worker($meadow_type, $meadow_name, $process_id) ) {
            $self->db->get_LogMessageAdaptor->store_hive_message("Preregistered Worker $meadow_type/$meadow_name:$process_id waiting $sec more seconds to fetch itself...", 'WORKER_CAUTION' );
            sleep($sec);
            $sec *= 2;
        }

            # only update the fields that were not available at the time of submission:
        $worker->meadow_host( $meadow_host );
        $worker->meadow_user( $meadow_user );
        $worker->when_born(   'CURRENT_TIMESTAMP' );
        $worker->status(      'READY' );

        $self->update( $worker );

    } else {
        my $resource_class;

        if( defined($resource_class_name) ) {
            $resource_class = $self->db->get_ResourceClassAdaptor->fetch_by_name($resource_class_name)
                or die "resource_class with name='$resource_class_name' could not be fetched from the database";
        } elsif( defined($resource_class_id) ) {
            $resource_class = $self->db->get_ResourceClassAdaptor->fetch_by_dbID($resource_class_id)
                or die "resource_class with dbID='$resource_class_id' could not be fetched from the database";
        }

        $worker = Bio::EnsEMBL::Hive::Worker->new(
            'meadow_type'       => $meadow_type,
            'meadow_name'       => $meadow_name,
            'process_id'        => $process_id,
            'resource_class'    => $resource_class,
            'beekeeper_id'      => $beekeeper_id,

            'meadow_host'       => $meadow_host,
            'meadow_user'       => $meadow_user,
        );

        if (ref($self)) {
            $self->store( $worker );

            $worker->when_born(   'CURRENT_TIMESTAMP' );
            $self->update_when_born( $worker );
211

212 213
            $self->refresh( $worker );
        }
214
    }
215

216
    $worker->set_log_directory_name($hive_log_dir, $worker_log_dir);
217 218 219

    $worker->init;

220 221
    if(defined($job_limit)) {
      $worker->job_limiter($job_limit);
222 223 224
      $worker->life_span(0);
    }

225
    $worker->life_span($life_span * 60)                 if($life_span); # $life_span min -> sec
226 227 228 229 230 231 232 233 234

    $worker->execute_writes(0)                          if($no_write);

    $worker->perform_cleanup(0)                         if($no_cleanup);

    $worker->debug($debug)                              if($debug);

    $worker->retry_throwing_jobs($retry_throwing_jobs)  if(defined $retry_throwing_jobs);

235 236
    $worker->can_respecialize($can_respecialize)        if(defined $can_respecialize);

237 238 239 240
    return $worker;
}


241
=head2 specialize_worker
242

243 244
  Description: If analysis_id or logic_name is specified it will try to specialize the Worker into this analysis.
               If not specified the Queen will analyze the hive and pick the most suitable analysis.
245
  Caller     : Bio::EnsEMBL::Hive::Worker
246 247 248

=cut

249
sub specialize_worker {
250 251
    my $self    = shift @_;
    my $worker  = shift @_;
252
    my $flags   = shift @_;
253

254 255
    my ($analyses_pattern, $job_id, $force)
     = @$flags{qw(-analyses_pattern -job_id -force)};
256

257 258
    if( $analyses_pattern and $job_id ) {
        die "At most one of the options {-analyses_pattern, -job_id} can be set to pre-specialize a Worker";
Leo Gordon's avatar
Leo Gordon committed
259 260
    }

261
    my $analysis;
262

263
    if( $job_id ) {
264

265
        warn "resetting and fetching job for job_id '$job_id'\n";
266

267
        my $job_adaptor = $self->db->get_AnalysisJobAdaptor;
268

269 270 271
        my $job = $job_adaptor->fetch_by_dbID( $job_id )
            or die "Could not fetch job with dbID='$job_id'";
        my $job_status = $job->status();
272

273
        if($job_status =~/(CLAIMED|PRE_CLEANUP|FETCH_INPUT|RUN|WRITE_OUTPUT|POST_HEALTHCHECK|POST_CLEANUP)/ ) {
274 275 276
            die "Job with dbID='$job_id' is already in progress, cannot run";   # FIXME: try GC first, then complain
        } elsif($job_status =~/(DONE|SEMAPHORED)/ and !$force) {
            die "Job with dbID='$job_id' is $job_status, please use -force 1 to override";
277 278
        }

279 280 281
        $analysis = $job->analysis;
        if(($analysis->stats->status eq 'BLOCKED') and !$force) {
            die "Analysis is BLOCKED, can't specialize a worker. Please use -force 1 to override";
282 283
        }

284
        if(($job_status eq 'DONE') and my $controlled_semaphore = $job->controlled_semaphore) {
285
            warn "Increasing the semaphore count of the dependent job";
286
            $controlled_semaphore->increase_by( [ $job ] );
287 288
        }

289 290 291
        my %status2counter = ('FAILED' => 'failed_job_count', 'READY' => 'ready_job_count', 'DONE' => 'done_job_count', 'PASSED_ON' => 'done_job_count', 'SEMAPHORED' => 'semaphored_job_count');
        $analysis->stats->adaptor->increment_a_counter( $status2counter{$job->status}, -1, $job->analysis_id );

292
    } else {
293

294
        $analyses_pattern //= '%';  # for printing
295
        my $analyses_matching_pattern   = $worker->hive_pipeline->collection_of( 'Analysis' )->find_all_by_pattern( $analyses_pattern );
296

297 298 299 300
            # refresh the stats of matching analyses before re-specialization:
        foreach my $analysis ( @$analyses_matching_pattern ) {
            $analysis->stats->refresh();
        }
301
        $self->db->hive_pipeline->invalidate_hive_current_load;
302 303

        $analysis = Bio::EnsEMBL::Hive::Scheduler::suggest_analysis_to_specialize_a_worker($worker, $analyses_matching_pattern, $analyses_pattern);
304 305 306 307 308 309 310 311

        unless( ref($analysis) ) {

            $worker->cause_of_death('NO_ROLE');

            my $msg = $analysis // "No analysis suitable for the worker was found";
            die "$msg\n";
        }
312
    }
313

314 315
    my $new_role = Bio::EnsEMBL::Hive::Role->new(
        'worker'        => $worker,
316
        'analysis'      => $analysis,
317
    );
318
    $self->db->get_RoleAdaptor->store( $new_role );
319 320
    $worker->current_role( $new_role );

321 322
    my $analysis_stats_adaptor = $self->db->get_AnalysisStatsAdaptor;

323 324 325 326 327 328 329 330 331
    if($job_id) {
        my $role_id = $new_role->dbID;
        if( my $job = $self->db->get_AnalysisJobAdaptor->reset_or_grab_job_by_dbID($job_id, $role_id) ) {

            $worker->special_batch( [ $job ] );
        } else {
            die "Could not claim job with dbID='$job_id' for Role with dbID='$role_id'";
        }

Leo Gordon's avatar
Leo Gordon committed
332
    } else {    # Note: special batch Workers should avoid flipping the status to 'WORKING' in case the analysis is still 'BLOCKED'
333

334
        $analysis_stats_adaptor->update_status($analysis->dbID, 'WORKING');
335 336 337 338 339 340 341 342
    }

        # The following increment used to be done only when no specific task was given to the worker,
        # thereby excluding such "special task" workers from being counted in num_running_workers.
        #
        # However this may be tricky to emulate by triggers that know nothing about "special tasks",
        # so I am (temporarily?) simplifying the accounting algorithm.
        #
343
    $analysis_stats_adaptor->increment_a_counter( 'num_running_workers', 1, $analysis->dbID );
Jessica Severin's avatar
Jessica Severin committed
344 345
}

346

Jessica Severin's avatar
Jessica Severin committed
347
sub register_worker_death {
348
    my ($self, $worker, $update_when_checked_in) = @_;
349

350 351 352
    my $worker_id       = $worker->dbID;
    my $work_done       = $worker->work_done;
    my $cause_of_death  = $worker->cause_of_death || 'UNKNOWN';    # make sure we do not attempt to insert a void
353
    my $worker_died     = $worker->when_died;
354

355 356 357
    my $current_role    = $worker->current_role;

    unless( $current_role ) {
358
        $worker->current_role( $current_role = $self->db->get_RoleAdaptor->fetch_last_unfinished_by_worker_id( $worker_id ) );
359 360
    }

361
    if( $current_role and !$current_role->when_finished() ) {
362
        # List of cause_of_death:
363 364
        # only happen before or after a batch: 'NO_ROLE','NO_WORK','JOB_LIMIT','HIVE_OVERLOAD','LIFESPAN','SEE_MSG'
        # can happen whilst the worker is running a batch: 'CONTAMINATED','RELOCATED','KILLED_BY_USER','MEMLIMIT','RUNLIMIT','SEE_MSG','UNKNOWN'
365
        my $release_undone_jobs = ($cause_of_death =~ /^(CONTAMINATED|RELOCATED|KILLED_BY_USER|MEMLIMIT|RUNLIMIT|SEE_MSG|UNKNOWN|SEE_EXIT_STATUS)$/);
366
        $current_role->worker($worker); # So that release_undone_jobs_from_role() has the correct cause_of_death and work_done
367
        $current_role->when_finished( $worker_died );
368
        $self->db->get_RoleAdaptor->finalize_role( $current_role, $release_undone_jobs );
369
    }
370 371

    my $sql = "UPDATE worker SET status='DEAD', work_done='$work_done', cause_of_death='$cause_of_death'"
372 373
            . ( $update_when_checked_in ? ', when_checked_in=CURRENT_TIMESTAMP ' : '' )
            . ( $worker_died ? ", when_died='$worker_died'" : ', when_died=CURRENT_TIMESTAMP' )
374 375
            . " WHERE worker_id='$worker_id' ";

376
    $self->dbc->protected_prepare_execute( [ $sql ],
377
        sub { my ($after) = @_; $self->db->get_LogMessageAdaptor->store_worker_message( $worker, "register_worker_death".$after, 'INFO' ); }
378
    );
Jessica Severin's avatar
Jessica Severin committed
379 380
}

381

382 383 384 385 386 387 388
sub cached_resource_mapping {
    my $self = shift;
    $self->{'_cached_resource_mapping'} ||= { map { $_->dbID => $_->name } $self->db->hive_pipeline->collection_of('ResourceClass')->list };
    return $self->{'_cached_resource_mapping'};
}


389
sub registered_workers_attributes {
390 391
    my $self = shift @_;

392
    return $self->fetch_all("status!='DEAD'", 1, ['meadow_type', 'meadow_name', 'meadow_user', 'process_id'], ['resource_class_id', 'status'] );
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
}


sub get_submitted_worker_counts_by_meadow_type_rc_name {
    my $self = shift @_;

    my $worker_counts_by_meadow_type_rc_id  = $self->count_all("status='SUBMITTED'", ['meadow_type', 'resource_class_id'] );
    my $cached_resource_mapping             = $self->cached_resource_mapping;

    my %counts_by_meadow_type_rc_name = ();

    while(my ($meadow_type, $counts_by_rc_id) = each %$worker_counts_by_meadow_type_rc_id) {
        while(my ($rc_id, $count) = each %$counts_by_rc_id) {
            my $rc_name = $cached_resource_mapping->{ $rc_id } || '__undefined_rc_name__';
            $counts_by_meadow_type_rc_name{ $meadow_type }{ $rc_name } = $count;
        }
    }

    return \%counts_by_meadow_type_rc_name;
412 413 414
}


415
sub check_for_dead_workers {    # scans the whole Valley for lost Workers (but ignores unreachable ones)
416
    my ($self, $valley, $check_buried_in_haste, $bury_unkwn_workers) = @_;
Leo Gordon's avatar
Leo Gordon committed
417

418 419
    my $last_few_seconds            = 5;    # FIXME: It is probably a good idea to expose this parameter for easier tuning.

420
    warn "GarbageCollector:\tChecking for lost Workers...\n";
421

422 423
    my $reconciled_worker_statuses          = $valley->query_worker_statuses( $self->registered_workers_attributes );
    my $signature_and_pid_to_worker_status  = $valley->status_of_all_our_workers_by_meadow_signature( $reconciled_worker_statuses );
424

425
    my $queen_overdue_workers               = $self->fetch_overdue_workers( $last_few_seconds );    # check the workers we have not seen active during the $last_few_seconds
426
    warn "GarbageCollector:\t[Queen:] out of ".scalar(@$queen_overdue_workers)." Workers that haven't checked in during the last $last_few_seconds seconds...\n";
427

428 429 430
    my $update_when_seen_sql = "UPDATE worker SET when_seen=CURRENT_TIMESTAMP WHERE worker_id=?";
    my $update_when_seen_sth;

431 432
    my %meadow_status_counts        = ();
    my %mt_and_pid_to_lost_worker   = ();
433
    foreach my $worker (@$queen_overdue_workers) {
Leo Gordon's avatar
Leo Gordon committed
434

435
        my $meadow_signature    = $worker->meadow_type.'/'.$worker->meadow_name;
436
        if(my $pid_to_worker_status = $signature_and_pid_to_worker_status->{$meadow_signature}) {   # the whole Meadow subhash is either present or the Meadow is unreachable
Leo Gordon's avatar
Leo Gordon committed
437

438 439
            my $meadow_type = $worker->meadow_type;
            my $process_id  = $worker->process_id;
440 441 442 443 444 445 446 447
            my $status = $pid_to_worker_status->{$process_id};

            if($bury_unkwn_workers and ($status eq 'UNKWN')) {
                if( my $meadow = $valley->find_available_meadow_responsible_for_worker( $worker ) ) {
                    if($meadow->can('kill_worker')) {
                        if($worker->meadow_user eq $ENV{'USER'}) {  # if I'm actually allowed to kill the worker...
                            warn "GarbageCollector:\tKilling/forgetting the UNKWN worker by process_id $process_id";

448
                            $meadow->kill_worker($worker, 1);
449
                            $status = 'LOST';
450 451 452 453 454
                        }
                    }
                }
            }

455 456 457
            $meadow_status_counts{$meadow_signature}{$status}++;

            if(($status eq 'LOST') or ($status eq 'SUBMITTED')) {
458 459 460

                $mt_and_pid_to_lost_worker{$meadow_type}{$process_id} = $worker;
            } else {  # can be RUN|PEND|xSUSP
461

462
                $update_when_seen_sth ||= $self->prepare( $update_when_seen_sql );  # only prepare once at most
463 464

                $update_when_seen_sth->execute( $worker->dbID );
465
            }
466
        } else {
467
            $meadow_status_counts{$meadow_signature}{'UNREACHABLE'}++;   # Worker is unreachable from this Valley
468
        }
469 470
    }

471 472
    $update_when_seen_sth->finish() if $update_when_seen_sth;

473
        # print a quick summary report:
474 475
    while(my ($meadow_signature, $status_count) = each %meadow_status_counts) {
        warn "GarbageCollector:\t[$meadow_signature Meadow:]\t".join(', ', map { "$_:$status_count->{$_}" } keys %$status_count )."\n\n";
476
    }
477

478 479 480 481 482 483
    while(my ($meadow_type, $pid_to_lost_worker) = each %mt_and_pid_to_lost_worker) {
        my $this_meadow = $valley->available_meadow_hash->{$meadow_type};

        if(my $lost_this_meadow = scalar(keys %$pid_to_lost_worker) ) {
            warn "GarbageCollector:\tDiscovered $lost_this_meadow lost $meadow_type Workers\n";

484
            my $report_entries;
485

486
            if($report_entries = $this_meadow->get_report_entries_for_process_ids( keys %$pid_to_lost_worker )) {
487
                my $lost_with_known_cod = scalar( grep { $_->{'cause_of_death'} } values %$report_entries);
488 489 490
                warn "GarbageCollector:\tFound why $lost_with_known_cod of $meadow_type Workers died\n";
            }

491
            warn "GarbageCollector:\tRecording workers' missing attributes, registereing their death, releasing their jobs and cleaning up temp directories\n";
492
            while(my ($process_id, $worker) = each %$pid_to_lost_worker) {
493 494 495 496 497 498 499 500 501 502 503
                if(my $report_entry = $report_entries && $report_entries->{$process_id}) {
                    my @updated_attribs = ();
                    foreach my $worker_attrib ( qw(when_born meadow_host when_died cause_of_death) ) {
                        if( defined( $report_entry->{$worker_attrib} ) ) {
                            $worker->$worker_attrib( $report_entry->{$worker_attrib} );
                            push @updated_attribs, $worker_attrib;
                        }
                    }
                    $self->update( $worker, @updated_attribs ) if(scalar(@updated_attribs));
                }

504 505 506
                my $max_limbo_seconds = $this_meadow->config_get('MaxLimboSeconds') // 0;   # The maximum time for a Meadow to start showing the Worker (even in PEND state) after submission.
                                                                                            # We use it as a timeout for burying SUBMITTED and Meadow-invisible entries in the 'worker' table.

507
                if( ($worker->status eq 'LOST')
508
                 || $worker->when_died                                                      # reported by Meadow as DEAD (only if Meadow supports get_report_entries_for_process_ids)
509
                 || ($worker->seconds_since_when_submitted > $max_limbo_seconds) ) {        # SUBMITTED and Meadow-invisible for too long => we consider them LOST
510 511 512

                    $worker->cause_of_death('LIMBO') if( ($worker->status eq 'SUBMITTED') and !$worker->cause_of_death);    # LIMBO cause_of_death means: found in SUBMITTED state, exceeded the timeout, Meadow did not tell us more

513
                    $self->register_worker_death( $worker );
514 515 516 517

                    if( ($worker->status eq 'LOST')                 # There is no worker_temp_directory before specialization
                    and ($worker->meadow_user eq $ENV{'USER'}) ) {  # if I'm actually allowed to kill the worker...
                            $valley->cleanup_left_temp_directory( $worker );
518
                    }
519
                }
520
            }
521

522
            if( $report_entries && %$report_entries ) {    # use the opportunity to also store resource usage of the buried workers:
523 524 525
                my $processid_2_workerid = { map { $_ => $pid_to_lost_worker->{$_}->dbID } keys %$pid_to_lost_worker };
                $self->store_resource_usage( $report_entries, $processid_2_workerid );
            }
526 527 528
        }
    }

529
        # the following bit is completely Meadow-agnostic and only restores database integrity:
Leo Gordon's avatar
Leo Gordon committed
530
    if($check_buried_in_haste) {
Matthieu Muffato's avatar
typo  
Matthieu Muffato committed
531
        my $role_adaptor = $self->db->get_RoleAdaptor;
532 533
        my $job_adaptor = $self->db->get_AnalysisJobAdaptor;

534
        warn "GarbageCollector:\tChecking for orphan roles...\n";
535
        my $orphan_roles = $role_adaptor->fetch_all_unfinished_roles_of_dead_workers();
536 537 538
        if(my $orphan_role_number = scalar @$orphan_roles) {
            warn "GarbageCollector:\tfound $orphan_role_number orphan roles, finalizing...\n\n";
            foreach my $orphan_role (@$orphan_roles) {
539
                $role_adaptor->finalize_role( $orphan_role );
540
            }
541 542
        } else {
            warn "GarbageCollector:\tfound none\n";
543 544
        }

545 546
        warn "GarbageCollector:\tChecking for roles buried in haste...\n";
        my $buried_in_haste_roles = $role_adaptor->fetch_all_finished_roles_with_unfinished_jobs();
547
        if(my $bih_number = scalar @$buried_in_haste_roles) {
548
            warn "GarbageCollector:\tfound $bih_number buried roles with unfinished jobs, reclaiming.\n\n";
549 550
            foreach my $role (@$buried_in_haste_roles) {
                $job_adaptor->release_undone_jobs_from_role( $role );
Leo Gordon's avatar
Leo Gordon committed
551 552
            }
        } else {
553
            warn "GarbageCollector:\tfound none\n";
Leo Gordon's avatar
Leo Gordon committed
554
        }
555 556 557 558 559 560 561 562 563 564 565

        warn "GarbageCollector:\tChecking for orphan jobs...\n";
        my $orphan_jobs = $job_adaptor->fetch_all_unfinished_jobs_with_no_roles();
        if(my $sj_number = scalar @$orphan_jobs) {
            warn "GarbageCollector:\tfound $sj_number unfinished jobs with no roles, reclaiming.\n\n";
            foreach my $job (@$orphan_jobs) {
                $job_adaptor->release_and_age_job($job->dbID, $job->analysis->max_retry_count, 1);
            }
        } else {
            warn "GarbageCollector:\tfound none\n";
        }
Leo Gordon's avatar
Leo Gordon committed
566 567
    }
}
Jessica Severin's avatar
Jessica Severin committed
568 569


570 571 572 573
    # To tackle the RELOCATED event: this method checks whether there are already workers with these attributes
sub find_previous_worker_incarnations {
    my ($self, $meadow_type, $meadow_name, $process_id) = @_;

574 575 576
    # This happens in standalone mode, when there is no database
    return [] unless ref($self);

577 578 579 580 581 582 583 584 585 586 587 588 589
    return $self->fetch_all( "status!='DEAD' AND status!='SUBMITTED' AND meadow_type='$meadow_type' AND meadow_name='$meadow_name' AND process_id='$process_id'" );
}


sub fetch_preregistered_worker {
    my ($self, $meadow_type, $meadow_name, $process_id) = @_;

    # This happens in standalone mode, when there is no database
    return [] unless ref($self);

    my ($worker) = @{ $self->fetch_all( "status='SUBMITTED' AND meadow_type='$meadow_type' AND meadow_name='$meadow_name' AND process_id='$process_id'" ) };

    return $worker;
590 591 592
}


593 594 595
    # a new version that both checks in and updates the status
sub check_in_worker {
    my ($self, $worker) = @_;
Jessica Severin's avatar
Jessica Severin committed
596

597 598 599
    my $sql = "UPDATE worker SET when_checked_in=CURRENT_TIMESTAMP, status='".$worker->status."', work_done='".$worker->work_done."' WHERE worker_id='".$worker->dbID."'";

    $self->dbc->protected_prepare_execute( [ $sql ],
600
        sub { my ($after) = @_; $self->db->get_LogMessageAdaptor->store_worker_message( $worker, "check_in_worker".$after, 'INFO' ); }
601
    );
Jessica Severin's avatar
Jessica Severin committed
602 603 604
}


605
=head2 reset_job_by_dbID_and_sync
606

607
  Arg [1]: int $job_id
608
  Example: 
609
    my $job = $queen->reset_job_by_dbID_and_sync($job_id);
610
  Description: 
611
    For the specified job_id it will fetch just that job, 
612 613 614
    reset it completely as if it has never run, and return it.  
    Specifying a specific job bypasses the safety checks, 
    thus multiple workers could be running the 
615
    same job simultaneously (use only for debugging).
616
  Returntype : none
617
  Exceptions :
618
  Caller     : beekeeper.pl
619 620 621

=cut

622 623
sub reset_job_by_dbID_and_sync {
    my ($self, $job_id) = @_;
624

625 626 627
    my $job     = $self->db->get_AnalysisJobAdaptor->reset_or_grab_job_by_dbID($job_id);

    my $stats   = $job->analysis->stats;
628 629

    $self->synchronize_AnalysisStats($stats);
630 631 632
}


633 634 635 636 637 638
######################################
#
# Public API interface for beekeeper
#
######################################

639

640 641 642
    # Note: asking for Queen->fetch_overdue_workers(0) essentially means
    #       "fetch all workers known to the Queen not to be officially dead"
    #
643
sub fetch_overdue_workers {
644
    my ($self,$overdue_secs) = @_;
645

646
    $overdue_secs = 3600 unless(defined($overdue_secs));
647

648
    my $constraint = "status!='DEAD' AND (when_checked_in IS NULL OR ".{
649 650 651
            'mysql'     =>  "(UNIX_TIMESTAMP()-UNIX_TIMESTAMP(when_checked_in)) > $overdue_secs",
            'sqlite'    =>  "(strftime('%s','now')-strftime('%s',when_checked_in)) > $overdue_secs",
            'pgsql'     =>  "EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - when_checked_in) > $overdue_secs",
652
        }->{ $self->dbc->driver }.' )';
653

654
    return $self->fetch_all( $constraint );
655 656
}

657

658 659
=head2 synchronize_hive

660 661 662 663 664
  Arg [1]    : $list_of_analyses
  Example    : $queen->synchronize_hive( [ $analysis_A, $analysis_B ] );
  Description: Runs through all analyses in the given list and synchronizes
              the analysis_stats summary with the states in the job and worker tables.
              Then follows by checking all the blocking rules and blocks/unblocks analyses as needed.
665 666 667 668 669 670
  Exceptions : none
  Caller     : general

=cut

sub synchronize_hive {
671
    my ($self, $list_of_analyses) = @_;
672

673
    my $start_time = time();
674

675 676 677 678 679 680
    print STDERR "\nSynchronizing the hive (".scalar(@$list_of_analyses)." analyses this time):\n";
    foreach my $analysis (@$list_of_analyses) {
        $self->synchronize_AnalysisStats($analysis->stats);
        print STDERR ( ($analysis->stats()->status eq 'BLOCKED') ? 'x' : 'o');
    }
    print STDERR "\n";
Leo Gordon's avatar
Leo Gordon committed
681

682
    print STDERR ''.((time() - $start_time))." seconds to synchronize_hive\n\n";
683
}
684

685

686 687 688
=head2 safe_synchronize_AnalysisStats

  Arg [1]    : Bio::EnsEMBL::Hive::AnalysisStats object
689
  Example    : $self->safe_synchronize_AnalysisStats($stats);
690 691 692
  Description: Prewrapper around synchronize_AnalysisStats that does
               checks and grabs sync_lock before proceeding with sync.
               Used by distributed worker sync system to avoid contention.
693 694 695
               Returns 1 on success and 0 if the lock could not have been obtained,
               and so no sync was attempted.
  Returntype : boolean
696 697 698 699 700
  Caller     : general

=cut

sub safe_synchronize_AnalysisStats {
701 702
    my ($self, $stats) = @_;

703 704
    $stats->refresh();

705 706
    my $max_refresh_attempts = 5;
    while($stats->sync_lock and $max_refresh_attempts--) {   # another Worker/Beekeeper is synching this analysis right now
707
            # ToDo: it would be nice to report the detected collision
708 709 710 711
        sleep(1);
        $stats->refresh();  # just try to avoid collision
    }

712
    unless( ($stats->status eq 'DONE')
713
         or ( ($stats->status eq 'WORKING') and defined($stats->seconds_since_when_updated) and ($stats->seconds_since_when_updated < 3*60) ) ) {
714 715 716 717 718

        my $sql = "UPDATE analysis_stats SET status='SYNCHING', sync_lock=1 ".
                  "WHERE sync_lock=0 and analysis_id=" . $stats->analysis_id;

        my $row_count = $self->dbc->do($sql);   # try to claim the sync_lock
719

720
        if( $row_count == 1 ) {     # if we managed to obtain the lock, let's go and perform the sync:
721
            $self->synchronize_AnalysisStats($stats, 1);
722 723 724 725 726
            return 'sync_done';
        } else {
            # otherwise assume it's locked and just return un-updated
            return 0;
        }
727
    }
728

729
    return 'stats_fresh_enough';
730 731 732
}


733
=head2 synchronize_AnalysisStats
734

735
  Arg [1]    : Bio::EnsEMBL::Hive::AnalysisStats object
736
  Example    : $self->synchronize_AnalysisStats( $stats );
737
  Description: Queries the job and worker tables to get summary counts
738 739
               and rebuilds the AnalysisStats object.
               Then updates the analysis_stats table with the new summary info.
740 741
  Exceptions : none
  Caller     : general
742

743
=cut
744

745
sub synchronize_AnalysisStats {
746
    my ($self, $stats, $has_refresh_just_been_done) = @_;
747

748
    if( $stats and $stats->analysis_id ) {
749

750
        $stats->refresh() unless $has_refresh_just_been_done;
751

Leo Gordon's avatar
Leo Gordon committed
752
        my $job_counts = $stats->hive_pipeline->hive_use_triggers() ? undef : $self->db->get_AnalysisJobAdaptor->fetch_job_counts_hashed_by_status( $stats->analysis_id );
753

754
        $stats->recalculate_from_job_counts( $job_counts );
755

756 757 758
        # $stats->sync_lock(0); ## do we perhaps need it here?
        $stats->update;  #update and release sync_lock
    }
759
}
760 761


762 763 764 765 766 767 768
=head2 check_nothing_to_run_but_semaphored

  Arg [1]    : $list_of_analyses
  Example    : $self->check_nothing_to_run_but_semaphored( [ $analysis_A, $analysis_B ] );
  Description: Counts the number of immediately runnable jobs in the given analyses.
  Exceptions : none
  Caller     : Scheduler
769

770 771 772 773
=cut

sub check_nothing_to_run_but_semaphored {   # make sure it is run after a recent sync
    my ($self, $list_of_analyses) = @_;
774 775 776 777 778 779 780

    my $only_semaphored_jobs_to_run = 1;
    my $total_semaphored_job_count  = 0;

    foreach my $analysis (@$list_of_analyses) {
        my $stats = $analysis->stats;

781
        $only_semaphored_jobs_to_run = 0 if( $stats->total_job_count != $stats->done_job_count + $stats->failed_job_count + $stats->semaphored_job_count );
782 783 784 785 786 787 788
        $total_semaphored_job_count += $stats->semaphored_job_count;
    }

    return ( $total_semaphored_job_count && $only_semaphored_jobs_to_run );
}


789
=head2 print_status_and_return_reasons_to_exit
790

791
  Arg [1]    : $list_of_analyses
792
  Arg [2]    : $debug
793
  Example    : my $reasons_to_exit = $queen->print_status_and_return_reasons_to_exit( [ $analysis_A, $analysis_B ] );
794 795 796 797 798 799 800 801 802 803 804 805 806 807
             : foreach my $reason_to_exit (@$reasons_to_exit) {
             :     my $exit_message  = $reason_to_exit->{'message'};
             :     my $exit_status   = $reason_to_exit->{'exit_status'};
  Description: Runs through all analyses in the given list, reports failed analyses, and computes some totals.
             : It returns a list of exit messages and status codes. Each element of the list is a hashref,
             : with the exit message keyed by 'message' and the status code keyed by 'exit_status'
             :
             : Possible status codes are:
             :   'JOB_FAILED'
             :   'ANALYSIS_FAILED'
             :   'NO_WORK'
             :
             : If $debug is set, the list will contain all analyses. Otherwise, empty and done analyses
             : will not be listed
808
  Exceptions : none
809
  Caller     : beekeeper.pl
810 811 812

=cut

813
sub print_status_and_return_reasons_to_exit {
814
    my ($self, $list_of_analyses, $debug) = @_;
815

816
    my ($total_done_jobs, $total_failed_jobs, $total_jobs, $total_excluded_jobs, $cpumsec_to_do) = (0) x 5;
817 818
    my %skipped_analyses = ('EMPTY' => [], 'DONE' => []);
    my @analyses_to_display;
819
    my @reasons_to_exit;
820

821
    foreach my $analysis (sort {$a->dbID <=> $b->dbID} @$list_of_analyses) {
822 823
        my $stats               = $analysis->stats;
        my $failed_job_count    = $stats->failed_job_count;
824
        my $is_excluded         = $stats->is_excluded;
825

826 827