github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/allocrunner/taskrunner/lifecycle.go (about)

     1  package taskrunner
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/hashicorp/nomad/nomad/structs"
     7  )
     8  
     9  // Restart a task. Returns immediately if no task is running. Blocks until
    10  // existing task exits or passed-in context is canceled.
    11  func (tr *TaskRunner) Restart(ctx context.Context, event *structs.TaskEvent, failure bool) error {
    12  	tr.logger.Trace("Restart requested", "failure", failure)
    13  
    14  	// Grab the handle
    15  	handle := tr.getDriverHandle()
    16  
    17  	// Check it is running
    18  	if handle == nil {
    19  		return ErrTaskNotRunning
    20  	}
    21  
    22  	// Emit the event since it may take a long time to kill
    23  	tr.EmitEvent(event)
    24  
    25  	// Run the pre-kill hooks prior to restarting the task
    26  	tr.preKill()
    27  
    28  	// Tell the restart tracker that a restart triggered the exit
    29  	tr.restartTracker.SetRestartTriggered(failure)
    30  
    31  	// Grab a handle to the wait channel that will timeout with context cancelation
    32  	// _before_ killing the task.
    33  	waitCh, err := handle.WaitCh(ctx)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	// Kill the task using an exponential backoff in-case of failures.
    39  	if err := tr.killTask(handle); err != nil {
    40  		// We couldn't successfully destroy the resource created.
    41  		tr.logger.Error("failed to kill task. Resources may have been leaked", "error", err)
    42  	}
    43  
    44  	select {
    45  	case <-waitCh:
    46  	case <-ctx.Done():
    47  	}
    48  	return nil
    49  }
    50  
    51  func (tr *TaskRunner) Signal(event *structs.TaskEvent, s string) error {
    52  	tr.logger.Trace("Signal requested", "signal", s)
    53  
    54  	// Grab the handle
    55  	handle := tr.getDriverHandle()
    56  
    57  	// Check it is running
    58  	if handle == nil {
    59  		return ErrTaskNotRunning
    60  	}
    61  
    62  	// Emit the event
    63  	tr.EmitEvent(event)
    64  
    65  	// Send the signal
    66  	return handle.Signal(s)
    67  }
    68  
    69  // Kill a task. Blocks until task exits or context is canceled. State is set to
    70  // dead.
    71  func (tr *TaskRunner) Kill(ctx context.Context, event *structs.TaskEvent) error {
    72  	tr.logger.Trace("Kill requested", "event_type", event.Type, "event_reason", event.KillReason)
    73  
    74  	// Cancel the task runner to break out of restart delay or the main run
    75  	// loop.
    76  	tr.killCtxCancel()
    77  
    78  	// Emit kill event
    79  	tr.EmitEvent(event)
    80  
    81  	select {
    82  	case <-tr.WaitCh():
    83  	case <-ctx.Done():
    84  		return ctx.Err()
    85  	}
    86  
    87  	return tr.getKillErr()
    88  }