Queen.pm 35.6 KB
Newer Older
Jessica Severin's avatar
Jessica Severin committed
1 2 3 4 5 6
#
# You may distribute this module under the same terms as perl itself

=pod 

=head1 NAME
7

8
  Bio::EnsEMBL::Hive::Queen
Jessica Severin's avatar
Jessica Severin committed
9 10

=head1 SYNOPSIS
11

12
  The Queen of the Hive based job control system
Jessica Severin's avatar
Jessica Severin committed
13 14

=head1 DESCRIPTION
15

16 17 18 19 20 21 22 23 24 25 26 27
  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.

  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).

  Each worker is linked to an analysis_id, registers its self on creation
  into the Hive, creates a RunnableDB instance of the Analysis->module,
28 29
  gets $analysis->stats->batch_size jobs from the job table, does its work,
  creates the next layer of job entries by interfacing to
30 31 32
  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
33 34 35 36 37 38 39 40 41 42
  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.

  The Beekeeper is in charge of interfacing between the Queen and a compute resource
43
  or 'compute farm'.  Its job is to query Queens if they need any workers and to
44 45 46
  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.
Jessica Severin's avatar
Jessica Severin committed
47 48

=head1 CONTACT
49

50
  Please contact ehive-users@ebi.ac.uk mailing list with questions/suggestions.
Jessica Severin's avatar
Jessica Severin committed
51 52

=head1 APPENDIX
53

54 55
  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
56 57 58

=cut

59

Jessica Severin's avatar
Jessica Severin committed
60 61 62
package Bio::EnsEMBL::Hive::Queen;

use strict;
63
use POSIX;
64 65 66
use Bio::EnsEMBL::Utils::Argument;
use Bio::EnsEMBL::Utils::Exception;

67
use Bio::EnsEMBL::Hive::Utils ('destringify', 'dir_revhash');  # import 'destringify()' and 'dir_revhash()'
68
use Bio::EnsEMBL::Hive::AnalysisJob;
Jessica Severin's avatar
Jessica Severin committed
69 70
use Bio::EnsEMBL::Hive::Worker;

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
use base ('Bio::EnsEMBL::Hive::DBSQL::ObjectAdaptor');


sub default_table_name {
    return 'worker';
}


sub default_insertion_method {
    return 'INSERT';
}


sub object_class {
    return 'Bio::EnsEMBL::Hive::Worker';
}
87

Jessica Severin's avatar
Jessica Severin committed
88

89
############################
Jessica Severin's avatar
Jessica Severin committed
90
#
91
# PUBLIC API
Jessica Severin's avatar
Jessica Severin committed
92
#
93
############################
Jessica Severin's avatar
Jessica Severin committed
94

95

Jessica Severin's avatar
Jessica Severin committed
96 97
=head2 create_new_worker

98 99 100 101
  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
102
  Returntype : Bio::EnsEMBL::Hive::Worker
103
  Caller     : runWorker.pl
Jessica Severin's avatar
Jessica Severin committed
104 105 106 107

=cut

sub create_new_worker {
108
    my ($self, @args) = @_;
109

110 111 112 113 114 115
    my ($meadow_type, $meadow_name, $process_id, $exec_host, $resource_class_id, $resource_class_name,
        $no_write, $debug, $worker_log_dir, $hive_log_dir, $job_limit, $life_span, $no_cleanup, $retry_throwing_jobs, $compile_module_once) =

    rearrange([qw(meadow_type meadow_name process_id exec_host resource_class_id resource_class_name
                no_write debug worker_log_dir hive_log_dir job_limit life_span no_cleanup retry_throwing_jobs compile_module_once) ], @args);

116
    if( defined($resource_class_name) ) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        my $rc = $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";

        $resource_class_id = $rc->dbID;
    }

    my $sql = q{INSERT INTO worker (born, last_check_in, meadow_type, meadow_name, host, process_id, resource_class_id)
              VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?, ?, ?, ?)};

    my $sth = $self->prepare($sql);
    $sth->execute($meadow_type, $meadow_name, $exec_host, $process_id, $resource_class_id);
    my $worker_id = $self->dbc->db_handle->last_insert_id(undef, undef, 'worker', 'worker_id')
        or die "Could not create a new worker";
    $sth->finish;

    if($hive_log_dir or $worker_log_dir) {
        my $dir_revhash = dir_revhash($worker_id);
        $worker_log_dir ||= $hive_log_dir .'/'. ($dir_revhash ? "$dir_revhash/" : '') .'worker_id_'.$worker_id;

            # Note: the following die-message will not reach the log files for circular reason!
        system("mkdir -p $worker_log_dir") && die "Could not create '$worker_log_dir' because: $!";

        my $sth_add_log = $self->prepare( "UPDATE worker SET log_dir=? WHERE worker_id=?" );
        $sth_add_log->execute($worker_log_dir, $worker_id);
        $sth_add_log->finish;
    }

    my $worker = $self->fetch_by_dbID($worker_id)
        or die "Could not fetch worker with dbID=$worker_id";

    $worker->init;

    if($job_limit) {
      $worker->job_limit($job_limit);
      $worker->life_span(0);
    }

    $worker->life_span($life_span * 60)                 if($life_span);

    $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);

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

    return $worker;
}


