github.com/taylorchu/nomad@v0.5.3-rc1.0.20170407200202-db11e7dd7b55/client/driver/raw_exec.go (about)

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