github.com/bigcommerce/nomad@v0.9.3-bc/drivers/rawexec/handle.go (about)

     1  package rawexec
     2  
     3  import (
     4  	"context"
     5  	"strconv"
     6  	"sync"
     7  	"time"
     8  
     9  	hclog "github.com/hashicorp/go-hclog"
    10  	plugin "github.com/hashicorp/go-plugin"
    11  	"github.com/hashicorp/nomad/drivers/shared/executor"
    12  	"github.com/hashicorp/nomad/plugins/drivers"
    13  )
    14  
    15  type taskHandle struct {
    16  	exec         executor.Executor
    17  	pid          int
    18  	pluginClient *plugin.Client
    19  	logger       hclog.Logger
    20  
    21  	// stateLock syncs access to all fields below
    22  	stateLock sync.RWMutex
    23  
    24  	taskConfig  *drivers.TaskConfig
    25  	procState   drivers.TaskState
    26  	startedAt   time.Time
    27  	completedAt time.Time
    28  	exitResult  *drivers.ExitResult
    29  	doneCh      chan struct{}
    30  }
    31  
    32  func (h *taskHandle) TaskStatus() *drivers.TaskStatus {
    33  	h.stateLock.RLock()
    34  	defer h.stateLock.RUnlock()
    35  
    36  	return &drivers.TaskStatus{
    37  		ID:          h.taskConfig.ID,
    38  		Name:        h.taskConfig.Name,
    39  		State:       h.procState,
    40  		StartedAt:   h.startedAt,
    41  		CompletedAt: h.completedAt,
    42  		ExitResult:  h.exitResult,
    43  		DriverAttributes: map[string]string{
    44  			"pid": strconv.Itoa(h.pid),
    45  		},
    46  	}
    47  }
    48  
    49  func (h *taskHandle) IsRunning() bool {
    50  	h.stateLock.RLock()
    51  	defer h.stateLock.RUnlock()
    52  	return h.procState == drivers.TaskStateRunning
    53  }
    54  
    55  func (h *taskHandle) run() {
    56  	defer close(h.doneCh)
    57  	h.stateLock.Lock()
    58  	if h.exitResult == nil {
    59  		h.exitResult = &drivers.ExitResult{}
    60  	}
    61  	h.stateLock.Unlock()
    62  
    63  	// Block until process exits
    64  	ps, err := h.exec.Wait(context.Background())
    65  
    66  	h.stateLock.Lock()
    67  	defer h.stateLock.Unlock()
    68  
    69  	if err != nil {
    70  		h.exitResult.Err = err
    71  		h.procState = drivers.TaskStateUnknown
    72  		h.completedAt = time.Now()
    73  		return
    74  	}
    75  	h.procState = drivers.TaskStateExited
    76  	h.exitResult.ExitCode = ps.ExitCode
    77  	h.exitResult.Signal = ps.Signal
    78  	h.completedAt = ps.Time
    79  
    80  	// TODO: detect if the task OOMed
    81  }