github.com/emate/nomad@v0.8.2-wo-binpacking/client/driver/raw_exec.go (about)

     1  package driver
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"log"
     8  	"os"
     9  	"path/filepath"
    10  	"time"
    11  
    12  	"github.com/hashicorp/go-plugin"
    13  	"github.com/hashicorp/nomad/client/allocdir"
    14  	"github.com/hashicorp/nomad/client/driver/env"
    15  	"github.com/hashicorp/nomad/client/driver/executor"
    16  	dstructs "github.com/hashicorp/nomad/client/driver/structs"
    17  	"github.com/hashicorp/nomad/client/fingerprint"
    18  	cstructs "github.com/hashicorp/nomad/client/structs"
    19  	"github.com/hashicorp/nomad/helper/fields"
    20  	"github.com/hashicorp/nomad/nomad/structs"
    21  	"github.com/mitchellh/mapstructure"
    22  )
    23  
    24  const (
    25  	// The option that enables this driver in the Config.Options map.
    26  	rawExecConfigOption = "driver.raw_exec.enable"
    27  
    28  	// The key populated in Node Attributes to indicate presence of the Raw Exec
    29  	// driver
    30  	rawExecDriverAttr = "driver.raw_exec"
    31  )
    32  
    33  // The RawExecDriver is a privileged version of the exec driver. It provides no
    34  // resource isolation and just fork/execs. The Exec driver should be preferred
    35  // and this should only be used when explicitly needed.
    36  type RawExecDriver struct {
    37  	DriverContext
    38  	fingerprint.StaticFingerprinter
    39  }
    40  
    41  // rawExecHandle is returned from Start/Open as a handle to the PID
    42  type rawExecHandle struct {
    43  	version        string
    44  	pluginClient   *plugin.Client
    45  	userPid        int
    46  	executor       executor.Executor
    47  	killTimeout    time.Duration
    48  	maxKillTimeout time.Duration
    49  	logger         *log.Logger
    50  	waitCh         chan *dstructs.WaitResult
    51  	doneCh         chan struct{}
    52  	taskEnv        *env.TaskEnv
    53  	taskDir        *allocdir.TaskDir
    54  }
    55  
    56  // NewRawExecDriver is used to create a new raw exec driver
    57  func NewRawExecDriver(ctx *DriverContext) Driver {
    58  	return &RawExecDriver{DriverContext: *ctx}
    59  }
    60  
    61  // Validate is used to validate the driver configuration
    62  func (d *RawExecDriver) Validate(config map[string]interface{}) error {
    63  	fd := &fields.FieldData{
    64  		Raw: config,
    65  		Schema: map[string]*fields.FieldSchema{
    66  			"command": {
    67  				Type:     fields.TypeString,
    68  				Required: true,
    69  			},
    70  			"args": {
    71  				Type: fields.TypeArray,
    72  			},
    73  		},
    74  	}
    75  
    76  	if err := fd.Validate(); err != nil {
    77  		return err
    78  	}
    79  
    80  	return nil
    81  }
    82  
    83  func (d *RawExecDriver) Abilities() DriverAbilities {
    84  	return DriverAbilities{
    85  		SendSignals: true,
    86  		Exec:        true,
    87  	}
    88  }
    89  
    90  func (d *RawExecDriver) FSIsolation() cstructs.FSIsolation {
    91  	return cstructs.FSIsolationNone
    92  }
    93  
    94  func (d *RawExecDriver) Fingerprint(req *cstructs.FingerprintRequest, resp *cstructs.FingerprintResponse) error {
    95  	// Check that the user has explicitly enabled this executor.
    96  	enabled := req.Config.ReadBoolDefault(rawExecConfigOption, false)
    97  
    98  	if enabled || req.Config.DevMode {
    99  		d.logger.Printf("[WARN] driver.raw_exec: raw exec is enabled. Only enable if needed")
   100  		resp.AddAttribute(rawExecDriverAttr, "1")
   101  		resp.Detected = true
   102  		return nil
   103  	}
   104  
   105  	resp.RemoveAttribute(rawExecDriverAttr)
   106  	return nil
   107  }
   108  
   109  func (d *RawExecDriver) Prestart(*ExecContext, *structs.Task) (*PrestartResponse, error) {
   110  	return nil, nil
   111  }
   112  
   113  func (d *RawExecDriver) Start(ctx *ExecContext, task *structs.Task) (*StartResponse, error) {
   114  	var driverConfig ExecDriverConfig
   115  	if err := mapstructure.WeakDecode(task.Config, &driverConfig); err != nil {
   116  		return nil, err
   117  	}
   118  
   119  	// Get the command to be ran
   120  	command := driverConfig.Command
   121  	if err := validateCommand(command, "args"); err != nil {
   122  		return nil, err
   123  	}
   124  
   125  	pluginLogFile := filepath.Join(ctx.TaskDir.Dir, "executor.out")
   126  	executorConfig := &dstructs.ExecutorConfig{
   127  		LogFile:  pluginLogFile,
   128  		LogLevel: d.config.LogLevel,
   129  	}
   130  
   131  	exec, pluginClient, err := createExecutor(d.config.LogOutput, d.config, executorConfig)
   132  	if err != nil {
   133  		return nil, err
   134  	}
   135  	executorCtx := &executor.ExecutorContext{
   136  		TaskEnv: ctx.TaskEnv,
   137  		Driver:  "raw_exec",
   138  		Task:    task,
   139  		TaskDir: ctx.TaskDir.Dir,
   140  		LogDir:  ctx.TaskDir.LogDir,
   141  	}
   142  	if err := exec.SetContext(executorCtx); err != nil {
   143  		pluginClient.Kill()
   144  		return nil, fmt.Errorf("failed to set executor context: %v", err)
   145  	}
   146  
   147  	taskKillSignal, err := getTaskKillSignal(task.KillSignal)
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  
   152  	execCmd := &executor.ExecCommand{
   153  		Cmd:            command,
   154  		Args:           driverConfig.Args,
   155  		User:           task.User,
   156  		TaskKillSignal: taskKillSignal,
   157  	}
   158  	ps, err := exec.LaunchCmd(execCmd)
   159  	if err != nil {
   160  		pluginClient.Kill()
   161  		return nil, err
   162  	}
   163  	d.logger.Printf("[DEBUG] driver.raw_exec: started process with pid: %v", ps.Pid)
   164  
   165  	// Return a driver handle
   166  	maxKill := d.DriverContext.config.MaxKillTimeout
   167  	h := &rawExecHandle{
   168  		pluginClient:   pluginClient,
   169  		executor:       exec,
   170  		userPid:        ps.Pid,
   171  		killTimeout:    GetKillTimeout(task.KillTimeout, maxKill),
   172  		maxKillTimeout: maxKill,
   173  		version:        d.config.Version.VersionNumber(),
   174  		logger:         d.logger,
   175  		doneCh:         make(chan struct{}),
   176  		waitCh:         make(chan *dstructs.WaitResult, 1),
   177  		taskEnv:        ctx.TaskEnv,
   178  		taskDir:        ctx.TaskDir,
   179  	}
   180  	go h.run()
   181  	return &StartResponse{Handle: h}, nil
   182  }
   183  
   184  func (d *RawExecDriver) Cleanup(*ExecContext, *CreatedResources) error { return nil }
   185  
   186  type rawExecId struct {
   187  	Version        string
   188  	KillTimeout    time.Duration
   189  	MaxKillTimeout time.Duration
   190  	UserPid        int
   191  	PluginConfig   *PluginReattachConfig
   192  }
   193  
   194  func (d *RawExecDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
   195  	id := &rawExecId{}
   196  	if err := json.Unmarshal([]byte(handleID), id); err != nil {
   197  		return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
   198  	}
   199  
   200  	pluginConfig := &plugin.ClientConfig{
   201  		Reattach: id.PluginConfig.PluginConfig(),
   202  	}
   203  	exec, pluginClient, err := createExecutorWithConfig(pluginConfig, d.config.LogOutput)
   204  	if err != nil {
   205  		d.logger.Println("[ERR] driver.raw_exec: error connecting to plugin so destroying plugin pid and user pid")
   206  		if e := destroyPlugin(id.PluginConfig.Pid, id.UserPid); e != nil {
   207  			d.logger.Printf("[ERR] driver.raw_exec: error destroying plugin and userpid: %v", e)
   208  		}
   209  		return nil, fmt.Errorf("error connecting to plugin: %v", err)
   210  	}
   211  
   212  	ver, _ := exec.Version()
   213  	d.logger.Printf("[DEBUG] driver.raw_exec: version of executor: %v", ver.Version)
   214  
   215  	// Return a driver handle
   216  	h := &rawExecHandle{
   217  		pluginClient:   pluginClient,
   218  		executor:       exec,
   219  		userPid:        id.UserPid,
   220  		logger:         d.logger,
   221  		killTimeout:    id.KillTimeout,
   222  		maxKillTimeout: id.MaxKillTimeout,
   223  		version:        id.Version,
   224  		doneCh:         make(chan struct{}),
   225  		waitCh:         make(chan *dstructs.WaitResult, 1),
   226  		taskEnv:        ctx.TaskEnv,
   227  		taskDir:        ctx.TaskDir,
   228  	}
   229  	go h.run()
   230  	return h, nil
   231  }
   232  
   233  func (h *rawExecHandle) ID() string {
   234  	id := rawExecId{
   235  		Version:        h.version,
   236  		KillTimeout:    h.killTimeout,
   237  		MaxKillTimeout: h.maxKillTimeout,
   238  		PluginConfig:   NewPluginReattachConfig(h.pluginClient.ReattachConfig()),
   239  		UserPid:        h.userPid,
   240  	}
   241  
   242  	data, err := json.Marshal(id)
   243  	if err != nil {
   244  		h.logger.Printf("[ERR] driver.raw_exec: failed to marshal ID to JSON: %s", err)
   245  	}
   246  	return string(data)
   247  }
   248  
   249  func (h *rawExecHandle) WaitCh() chan *dstructs.WaitResult {
   250  	return h.waitCh
   251  }
   252  
   253  func (h *rawExecHandle) Update(task *structs.Task) error {
   254  	// Store the updated kill timeout.
   255  	h.killTimeout = GetKillTimeout(task.KillTimeout, h.maxKillTimeout)
   256  	h.executor.UpdateTask(task)
   257  
   258  	// Update is not possible
   259  	return nil
   260  }
   261  
   262  func (h *rawExecHandle) Exec(ctx context.Context, cmd string, args []string) ([]byte, int, error) {
   263  	return executor.ExecScript(ctx, h.taskDir.Dir, h.taskEnv, nil, cmd, args)
   264  }
   265  
   266  func (h *rawExecHandle) Signal(s os.Signal) error {
   267  	return h.executor.Signal(s)
   268  }
   269  
   270  func (h *rawExecHandle) Kill() error {
   271  	if err := h.executor.ShutDown(); err != nil {
   272  		if h.pluginClient.Exited() {
   273  			return nil
   274  		}
   275  		return fmt.Errorf("executor Shutdown failed: %v", err)
   276  	}
   277  
   278  	select {
   279  	case <-h.doneCh:
   280  		return nil
   281  	case <-time.After(h.killTimeout):
   282  		if h.pluginClient.Exited() {
   283  			return nil
   284  		}
   285  		if err := h.executor.Exit(); err != nil {
   286  			return fmt.Errorf("executor Exit failed: %v", err)
   287  		}
   288  
   289  		return nil
   290  	}
   291  }
   292  
   293  func (h *rawExecHandle) Stats() (*cstructs.TaskResourceUsage, error) {
   294  	return h.executor.Stats()
   295  }
   296  
   297  func (h *rawExecHandle) run() {
   298  	ps, werr := h.executor.Wait()
   299  	close(h.doneCh)
   300  	if ps.ExitCode == 0 && werr != nil {
   301  		if e := killProcess(h.userPid); e != nil {
   302  			h.logger.Printf("[ERR] driver.raw_exec: error killing user process: %v", e)
   303  		}
   304  	}
   305  
   306  	// Exit the executor
   307  	if err := h.executor.Exit(); err != nil {
   308  		h.logger.Printf("[ERR] driver.raw_exec: error killing executor: %v", err)
   309  	}
   310  	h.pluginClient.Kill()
   311  
   312  	// Send the results
   313  	h.waitCh <- &dstructs.WaitResult{ExitCode: ps.ExitCode, Signal: ps.Signal, Err: werr}
   314  	close(h.waitCh)
   315  }