github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/plugins/drivers/task_handle.go (about)

     1  package drivers
     2  
     3  import (
     4  	"github.com/hashicorp/nomad/nomad/structs"
     5  	"github.com/hashicorp/nomad/plugins/base"
     6  )
     7  
     8  // TaskHandle is the state shared between a driver and the client.
     9  // It is returned to the client after starting the task and used
    10  // for recovery of tasks during a driver restart.
    11  type TaskHandle struct {
    12  	// Version is set by the driver an allows it to handle upgrading from
    13  	// an older DriverState struct. Prior to 0.9 the only state stored for
    14  	// driver was the reattach config for the executor. To allow upgrading to
    15  	// 0.9, Version 0 is handled as if it is the json encoded reattach config.
    16  	Version     int
    17  	Config      *TaskConfig
    18  	State       TaskState
    19  	DriverState []byte
    20  }
    21  
    22  func NewTaskHandle(version int) *TaskHandle {
    23  	return &TaskHandle{Version: version}
    24  }
    25  
    26  func (h *TaskHandle) SetDriverState(v interface{}) error {
    27  	h.DriverState = []byte{}
    28  	return base.MsgPackEncode(&h.DriverState, v)
    29  }
    30  
    31  func (h *TaskHandle) GetDriverState(v interface{}) error {
    32  	return base.MsgPackDecode(h.DriverState, v)
    33  
    34  }
    35  
    36  func (h *TaskHandle) Copy() *TaskHandle {
    37  	if h == nil {
    38  		return nil
    39  	}
    40  
    41  	handle := new(TaskHandle)
    42  	handle.Version = h.Version
    43  	handle.Config = h.Config.Copy()
    44  	handle.State = h.State
    45  	handle.DriverState = make([]byte, len(h.DriverState))
    46  	copy(handle.DriverState, h.DriverState)
    47  	return handle
    48  }
    49  
    50  // Store this TaskHandle on the given TaskState.
    51  func (h *TaskHandle) Store(ts *structs.TaskState) {
    52  	if h == nil || len(h.DriverState) == 0 {
    53  		// No handle or state, clear existing state
    54  		ts.TaskHandle = nil
    55  		return
    56  	}
    57  
    58  	ds := make([]byte, len(h.DriverState))
    59  	copy(ds, h.DriverState)
    60  	ts.TaskHandle = &structs.TaskHandle{
    61  		Version:     h.Version,
    62  		DriverState: ds,
    63  	}
    64  }
    65  
    66  // NewTaskHandleFromState returns the TaskHandle stored in a TaskState or nil
    67  // if no handle was stored.
    68  func NewTaskHandleFromState(ts *structs.TaskState) *TaskHandle {
    69  	if ts.TaskHandle == nil {
    70  		return nil
    71  	}
    72  
    73  	th := TaskHandle{
    74  		Version:     ts.TaskHandle.Version,
    75  		DriverState: make([]byte, len(ts.TaskHandle.DriverState)),
    76  	}
    77  	copy(th.DriverState, ts.TaskHandle.DriverState)
    78  	return &th
    79  }