open-nomad/client/driver/exec.go

296 lines
8.7 KiB
Go
Raw Normal View History

2015-08-20 23:50:28 +00:00
package driver
import (
"encoding/json"
2015-08-29 23:20:07 +00:00
"fmt"
"log"
2016-02-02 21:38:38 +00:00
"os/exec"
"path/filepath"
"strings"
"syscall"
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"
"github.com/hashicorp/nomad/client/config"
2016-02-05 00:03:17 +00:00
"github.com/hashicorp/nomad/client/driver/executor"
2015-11-17 00:23:03 +00:00
cstructs "github.com/hashicorp/nomad/client/driver/structs"
2016-02-02 22:36:11 +00:00
"github.com/hashicorp/nomad/helper/discover"
"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
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
2016-02-19 22:01:07 +00:00
isolationConfig *cstructs.IsolationConfig
userPid int
allocDir *allocdir.AllocDir
killTimeout time.Duration
maxKillTimeout time.Duration
logger *log.Logger
waitCh chan *cstructs.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
}
func (d *ExecDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
// Only enable if cgroups are available and we are root
if _, ok := node.Attributes["unique.cgroup.mountpoint"]; !ok {
d.logger.Printf("[DEBUG] driver.exec: cgroups unavailable, disabling")
return false, nil
} else if syscall.Geteuid() != 0 {
d.logger.Printf("[DEBUG] driver.exec: must run as root user, disabling")
return false, nil
}
2015-08-20 23:53:43 +00:00
node.Attributes["driver.exec"] = "1"
2015-08-20 23:50:28 +00:00
return true, nil
}
2015-08-23 23:49:48 +00:00
func (d *ExecDriver) Periodic() (bool, time.Duration) {
return true, 15 * time.Second
}
2015-08-23 23:49:48 +00:00
func (d *ExecDriver) Start(ctx *ExecContext, task *structs.Task) (DriverHandle, 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
}
// Set the host environment variables.
filter := strings.Split(d.config.ReadDefault("env.blacklist", config.DefaultEnvBlacklist), ",")
d.taskEnv.AppendHostEnvvars(filter)
// Get the task directory for storing the executor logs.
taskDir, ok := ctx.AllocDir.TaskDirs[d.DriverContext.taskName]
if !ok {
return nil, fmt.Errorf("Could not find task directory for task: %v", d.DriverContext.taskName)
}
2016-02-02 22:36:11 +00:00
bin, err := discover.NomadExecutable()
if err != nil {
return nil, fmt.Errorf("unable to find the nomad binary: %v", err)
}
2016-02-06 01:07:02 +00:00
pluginLogFile := filepath.Join(taskDir, fmt.Sprintf("%s-executor.out", task.Name))
pluginConfig := &plugin.ClientConfig{
Cmd: exec.Command(bin, "executor", pluginLogFile),
}
2015-09-16 14:13:54 +00:00
exec, pluginClient, err := createExecutor(pluginConfig, d.config.LogOutput, d.config)
2016-02-02 21:38:38 +00:00
if err != nil {
return nil, err
2015-09-25 23:49:14 +00:00
}
2016-02-05 00:03:17 +00:00
executorCtx := &executor.ExecutorContext{
2016-03-24 22:39:10 +00:00
TaskEnv: d.taskEnv,
Driver: "exec",
AllocDir: ctx.AllocDir,
AllocID: ctx.AllocID,
Task: task,
}
ps, err := exec.LaunchCmd(&executor.ExecCommand{
Cmd: command,
Args: driverConfig.Args,
FSIsolation: true,
ResourceLimits: true,
User: getExecutorUser(task),
}, executorCtx)
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-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,
executor: exec,
allocDir: ctx.AllocDir,
isolationConfig: ps.IsolationConfig,
killTimeout: GetKillTimeout(task.KillTimeout, maxKill),
maxKillTimeout: maxKill,
logger: d.logger,
version: d.config.Version,
doneCh: make(chan struct{}),
waitCh: make(chan *cstructs.WaitResult, 1),
2015-08-29 23:20:07 +00:00
}
2016-03-24 22:39:10 +00:00
if err := exec.SyncServices(consulContext(d.config, "")); err != nil {
2016-03-24 21:53:53 +00:00
d.logger.Printf("[ERR] driver.exec: error registering services with consul for task: %q: %v", task.Name, err)
2016-03-23 20:19:45 +00:00
}
2015-08-29 23:20:07 +00:00
go h.run()
return h, nil
2015-08-23 23:49:48 +00:00
}
type execId struct {
Version string
KillTimeout time.Duration
MaxKillTimeout time.Duration
UserPid int
TaskDir string
AllocDir *allocdir.AllocDir
2016-02-19 22:01:07 +00:00
IsolationConfig *cstructs.IsolationConfig
2016-02-09 20:59:05 +00:00
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
}
exec, client, err := createExecutor(pluginConfig, d.config.LogOutput, d.config)
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))
}
if id.IsolationConfig != nil {
if e := executor.DestroyCgroup(id.IsolationConfig.Cgroup); e != nil {
2016-02-09 00:27:31 +00:00
merrs.Errors = append(merrs.Errors, fmt.Errorf("destroying cgroup failed: %v", e))
}
}
if e := ctx.AllocDir.UnmountAll(); e != nil {
merrs.Errors = append(merrs.Errors, e)
}
return nil, fmt.Errorf("error connecting to plugin: %v", merrs.ErrorOrNil())
2015-08-29 23:20:07 +00:00
}
// Return a driver handle
h := &execHandle{
pluginClient: client,
executor: exec,
userPid: id.UserPid,
allocDir: id.AllocDir,
isolationConfig: id.IsolationConfig,
logger: d.logger,
version: id.Version,
killTimeout: id.KillTimeout,
maxKillTimeout: id.MaxKillTimeout,
doneCh: make(chan struct{}),
waitCh: make(chan *cstructs.WaitResult, 1),
2015-08-29 23:20:07 +00:00
}
2016-03-24 22:39:10 +00:00
if err := exec.SyncServices(consulContext(d.config, "")); err != nil {
d.logger.Printf("[ERR] driver.exec: error registering services with consul: %v", err)
}
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,
2016-02-09 20:59:05 +00:00
PluginConfig: NewPluginReattachConfig(h.pluginClient.ReattachConfig()),
UserPid: h.userPid,
AllocDir: h.allocDir,
IsolationConfig: h.isolationConfig,
}
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 *cstructs.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.UpdateTask(task)
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) Kill() error {
2016-02-09 03:31:57 +00:00
if err := h.executor.ShutDown(); err != nil {
if h.pluginClient.Exited() {
return nil
}
2016-02-09 03:31:57 +00:00
return fmt.Errorf("executor Shutdown failed: %v", err)
}
2015-08-29 23:20:07 +00:00
select {
case <-h.doneCh:
return nil
case <-time.After(h.killTimeout):
2016-02-04 20:40:48 +00:00
if h.pluginClient.Exited() {
return nil
}
2016-02-09 03:31:57 +00:00
if err := h.executor.Exit(); err != nil {
return fmt.Errorf("executor Exit failed: %v", err)
}
return nil
2015-08-29 23:20:07 +00:00
}
}
func (h *execHandle) run() {
2016-02-02 21:38:38 +00:00
ps, err := h.executor.Wait()
2015-08-29 23:20:07 +00:00
close(h.doneCh)
// If the exitcode is 0 and we had an error that means the plugin didn't
// connect and doesn't know the state of the user process so we are killing
// the user process so that when we create a new executor on restarting the
// new user process doesn't have collisions with resources that the older
// user pid might be holding onto.
if ps.ExitCode == 0 && err != nil {
if h.isolationConfig != nil {
if e := executor.DestroyCgroup(h.isolationConfig.Cgroup); e != nil {
h.logger.Printf("[ERR] driver.exec: destroying cgroup failed while killing cgroup: %v", e)
}
}
if e := h.allocDir.UnmountAll(); e != nil {
h.logger.Printf("[ERR] driver.exec: unmounting dev,proc and alloc dirs failed: %v", e)
}
}
h.waitCh <- cstructs.NewWaitResult(ps.ExitCode, 0, err)
2015-08-29 23:20:07 +00:00
close(h.waitCh)
2016-03-23 20:19:45 +00:00
// Remove services
if err := h.executor.DeregisterServices(); err != nil {
h.logger.Printf("[ERR] driver.exec: failed to deregister services: %v", err)
}
if err := h.executor.Exit(); err != nil {
h.logger.Printf("[ERR] driver.exec: error destroying executor: %v", err)
}
2016-02-03 19:54:54 +00:00
h.pluginClient.Kill()
2015-08-29 23:20:07 +00:00
}