=head2 specialize_new_worker
171

172 173
  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.
174
  Caller     : Bio::EnsEMBL::Hive::Worker
175 176 177 178 179 180 181 182

=cut

sub specialize_new_worker {
    my ($self, $worker, @args) = @_;

    my ($analysis_id, $logic_name, $job_id, $force) =
        rearrange([qw(analysis_id logic_name job_id force) ], @args);
183

184 185
    if( scalar( grep {defined($_)} ($analysis_id, $logic_name, $job_id) ) > 1) {
        die "At most one of the options {-analysis_id, -logic_name, -job_id} can be set to pre-specialize a Worker";
Leo Gordon's avatar
Leo Gordon committed
186 187
    }

188
    my ($analysis, $stats, $special_batch);
189
    my $analysis_stats_adaptor = $self->db->get_AnalysisStatsAdaptor;
Jessica Severin's avatar
Jessica Severin committed
190

191
    if($job_id or $analysis_id or $logic_name) {    # probably pre-specialized from command-line
192

193
        if($job_id) {
194 195 196
            print "resetting and fetching job for job_id '$job_id'\n";

            my $job_adaptor = $self->db->get_AnalysisJobAdaptor;
197

198 199 200 201 202 203 204 205 206
            my $job = $job_adaptor->fetch_by_dbID( $job_id )
                or die "Could not fetch job with dbID='$job_id'";
            my $job_status = $job->status();

            if($job_status =~/(CLAIMED|PRE_CLEANUP|FETCH_INPUT|RUN|WRITE_OUTPUT|POST_CLEANUP)/ ) {
                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";
            }
207

208 209 210 211 212 213 214 215
            if(($job_status eq 'DONE') and $job->semaphored_job_id) {
                warn "Increasing the semaphore count of the dependent job";
                $job_adaptor->increase_semaphore_count_for_jobid( $job->semaphored_job_id );
            }

            my $worker_id = $worker->dbID;
            if($job = $job_adaptor->reset_or_grab_job_by_dbID($job_id, $worker_id)) {
                $special_batch = [ $job ];
216 217
                $analysis_id = $job->analysis_id;
            } else {
218
                die "Could not claim job with dbID='$job_id' for worker with dbID='$worker_id'";
219
            }
220 221 222 223 224 225 226 227 228 229 230 231 232
        }

        if($logic_name) {
            $analysis = $self->db->get_AnalysisAdaptor->fetch_by_logic_name($logic_name)
                or die "analysis with name='$logic_name' could not be fetched from the database";

            $analysis_id = $analysis->dbID;

        } elsif($analysis_id) {
            $analysis = $self->db->get_AnalysisAdaptor->fetch_by_dbID($analysis_id)
                or die "analysis with dbID='$analysis_id' could not be fetched from the database";
        }

233 234 235
        if( $worker->resource_class_id
        and $worker->resource_class_id != $analysis->resource_class_id) {
                die "resource_class of analysis ".$analysis->logic_name." is incompatible with this Worker's resource_class";
236 237
        }

238 239 240
        $stats = $analysis_stats_adaptor->fetch_by_analysis_id($analysis_id);
        $self->safe_synchronize_AnalysisStats($stats);

241
        unless($special_batch or $force) {    # do we really need to run this analysis?
242
            if($self->get_hive_current_load() >= 1.1) {
243
                die "Hive is overloaded, can't specialize a worker";
244 245
            }
            if($stats->status eq 'BLOCKED') {
246
                die "Analysis is BLOCKED, can't specialize a worker";
247 248
            }
            if($stats->num_required_workers <= 0) {
249
                die "Analysis requires 0 workers at the moment";
250 251
            }
            if($stats->status eq 'DONE') {
252
                die "Analysis is DONE, and doesn't require workers";
253 254
            }
        }
255

256
    } else {    # probably scheduled by beekeeper.pl
257

258
        $stats = $self->suggest_analysis_to_specialize_by_rc_id($worker->resource_class_id)
259
            or die "Scheduler failed to pick an analysis for the worker";
260

261
        print "Scheduler picked analysis with dbID=".$stats->analysis_id." for the worker\n";
262 263

        $analysis_id = $stats->analysis_id;
264
    }
265

266
        # now set it in the $worker:
Jessica Severin's avatar
Jessica Severin committed
267

268
    $worker->analysis_id( $analysis_id );
Jessica Severin's avatar
Jessica Severin committed
269

270 271 272 273
    my $sth_update_analysis_id = $self->prepare( "UPDATE worker SET analysis_id=? WHERE worker_id=?" );
    $sth_update_analysis_id->execute($worker->analysis_id, $worker->dbID);
    $sth_update_analysis_id->finish;

274 275
    if($special_batch) {
        $worker->special_batch( $special_batch );
276
    } else {    # count it as autonomous worker sharing the load of that analysis:
277 278 279

        $stats->update_status('WORKING');

280
        $analysis_stats_adaptor->decrease_required_workers($worker->analysis_id);
281 282 283 284 285 286 287 288 289
    }

        # 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.
        #
    unless( $self->db->hive_use_triggers() ) {
290
        $analysis_stats_adaptor->increase_running_workers($worker->analysis_id);
291
    }
Jessica Severin's avatar
Jessica Severin committed
292 293
}

