github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/container_operations_unix.go (about)

     1  // +build linux freebsd
     2  
     3  package daemon
     4  
     5  import (
     6  	"context"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"strconv"
    12  	"time"
    13  
    14  	"github.com/docker/docker/container"
    15  	"github.com/docker/docker/daemon/links"
    16  	"github.com/docker/docker/pkg/idtools"
    17  	"github.com/docker/docker/pkg/mount"
    18  	"github.com/docker/docker/pkg/stringid"
    19  	"github.com/docker/docker/runconfig"
    20  	"github.com/docker/libnetwork"
    21  	"github.com/opencontainers/selinux/go-selinux/label"
    22  	"github.com/pkg/errors"
    23  	"github.com/sirupsen/logrus"
    24  	"golang.org/x/sys/unix"
    25  )
    26  
    27  func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
    28  	var env []string
    29  	children := daemon.children(container)
    30  
    31  	bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
    32  	if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
    33  		return nil, nil
    34  	}
    35  
    36  	for linkAlias, child := range children {
    37  		if !child.IsRunning() {
    38  			return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
    39  		}
    40  
    41  		childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
    42  		if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
    43  			return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
    44  		}
    45  
    46  		link := links.NewLink(
    47  			bridgeSettings.IPAddress,
    48  			childBridgeSettings.IPAddress,
    49  			linkAlias,
    50  			child.Config.Env,
    51  			child.Config.ExposedPorts,
    52  		)
    53  
    54  		env = append(env, link.ToEnv()...)
    55  	}
    56  
    57  	return env, nil
    58  }
    59  
    60  func (daemon *Daemon) getIpcContainer(id string) (*container.Container, error) {
    61  	errMsg := "can't join IPC of container " + id
    62  	// Check the container exists
    63  	container, err := daemon.GetContainer(id)
    64  	if err != nil {
    65  		return nil, errors.Wrap(err, errMsg)
    66  	}
    67  	// Check the container is running and not restarting
    68  	if err := daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting); err != nil {
    69  		return nil, errors.Wrap(err, errMsg)
    70  	}
    71  	// Check the container ipc is shareable
    72  	if st, err := os.Stat(container.ShmPath); err != nil || !st.IsDir() {
    73  		if err == nil || os.IsNotExist(err) {
    74  			return nil, errors.New(errMsg + ": non-shareable IPC")
    75  		}
    76  		// stat() failed?
    77  		return nil, errors.Wrap(err, errMsg+": unexpected error from stat "+container.ShmPath)
    78  	}
    79  
    80  	return container, nil
    81  }
    82  
    83  func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
    84  	containerID := container.HostConfig.PidMode.Container()
    85  	container, err := daemon.GetContainer(containerID)
    86  	if err != nil {
    87  		return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", containerID)
    88  	}
    89  	return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
    90  }
    91  
    92  func containerIsRunning(c *container.Container) error {
    93  	if !c.IsRunning() {
    94  		return stateConflictError{errors.Errorf("container %s is not running", c.ID)}
    95  	}
    96  	return nil
    97  }
    98  
    99  func containerIsNotRestarting(c *container.Container) error {
   100  	if c.IsRestarting() {
   101  		return errContainerIsRestarting(c.ID)
   102  	}
   103  	return nil
   104  }
   105  
   106  func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
   107  	ipcMode := c.HostConfig.IpcMode
   108  
   109  	switch {
   110  	case ipcMode.IsContainer():
   111  		ic, err := daemon.getIpcContainer(ipcMode.Container())
   112  		if err != nil {
   113  			return err
   114  		}
   115  		c.ShmPath = ic.ShmPath
   116  
   117  	case ipcMode.IsHost():
   118  		if _, err := os.Stat("/dev/shm"); err != nil {
   119  			return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
   120  		}
   121  		c.ShmPath = "/dev/shm"
   122  
   123  	case ipcMode.IsPrivate(), ipcMode.IsNone():
   124  		// c.ShmPath will/should not be used, so make it empty.
   125  		// Container's /dev/shm mount comes from OCI spec.
   126  		c.ShmPath = ""
   127  
   128  	case ipcMode.IsEmpty():
   129  		// A container was created by an older version of the daemon.
   130  		// The default behavior used to be what is now called "shareable".
   131  		fallthrough
   132  
   133  	case ipcMode.IsShareable():
   134  		rootIDs := daemon.idMappings.RootPair()
   135  		if !c.HasMountFor("/dev/shm") {
   136  			shmPath, err := c.ShmResourcePath()
   137  			if err != nil {
   138  				return err
   139  			}
   140  
   141  			if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
   142  				return err
   143  			}
   144  
   145  			shmproperty := "mode=1777,size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10)
   146  			if err := unix.Mount("shm", shmPath, "tmpfs", uintptr(unix.MS_NOEXEC|unix.MS_NOSUID|unix.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
   147  				return fmt.Errorf("mounting shm tmpfs: %s", err)
   148  			}
   149  			if err := os.Chown(shmPath, rootIDs.UID, rootIDs.GID); err != nil {
   150  				return err
   151  			}
   152  			c.ShmPath = shmPath
   153  		}
   154  
   155  	default:
   156  		return fmt.Errorf("invalid IPC mode: %v", ipcMode)
   157  	}
   158  
   159  	return nil
   160  }
   161  
   162  func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
   163  	if len(c.SecretReferences) == 0 {
   164  		return nil
   165  	}
   166  
   167  	localMountPath := c.SecretMountPath()
   168  	logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
   169  
   170  	// retrieve possible remapped range start for root UID, GID
   171  	rootIDs := daemon.idMappings.RootPair()
   172  	// create tmpfs
   173  	if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil {
   174  		return errors.Wrap(err, "error creating secret local mount path")
   175  	}
   176  
   177  	defer func() {
   178  		if setupErr != nil {
   179  			// cleanup
   180  			_ = detachMounted(localMountPath)
   181  
   182  			if err := os.RemoveAll(localMountPath); err != nil {
   183  				logrus.Errorf("error cleaning up secret mount: %s", err)
   184  			}
   185  		}
   186  	}()
   187  
   188  	tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
   189  	if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
   190  		return errors.Wrap(err, "unable to setup secret mount")
   191  	}
   192  
   193  	if c.DependencyStore == nil {
   194  		return fmt.Errorf("secret store is not initialized")
   195  	}
   196  
   197  	for _, s := range c.SecretReferences {
   198  		// TODO (ehazlett): use type switch when more are supported
   199  		if s.File == nil {
   200  			logrus.Error("secret target type is not a file target")
   201  			continue
   202  		}
   203  
   204  		// secrets are created in the SecretMountPath on the host, at a
   205  		// single level
   206  		fPath := c.SecretFilePath(*s)
   207  		if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
   208  			return errors.Wrap(err, "error creating secret mount path")
   209  		}
   210  
   211  		logrus.WithFields(logrus.Fields{
   212  			"name": s.File.Name,
   213  			"path": fPath,
   214  		}).Debug("injecting secret")
   215  		secret, err := c.DependencyStore.Secrets().Get(s.SecretID)
   216  		if err != nil {
   217  			return errors.Wrap(err, "unable to get secret from secret store")
   218  		}
   219  		if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
   220  			return errors.Wrap(err, "error injecting secret")
   221  		}
   222  
   223  		uid, err := strconv.Atoi(s.File.UID)
   224  		if err != nil {
   225  			return err
   226  		}
   227  		gid, err := strconv.Atoi(s.File.GID)
   228  		if err != nil {
   229  			return err
   230  		}
   231  
   232  		if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
   233  			return errors.Wrap(err, "error setting ownership for secret")
   234  		}
   235  	}
   236  
   237  	label.Relabel(localMountPath, c.MountLabel, false)
   238  
   239  	// remount secrets ro
   240  	if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
   241  		return errors.Wrap(err, "unable to remount secret dir as readonly")
   242  	}
   243  
   244  	return nil
   245  }
   246  
   247  func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
   248  	if len(c.ConfigReferences) == 0 {
   249  		return nil
   250  	}
   251  
   252  	localPath := c.ConfigsDirPath()
   253  	logrus.Debugf("configs: setting up config dir: %s", localPath)
   254  
   255  	// retrieve possible remapped range start for root UID, GID
   256  	rootIDs := daemon.idMappings.RootPair()
   257  	// create tmpfs
   258  	if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil {
   259  		return errors.Wrap(err, "error creating config dir")
   260  	}
   261  
   262  	defer func() {
   263  		if setupErr != nil {
   264  			if err := os.RemoveAll(localPath); err != nil {
   265  				logrus.Errorf("error cleaning up config dir: %s", err)
   266  			}
   267  		}
   268  	}()
   269  
   270  	if c.DependencyStore == nil {
   271  		return fmt.Errorf("config store is not initialized")
   272  	}
   273  
   274  	for _, configRef := range c.ConfigReferences {
   275  		// TODO (ehazlett): use type switch when more are supported
   276  		if configRef.File == nil {
   277  			logrus.Error("config target type is not a file target")
   278  			continue
   279  		}
   280  
   281  		fPath := c.ConfigFilePath(*configRef)
   282  
   283  		log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
   284  
   285  		if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
   286  			return errors.Wrap(err, "error creating config path")
   287  		}
   288  
   289  		log.Debug("injecting config")
   290  		config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
   291  		if err != nil {
   292  			return errors.Wrap(err, "unable to get config from config store")
   293  		}
   294  		if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
   295  			return errors.Wrap(err, "error injecting config")
   296  		}
   297  
   298  		uid, err := strconv.Atoi(configRef.File.UID)
   299  		if err != nil {
   300  			return err
   301  		}
   302  		gid, err := strconv.Atoi(configRef.File.GID)
   303  		if err != nil {
   304  			return err
   305  		}
   306  
   307  		if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
   308  			return errors.Wrap(err, "error setting ownership for config")
   309  		}
   310  
   311  		label.Relabel(fPath, c.MountLabel, false)
   312  	}
   313  
   314  	return nil
   315  }
   316  
   317  func killProcessDirectly(cntr *container.Container) error {
   318  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   319  	defer cancel()
   320  
   321  	// Block until the container to stops or timeout.
   322  	status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
   323  	if status.Err() != nil {
   324  		// Ensure that we don't kill ourselves
   325  		if pid := cntr.GetPID(); pid != 0 {
   326  			logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
   327  			if err := unix.Kill(pid, 9); err != nil {
   328  				if err != unix.ESRCH {
   329  					return err
   330  				}
   331  				e := errNoSuchProcess{pid, 9}
   332  				logrus.Debug(e)
   333  				return e
   334  			}
   335  		}
   336  	}
   337  	return nil
   338  }
   339  
   340  func detachMounted(path string) error {
   341  	return unix.Unmount(path, unix.MNT_DETACH)
   342  }
   343  
   344  func isLinkable(child *container.Container) bool {
   345  	// A container is linkable only if it belongs to the default network
   346  	_, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
   347  	return ok
   348  }
   349  
   350  func enableIPOnPredefinedNetwork() bool {
   351  	return false
   352  }
   353  
   354  func (daemon *Daemon) isNetworkHotPluggable() bool {
   355  	return true
   356  }
   357  
   358  func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
   359  	var err error
   360  
   361  	container.HostsPath, err = container.GetRootResourcePath("hosts")
   362  	if err != nil {
   363  		return err
   364  	}
   365  	*sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
   366  
   367  	container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
   368  	if err != nil {
   369  		return err
   370  	}
   371  	*sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
   372  	return nil
   373  }
   374  
   375  func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
   376  	container.HostnamePath = nc.HostnamePath
   377  	container.HostsPath = nc.HostsPath
   378  	container.ResolvConfPath = nc.ResolvConfPath
   379  	return nil
   380  }