github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/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/config" 15 "github.com/hashicorp/nomad/client/driver/env" 16 "github.com/hashicorp/nomad/client/driver/executor" 17 dstructs "github.com/hashicorp/nomad/client/driver/structs" 18 "github.com/hashicorp/nomad/client/fingerprint" 19 cstructs "github.com/hashicorp/nomad/client/structs" 20 "github.com/hashicorp/nomad/helper/fields" 21 "github.com/hashicorp/nomad/nomad/structs" 22 "github.com/mitchellh/mapstructure" 23 ) 24 25 const ( 26 // The option that enables this driver in the Config.Options map. 27 rawExecConfigOption = "driver.raw_exec.enable" 28 29 // The key populated in Node Attributes to indicate presence of the Raw Exec 30 // driver 31 rawExecDriverAttr = "driver.raw_exec" 32 ) 33 34 // The RawExecDriver is a privileged version of the exec driver. It provides no 35 // resource isolation and just fork/execs. The Exec driver should be preferred 36 // and this should only be used when explicitly needed. 37 type RawExecDriver struct { 38 DriverContext 39 fingerprint.StaticFingerprinter 40 } 41 42 // rawExecHandle is returned from Start/Open as a handle to the PID 43 type rawExecHandle struct { 44 version string 45 pluginClient *plugin.Client 46 userPid int 47 executor executor.Executor 48 killTimeout time.Duration 49 maxKillTimeout time.Duration 50 logger *log.Logger 51 waitCh chan *dstructs.WaitResult 52 doneCh chan struct{} 53 taskEnv *env.TaskEnv 54 taskDir *allocdir.TaskDir 55 } 56 57 // NewRawExecDriver is used to create a new raw exec driver 58 func NewRawExecDriver(ctx *DriverContext) Driver { 59 return &RawExecDriver{DriverContext: *ctx} 60 } 61 62 // Validate is used to validate the driver configuration 63 func (d *RawExecDriver) Validate(config map[string]interface{}) error { 64 fd := &fields.FieldData{ 65 Raw: config, 66 Schema: map[string]*fields.FieldSchema{ 67 "command": { 68 Type: fields.TypeString, 69 Required: true, 70 }, 71 "args": { 72 Type: fields.TypeArray, 73 }, 74 }, 75 } 76 77 if err := fd.Validate(); err != nil { 78 return err 79 } 80 81 return nil 82 } 83 84 func (d *RawExecDriver) Abilities() DriverAbilities { 85 return DriverAbilities{ 86 SendSignals: true, 87 Exec: true, 88 } 89 } 90 91 func (d *RawExecDriver) FSIsolation() cstructs.FSIsolation { 92 return cstructs.FSIsolationNone 93 } 94 95 func (d *RawExecDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) { 96 // Check that the user has explicitly enabled this executor. 97 enabled := cfg.ReadBoolDefault(rawExecConfigOption, false) 98 99 if enabled || cfg.DevMode { 100 d.logger.Printf("[WARN] driver.raw_exec: raw exec is enabled. Only enable if needed") 101 node.Attributes[rawExecDriverAttr] = "1" 102 return true, nil 103 } 104 105 delete(node.Attributes, rawExecDriverAttr) 106 return false, 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 }