294

Jessica Severin's avatar
Jessica Severin committed
295
sub register_worker_death {
296
    my ($self, $worker) = @_;
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    return unless($worker);

    my $cod = $worker->cause_of_death() || 'UNKNOWN';    # make sure we do not attempt to insert a void

    my $sql = qq{UPDATE worker SET died=CURRENT_TIMESTAMP
                    ,last_check_in=CURRENT_TIMESTAMP
                    ,status='DEAD'
                    ,work_done='}. $worker->work_done . qq{'
                    ,cause_of_death='$cod'
                WHERE worker_id='}. $worker->dbID . qq{'};
    $self->dbc->do( $sql );

    if(my $analysis_id = $worker->analysis_id) {
        my $analysis_stats_adaptor = $self->db->get_AnalysisStatsAdaptor;

        unless( $self->db->hive_use_triggers() ) {
            $analysis_stats_adaptor->decrease_running_workers($worker->analysis_id);
        }

        if($cod eq 'NO_WORK') {
            $analysis_stats_adaptor->update_status($worker->analysis_id, 'ALL_CLAIMED');
        } elsif($cod eq 'UNKNOWN'
            or $cod eq 'MEMLIMIT'
            or $cod eq 'RUNLIMIT'
            or $cod eq 'KILLED_BY_USER') {
                $self->db->get_AnalysisJobAdaptor->release_undone_jobs_from_worker($worker);
        }

            # re-sync the analysis_stats when a worker dies as part of dynamic sync system
        if($self->safe_synchronize_AnalysisStats($worker->analysis->stats)->status ne 'DONE') {
            # since I'm dying I should make sure there is someone to take my place after I'm gone ...
            # above synch still sees me as a 'living worker' so I need to compensate for that
            $analysis_stats_adaptor->increase_required_workers($worker->analysis_id);
        }
    }
Jessica Severin's avatar
Jessica Severin committed
333 334
}

335

