github.com/gondor/docker@v1.9.0-rc1/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  	oomKill := false
   328  	oomKillNotification, err := notifyOnOOM(cgroupPaths)
   329  
   330  	if hooks.Start != nil {
   331  		logrus.Debugf("Invoking startCallback")
   332  		hooks.Start(&c.ProcessConfig, pid, oomKillNotification)
   333  
   334  	}
   335  
   336  	<-waitLock
   337  	exitCode := getExitCode(c)
   338  
   339  	if err == nil {
   340  		_, oomKill = <-oomKillNotification
   341  		logrus.Debugf("oomKill error: %v, waitErr: %v", oomKill, waitErr)
   342  	} else {
   343  		logrus.Warnf("Your kernel does not support OOM notifications: %s", err)
   344  	}
   345  
   346  	// check oom error
   347  	if oomKill {
   348  		exitCode = 137
   349  	}
   350  
   351  	return execdriver.ExitStatus{ExitCode: exitCode, OOMKilled: oomKill}, waitErr
   352  }
   353  
   354  // copy from libcontainer
   355  func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) {
   356  	dir := paths["memory"]
   357  	if dir == "" {
   358  		return nil, fmt.Errorf("There is no path for %q in state", "memory")
   359  	}
   360  	oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control"))
   361  	if err != nil {
   362  		return nil, err
   363  	}
   364  	fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0)
   365  	if syserr != 0 {
   366  		oomControl.Close()
   367  		return nil, syserr
   368  	}
   369  
   370  	eventfd := os.NewFile(fd, "eventfd")
   371  
   372  	eventControlPath := filepath.Join(dir, "cgroup.event_control")
   373  	data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd())
   374  	if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil {
   375  		eventfd.Close()
   376  		oomControl.Close()
   377  		return nil, err
   378  	}
   379  	ch := make(chan struct{})
   380  	go func() {
   381  		defer func() {
   382  			close(ch)
   383  			eventfd.Close()
   384  			oomControl.Close()
   385  		}()
   386  		buf := make([]byte, 8)
   387  		for {
   388  			if _, err := eventfd.Read(buf); err != nil {
   389  				return
   390  			}
   391  			// When a cgroup is destroyed, an event is sent to eventfd.
   392  			// So if the control path is gone, return instead of notifying.
   393  			if _, err := os.Lstat(eventControlPath); os.IsNotExist(err) {
   394  				return
   395  			}
   396  			ch <- struct{}{}
   397  		}
   398  	}()
   399  	return ch, nil
   400  }
   401  
   402  // createContainer populates and configures the container type with the
   403  // data provided by the execdriver.Command
   404  func (d *Driver) createContainer(c *execdriver.Command) (*configs.Config, error) {
   405  	container := execdriver.InitContainer(c)
   406  	if err := execdriver.SetupCgroups(container, c); err != nil {
   407  		return nil, err
   408  	}
   409  	return container, nil
   410  }
   411  
   412  // Return an map of susbystem -> absolute container cgroup path
   413  func cgroupPaths(containerID string) (map[string]string, error) {
   414  	subsystems, err := cgroups.GetAllSubsystems()
   415  	if err != nil {
   416  		return nil, err
   417  	}
   418  	logrus.Debugf("subsystems: %s", subsystems)
   419  	paths := make(map[string]string)
   420  	for _, subsystem := range subsystems {
   421  		cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem)
   422  		logrus.Debugf("cgroup path %s %s", cgroupRoot, cgroupDir)
   423  		if err != nil {
   424  			//unsupported subystem
   425  			continue
   426  		}
   427  		path := filepath.Join(cgroupRoot, cgroupDir, "lxc", containerID)
   428  		paths[subsystem] = path
   429  	}
   430  
   431  	return paths, nil
   432  }
   433  
   434  // this is copy from old libcontainer nodes.go
   435  func createDeviceNodes(rootfs string, nodesToCreate []*configs.Device) error {
   436  	oldMask := syscall.Umask(0000)
   437  	defer syscall.Umask(oldMask)
   438  
   439  	for _, node := range nodesToCreate {
   440  		if err := createDeviceNode(rootfs, node); err != nil {
   441  			return err
   442  		}
   443  	}
   444  	return nil
   445  }
   446  
   447  // Creates the device node in the rootfs of the container.
   448  func createDeviceNode(rootfs string, node *configs.Device) error {
   449  	var (
   450  		dest   = filepath.Join(rootfs, node.Path)
   451  		parent = filepath.Dir(dest)
   452  	)
   453  
   454  	if err := os.MkdirAll(parent, 0755); err != nil {
   455  		return err
   456  	}
   457  
   458  	fileMode := node.FileMode
   459  	switch node.Type {
   460  	case 'c':
   461  		fileMode |= syscall.S_IFCHR
   462  	case 'b':
   463  		fileMode |= syscall.S_IFBLK
   464  	default:
   465  		return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path)
   466  	}
   467  
   468  	if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil && !os.IsExist(err) {
   469  		return fmt.Errorf("mknod %s %s", node.Path, err)
   470  	}
   471  
   472  	if err := syscall.Chown(dest, int(node.Uid), int(node.Gid)); err != nil {
   473  		return fmt.Errorf("chown %s to %d:%d", node.Path, node.Uid, node.Gid)
   474  	}
   475  
   476  	return nil
   477  }
   478  
   479  // setupUser changes the groups, gid, and uid for the user inside the container
   480  // copy from libcontainer, cause not it's private
   481  func setupUser(userSpec string) error {
   482  	// Set up defaults.
   483  	defaultExecUser := user.ExecUser{
   484  		Uid:  syscall.Getuid(),
   485  		Gid:  syscall.Getgid(),
   486  		Home: "/",
   487  	}
   488  	passwdPath, err := user.GetPasswdPath()
   489  	if err != nil {
   490  		return err
   491  	}
   492  	groupPath, err := user.GetGroupPath()
   493  	if err != nil {
   494  		return err
   495  	}
   496  	execUser, err := user.GetExecUserPath(userSpec, &defaultExecUser, passwdPath, groupPath)
   497  	if err != nil {
   498  		return err
   499  	}
   500  	if err := syscall.Setgroups(execUser.Sgids); err != nil {
   501  		return err
   502  	}
   503  	if err := system.Setgid(execUser.Gid); err != nil {
   504  		return err
   505  	}
   506  	if err := system.Setuid(execUser.Uid); err != nil {
   507  		return err
   508  	}
   509  	// if we didn't get HOME already, set it based on the user's HOME
   510  	if envHome := os.Getenv("HOME"); envHome == "" {
   511  		if err := os.Setenv("HOME", execUser.Home); err != nil {
   512  			return err
   513  		}
   514  	}
   515  	return nil
   516  }
   517  
   518  // getExitCode returns the exit code of the process.
   519  // If the process has not exited -1 will be returned.
   520  func getExitCode(c *execdriver.Command) int {
   521  	if c.ProcessConfig.ProcessState == nil {
   522  		return -1
   523  	}
   524  	return c.ProcessConfig.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
   525  }
   526  
   527  // Kill implements the exec driver Driver interface.
   528  func (d *Driver) Kill(c *execdriver.Command, sig int) error {
   529  	if sig == 9 || c.ProcessConfig.Process == nil {
   530  		return killLxc(c.ID, sig)
   531  	}
   532  
   533  	return c.ProcessConfig.Process.Signal(syscall.Signal(sig))
   534  }
   535  
   536  // Pause implements the exec driver Driver interface,
   537  // it executes lxc-freeze to pause a container.
   538  func (d *Driver) Pause(c *execdriver.Command) error {
   539  	_, err := exec.LookPath("lxc-freeze")
   540  	if err == nil {
   541  		output, errExec := exec.Command("lxc-freeze", "-n", c.ID).CombinedOutput()
   542  		if errExec != nil {
   543  			return fmt.Errorf("Err: %s Output: %s", errExec, output)
   544  		}
   545  	}
   546  
   547  	return err
   548  }
   549  
   550  // Unpause implements the exec driver Driver interface,
   551  // it executes lxc-unfreeze to unpause a container.
   552  func (d *Driver) Unpause(c *execdriver.Command) error {
   553  	_, err := exec.LookPath("lxc-unfreeze")
   554  	if err == nil {
   555  		output, errExec := exec.Command("lxc-unfreeze", "-n", c.ID).CombinedOutput()
   556  		if errExec != nil {
   557  			return fmt.Errorf("Err: %s Output: %s", errExec, output)
   558  		}
   559  	}
   560  
   561  	return err
   562  }
   563  
   564  // Terminate implements the exec driver Driver interface.
   565  func (d *Driver) Terminate(c *execdriver.Command) error {
   566  	return killLxc(c.ID, 9)
   567  }
   568  
   569  func (d *Driver) version() string {
   570  	var (
   571  		version string
   572  		output  []byte
   573  		err     error
   574  	)
   575  	if _, errPath := exec.LookPath("lxc-version"); errPath == nil {
   576  		output, err = exec.Command("lxc-version").CombinedOutput()
   577  	} else {
   578  		output, err = exec.Command("lxc-start", "--version").CombinedOutput()
   579  	}
   580  	if err == nil {
   581  		version = strings.TrimSpace(string(output))
   582  		if parts := strings.SplitN(version, ":", 2); len(parts) == 2 {
   583  			version = strings.TrimSpace(parts[1])
   584  		}
   585  	}
   586  	return version
   587  }
   588  
   589  func killLxc(id string, sig int) error {
   590  	var (
   591  		err    error
   592  		output []byte
   593  	)
   594  	_, err = exec.LookPath("lxc-kill")
   595  	if err == nil {
   596  		output, err = exec.Command("lxc-kill", "-n", id, strconv.Itoa(sig)).CombinedOutput()
   597  	} else {
   598  		// lxc-stop does not take arbitrary signals like lxc-kill does
   599  		output, err = exec.Command("lxc-stop", "-k", "-n", id).CombinedOutput()
   600  	}
   601  	if err != nil {
   602  		return fmt.Errorf("Err: %s Output: %s", err, output)
   603  	}
   604  	return nil
   605  }
   606  
   607  // wait for the process to start and return the pid for the process
   608  func (d *Driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (int, error) {
   609  	var (
   610  		err    error
   611  		output []byte
   612  	)
   613  	// We wait for the container to be fully running.
   614  	// Timeout after 5 seconds. In case of broken pipe, just retry.
   615  	// Note: The container can run and finish correctly before
   616  	// the end of this loop
   617  	for now := time.Now(); time.Since(now) < 5*time.Second; {
   618  		select {
   619  		case <-waitLock:
   620  			// If the process dies while waiting for it, just return
   621  			return -1, nil
   622  		default:
   623  		}
   624  
   625  		output, err = d.getInfo(c.ID)
   626  		if err == nil {
   627  			info, err := parseLxcInfo(string(output))
   628  			if err != nil {
   629  				return -1, err
   630  			}
   631  			if info.Running {
   632  				return info.Pid, nil
   633  			}
   634  		}
   635  		time.Sleep(50 * time.Millisecond)
   636  	}
   637  	return -1, execdriver.ErrNotRunning
   638  }
   639  
   640  func (d *Driver) getInfo(id string) ([]byte, error) {
   641  	return exec.Command("lxc-info", "-n", id).CombinedOutput()
   642  }
   643  
   644  type info struct {
   645  	ID     string
   646  	driver *Driver
   647  }
   648  
   649  func (i *info) IsRunning() bool {
   650  	var running bool
   651  
   652  	output, err := i.driver.getInfo(i.ID)
   653  	if err != nil {
   654  		logrus.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output)
   655  		return false
   656  	}
   657  	if strings.Contains(string(output), "RUNNING") {
   658  		running = true
   659  	}
   660  	return running
   661  }
   662  
   663  // Info implements the exec driver Driver interface.
   664  func (d *Driver) Info(id string) execdriver.Info {
   665  	return &info{
   666  		ID:     id,
   667  		driver: d,
   668  	}
   669  }
   670  
   671  func findCgroupRootAndDir(subsystem string) (string, string, error) {
   672  	cgroupRoot, err := cgroups.FindCgroupMountpoint(subsystem)
   673  	if err != nil {
   674  		return "", "", err
   675  	}
   676  
   677  	cgroupDir, err := cgroups.GetThisCgroupDir(subsystem)
   678  	if err != nil {
   679  		return "", "", err
   680  	}
   681  	return cgroupRoot, cgroupDir, nil
   682  }
   683  
   684  // GetPidsForContainer implements the exec driver Driver interface.
   685  func (d *Driver) GetPidsForContainer(id string) ([]int, error) {
   686  	pids := []int{}
   687  
   688  	// cpu is chosen because it is the only non optional subsystem in cgroups
   689  	subsystem := "cpu"
   690  	cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem)
   691  	if err != nil {
   692  		return pids, err
   693  	}
   694  
   695  	filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks")
   696  	if _, err := os.Stat(filename); os.IsNotExist(err) {
   697  		// With more recent lxc versions use, cgroup will be in lxc/
   698  		filename = filepath.Join(cgroupRoot, cgroupDir, "lxc", id, "tasks")
   699  	}
   700  
   701  	output, err := ioutil.ReadFile(filename)
   702  	if err != nil {
   703  		return pids, err
   704  	}
   705  	for _, p := range strings.Split(string(output), "\n") {
   706  		if len(p) == 0 {
   707  			continue
   708  		}
   709  		pid, err := strconv.Atoi(p)
   710  		if err != nil {
   711  			return pids, fmt.Errorf("Invalid pid '%s': %s", p, err)
   712  		}
   713  		pids = append(pids, pid)
   714  	}
   715  	return pids, nil
   716  }
   717  
   718  func linkLxcStart(root string) error {
   719  	sourcePath, err := exec.LookPath("lxc-start")
   720  	if err != nil {
   721  		return err
   722  	}
   723  	targetPath := path.Join(root, "lxc-start-unconfined")
   724  
   725  	if _, err := os.Lstat(targetPath); err != nil && !os.IsNotExist(err) {
   726  		return err
   727  	} else if err == nil {
   728  		if err := os.Remove(targetPath); err != nil {
   729  			return err
   730  		}
   731  	}
   732  	return os.Symlink(sourcePath, targetPath)
   733  }
   734  
   735  // TODO: This can be moved to the mountinfo reader in the mount pkg
   736  func rootIsShared() bool {
   737  	if data, err := ioutil.ReadFile("/proc/self/mountinfo"); err == nil {
   738  		for _, line := range strings.Split(string(data), "\n") {
   739  			cols := strings.Split(line, " ")
   740  			if len(cols) >= 6 && cols[4] == "/" {
   741  				return strings.HasPrefix(cols[6], "shared")
   742  			}
   743  		}
   744  	}
   745  
   746  	// No idea, probably safe to assume so
   747  	return true
   748  }
   749  
   750  func (d *Driver) containerDir(containerID string) string {
   751  	return path.Join(d.libPath, "containers", containerID)
   752  }
   753  
   754  func (d *Driver) generateLXCConfig(c *execdriver.Command) (string, error) {
   755  	root := path.Join(d.containerDir(c.ID), "config.lxc")
   756  
   757  	fo, err := os.Create(root)
   758  	if err != nil {
   759  		return "", err
   760  	}
   761  	defer fo.Close()
   762  
   763  	if err := lxcTemplateCompiled.Execute(fo, struct {
   764  		*execdriver.Command
   765  		AppArmor bool
   766  	}{
   767  		Command:  c,
   768  		AppArmor: d.apparmor,
   769  	}); err != nil {
   770  		return "", err
   771  	}
   772  
   773  	return root, nil
   774  }
   775  
   776  func (d *Driver) generateEnvConfig(c *execdriver.Command) error {
   777  	data, err := json.Marshal(c.ProcessConfig.Env)
   778  	if err != nil {
   779  		return err
   780  	}
   781  	p := path.Join(d.libPath, "containers", c.ID, "config.env")
   782  	c.Mounts = append(c.Mounts, execdriver.Mount{
   783  		Source:      p,
   784  		Destination: "/.dockerenv",
   785  		Writable:    false,
   786  		Private:     true,
   787  	})
   788  
   789  	return ioutil.WriteFile(p, data, 0600)
   790  }
   791  
   792  // Clean implements the exec driver Driver interface,
   793  // it's not implemented by lxc.
   794  func (d *Driver) Clean(id string) error {
   795  	return nil
   796  }
   797  
   798  // TtyConsole implements the exec driver Terminal interface,
   799  // it stores the master and slave ends of the container's pty.
   800  type TtyConsole struct {
   801  	MasterPty *os.File
   802  	SlavePty  *os.File
   803  }
   804  
   805  // NewTtyConsole returns a new TtyConsole struct.
   806  // Wired up to the provided process config and stdin/stdout/stderr pipes.
   807  func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes) (*TtyConsole, error) {
   808  	// lxc is special in that we cannot create the master outside of the container without
   809  	// opening the slave because we have nothing to provide to the cmd.  We have to open both then do
   810  	// the crazy setup on command right now instead of passing the console path to lxc and telling it
   811  	// to open up that console.  we save a couple of openfiles in the native driver because we can do
   812  	// this.
   813  	ptyMaster, ptySlave, err := pty.Open()
   814  	if err != nil {
   815  		return nil, err
   816  	}
   817  
   818  	tty := &TtyConsole{
   819  		MasterPty: ptyMaster,
   820  		SlavePty:  ptySlave,
   821  	}
   822  
   823  	if err := tty.AttachPipes(&processConfig.Cmd, pipes); err != nil {
   824  		tty.Close()
   825  		return nil, err
   826  	}
   827  
   828  	processConfig.Console = tty.SlavePty.Name()
   829  
   830  	return tty, nil
   831  }
   832  
   833  // Resize implements Resize method of Terminal interface
   834  func (t *TtyConsole) Resize(h, w int) error {
   835  	return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
   836  }
   837  
   838  // AttachPipes attaches given pipes to exec.Cmd
   839  func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error {
   840  	command.Stdout = t.SlavePty
   841  	command.Stderr = t.SlavePty
   842  
   843  	go func() {
   844  		if wb, ok := pipes.Stdout.(interface {
   845  			CloseWriters() error
   846  		}); ok {
   847  			defer wb.CloseWriters()
   848  		}
   849  
   850  		io.Copy(pipes.Stdout, t.MasterPty)
   851  	}()
   852  
   853  	if pipes.Stdin != nil {
   854  		command.Stdin = t.SlavePty
   855  		command.SysProcAttr.Setctty = true
   856  
   857  		go func() {
   858  			io.Copy(t.MasterPty, pipes.Stdin)
   859  
   860  			pipes.Stdin.Close()
   861  		}()
   862  	}
   863  	return nil
   864  }
   865  
   866  // Close implements Close method of Terminal interface
   867  func (t *TtyConsole) Close() error {
   868  	t.SlavePty.Close()
   869  	return t.MasterPty.Close()
   870  }
   871  
   872  // Exec implements the exec driver Driver interface,
   873  // it is not implemented by lxc.
   874  func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) {
   875  	return -1, ErrExec
   876  }
   877  
   878  // Stats implements the exec driver Driver interface.
   879  // Lxc doesn't implement it's own Stats, it does some trick by implementing
   880  // execdriver.Stats to get stats info by libcontainer APIs.
   881  func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) {
   882  	if _, ok := d.activeContainers[id]; !ok {
   883  		return nil, fmt.Errorf("%s is not a key in active containers", id)
   884  	}
   885  	return execdriver.Stats(d.containerDir(id), d.activeContainers[id].container.Cgroups.Memory, d.machineMemory)
   886  }
   887  
   888  // SupportsHooks implements the execdriver Driver interface.
   889  // The LXC execdriver does not support the hook mechanism, which is currently unique to runC/libcontainer.
   890  func (d *Driver) SupportsHooks() bool {
   891  	return false
   892  }