github.com/jmitchell/nomad@v0.1.3-0.20151007230021-7ab84c2862d8/client/executor/exec_linux.go (about) 1 package executor 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "io" 9 "os" 10 "os/exec" 11 "os/user" 12 "path/filepath" 13 "strconv" 14 "strings" 15 "syscall" 16 17 "github.com/hashicorp/go-multierror" 18 "github.com/hashicorp/nomad/client/allocdir" 19 "github.com/hashicorp/nomad/client/driver/args" 20 "github.com/hashicorp/nomad/client/driver/environment" 21 "github.com/hashicorp/nomad/command" 22 "github.com/hashicorp/nomad/helper/discover" 23 "github.com/hashicorp/nomad/nomad/structs" 24 25 cgroupFs "github.com/opencontainers/runc/libcontainer/cgroups/fs" 26 cgroupConfig "github.com/opencontainers/runc/libcontainer/configs" 27 ) 28 29 const ( 30 cgroupMount = "/sys/fs/cgroup" 31 ) 32 33 var ( 34 // A mapping of directories on the host OS to attempt to embed inside each 35 // task's chroot. 36 chrootEnv = map[string]string{ 37 "/bin": "/bin", 38 "/etc": "/etc", 39 "/lib": "/lib", 40 "/lib32": "/lib32", 41 "/lib64": "/lib64", 42 "/usr/bin": "/usr/bin", 43 "/usr/lib": "/usr/lib", 44 } 45 ) 46 47 func NewExecutor() Executor { 48 e := LinuxExecutor{} 49 50 // TODO: In a follow-up PR make it so this only happens once per client. 51 // Fingerprinting shouldn't happen per task. 52 53 // Check that cgroups are available. 54 if _, err := os.Stat(cgroupMount); err == nil { 55 e.cgroupEnabled = true 56 } 57 58 return &e 59 } 60 61 // Linux executor is designed to run on linux kernel 2.8+. 62 type LinuxExecutor struct { 63 cmd 64 user *user.User 65 66 // Finger print capabilities. 67 cgroupEnabled bool 68 69 // Isolation configurations. 70 groups *cgroupConfig.Cgroup 71 alloc *allocdir.AllocDir 72 taskName string 73 taskDir string 74 75 // Tracking of child process. 76 spawnChild exec.Cmd 77 spawnOutputWriter *os.File 78 spawnOutputReader *os.File 79 80 // Track whether there are filesystems mounted in the task dir. 81 mounts bool 82 } 83 84 func (e *LinuxExecutor) Limit(resources *structs.Resources) error { 85 if resources == nil { 86 return errNoResources 87 } 88 89 if e.cgroupEnabled { 90 return e.configureCgroups(resources) 91 } 92 93 return nil 94 } 95 96 func (e *LinuxExecutor) ConfigureTaskDir(taskName string, alloc *allocdir.AllocDir) error { 97 e.taskName = taskName 98 taskDir, ok := alloc.TaskDirs[taskName] 99 if !ok { 100 fmt.Errorf("Couldn't find task directory for task %v", taskName) 101 } 102 e.taskDir = taskDir 103 104 if err := alloc.MountSharedDir(taskName); err != nil { 105 return err 106 } 107 108 if err := alloc.Embed(taskName, chrootEnv); err != nil { 109 return err 110 } 111 112 // Mount dev 113 dev := filepath.Join(taskDir, "dev") 114 if err := os.Mkdir(dev, 0777); err != nil { 115 return fmt.Errorf("Mkdir(%v) failed: %v", dev) 116 } 117 118 if err := syscall.Mount("", dev, "devtmpfs", syscall.MS_RDONLY, ""); err != nil { 119 return fmt.Errorf("Couldn't mount /dev to %v: %v", dev, err) 120 } 121 122 // Mount proc 123 proc := filepath.Join(taskDir, "proc") 124 if err := os.Mkdir(proc, 0777); err != nil { 125 return fmt.Errorf("Mkdir(%v) failed: %v", proc) 126 } 127 128 if err := syscall.Mount("", proc, "proc", syscall.MS_RDONLY, ""); err != nil { 129 return fmt.Errorf("Couldn't mount /proc to %v: %v", proc, err) 130 } 131 132 // Set the tasks AllocDir environment variable. 133 env, err := environment.ParseFromList(e.Cmd.Env) 134 if err != nil { 135 return err 136 } 137 env.SetAllocDir(filepath.Join("/", allocdir.SharedAllocName)) 138 e.Cmd.Env = env.List() 139 140 e.alloc = alloc 141 e.mounts = true 142 return nil 143 } 144 145 func (e *LinuxExecutor) cleanTaskDir() error { 146 if e.alloc == nil { 147 return errors.New("ConfigureTaskDir() must be called before Start()") 148 } 149 150 if !e.mounts { 151 return nil 152 } 153 154 // Unmount dev. 155 errs := new(multierror.Error) 156 dev := filepath.Join(e.taskDir, "dev") 157 if err := syscall.Unmount(dev, 0); err != nil { 158 errs = multierror.Append(errs, fmt.Errorf("Failed to unmount dev (%v): %v", dev, err)) 159 } 160 161 // Unmount proc. 162 proc := filepath.Join(e.taskDir, "proc") 163 if err := syscall.Unmount(proc, 0); err != nil { 164 errs = multierror.Append(errs, fmt.Errorf("Failed to unmount proc (%v): %v", proc, err)) 165 } 166 167 e.mounts = false 168 return errs.ErrorOrNil() 169 } 170 171 func (e *LinuxExecutor) configureCgroups(resources *structs.Resources) error { 172 if !e.cgroupEnabled { 173 return nil 174 } 175 176 e.groups = &cgroupConfig.Cgroup{} 177 178 // Groups will be created in a heiarchy according to the resource being 179 // constrained, current session, and then this unique name. Restraints are 180 // then placed in the corresponding files. 181 // Ex: restricting a process to 2048Mhz CPU and 2MB of memory: 182 // $ cat /sys/fs/cgroup/cpu/user/1000.user/4.session/<uuid>/cpu.shares 183 // 2028 184 // $ cat /sys/fs/cgroup/memory/user/1000.user/4.session/<uuid>/memory.limit_in_bytes 185 // 2097152 186 e.groups.Name = structs.GenerateUUID() 187 188 // TODO: verify this is needed for things like network access 189 e.groups.AllowAllDevices = true 190 191 if resources.MemoryMB > 0 { 192 // Total amount of memory allowed to consume 193 e.groups.Memory = int64(resources.MemoryMB * 1024 * 1024) 194 // Disable swap to avoid issues on the machine 195 e.groups.MemorySwap = int64(-1) 196 } 197 198 if resources.CPU > 0.0 { 199 // Set the relative CPU shares for this cgroup. 200 // The simplest scale is 1 share to 1 MHz so 1024 = 1GHz. This means any 201 // given process will have at least that amount of resources, but likely 202 // more since it is (probably) rare that the machine will run at 100% 203 // CPU. This scale will cease to work if a node is overprovisioned. 204 e.groups.CpuShares = int64(resources.CPU) 205 } 206 207 if resources.IOPS != 0 { 208 // Validate it is in an acceptable range. 209 if resources.IOPS < 10 || resources.IOPS > 1000 { 210 return fmt.Errorf("resources.IOPS must be between 10 and 1000: %d", resources.IOPS) 211 } 212 213 e.groups.BlkioWeight = uint16(resources.IOPS) 214 } 215 216 return nil 217 } 218 219 func (e *LinuxExecutor) runAs(userid string) error { 220 errs := new(multierror.Error) 221 222 // First, try to lookup the user by uid 223 u, err := user.LookupId(userid) 224 if err == nil { 225 e.user = u 226 return nil 227 } else { 228 errs = multierror.Append(errs, err) 229 } 230 231 // Lookup failed, so try by username instead 232 u, err = user.Lookup(userid) 233 if err == nil { 234 e.user = u 235 return nil 236 } else { 237 errs = multierror.Append(errs, err) 238 } 239 240 // If we got here we failed to lookup based on id and username, so we'll 241 // return those errors. 242 return fmt.Errorf("Failed to identify user to run as: %s", errs) 243 } 244 245 func (e *LinuxExecutor) Start() error { 246 // Run as "nobody" user so we don't leak root privilege to the 247 // spawned process. 248 if err := e.runAs("nobody"); err == nil && e.user != nil { 249 e.cmd.SetUID(e.user.Uid) 250 e.cmd.SetGID(e.user.Gid) 251 } 252 253 if e.alloc == nil { 254 return errors.New("ConfigureTaskDir() must be called before Start()") 255 } 256 257 // Parse the commands arguments and replace instances of Nomad environment 258 // variables. 259 envVars, err := environment.ParseFromList(e.Cmd.Env) 260 if err != nil { 261 return err 262 } 263 264 combined := strings.Join(e.Cmd.Args, " ") 265 parsed, err := args.ParseAndReplace(combined, envVars.Map()) 266 if err != nil { 267 return err 268 } 269 e.Cmd.Args = parsed 270 271 return e.spawnDaemon() 272 } 273 274 // spawnDaemon executes a double fork to start the user command with proper 275 // isolation. Stores the child process for use in Wait. 276 func (e *LinuxExecutor) spawnDaemon() error { 277 bin, err := discover.NomadExecutable() 278 if err != nil { 279 return fmt.Errorf("Failed to determine the nomad executable: %v", err) 280 } 281 282 // Serialize the cmd and the cgroup configuration so it can be passed to the 283 // sub-process. 284 var buffer bytes.Buffer 285 enc := json.NewEncoder(&buffer) 286 287 c := command.DaemonConfig{ 288 Cmd: e.cmd.Cmd, 289 Chroot: e.taskDir, 290 StdoutFile: filepath.Join(e.taskDir, allocdir.TaskLocal, fmt.Sprintf("%v.stdout", e.taskName)), 291 StderrFile: filepath.Join(e.taskDir, allocdir.TaskLocal, fmt.Sprintf("%v.stderr", e.taskName)), 292 StdinFile: "/dev/null", 293 } 294 if err := enc.Encode(c); err != nil { 295 return fmt.Errorf("Failed to serialize daemon configuration: %v", err) 296 } 297 298 // Create a pipe to capture Stdout. 299 pr, pw, err := os.Pipe() 300 if err != nil { 301 return err 302 } 303 e.spawnOutputWriter = pw 304 e.spawnOutputReader = pr 305 306 // Call ourselves using a hidden flag. The new instance of nomad will join 307 // the passed cgroup, forkExec the cmd, and output status codes through 308 // Stdout. 309 escaped := strconv.Quote(buffer.String()) 310 spawn := exec.Command(bin, "spawn-daemon", escaped) 311 spawn.Stdout = e.spawnOutputWriter 312 313 // Capture its Stdin. 314 spawnStdIn, err := spawn.StdinPipe() 315 if err != nil { 316 return err 317 } 318 319 if err := spawn.Start(); err != nil { 320 fmt.Errorf("Failed to call spawn-daemon on nomad executable: %v", err) 321 } 322 323 // Join the spawn-daemon to the cgroup. 324 if e.groups != nil { 325 manager := cgroupFs.Manager{} 326 manager.Cgroups = e.groups 327 328 // Apply will place the current pid into the tasks file for each of the 329 // created cgroups: 330 // /sys/fs/cgroup/memory/user/1000.user/4.session/<uuid>/tasks 331 // 332 // Apply requires superuser permissions, and may fail if Nomad is not run with 333 // the required permissions 334 if err := manager.Apply(spawn.Process.Pid); err != nil { 335 errs := new(multierror.Error) 336 errs = multierror.Append(errs, fmt.Errorf("Failed to join spawn-daemon to the cgroup (config => %+v): %v", manager.Cgroups, err)) 337 338 if err := sendAbortCommand(spawnStdIn); err != nil { 339 errs = multierror.Append(errs, err) 340 } 341 342 return errs 343 } 344 } 345 346 // Tell it to start. 347 if err := sendStartCommand(spawnStdIn); err != nil { 348 return err 349 } 350 351 // Parse the response. 352 dec := json.NewDecoder(e.spawnOutputReader) 353 var resp command.SpawnStartStatus 354 if err := dec.Decode(&resp); err != nil { 355 return fmt.Errorf("Failed to parse spawn-daemon start response: %v", err) 356 } 357 358 if resp.ErrorMsg != "" { 359 return fmt.Errorf("Failed to execute user command: %s", resp.ErrorMsg) 360 } 361 362 e.spawnChild = *spawn 363 return nil 364 } 365 366 func sendStartCommand(w io.Writer) error { 367 enc := json.NewEncoder(w) 368 if err := enc.Encode(true); err != nil { 369 return fmt.Errorf("Failed to serialize start command: %v", err) 370 } 371 372 return nil 373 } 374 375 func sendAbortCommand(w io.Writer) error { 376 enc := json.NewEncoder(w) 377 if err := enc.Encode(false); err != nil { 378 return fmt.Errorf("Failed to serialize abort command: %v", err) 379 } 380 381 return nil 382 } 383 384 // Open's behavior is to kill all processes associated with the id and return an 385 // error. This is done because it is not possible to re-attach to the 386 // spawn-daemon's stdout to retrieve status messages. 387 func (e *LinuxExecutor) Open(id string) error { 388 parts := strings.SplitN(id, ":", 2) 389 if len(parts) != 2 { 390 return fmt.Errorf("Invalid id: %v", id) 391 } 392 393 switch parts[0] { 394 case "PID": 395 pid, err := strconv.Atoi(parts[1]) 396 if err != nil { 397 return fmt.Errorf("Invalid id: failed to parse pid %v", parts[1]) 398 } 399 400 process, err := os.FindProcess(pid) 401 if err != nil { 402 return fmt.Errorf("Failed to find Pid %v: %v", pid, err) 403 } 404 405 if err := process.Kill(); err != nil { 406 return fmt.Errorf("Failed to kill Pid %v: %v", pid, err) 407 } 408 case "CGROUP": 409 if !e.cgroupEnabled { 410 return errors.New("Passed a a cgroup identifier, but cgroups are disabled") 411 } 412 413 // De-serialize the cgroup configuration. 414 dec := json.NewDecoder(strings.NewReader(parts[1])) 415 var groups cgroupConfig.Cgroup 416 if err := dec.Decode(&groups); err != nil { 417 return fmt.Errorf("Failed to parse cgroup configuration: %v", err) 418 } 419 420 e.groups = &groups 421 if err := e.destroyCgroup(); err != nil { 422 return err 423 } 424 // TODO: cleanTaskDir is a little more complicated here because the OS 425 // may have already unmounted in the case of a restart. Need to scan. 426 default: 427 return fmt.Errorf("Invalid id type: %v", parts[0]) 428 } 429 430 return errors.New("Could not re-open to id (intended).") 431 } 432 433 func (e *LinuxExecutor) Wait() error { 434 if e.spawnChild.Process == nil { 435 return errors.New("Can not find child to wait on") 436 } 437 438 defer e.spawnOutputWriter.Close() 439 defer e.spawnOutputReader.Close() 440 441 errs := new(multierror.Error) 442 if err := e.spawnChild.Wait(); err != nil { 443 errs = multierror.Append(errs, fmt.Errorf("Wait failed on pid %v: %v", e.spawnChild.Process.Pid, err)) 444 } 445 446 // If they fork/exec and then exit, wait will return but they will be still 447 // running processes so we need to kill the full cgroup. 448 if e.groups != nil { 449 if err := e.destroyCgroup(); err != nil { 450 errs = multierror.Append(errs, err) 451 } 452 } 453 454 if err := e.cleanTaskDir(); err != nil { 455 errs = multierror.Append(errs, err) 456 } 457 458 return errs.ErrorOrNil() 459 } 460 461 // If cgroups are used, the ID is the cgroup structurue. Otherwise, it is the 462 // PID of the spawn-daemon process. An error is returned if the process was 463 // never started. 464 func (e *LinuxExecutor) ID() (string, error) { 465 if e.spawnChild.Process != nil { 466 if e.cgroupEnabled && e.groups != nil { 467 // Serialize the cgroup structure so it can be undone on suabsequent 468 // opens. 469 var buffer bytes.Buffer 470 enc := json.NewEncoder(&buffer) 471 if err := enc.Encode(e.groups); err != nil { 472 return "", fmt.Errorf("Failed to serialize daemon configuration: %v", err) 473 } 474 475 return fmt.Sprintf("CGROUP:%v", buffer.String()), nil 476 } 477 478 return fmt.Sprintf("PID:%d", e.spawnChild.Process.Pid), nil 479 } 480 481 return "", fmt.Errorf("Process has finished or was never started") 482 } 483 484 func (e *LinuxExecutor) Shutdown() error { 485 return e.ForceStop() 486 } 487 488 func (e *LinuxExecutor) ForceStop() error { 489 if e.spawnOutputReader != nil { 490 e.spawnOutputReader.Close() 491 } 492 493 if e.spawnOutputWriter != nil { 494 e.spawnOutputWriter.Close() 495 } 496 497 // If the task is not running inside a cgroup then just the spawn-daemon child is killed. 498 // TODO: Find a good way to kill the children of the spawn-daemon. 499 if e.groups == nil { 500 if err := e.spawnChild.Process.Kill(); err != nil { 501 return fmt.Errorf("Failed to kill child (%v): %v", e.spawnChild.Process.Pid, err) 502 } 503 504 return nil 505 } 506 507 errs := new(multierror.Error) 508 if e.groups != nil { 509 if err := e.destroyCgroup(); err != nil { 510 errs = multierror.Append(errs, err) 511 } 512 } 513 514 if err := e.cleanTaskDir(); err != nil { 515 errs = multierror.Append(errs, err) 516 } 517 518 return errs.ErrorOrNil() 519 } 520 521 func (e *LinuxExecutor) destroyCgroup() error { 522 if e.groups == nil { 523 return errors.New("Can't destroy: cgroup configuration empty") 524 } 525 526 manager := cgroupFs.Manager{} 527 manager.Cgroups = e.groups 528 pids, err := manager.GetPids() 529 if err != nil { 530 return fmt.Errorf("Failed to get pids in the cgroup %v: %v", e.groups.Name, err) 531 } 532 533 errs := new(multierror.Error) 534 for _, pid := range pids { 535 process, err := os.FindProcess(pid) 536 if err != nil { 537 multierror.Append(errs, fmt.Errorf("Failed to find Pid %v: %v", pid, err)) 538 continue 539 } 540 541 if err := process.Kill(); err != nil { 542 multierror.Append(errs, fmt.Errorf("Failed to kill Pid %v: %v", pid, err)) 543 continue 544 } 545 } 546 547 // Remove the cgroup. 548 if err := manager.Destroy(); err != nil { 549 multierror.Append(errs, fmt.Errorf("Failed to delete the cgroup directories: %v", err)) 550 } 551 552 if len(errs.Errors) != 0 { 553 return fmt.Errorf("Failed to destroy cgroup: %v", errs) 554 } 555 556 return nil 557 } 558 559 func (e *LinuxExecutor) Command() *cmd { 560 return &e.cmd 561 }