336
sub check_for_dead_workers {    # scans the whole Valley for lost Workers (but ignores unreachagle ones)
337
    my ($self, $valley, $check_buried_in_haste) = @_;
Leo Gordon's avatar
Leo Gordon committed
338

339
    warn "GarbageCollector:\tChecking for lost Workers...\n";
340

341 342 343 344
    my $queen_worker_list           = $self->fetch_overdue_workers(0);
    my %mt_and_pid_to_worker_status = ();
    my %worker_status_counts        = ();
    my %mt_and_pid_to_lost_worker   = ();
Leo Gordon's avatar
Leo Gordon committed
345

346
    warn "GarbageCollector:\t[Queen:] we have ".scalar(@$queen_worker_list)." Workers alive.\n";
347

Leo Gordon's avatar
Leo Gordon committed
348 349
    foreach my $worker (@$queen_worker_list) {

350 351 352
        my $meadow_type = $worker->meadow_type;
        if(my $meadow = $valley->find_available_meadow_responsible_for_worker($worker)) {
            $mt_and_pid_to_worker_status{$meadow_type} ||= $meadow->status_of_all_our_workers;
Leo Gordon's avatar
Leo Gordon committed
353
        } else {
354
            $worker_status_counts{$meadow_type}{'UNREACHABLE'}++;
355

356
            next;   # Worker is unreachable from this Valley
Leo Gordon's avatar
Leo Gordon committed
357 358
        }

359 360 361 362 363
        my $process_id = $worker->process_id;
        if(my $status = $mt_and_pid_to_worker_status{$meadow_type}{$process_id}) { # can be RUN|PEND|xSUSP
            $worker_status_counts{$meadow_type}{$status}++;
        } else {
            $worker_status_counts{$meadow_type}{'LOST'}++;
364

365
            $mt_and_pid_to_lost_worker{$meadow_type}{$process_id} = $worker;
366
        }
367 368 369 370 371 372
    }

        # just a quick summary report:
    foreach my $meadow_type (keys %worker_status_counts) {
        warn "GarbageCollector:\t[$meadow_type Meadow:]\t".join(', ', map { "$_:$worker_status_counts{$meadow_type}{$_}" } keys %{$worker_status_counts{$meadow_type}})."\n\n";
    }
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    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";

            my $wpid_to_cod = {};
            if($this_meadow->can('find_out_causes')) {
                $wpid_to_cod = $this_meadow->find_out_causes( keys %$pid_to_lost_worker );
                my $lost_with_known_cod = scalar(keys %$wpid_to_cod);
                warn "GarbageCollector:\tFound why $lost_with_known_cod of $meadow_type Workers died\n";
            } else {
                warn "GarbageCollector:\t$meadow_type meadow does not support post-mortem examination\n";
            }

            warn "GarbageCollector:\tReleasing the jobs\n";
            while(my ($process_id, $worker) = each %$pid_to_lost_worker) {
391
                $worker->cause_of_death( $wpid_to_cod->{$process_id} || 'UNKNOWN');
392 393
                $self->register_worker_death($worker);
            }
394 395 396
        }
    }

397
        # the following bit is completely Meadow-agnostic and only restores database integrity:
Leo Gordon's avatar
Leo Gordon committed
398
    if($check_buried_in_haste) {
399
        warn "GarbageCollector:\tChecking for Workers buried in haste...\n";
400
        my $buried_in_haste_list = $self->fetch_all_dead_workers_with_jobs();
Leo Gordon's avatar
Leo Gordon committed
401
        if(my $bih_number = scalar(@$buried_in_haste_list)) {
402
            warn "GarbageCollector:\tfound $bih_number jobs, reclaiming.\n\n";
Leo Gordon's avatar
Leo Gordon committed
403 404 405
            if($bih_number) {
                my $job_adaptor = $self->db->get_AnalysisJobAdaptor();
                foreach my $worker (@$buried_in_haste_list) {
Leo Gordon's avatar
Leo Gordon committed
406
                    $job_adaptor->release_undone_jobs_from_worker($worker);
Leo Gordon's avatar
Leo Gordon committed
407 408 409
                }
            }
        } else {
410
            warn "GarbageCollector:\tfound none\n";
Leo Gordon's avatar
Leo Gordon committed
411 412 413
        }
    }
}
Jessica Severin's avatar
Jessica Severin committed
414 415


416 417 418
    # 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
419

420
    $self->dbc->do("UPDATE worker SET last_check_in=CURRENT_TIMESTAMP, status='".$worker->status."', work_done='".$worker->work_done."' WHERE worker_id='".$worker->dbID."'");
Jessica Severin's avatar
Jessica Severin committed
421 422 423
}


424
=head2 reset_job_by_dbID_and_sync
425

426
  Arg [1]: int $job_id
427
  Example: 
428
    my $job = $queen->reset_job_by_dbID_and_sync($job_id);
429
  Description: 
430
    For the specified job_id it will fetch just that job, 
431 432 433
    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 
434
    same job simultaneously (use only for debugging).
435
  Returntype : none
436
  Exceptions :
437
  Caller     : beekeeper.pl
438 439 440

=cut

441 442
sub reset_job_by_dbID_and_sync {
    my ($self, $job_id) = @_;
443

444
    my $job_adaptor = $self->db->get_AnalysisJobAdaptor;
445
    my $job = $job_adaptor->reset_or_grab_job_by_dbID($job_id); 
446 447 448

    my $stats = $self->db->get_AnalysisStatsAdaptor->fetch_by_analysis_id($job->analysis_id);
    $self->synchronize_AnalysisStats($stats);
449 450 451
}


452 453 454 455 456 457
######################################
#
# Public API interface for beekeeper
#
######################################

458

459 460 461
    # Note: asking for Queen->fetch_overdue_workers(0) essentially means
    #       "fetch all workers known to the Queen not to be officially dead"
    #
