open-nomad/client/driver/exec.go

310 lines
8.1 KiB
Go
Raw Normal View History

2015-08-20 23:50:28 +00:00
package driver
import (
"context"
"encoding/json"
2015-08-29 23:20:07 +00:00
"fmt"
"log"
2016-10-07 19:37:52 +00:00
"os"
"path/filepath"
2015-08-29 23:20:07 +00:00
"time"
2015-08-20 23:50:28 +00:00
2016-02-09 00:27:31 +00:00
"github.com/hashicorp/go-multierror"
2016-02-02 21:38:38 +00:00
"github.com/hashicorp/go-plugin"
"github.com/hashicorp/nomad/client/allocdir"
2016-02-05 00:03:17 +00:00
"github.com/hashicorp/nomad/client/driver/executor"
dstructs "github.com/hashicorp/nomad/client/driver/structs"
cstructs "github.com/hashicorp/nomad/client/structs"
"github.com/hashicorp/nomad/helper/fields"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/mapstructure"
2015-08-20 23:50:28 +00:00
)
2015-09-25 23:49:14 +00:00
// ExecDriver fork/execs tasks using as many of the underlying OS's isolation
// features.
2015-08-20 23:50:28 +00:00
type ExecDriver struct {
DriverContext
// A tri-state boolean to know if the fingerprinting has happened and
// whether it has been successful
fingerprintSuccess *bool
2015-08-20 23:50:28 +00:00
}
2015-11-14 04:22:49 +00:00
type ExecDriverConfig struct {
Command string `mapstructure:"command"`
Args []string `mapstructure:"args"`
}
2015-08-20 23:50:28 +00:00
2015-08-23 23:49:48 +00:00
// execHandle is returned from Start/Open as a handle to the PID
type execHandle struct {
pluginClient *plugin.Client
executor executor.Executor
userPid int
taskShutdownSignal string
taskDir *allocdir.TaskDir
killTimeout time.Duration
maxKillTimeout time.Duration
logger *log.Logger
waitCh chan *dstructs.WaitResult
doneCh chan struct{}
version string
2015-08-23 23:49:48 +00:00
}
2015-08-20 23:50:28 +00:00
// NewExecDriver is used to create a new exec driver
func NewExecDriver(ctx *DriverContext) Driver {
2015-11-05 21:46:02 +00:00
return &ExecDriver{DriverContext: *ctx}
2015-08-20 23:50:28 +00:00
}
// Validate is used to validate the driver configuration
func (d *ExecDriver) Validate(config map[string]interface{}) error {
fd := &fields.FieldData{
Raw: config,
Schema: map[string]*fields.FieldSchema{
2017-09-26 22:26:33 +00:00
"command": {
Type: fields.TypeString,
Required: true,
},
2017-09-26 22:26:33 +00:00
"args": {
Type: fields.TypeArray,
},
},
}
if err := fd.Validate(); err != nil {
return err
}
return nil
}
2016-10-19 22:06:23 +00:00
func (d *ExecDriver) Abilities() DriverAbilities {
return DriverAbilities{
SendSignals: true,
Exec: true,
2016-10-19 22:06:23 +00:00
}
}
func (d *ExecDriver) FSIsolation() cstructs.FSIsolation {
return cstructs.FSIsolationChroot
}
func (d *ExecDriver) Periodic() (bool, time.Duration) {
return true, 15 * time.Second
}
func (d *ExecDriver) Prestart(*ExecContext, *structs.Task) (*PrestartResponse, error) {
return nil, nil
}
func (d *ExecDriver) Start(ctx *ExecContext, task *structs.Task) (*StartResponse, error) {
var driverConfig ExecDriverConfig
if err := mapstructure.WeakDecode(task.Config, &driverConfig); err != nil {
return nil, err
}
// Get the command to be ran
command := driverConfig.Command
if err := validateCommand(command, "args"); err != nil {
return nil, err
}
pluginLogFile := filepath.Join(ctx.TaskDir.Dir, "executor.out")
2017-01-12 19:50:49 +00:00
executorConfig := &dstructs.ExecutorConfig{
LogFile: pluginLogFile,
LogLevel: d.config.LogLevel,
FSIsolation: true,
}
2017-01-12 19:50:49 +00:00
exec, pluginClient, err := createExecutor(d.config.LogOutput, d.config, executorConfig)
2016-02-02 21:38:38 +00:00
if err != nil {
return nil, err
2015-09-25 23:49:14 +00:00
}
_, err = getTaskKillSignal(task.KillSignal)
2017-12-06 17:16:12 +00:00
if err != nil {
return nil, err
}
2016-10-12 18:35:29 +00:00
execCmd := &executor.ExecCommand{
Cmd: command,
Args: driverConfig.Args,
ResourceLimits: true,
User: getExecutorUser(task),
Resources: &executor.Resources{
CPU: task.Resources.CPU,
MemoryMB: task.Resources.MemoryMB,
IOPS: task.Resources.IOPS,
DiskMB: task.Resources.DiskMB,
},
Env: ctx.TaskEnv.List(),
TaskDir: ctx.TaskDir.Dir,
StdoutPath: ctx.StdoutFifo,
StderrPath: ctx.StderrFifo,
2016-10-12 18:35:29 +00:00
}
ps, err := exec.Launch(execCmd)
2016-02-02 21:38:38 +00:00
if err != nil {
pluginClient.Kill()
2016-03-19 19:18:10 +00:00
return nil, err
2015-08-29 23:20:07 +00:00
}
2016-10-12 18:35:29 +00:00
2016-02-06 02:07:06 +00:00
d.logger.Printf("[DEBUG] driver.exec: started process via plugin with pid: %v", ps.Pid)
2015-08-29 23:20:07 +00:00
// Return a driver handle
maxKill := d.DriverContext.config.MaxKillTimeout
2015-08-29 23:20:07 +00:00
h := &execHandle{
pluginClient: pluginClient,
userPid: ps.Pid,
taskShutdownSignal: task.KillSignal,
executor: exec,
killTimeout: GetKillTimeout(task.KillTimeout, maxKill),
maxKillTimeout: maxKill,
logger: d.logger,
version: d.config.Version.VersionNumber(),
doneCh: make(chan struct{}),
waitCh: make(chan *dstructs.WaitResult, 1),
taskDir: ctx.TaskDir,
2016-03-23 20:19:45 +00:00
}
2015-08-29 23:20:07 +00:00
go h.run()
return &StartResponse{Handle: h}, nil
2015-08-23 23:49:48 +00:00
}
func (d *ExecDriver) Cleanup(*ExecContext, *CreatedResources) error { return nil }
type execId struct {
Version string
KillTimeout time.Duration
MaxKillTimeout time.Duration
UserPid int
PluginConfig *PluginReattachConfig
}
2015-08-23 23:49:48 +00:00
func (d *ExecDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
id := &execId{}
if err := json.Unmarshal([]byte(handleID), id); err != nil {
return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
}
2016-02-02 21:38:38 +00:00
pluginConfig := &plugin.ClientConfig{
Reattach: id.PluginConfig.PluginConfig(),
2016-02-02 21:38:38 +00:00
}
2017-01-12 19:50:49 +00:00
exec, client, err := createExecutorWithConfig(pluginConfig, d.config.LogOutput)
2015-09-15 20:45:48 +00:00
if err != nil {
2016-02-09 00:27:31 +00:00
merrs := new(multierror.Error)
merrs.Errors = append(merrs.Errors, err)
d.logger.Println("[ERR] driver.exec: error connecting to plugin so destroying plugin pid and user pid")
if e := destroyPlugin(id.PluginConfig.Pid, id.UserPid); e != nil {
2016-02-09 00:27:31 +00:00
merrs.Errors = append(merrs.Errors, fmt.Errorf("error destroying plugin and userpid: %v", e))
}
return nil, fmt.Errorf("error connecting to plugin: %v", merrs.ErrorOrNil())
2015-08-29 23:20:07 +00:00
}
2016-03-30 05:05:02 +00:00
ver, _ := exec.Version()
d.logger.Printf("[DEBUG] driver.exec : version of executor: %v", ver.Version)
2015-08-29 23:20:07 +00:00
// Return a driver handle
h := &execHandle{
pluginClient: client,
executor: exec,
userPid: id.UserPid,
logger: d.logger,
version: id.Version,
killTimeout: id.KillTimeout,
maxKillTimeout: id.MaxKillTimeout,
doneCh: make(chan struct{}),
waitCh: make(chan *dstructs.WaitResult, 1),
taskDir: ctx.TaskDir,
2016-03-24 22:39:10 +00:00
}
2015-08-29 23:20:07 +00:00
go h.run()
return h, nil
2015-08-23 23:49:48 +00:00
}
func (h *execHandle) ID() string {
id := execId{
Version: h.version,
KillTimeout: h.killTimeout,
MaxKillTimeout: h.maxKillTimeout,
PluginConfig: NewPluginReattachConfig(h.pluginClient.ReattachConfig()),
UserPid: h.userPid,
}
data, err := json.Marshal(id)
if err != nil {
h.logger.Printf("[ERR] driver.exec: failed to marshal ID to JSON: %s", err)
}
return string(data)
2015-08-23 23:49:48 +00:00
}
func (h *execHandle) WaitCh() chan *dstructs.WaitResult {
2015-08-23 23:49:48 +00:00
return h.waitCh
}
2015-08-29 23:20:07 +00:00
func (h *execHandle) Update(task *structs.Task) error {
// Store the updated kill timeout.
h.killTimeout = GetKillTimeout(task.KillTimeout, h.maxKillTimeout)
h.executor.UpdateResources(&executor.Resources{
CPU: task.Resources.CPU,
MemoryMB: task.Resources.MemoryMB,
IOPS: task.Resources.IOPS,
DiskMB: task.Resources.DiskMB,
})
2015-08-29 23:20:07 +00:00
// Update is not possible
2015-08-23 23:49:48 +00:00
return nil
}
2015-08-29 23:20:07 +00:00
func (h *execHandle) Exec(ctx context.Context, cmd string, args []string) ([]byte, int, error) {
deadline, ok := ctx.Deadline()
if !ok {
// No deadline set on context; default to 1 minute
deadline = time.Now().Add(time.Minute)
}
return h.executor.Exec(deadline, cmd, args)
}
2016-10-07 19:37:52 +00:00
func (h *execHandle) Signal(s os.Signal) error {
2016-10-10 18:46:27 +00:00
return h.executor.Signal(s)
2016-10-07 19:37:52 +00:00
}
func (d *execHandle) Network() *cstructs.DriverNetwork {
return nil
}
2015-08-29 23:20:07 +00:00
func (h *execHandle) Kill() error {
if err := h.executor.Shutdown(h.taskShutdownSignal, h.killTimeout); err != nil {
if h.pluginClient.Exited() {
return nil
}
return fmt.Errorf("executor Kill failed: %v", err)
2016-02-09 03:31:57 +00:00
}
2015-08-29 23:20:07 +00:00
select {
case <-h.doneCh:
case <-time.After(h.killTimeout):
2016-02-04 20:40:48 +00:00
if h.pluginClient.Exited() {
break
2016-02-04 20:40:48 +00:00
}
if err := h.executor.Shutdown(h.taskShutdownSignal, h.killTimeout); err != nil {
return fmt.Errorf("executor Destroy failed: %v", err)
2016-02-09 03:31:57 +00:00
}
2015-08-29 23:20:07 +00:00
}
return nil
2015-08-29 23:20:07 +00:00
}
2016-04-28 23:06:01 +00:00
func (h *execHandle) Stats() (*cstructs.TaskResourceUsage, error) {
return h.executor.Stats()
}
2015-08-29 23:20:07 +00:00
func (h *execHandle) run() {
ps, werr := h.executor.Wait()
2015-08-29 23:20:07 +00:00
close(h.doneCh)
// Destroy the executor
if err := h.executor.Shutdown(h.taskShutdownSignal, 0); err != nil {
h.logger.Printf("[ERR] driver.exec: error destroying executor: %v", err)
}
2016-02-03 19:54:54 +00:00
h.pluginClient.Kill()
// Send the results
h.waitCh <- dstructs.NewWaitResult(ps.ExitCode, ps.Signal, werr)
close(h.waitCh)
2015-08-29 23:20:07 +00:00
}