github.com/mheon/docker@v0.11.2-0.20150922122814-44f47903a831/daemon/execdriver/lxc/driver.go (about) 1 // +build linux 2 3 package lxc 4 5 import ( 6 "encoding/json" 7 "errors" 8 "fmt" 9 "io" 10 "io/ioutil" 11 "os" 12 "os/exec" 13 "path" 14 "path/filepath" 15 "runtime" 16 "strconv" 17 "strings" 18 "sync" 19 "syscall" 20 "time" 21 22 "github.com/Sirupsen/logrus" 23 "github.com/docker/docker/daemon/execdriver" 24 "github.com/docker/docker/pkg/stringutils" 25 sysinfo "github.com/docker/docker/pkg/system" 26 "github.com/docker/docker/pkg/term" 27 "github.com/docker/docker/pkg/version" 28 "github.com/kr/pty" 29 "github.com/opencontainers/runc/libcontainer" 30 "github.com/opencontainers/runc/libcontainer/cgroups" 31 "github.com/opencontainers/runc/libcontainer/configs" 32 "github.com/opencontainers/runc/libcontainer/system" 33 "github.com/opencontainers/runc/libcontainer/user" 34 "github.com/vishvananda/netns" 35 ) 36 37 // DriverName for lxc driver 38 const DriverName = "lxc" 39 40 // ErrExec defines unsupported error message 41 var ErrExec = errors.New("Unsupported: Exec is not supported by the lxc driver") 42 43 // Driver contains all information for lxc driver, 44 // it implements execdriver.Driver 45 type Driver struct { 46 root string // root path for the driver to use 47 libPath string 48 initPath string 49 apparmor bool 50 sharedRoot bool 51 activeContainers map[string]*activeContainer 52 machineMemory int64 53 sync.Mutex 54 } 55 56 type activeContainer struct { 57 container *configs.Config 58 cmd *exec.Cmd 59 } 60 61 // NewDriver returns a new lxc driver, called from NewDriver of execdriver 62 func NewDriver(root, libPath, initPath string, apparmor bool) (*Driver, error) { 63 if err := os.MkdirAll(root, 0700); err != nil { 64 return nil, err 65 } 66 // setup unconfined symlink 67 if err := linkLxcStart(root); err != nil { 68 return nil, err 69 } 70 meminfo, err := sysinfo.ReadMemInfo() 71 if err != nil { 72 return nil, err 73 } 74 return &Driver{ 75 apparmor: apparmor, 76 root: root, 77 libPath: libPath, 78 initPath: initPath, 79 sharedRoot: rootIsShared(), 80 activeContainers: make(map[string]*activeContainer), 81 machineMemory: meminfo.MemTotal, 82 }, nil 83 } 84 85 // Name implements the exec driver Driver interface. 86 func (d *Driver) Name() string { 87 version := d.version() 88 return fmt.Sprintf("%s-%s", DriverName, version) 89 } 90 91 func setupNetNs(nsPath string) (*os.Process, error) { 92 runtime.LockOSThread() 93 defer runtime.UnlockOSThread() 94 95 origns, err := netns.Get() 96 if err != nil { 97 return nil, err 98 } 99 defer origns.Close() 100 101 f, err := os.OpenFile(nsPath, os.O_RDONLY, 0) 102 if err != nil { 103 return nil, fmt.Errorf("failed to get network namespace %q: %v", nsPath, err) 104 } 105 defer f.Close() 106 107 nsFD := f.Fd() 108 if err := netns.Set(netns.NsHandle(nsFD)); err != nil { 109 return nil, fmt.Errorf("failed to set network namespace %q: %v", nsPath, err) 110 } 111 defer netns.Set(origns) 112 113 cmd := exec.Command("/bin/sh", "-c", "while true; do sleep 1; done") 114 if err := cmd.Start(); err != nil { 115 return nil, fmt.Errorf("failed to start netns process: %v", err) 116 } 117 118 return cmd.Process, nil 119 } 120 121 func killNetNsProc(proc *os.Process) { 122 proc.Kill() 123 proc.Wait() 124 } 125 126 // Run implements the exec driver Driver interface, 127 // it calls 'exec.Cmd' to launch lxc commands to run a container. 128 func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { 129 var ( 130 term execdriver.Terminal 131 err error 132 dataPath = d.containerDir(c.ID) 133 ) 134 135 if c.Network == nil || (c.Network.NamespacePath == "" && c.Network.ContainerID == "") { 136 return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("empty namespace path for non-container network") 137 } 138 139 container, err := d.createContainer(c) 140 if err != nil { 141 return execdriver.ExitStatus{ExitCode: -1}, err 142 } 143 144 if c.ProcessConfig.Tty { 145 term, err = NewTtyConsole(&c.ProcessConfig, pipes) 146 } else { 147 term, err = execdriver.NewStdConsole(&c.ProcessConfig, pipes) 148 } 149 if err != nil { 150 return execdriver.ExitStatus{ExitCode: -1}, err 151 } 152 c.ProcessConfig.Terminal = term 153 154 d.Lock() 155 d.activeContainers[c.ID] = &activeContainer{ 156 container: container, 157 cmd: &c.ProcessConfig.Cmd, 158 } 159 d.Unlock() 160 161 c.Mounts = append(c.Mounts, execdriver.Mount{ 162 Source: d.initPath, 163 Destination: c.InitPath, 164 Writable: false, 165 Private: true, 166 }) 167 168 if err := d.generateEnvConfig(c); err != nil { 169 return execdriver.ExitStatus{ExitCode: -1}, err 170 } 171 configPath, err := d.generateLXCConfig(c) 172 if err != nil { 173 return execdriver.ExitStatus{ExitCode: -1}, err 174 } 175 params := []string{ 176 "lxc-start", 177 "-n", c.ID, 178 "-f", configPath, 179 "-q", 180 } 181 182 // From lxc>=1.1 the default behavior is to daemonize containers after start 183 lxcVersion := version.Version(d.version()) 184 if lxcVersion.GreaterThanOrEqualTo(version.Version("1.1")) { 185 params = append(params, "-F") 186 } 187 188 proc := &os.Process{} 189 if c.Network.ContainerID != "" { 190 params = append(params, 191 "--share-net", c.Network.ContainerID, 192 ) 193 } else { 194 proc, err = setupNetNs(c.Network.NamespacePath) 195 if err != nil { 196 return execdriver.ExitStatus{ExitCode: -1}, err 197 } 198 199 pidStr := fmt.Sprintf("%d", proc.Pid) 200 params = append(params, 201 "--share-net", pidStr) 202 } 203 if c.Ipc != nil { 204 if c.Ipc.ContainerID != "" { 205 params = append(params, 206 "--share-ipc", c.Ipc.ContainerID, 207 ) 208 } else if c.Ipc.HostIpc { 209 params = append(params, 210 "--share-ipc", "1", 211 ) 212 } 213 } 214 215 params = append(params, 216 "--", 217 c.InitPath, 218 ) 219 220 if c.ProcessConfig.User != "" { 221 params = append(params, "-u", c.ProcessConfig.User) 222 } 223 224 if c.ProcessConfig.Privileged { 225 if d.apparmor { 226 params[0] = path.Join(d.root, "lxc-start-unconfined") 227 228 } 229 params = append(params, "-privileged") 230 } 231 232 if c.WorkingDir != "" { 233 params = append(params, "-w", c.WorkingDir) 234 } 235 236 params = append(params, "--", c.ProcessConfig.Entrypoint) 237 params = append(params, c.ProcessConfig.Arguments...) 238 239 if d.sharedRoot { 240 // lxc-start really needs / to be non-shared, or all kinds of stuff break 241 // when lxc-start unmount things and those unmounts propagate to the main 242 // mount namespace. 243 // What we really want is to clone into a new namespace and then 244 // mount / MS_REC|MS_SLAVE, but since we can't really clone or fork 245 // without exec in go we have to do this horrible shell hack... 246 shellString := 247 "mount --make-rslave /; exec " + 248 stringutils.ShellQuoteArguments(params) 249 250 params = []string{ 251 "unshare", "-m", "--", "/bin/sh", "-c", shellString, 252 } 253 } 254 logrus.Debugf("lxc params %s", params) 255 var ( 256 name = params[0] 257 arg = params[1:] 258 ) 259 aname, err := exec.LookPath(name) 260 if err != nil { 261 aname = name 262 } 263 c.ProcessConfig.Path = aname 264 c.ProcessConfig.Args = append([]string{name}, arg...) 265 266 if err := createDeviceNodes(c.Rootfs, c.AutoCreatedDevices); err != nil { 267 killNetNsProc(proc) 268 return execdriver.ExitStatus{ExitCode: -1}, err 269 } 270 271 if err := c.ProcessConfig.Start(); err != nil { 272 killNetNsProc(proc) 273 return execdriver.ExitStatus{ExitCode: -1}, err 274 } 275 276 var ( 277 waitErr error 278 waitLock = make(chan struct{}) 279 ) 280 281 go func() { 282 if err := c.ProcessConfig.Wait(); err != nil { 283 if _, ok := err.(*exec.ExitError); !ok { // Do not propagate the error if it's simply a status code != 0 284 waitErr = err 285 } 286 } 287 close(waitLock) 288 }() 289 290 terminate := func(terr error) (execdriver.ExitStatus, error) { 291 if c.ProcessConfig.Process != nil { 292 c.ProcessConfig.Process.Kill() 293 c.ProcessConfig.Wait() 294 } 295 return execdriver.ExitStatus{ExitCode: -1}, terr 296 } 297 // Poll lxc for RUNNING status 298 pid, err := d.waitForStart(c, waitLock) 299 if err != nil { 300 killNetNsProc(proc) 301 return terminate(err) 302 } 303 killNetNsProc(proc) 304 305 cgroupPaths, err := cgroupPaths(c.ID) 306 if err != nil { 307 return terminate(err) 308 } 309 310 state := &libcontainer.State{ 311 InitProcessPid: pid, 312 CgroupPaths: cgroupPaths, 313 } 314 315 f, err := os.Create(filepath.Join(dataPath, "state.json")) 316 if err != nil { 317 return terminate(err) 318 } 319 defer f.Close() 320 321 if err := json.NewEncoder(f).Encode(state); err != nil { 322 return terminate(err) 323 } 324 325 c.ContainerPid = pid 326 327 if hooks.Start != nil { 328 logrus.Debugf("Invoking startCallback") 329 hooks.Start(&c.ProcessConfig, pid) 330 } 331 332 oomKill := false 333 oomKillNotification, err := notifyOnOOM(cgroupPaths) 334 335 <-waitLock 336 exitCode := getExitCode(c) 337 338 if err == nil { 339 _, oomKill = <-oomKillNotification 340 logrus.Debugf("oomKill error: %v, waitErr: %v", oomKill, waitErr) 341 } else { 342 logrus.Warnf("Your kernel does not support OOM notifications: %s", err) 343 } 344 345 // check oom error 346 if oomKill { 347 exitCode = 137 348 } 349 350 return execdriver.ExitStatus{ExitCode: exitCode, OOMKilled: oomKill}, waitErr 351 } 352 353 // copy from libcontainer 354 func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { 355 dir := paths["memory"] 356 if dir == "" { 357 return nil, fmt.Errorf("There is no path for %q in state", "memory") 358 } 359 oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control")) 360 if err != nil { 361 return nil, err 362 } 363 fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0) 364 if syserr != 0 { 365 oomControl.Close() 366 return nil, syserr 367 } 368 369 eventfd := os.NewFile(fd, "eventfd") 370 371 eventControlPath := filepath.Join(dir, "cgroup.event_control") 372 data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd()) 373 if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil { 374 eventfd.Close() 375 oomControl.Close() 376 return nil, err 377 } 378 ch := make(chan struct{}) 379 go func() { 380 defer func() { 381 close(ch) 382 eventfd.Close() 383 oomControl.Close() 384 }() 385 buf := make([]byte, 8) 386 for { 387 if _, err := eventfd.Read(buf); err != nil { 388 return 389 } 390 // When a cgroup is destroyed, an event is sent to eventfd. 391 // So if the control path is gone, return instead of notifying. 392 if _, err := os.Lstat(eventControlPath); os.IsNotExist(err) { 393 return 394 } 395 ch <- struct{}{} 396 } 397 }() 398 return ch, nil 399 } 400 401 // createContainer populates and configures the container type with the 402 // data provided by the execdriver.Command 403 func (d *Driver) createContainer(c *execdriver.Command) (*configs.Config, error) { 404 container := execdriver.InitContainer(c) 405 if err := execdriver.SetupCgroups(container, c); err != nil { 406 return nil, err 407 } 408 return container, nil 409 } 410 411 // Return an map of susbystem -> absolute container cgroup path 412 func cgroupPaths(containerID string) (map[string]string, error) { 413 subsystems, err := cgroups.GetAllSubsystems() 414 if err != nil { 415 return nil, err 416 } 417 logrus.Debugf("subsystems: %s", subsystems) 418 paths := make(map[string]string) 419 for _, subsystem := range subsystems { 420 cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem) 421 logrus.Debugf("cgroup path %s %s", cgroupRoot, cgroupDir) 422 if err != nil { 423 //unsupported subystem 424 continue 425 } 426 path := filepath.Join(cgroupRoot, cgroupDir, "lxc", containerID) 427 paths[subsystem] = path 428 } 429 430 return paths, nil 431 } 432 433 // this is copy from old libcontainer nodes.go 434 func createDeviceNodes(rootfs string, nodesToCreate []*configs.Device) error { 435 oldMask := syscall.Umask(0000) 436 defer syscall.Umask(oldMask) 437 438 for _, node := range nodesToCreate { 439 if err := createDeviceNode(rootfs, node); err != nil { 440 return err 441 } 442 } 443 return nil 444 } 445 446 // Creates the device node in the rootfs of the container. 447 func createDeviceNode(rootfs string, node *configs.Device) error { 448 var ( 449 dest = filepath.Join(rootfs, node.Path) 450 parent = filepath.Dir(dest) 451 ) 452 453 if err := os.MkdirAll(parent, 0755); err != nil { 454 return err 455 } 456 457 fileMode := node.FileMode 458 switch node.Type { 459 case 'c': 460 fileMode |= syscall.S_IFCHR 461 case 'b': 462 fileMode |= syscall.S_IFBLK 463 default: 464 return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path) 465 } 466 467 if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil && !os.IsExist(err) { 468 return fmt.Errorf("mknod %s %s", node.Path, err) 469 } 470 471 if err := syscall.Chown(dest, int(node.Uid), int(node.Gid)); err != nil { 472 return fmt.Errorf("chown %s to %d:%d", node.Path, node.Uid, node.Gid) 473 } 474 475 return nil 476 } 477 478 // setupUser changes the groups, gid, and uid for the user inside the container 479 // copy from libcontainer, cause not it's private 480 func setupUser(userSpec string) error { 481 // Set up defaults. 482 defaultExecUser := user.ExecUser{ 483 Uid: syscall.Getuid(), 484 Gid: syscall.Getgid(), 485 Home: "/", 486 } 487 passwdPath, err := user.GetPasswdPath() 488 if err != nil { 489 return err 490 } 491 groupPath, err := user.GetGroupPath() 492 if err != nil { 493 return err 494 } 495 execUser, err := user.GetExecUserPath(userSpec, &defaultExecUser, passwdPath, groupPath) 496 if err != nil { 497 return err 498 } 499 if err := syscall.Setgroups(execUser.Sgids); err != nil { 500 return err 501 } 502 if err := system.Setgid(execUser.Gid); err != nil { 503 return err 504 } 505 if err := system.Setuid(execUser.Uid); err != nil { 506 return err 507 } 508 // if we didn't get HOME already, set it based on the user's HOME 509 if envHome := os.Getenv("HOME"); envHome == "" { 510 if err := os.Setenv("HOME", execUser.Home); err != nil { 511 return err 512 } 513 } 514 return nil 515 } 516 517 // getExitCode returns the exit code of the process. 518 // If the process has not exited -1 will be returned. 519 func getExitCode(c *execdriver.Command) int { 520 if c.ProcessConfig.ProcessState == nil { 521 return -1 522 } 523 return c.ProcessConfig.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() 524 } 525 526 // Kill implements the exec driver Driver interface. 527 func (d *Driver) Kill(c *execdriver.Command, sig int) error { 528 if sig == 9 || c.ProcessConfig.Process == nil { 529 return killLxc(c.ID, sig) 530 } 531 532 return c.ProcessConfig.Process.Signal(syscall.Signal(sig)) 533 } 534 535 // Pause implements the exec driver Driver interface, 536 // it executes lxc-freeze to pause a container. 537 func (d *Driver) Pause(c *execdriver.Command) error { 538 _, err := exec.LookPath("lxc-freeze") 539 if err == nil { 540 output, errExec := exec.Command("lxc-freeze", "-n", c.ID).CombinedOutput() 541 if errExec != nil { 542 return fmt.Errorf("Err: %s Output: %s", errExec, output) 543 } 544 } 545 546 return err 547 } 548 549 // Unpause implements the exec driver Driver interface, 550 // it executes lxc-unfreeze to unpause a container. 551 func (d *Driver) Unpause(c *execdriver.Command) error { 552 _, err := exec.LookPath("lxc-unfreeze") 553 if err == nil { 554 output, errExec := exec.Command("lxc-unfreeze", "-n", c.ID).CombinedOutput() 555 if errExec != nil { 556 return fmt.Errorf("Err: %s Output: %s", errExec, output) 557 } 558 } 559 560 return err 561 } 562 563 // Terminate implements the exec driver Driver interface. 564 func (d *Driver) Terminate(c *execdriver.Command) error { 565 return killLxc(c.ID, 9) 566 } 567 568 func (d *Driver) version() string { 569 var ( 570 version string 571 output []byte 572 err error 573 ) 574 if _, errPath := exec.LookPath("lxc-version"); errPath == nil { 575 output, err = exec.Command("lxc-version").CombinedOutput() 576 } else { 577 output, err = exec.Command("lxc-start", "--version").CombinedOutput() 578 } 579 if err == nil { 580 version = strings.TrimSpace(string(output)) 581 if parts := strings.SplitN(version, ":", 2); len(parts) == 2 { 582 version = strings.TrimSpace(parts[1]) 583 } 584 } 585 return version 586 } 587 588 func killLxc(id string, sig int) error { 589 var ( 590 err error 591 output []byte 592 ) 593 _, err = exec.LookPath("lxc-kill") 594 if err == nil { 595 output, err = exec.Command("lxc-kill", "-n", id, strconv.Itoa(sig)).CombinedOutput() 596 } else { 597 // lxc-stop does not take arbitrary signals like lxc-kill does 598 output, err = exec.Command("lxc-stop", "-k", "-n", id).CombinedOutput() 599 } 600 if err != nil { 601 return fmt.Errorf("Err: %s Output: %s", err, output) 602 } 603 return nil 604 } 605 606 // wait for the process to start and return the pid for the process 607 func (d *Driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (int, error) { 608 var ( 609 err error 610 output []byte 611 ) 612 // We wait for the container to be fully running. 613 // Timeout after 5 seconds. In case of broken pipe, just retry. 614 // Note: The container can run and finish correctly before 615 // the end of this loop 616 for now := time.Now(); time.Since(now) < 5*time.Second; { 617 select { 618 case <-waitLock: 619 // If the process dies while waiting for it, just return 620 return -1, nil 621 default: 622 } 623 624 output, err = d.getInfo(c.ID) 625 if err == nil { 626 info, err := parseLxcInfo(string(output)) 627 if err != nil { 628 return -1, err 629 } 630 if info.Running { 631 return info.Pid, nil 632 } 633 } 634 time.Sleep(50 * time.Millisecond) 635 } 636 return -1, execdriver.ErrNotRunning 637 } 638 639 func (d *Driver) getInfo(id string) ([]byte, error) { 640 return exec.Command("lxc-info", "-n", id).CombinedOutput() 641 } 642 643 type info struct { 644 ID string 645 driver *Driver 646 } 647 648 func (i *info) IsRunning() bool { 649 var running bool 650 651 output, err := i.driver.getInfo(i.ID) 652 if err != nil { 653 logrus.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output) 654 return false 655 } 656 if strings.Contains(string(output), "RUNNING") { 657 running = true 658 } 659 return running 660 } 661 662 // Info implements the exec driver Driver interface. 663 func (d *Driver) Info(id string) execdriver.Info { 664 return &info{ 665 ID: id, 666 driver: d, 667 } 668 } 669 670 func findCgroupRootAndDir(subsystem string) (string, string, error) { 671 cgroupRoot, err := cgroups.FindCgroupMountpoint(subsystem) 672 if err != nil { 673 return "", "", err 674 } 675 676 cgroupDir, err := cgroups.GetThisCgroupDir(subsystem) 677 if err != nil { 678 return "", "", err 679 } 680 return cgroupRoot, cgroupDir, nil 681 } 682 683 // GetPidsForContainer implements the exec driver Driver interface. 684 func (d *Driver) GetPidsForContainer(id string) ([]int, error) { 685 pids := []int{} 686 687 // cpu is chosen because it is the only non optional subsystem in cgroups 688 subsystem := "cpu" 689 cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem) 690 if err != nil { 691 return pids, err 692 } 693 694 filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks") 695 if _, err := os.Stat(filename); os.IsNotExist(err) { 696 // With more recent lxc versions use, cgroup will be in lxc/ 697 filename = filepath.Join(cgroupRoot, cgroupDir, "lxc", id, "tasks") 698 } 699 700 output, err := ioutil.ReadFile(filename) 701 if err != nil { 702 return pids, err 703 } 704 for _, p := range strings.Split(string(output), "\n") { 705 if len(p) == 0 { 706 continue 707 } 708 pid, err := strconv.Atoi(p) 709 if err != nil { 710 return pids, fmt.Errorf("Invalid pid '%s': %s", p, err) 711 } 712 pids = append(pids, pid) 713 } 714 return pids, nil 715 } 716 717 func linkLxcStart(root string) error { 718 sourcePath, err := exec.LookPath("lxc-start") 719 if err != nil { 720 return err 721 } 722 targetPath := path.Join(root, "lxc-start-unconfined") 723 724 if _, err := os.Lstat(targetPath); err != nil && !os.IsNotExist(err) { 725 return err 726 } else if err == nil { 727 if err := os.Remove(targetPath); err != nil { 728 return err 729 } 730 } 731 return os.Symlink(sourcePath, targetPath) 732 } 733 734 // TODO: This can be moved to the mountinfo reader in the mount pkg 735 func rootIsShared() bool { 736 if data, err := ioutil.ReadFile("/proc/self/mountinfo"); err == nil { 737 for _, line := range strings.Split(string(data), "\n") { 738 cols := strings.Split(line, " ") 739 if len(cols) >= 6 && cols[4] == "/" { 740 return strings.HasPrefix(cols[6], "shared") 741 } 742 } 743 } 744 745 // No idea, probably safe to assume so 746 return true 747 } 748 749 func (d *Driver) containerDir(containerID string) string { 750 return path.Join(d.libPath, "containers", containerID) 751 } 752 753 func (d *Driver) generateLXCConfig(c *execdriver.Command) (string, error) { 754 root := path.Join(d.containerDir(c.ID), "config.lxc") 755 756 fo, err := os.Create(root) 757 if err != nil { 758 return "", err 759 } 760 defer fo.Close() 761 762 if err := lxcTemplateCompiled.Execute(fo, struct { 763 *execdriver.Command 764 AppArmor bool 765 }{ 766 Command: c, 767 AppArmor: d.apparmor, 768 }); err != nil { 769 return "", err 770 } 771 772 return root, nil 773 } 774 775 func (d *Driver) generateEnvConfig(c *execdriver.Command) error { 776 data, err := json.Marshal(c.ProcessConfig.Env) 777 if err != nil { 778 return err 779 } 780 p := path.Join(d.libPath, "containers", c.ID, "config.env") 781 c.Mounts = append(c.Mounts, execdriver.Mount{ 782 Source: p, 783 Destination: "/.dockerenv", 784 Writable: false, 785 Private: true, 786 }) 787 788 return ioutil.WriteFile(p, data, 0600) 789 } 790 791 // Clean implements the exec driver Driver interface, 792 // it's not implemented by lxc. 793 func (d *Driver) Clean(id string) error { 794 return nil 795 } 796 797 // TtyConsole implements the exec driver Terminal interface, 798 // it stores the master and slave ends of the container's pty. 799 type TtyConsole struct { 800 MasterPty *os.File 801 SlavePty *os.File 802 } 803 804 // NewTtyConsole returns a new TtyConsole struct. 805 // Wired up to the provided process config and stdin/stdout/stderr pipes. 806 func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes) (*TtyConsole, error) { 807 // lxc is special in that we cannot create the master outside of the container without 808 // opening the slave because we have nothing to provide to the cmd. We have to open both then do 809 // the crazy setup on command right now instead of passing the console path to lxc and telling it 810 // to open up that console. we save a couple of openfiles in the native driver because we can do 811 // this. 812 ptyMaster, ptySlave, err := pty.Open() 813 if err != nil { 814 return nil, err 815 } 816 817 tty := &TtyConsole{ 818 MasterPty: ptyMaster, 819 SlavePty: ptySlave, 820 } 821 822 if err := tty.AttachPipes(&processConfig.Cmd, pipes); err != nil { 823 tty.Close() 824 return nil, err 825 } 826 827 processConfig.Console = tty.SlavePty.Name() 828 829 return tty, nil 830 } 831 832 // Resize implements Resize method of Terminal interface 833 func (t *TtyConsole) Resize(h, w int) error { 834 return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) 835 } 836 837 // AttachPipes attaches given pipes to exec.Cmd 838 func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error { 839 command.Stdout = t.SlavePty 840 command.Stderr = t.SlavePty 841 842 go func() { 843 if wb, ok := pipes.Stdout.(interface { 844 CloseWriters() error 845 }); ok { 846 defer wb.CloseWriters() 847 } 848 849 io.Copy(pipes.Stdout, t.MasterPty) 850 }() 851 852 if pipes.Stdin != nil { 853 command.Stdin = t.SlavePty 854 command.SysProcAttr.Setctty = true 855 856 go func() { 857 io.Copy(t.MasterPty, pipes.Stdin) 858 859 pipes.Stdin.Close() 860 }() 861 } 862 return nil 863 } 864 865 // Close implements Close method of Terminal interface 866 func (t *TtyConsole) Close() error { 867 t.SlavePty.Close() 868 return t.MasterPty.Close() 869 } 870 871 // Exec implements the exec driver Driver interface, 872 // it is not implemented by lxc. 873 func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { 874 return -1, ErrExec 875 } 876 877 // Stats implements the exec driver Driver interface. 878 // Lxc doesn't implement it's own Stats, it does some trick by implementing 879 // execdriver.Stats to get stats info by libcontainer APIs. 880 func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) { 881 if _, ok := d.activeContainers[id]; !ok { 882 return nil, fmt.Errorf("%s is not a key in active containers", id) 883 } 884 return execdriver.Stats(d.containerDir(id), d.activeContainers[id].container.Cgroups.Memory, d.machineMemory) 885 } 886 887 // SupportsHooks implements the execdriver Driver interface. 888 // The LXC execdriver does not support the hook mechanism, which is currently unique to runC/libcontainer. 889 func (d *Driver) SupportsHooks() bool { 890 return false 891 }