462
sub fetch_overdue_workers {
463
    my ($self,$overdue_secs) = @_;
464

465
    $overdue_secs = 3600 unless(defined($overdue_secs));
466

467
    my $constraint = "status!='DEAD' AND ".
468
                    ( ($self->dbc->driver eq 'sqlite')
469 470 471
                        ? "(strftime('%s','now')-strftime('%s',last_check_in))>$overdue_secs"
                        : "(UNIX_TIMESTAMP()-UNIX_TIMESTAMP(last_check_in))>$overdue_secs");
    return $self->fetch_all( $constraint );
472 473
}

474 475 476

sub fetch_all_dead_workers_with_jobs {
    my $self = shift;
Leo Gordon's avatar
Leo Gordon committed
477

478
    return $self->fetch_all( "JOIN job j USING(worker_id) WHERE w.status='DEAD' AND j.status NOT IN ('DONE', 'READY', 'FAILED', 'PASSED_ON') GROUP BY worker_id" );
Leo Gordon's avatar
Leo Gordon committed
479
}
Jessica Severin's avatar
Jessica Severin committed
480

481

482 483
=head2 synchronize_hive

Leo Gordon's avatar
Leo Gordon committed
484
  Arg [1]    : $filter_analysis (optional)
485 486
  Example    : $queen->synchronize_hive();
  Description: Runs through all analyses in the system and synchronizes
487 488
              the analysis_stats summary with the states in the job 
              and worker tables.  Then follows by checking all the blocking rules
489 490 491 492 493 494 495
              and blocks/unblocks analyses as needed.
  Exceptions : none
  Caller     : general

=cut

sub synchronize_hive {
Leo Gordon's avatar
Leo Gordon committed
496
  my $self          = shift;
Leo Gordon's avatar
Leo Gordon committed
497
  my $filter_analysis = shift; # optional parameter
498

499
  my $start_time = time();
500

Leo Gordon's avatar
Leo Gordon committed
501
  my $list_of_analyses = $filter_analysis ? [$filter_analysis] : $self->db->get_AnalysisAdaptor->fetch_all;
Leo Gordon's avatar
Leo Gordon committed
502

Leo Gordon's avatar
Leo Gordon committed
503
  print STDERR "\nSynchronizing the hive (".scalar(@$list_of_analyses)." analyses this time):\n";
Leo Gordon's avatar
Leo Gordon committed
504 505
  foreach my $analysis (@$list_of_analyses) {
    $self->synchronize_AnalysisStats($analysis->stats);
506
    print STDERR ( ($analysis->stats()->status eq 'BLOCKED') ? 'x' : 'o');
507
  }
Leo Gordon's avatar
Leo Gordon committed
508
  print STDERR "\n";
Leo Gordon's avatar
Leo Gordon committed
509

Leo Gordon's avatar
Leo Gordon committed
510
  print STDERR ''.((time() - $start_time))." seconds to synchronize_hive\n\n";
511
}
512

513

514 515 516
=head2 safe_synchronize_AnalysisStats

  Arg [1]    : Bio::EnsEMBL::Hive::AnalysisStats object
517
  Example    : $self->safe_synchronize_AnalysisStats($stats);
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  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.
  Exceptions : none
  Caller     : general

=cut

sub safe_synchronize_AnalysisStats {
  my $self = shift;
  my $stats = shift;

  return $stats unless($stats->analysis_id);
  return $stats if($stats->status eq 'SYNCHING');
  return $stats if($stats->status eq 'DONE');
  return $stats if($stats->sync_lock);
  return $stats if(($stats->status eq 'WORKING') and
535
                   ($stats->seconds_since_last_update < 3*60));
536 537 538 539

  # OK try to claim the sync_lock
  my $sql = "UPDATE analysis_stats SET status='SYNCHING', sync_lock=1 ".
            "WHERE sync_lock=0 and analysis_id=" . $stats->analysis_id;
540
  #print("$sql\n");
541
  my $row_count = $self->dbc->do($sql);  
542
  return $stats unless($row_count == 1);        # return the un-updated status if locked
543
  #printf("got sync_lock on analysis_stats(%d)\n", $stats->analysis_id);
544
  
545
      # since we managed to obtain the lock, let's go and perform the sync:
546
  $self->synchronize_AnalysisStats($stats);
547

548 549 550 551
  return $stats;
}


552
=head2 synchronize_AnalysisStats
553

554 555
  Arg [1]    : Bio::EnsEMBL::Hive::AnalysisStats object
  Example    : $self->synchronize($analysisStats);
556
  Description: Queries the job and worker tables to get summary counts
557 558 559 560 561
               and rebuilds the AnalysisStats object.  Then updates the
               analysis_stats table with the new summary info
  Returntype : newly synced Bio::EnsEMBL::Hive::AnalysisStats object
  Exceptions : none
  Caller     : general
562

563
=cut
564

565
sub synchronize_AnalysisStats {
566
  my $self = shift;
567
  my $analysisStats = shift;
568

569
  return $analysisStats unless($analysisStats);
570
  return $analysisStats unless($analysisStats->analysis_id);
571

572
  $analysisStats->refresh(); ## Need to get the new hive_capacity for dynamic analyses
573 574
  my $hive_capacity = $analysisStats->hive_capacity;

575 576
  if($self->db->hive_use_triggers()) {

577 578
            my $job_count = $analysisStats->ready_job_count();
            my $required_workers = $hive_capacity && POSIX::ceil( $job_count / $analysisStats->get_or_estimate_batch_size() );
579

580 581
                # adjust_stats_for_living_workers:
            if($hive_capacity > 0) {
582
                my $unfulfilled_capacity = $hive_capacity - $analysisStats->num_running_workers();
583

584 585
                if($unfulfilled_capacity < $required_workers ) {
                    $required_workers = (0 < $unfulfilled_capacity) ? $unfulfilled_capacity : 0;
586 587 588 589 590 591
                }
            }
            $analysisStats->num_required_workers( $required_workers );

  } else {
      $analysisStats->total_job_count(0);
592 593
      $analysisStats->semaphored_job_count(0);
      $analysisStats->ready_job_count(0);
594 595 596
      $analysisStats->done_job_count(0);
      $analysisStats->failed_job_count(0);
      $analysisStats->num_required_workers(0);
597

598
            # ask for analysis_id to force MySQL to use existing index on (analysis_id, status)
599
      my $sql = "SELECT analysis_id, status, count(*) FROM job WHERE analysis_id=? GROUP BY analysis_id, status";
600 601
      my $sth = $self->prepare($sql);
      $sth->execute($analysisStats->analysis_id);
602

603 604 605
      my $done_here       = 0;
      my $done_elsewhere  = 0;
      my $total_job_count = 0;
606
      while (my ($dummy_analysis_id, $status, $job_count)=$sth->fetchrow_array()) {
607
    # print STDERR "$status: $job_count\n";
608

609
        $total_job_count += $job_count;
610

611
        if($status eq 'READY') {
612
            $analysisStats->ready_job_count($job_count);
613

614
            my $required_workers = $hive_capacity && POSIX::ceil( $job_count / $analysisStats->get_or_estimate_batch_size() );
615 616 617

                # adjust_stats_for_living_workers:
            if($hive_capacity > 0) {
618
                my $unfulfilled_capacity = $hive_capacity - $self->count_running_workers( $analysisStats->analysis_id() );
619

620 621
                if($unfulfilled_capacity < $required_workers ) {
                    $required_workers = (0 < $unfulfilled_capacity) ? $unfulfilled_capacity : 0;
622
                }
623
            }
624 625
            $analysisStats->num_required_workers( $required_workers );

626 627
        } elsif($status eq 'SEMAPHORED') {
            $analysisStats->semaphored_job_count($job_count);
628
        } elsif($status eq 'DONE') {
629
            $done_here = $job_count;
630
        } elsif($status eq 'PASSED_ON') {
631 632 633
            $done_elsewhere = $job_count;
        } elsif ($status eq 'FAILED') {
            $analysisStats->failed_job_count($job_count);
634
        }
635
      } # /while
636
      $sth->finish;
637

638 639
      $analysisStats->total_job_count( $total_job_count );
      $analysisStats->done_job_count( $done_here + $done_elsewhere );
640
  } # /unless $self->{'_hive_use_triggers'}
641

642
  $analysisStats->check_blocking_control_rules();
643

644 645 646
  if($analysisStats->status ne 'BLOCKED') {
    $analysisStats->determine_status();
  }
647

648
  # $analysisStats->sync_lock(0); ## do we perhaps need it here?
649
  $analysisStats->update;  #update and release sync_lock
650

651
  return $analysisStats;
652
}
653 654


655 656 657 658 659 660 661 662 663 664 665 666 667 668
=head2 get_num_failed_analyses

  Arg [1]    : Bio::EnsEMBL::Hive::AnalysisStats object (optional)
  Example    : if( $self->get_num_failed_analyses( $my_analysis )) { do_something; }
  Example    : my $num_failed_analyses = $self->get_num_failed_analyses();
  Description: Reports all failed analyses and returns
                either the number of total failed (if no $filter_analysis was provided)
                or 1/0, depending on whether $filter_analysis failed or not.
  Returntype : int
  Exceptions : none
  Caller     : general

=cut

Leo Gordon's avatar
Leo Gordon committed
669
sub get_num_failed_analyses {
670
    my ($self, $filter_analysis) = @_;
671

672 673 674 675 676 677 678 679 680 681 682 683
    my $failed_analyses = $self->db->get_AnalysisAdaptor->fetch_all_failed_analyses();

    my $filter_analysis_failed = 0;

    foreach my $failed_analysis (@$failed_analyses) {
        print "\t##########################################################\n";
        print "\t# Too many jobs in analysis '".$failed_analysis->logic_name."' FAILED #\n";
        print "\t##########################################################\n\n";
        if($filter_analysis and ($filter_analysis->dbID == $failed_analysis)) {
            $filter_analysis_failed = 1;
        }
    }
684

685
    return $filter_analysis ? $filter_analysis_failed : scalar(@$failed_analyses);
686 687 688
}


689
sub get_hive_current_load {
690 691 692
    my $self = shift;
    my $sql = qq{
        SELECT sum(1/hive_capacity)
693 694 695 696
        FROM worker w
        JOIN analysis_stats USING(analysis_id)
        WHERE w.status!='DEAD'
        AND hive_capacity>0
697 698 699 700 701 702
    };
    my $sth = $self->prepare($sql);
    $sth->execute();
    my ($load)=$sth->fetchrow_array();
    $sth->finish;
    return ($load || 0);
703 704 705
}


706 707 708
sub count_running_workers {
    my ($self, $analysis_id) = @_;

709 710 711 712 713
    my $sql = qq{
            SELECT count(*)
            FROM worker
            WHERE status!='DEAD'
        } . ($analysis_id ? " AND analysis_id='$analysis_id'" : '');
714 715 716 717 718 719 720

    my $sth = $self->prepare($sql);
    $sth->execute();
    (my $running_workers_count)=$sth->fetchrow_array();
    $sth->finish();

    return $running_workers_count || 0;
721 722
}

723

724
=head2 schedule_workers
725

726
  Arg[1]     : Bio::EnsEMBL::Hive::Analysis object (optional)
727
  Example    : $count = $queen->schedule_workers();
728 729 730
  Description: Runs through the analyses in the system which are waiting
               for workers to be created for them.  Calculates the maximum
               number of workers needed to fill the current needs of the system
731
               If Arg[1] is defined, does it only for the given analysis.
732
  Exceptions : none
733
  Caller     : beekeepers and other external processes
734 735 736

=cut

737
sub schedule_workers {
738
  my ($self, $filter_analysis, $orig_pending_by_rc_name, $available_submit_limit) = @_;
739

740 741 742
  my @suitable_analyses         = $filter_analysis
                                    ? ( $filter_analysis->stats )
                                    : @{ $self->db->get_AnalysisStatsAdaptor->fetch_all_by_suitability_rc_id() };
743

744 745 746 747
  my $analysis_id2rc_id         = $self->db->get_AnalysisAdaptor->fetch_HASHED_FROM_analysis_id_TO_resource_class_id();
  my $rc_id2name                = $self->db->get_ResourceClassAdaptor->fetch_HASHED_FROM_resource_class_id_TO_name();
        # combined mapping
  my %analysis_id2rc_name       = map { $_ => $rc_id2name->{ $analysis_id2rc_id->{ $_ }} } keys %$analysis_id2rc_id;
748

749
  return {} unless(@suitable_analyses);
750

751
  my %pending_by_rc_name        = %{ $orig_pending_by_rc_name || {} };  # NB: make our own copy to be able to modify it
752
  my $total_workers_to_run      = 0;
753
  my %workers_to_run_by_rc_name = ();
754
  my $available_load            = 1.0 - $self->get_hive_current_load();
755

756

757
  foreach my $analysis_stats (@suitable_analyses) {
758 759
    last if ($available_load <= 0.0);
    last if (defined($available_submit_limit) and !$available_submit_limit);
760

Leo Gordon's avatar
Leo Gordon committed
761
        #digging deeper under the surface so need to sync
762
    if(($analysis_stats->status eq 'LOADING') or ($analysis_stats->status eq 'BLOCKED') or ($analysis_stats->status eq 'ALL_CLAIMED')) {
763 764 765 766 767 768
      $self->synchronize_AnalysisStats($analysis_stats);
    }

    next if($analysis_stats->status eq 'BLOCKED');
    next if($analysis_stats->num_required_workers == 0);

769
        # FIXME: the following call *sometimes* returns a stale number greater than the number of workers actually needed for an analysis; -sync fixes it
Leo Gordon's avatar
Leo Gordon committed
770
    my $workers_this_analysis = $analysis_stats->num_required_workers;
771

772 773 774 775 776 777
    if(defined($available_submit_limit)) {                              # submit_limit total capping, if available
        if($workers_this_analysis > $available_submit_limit) {
            $workers_this_analysis = $available_submit_limit;
        }
        $available_submit_limit -= $workers_this_analysis;
    }
Leo Gordon's avatar
Leo Gordon committed
778

779 780 781 782 783
    if((my $hive_capacity = $analysis_stats->hive_capacity) > 0) {      # per-analysis hive_capacity capping, if available
        my $remaining_capacity_for_this_analysis = int($available_load * $hive_capacity);

        if($workers_this_analysis > $remaining_capacity_for_this_analysis) {
            $workers_this_analysis = $remaining_capacity_for_this_analysis;
Leo Gordon's avatar
Leo Gordon committed
784 785
        }

786
        $available_load -= 1.0*$workers_this_analysis/$hive_capacity;
787
    }
Leo Gordon's avatar
Leo Gordon committed
788

789
    my $curr_rc_name    = $analysis_id2rc_name{ $analysis_stats->analysis_id };
790

791 792 793 794 795 796
    if($pending_by_rc_name{ $curr_rc_name }) {                              # per-rc_name capping by pending processes, if available
        my $pending_this_analysis = ($pending_by_rc_name{ $curr_rc_name } < $workers_this_analysis) ? $pending_by_rc_name{ $curr_rc_name } : $workers_this_analysis;

        print "Scheduler detected $pending_this_analysis pending workers with resource_class_name=$curr_rc_name\n";
        $workers_this_analysis                  -= $pending_this_analysis;
        $pending_by_rc_name{ $curr_rc_name }    -= $pending_this_analysis;
797 798
    }

799 800
    next unless($workers_this_analysis);    # do not autovivify the hash by a zero

801
    $total_workers_to_run += $workers_this_analysis;
802
    $workers_to_run_by_rc_name{ $curr_rc_name } += $workers_this_analysis;
803
    $analysis_stats->print_stats();
804
    printf("Scheduler suggests adding %d more workers of resource_class_name=%s for analysis_id=%d [%1.3f hive_load remaining]\n", $workers_this_analysis, $curr_rc_name, $analysis_stats->analysis_id, $available_load);
805
  }
806

807
  printf("Scheduler suggests adding a total of %d workers [%1.5f hive_load remaining]\n", $total_workers_to_run, $available_load);
808
  return \%workers_to_run_by_rc_name;
Leo Gordon's avatar
Leo Gordon committed
809 810
}

811

812
sub schedule_workers_resync_if_necessary {
813 814 815
    my ($self, $valley, $analysis) = @_;

    my $meadow              = $valley->get_current_meadow();
Leo Gordon's avatar
Leo Gordon committed
816

817
    my $pending_by_rc_name  = ($meadow->can('count_pending_workers_by_rc_name') and $meadow->config_get('PendingAdjust')) ? $meadow->count_pending_workers_by_rc_name() : {};
818 819
    my $submit_limit        = $meadow->config_get('SubmitWorkersMax');
    my $meadow_limit        = ($meadow->can('count_running_workers') and defined($meadow->config_get('TotalRunningWorkersMax'))) ? $meadow->config_get('TotalRunningWorkersMax') - $meadow->count_running_workers : undef;
Leo Gordon's avatar
Leo Gordon committed
820

821 822 823 824
    my $available_submit_limit = ($submit_limit and $meadow_limit)
                                    ? (($submit_limit<$meadow_limit) ? $submit_limit : $meadow_limit)
                                    : (defined($submit_limit) ? $submit_limit : $meadow_limit);

825
    my $workers_to_run_by_rc_name = $self->schedule_workers($analysis, $pending_by_rc_name, $available_submit_limit);
826

827
    unless( keys %$workers_to_run_by_rc_name or $self->get_hive_current_load() or $self->count_running_workers() ) {
828
        print "\nScheduler: nothing is running and nothing to do (according to analysis_stats) => executing garbage collection and sync\n" ;
Leo Gordon's avatar
Leo Gordon committed
829

830
        $self->check_for_dead_workers($valley, 1);
Leo Gordon's avatar