github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/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  	"syscall"
    13  	"time"
    14  
    15  	"github.com/Sirupsen/logrus"
    16  	"github.com/docker/docker/container"
    17  	"github.com/docker/docker/daemon/links"
    18  	"github.com/docker/docker/pkg/idtools"
    19  	"github.com/docker/docker/pkg/mount"
    20  	"github.com/docker/docker/pkg/stringid"
    21  	"github.com/docker/docker/runconfig"
    22  	"github.com/docker/libnetwork"
    23  	"github.com/opencontainers/selinux/go-selinux/label"
    24  	"github.com/pkg/errors"
    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(container *container.Container) (*container.Container, error) {
    61  	containerID := container.HostConfig.IpcMode.Container()
    62  	container, err := daemon.GetContainer(containerID)
    63  	if err != nil {
    64  		return nil, errors.Wrapf(err, "cannot join IPC of a non running container: %s", container.ID)
    65  	}
    66  	return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
    67  }
    68  
    69  func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
    70  	containerID := container.HostConfig.PidMode.Container()
    71  	container, err := daemon.GetContainer(containerID)
    72  	if err != nil {
    73  		return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", container.ID)
    74  	}
    75  	return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
    76  }
    77  
    78  func containerIsRunning(c *container.Container) error {
    79  	if !c.IsRunning() {
    80  		return errors.Errorf("container %s is not running", c.ID)
    81  	}
    82  	return nil
    83  }
    84  
    85  func containerIsNotRestarting(c *container.Container) error {
    86  	if c.IsRestarting() {
    87  		return errContainerIsRestarting(c.ID)
    88  	}
    89  	return nil
    90  }
    91  
    92  func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
    93  	var err error
    94  
    95  	c.ShmPath, err = c.ShmResourcePath()
    96  	if err != nil {
    97  		return err
    98  	}
    99  
   100  	if c.HostConfig.IpcMode.IsContainer() {
   101  		ic, err := daemon.getIpcContainer(c)
   102  		if err != nil {
   103  			return err
   104  		}
   105  		c.ShmPath = ic.ShmPath
   106  	} else if c.HostConfig.IpcMode.IsHost() {
   107  		if _, err := os.Stat("/dev/shm"); err != nil {
   108  			return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
   109  		}
   110  		c.ShmPath = "/dev/shm"
   111  	} else {
   112  		rootIDs := daemon.idMappings.RootPair()
   113  		if !c.HasMountFor("/dev/shm") {
   114  			shmPath, err := c.ShmResourcePath()
   115  			if err != nil {
   116  				return err
   117  			}
   118  
   119  			if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
   120  				return err
   121  			}
   122  
   123  			shmSize := int64(daemon.configStore.ShmSize)
   124  			if c.HostConfig.ShmSize != 0 {
   125  				shmSize = c.HostConfig.ShmSize
   126  			}
   127  			shmproperty := "mode=1777,size=" + strconv.FormatInt(shmSize, 10)
   128  			if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
   129  				return fmt.Errorf("mounting shm tmpfs: %s", err)
   130  			}
   131  			if err := os.Chown(shmPath, rootIDs.UID, rootIDs.GID); err != nil {
   132  				return err
   133  			}
   134  		}
   135  
   136  	}
   137  
   138  	return nil
   139  }
   140  
   141  func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
   142  	if len(c.SecretReferences) == 0 {
   143  		return nil
   144  	}
   145  
   146  	localMountPath := c.SecretMountPath()
   147  	logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
   148  
   149  	// retrieve possible remapped range start for root UID, GID
   150  	rootIDs := daemon.idMappings.RootPair()
   151  	// create tmpfs
   152  	if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil {
   153  		return errors.Wrap(err, "error creating secret local mount path")
   154  	}
   155  
   156  	defer func() {
   157  		if setupErr != nil {
   158  			// cleanup
   159  			_ = detachMounted(localMountPath)
   160  
   161  			if err := os.RemoveAll(localMountPath); err != nil {
   162  				logrus.Errorf("error cleaning up secret mount: %s", err)
   163  			}
   164  		}
   165  	}()
   166  
   167  	tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
   168  	if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
   169  		return errors.Wrap(err, "unable to setup secret mount")
   170  	}
   171  
   172  	if c.DependencyStore == nil {
   173  		return fmt.Errorf("secret store is not initialized")
   174  	}
   175  
   176  	for _, s := range c.SecretReferences {
   177  		// TODO (ehazlett): use type switch when more are supported
   178  		if s.File == nil {
   179  			logrus.Error("secret target type is not a file target")
   180  			continue
   181  		}
   182  
   183  		// secrets are created in the SecretMountPath on the host, at a
   184  		// single level
   185  		fPath := c.SecretFilePath(*s)
   186  		if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
   187  			return errors.Wrap(err, "error creating secret mount path")
   188  		}
   189  
   190  		logrus.WithFields(logrus.Fields{
   191  			"name": s.File.Name,
   192  			"path": fPath,
   193  		}).Debug("injecting secret")
   194  		secret := c.DependencyStore.Secrets().Get(s.SecretID)
   195  		if secret == nil {
   196  			return fmt.Errorf("unable to get secret from secret store")
   197  		}
   198  		if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
   199  			return errors.Wrap(err, "error injecting secret")
   200  		}
   201  
   202  		uid, err := strconv.Atoi(s.File.UID)
   203  		if err != nil {
   204  			return err
   205  		}
   206  		gid, err := strconv.Atoi(s.File.GID)
   207  		if err != nil {
   208  			return err
   209  		}
   210  
   211  		if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
   212  			return errors.Wrap(err, "error setting ownership for secret")
   213  		}
   214  	}
   215  
   216  	label.Relabel(localMountPath, c.MountLabel, false)
   217  
   218  	// remount secrets ro
   219  	if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
   220  		return errors.Wrap(err, "unable to remount secret dir as readonly")
   221  	}
   222  
   223  	return nil
   224  }
   225  
   226  func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
   227  	if len(c.ConfigReferences) == 0 {
   228  		return nil
   229  	}
   230  
   231  	localPath := c.ConfigsDirPath()
   232  	logrus.Debugf("configs: setting up config dir: %s", localPath)
   233  
   234  	// retrieve possible remapped range start for root UID, GID
   235  	rootIDs := daemon.idMappings.RootPair()
   236  	// create tmpfs
   237  	if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil {
   238  		return errors.Wrap(err, "error creating config dir")
   239  	}
   240  
   241  	defer func() {
   242  		if setupErr != nil {
   243  			if err := os.RemoveAll(localPath); err != nil {
   244  				logrus.Errorf("error cleaning up config dir: %s", err)
   245  			}
   246  		}
   247  	}()
   248  
   249  	if c.DependencyStore == nil {
   250  		return fmt.Errorf("config store is not initialized")
   251  	}
   252  
   253  	for _, configRef := range c.ConfigReferences {
   254  		// TODO (ehazlett): use type switch when more are supported
   255  		if configRef.File == nil {
   256  			logrus.Error("config target type is not a file target")
   257  			continue
   258  		}
   259  
   260  		fPath := c.ConfigFilePath(*configRef)
   261  
   262  		log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
   263  
   264  		if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
   265  			return errors.Wrap(err, "error creating config path")
   266  		}
   267  
   268  		log.Debug("injecting config")
   269  		config := c.DependencyStore.Configs().Get(configRef.ConfigID)
   270  		if config == nil {
   271  			return fmt.Errorf("unable to get config from config store")
   272  		}
   273  		if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
   274  			return errors.Wrap(err, "error injecting config")
   275  		}
   276  
   277  		uid, err := strconv.Atoi(configRef.File.UID)
   278  		if err != nil {
   279  			return err
   280  		}
   281  		gid, err := strconv.Atoi(configRef.File.GID)
   282  		if err != nil {
   283  			return err
   284  		}
   285  
   286  		if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
   287  			return errors.Wrap(err, "error setting ownership for config")
   288  		}
   289  	}
   290  
   291  	return nil
   292  }
   293  
   294  func killProcessDirectly(cntr *container.Container) error {
   295  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   296  	defer cancel()
   297  
   298  	// Block until the container to stops or timeout.
   299  	status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
   300  	if status.Err() != nil {
   301  		// Ensure that we don't kill ourselves
   302  		if pid := cntr.GetPID(); pid != 0 {
   303  			logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
   304  			if err := syscall.Kill(pid, 9); err != nil {
   305  				if err != syscall.ESRCH {
   306  					return err
   307  				}
   308  				e := errNoSuchProcess{pid, 9}
   309  				logrus.Debug(e)
   310  				return e
   311  			}
   312  		}
   313  	}
   314  	return nil
   315  }
   316  
   317  func detachMounted(path string) error {
   318  	return syscall.Unmount(path, syscall.MNT_DETACH)
   319  }
   320  
   321  func isLinkable(child *container.Container) bool {
   322  	// A container is linkable only if it belongs to the default network
   323  	_, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
   324  	return ok
   325  }
   326  
   327  func enableIPOnPredefinedNetwork() bool {
   328  	return false
   329  }
   330  
   331  func (daemon *Daemon) isNetworkHotPluggable() bool {
   332  	return true
   333  }
   334  
   335  func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
   336  	var err error
   337  
   338  	container.HostsPath, err = container.GetRootResourcePath("hosts")
   339  	if err != nil {
   340  		return err
   341  	}
   342  	*sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
   343  
   344  	container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
   345  	if err != nil {
   346  		return err
   347  	}
   348  	*sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
   349  	return nil
   350  }
   351  
   352  func initializeNetworkingPaths(container *container.Container, nc *container.Container) {
   353  	container.HostnamePath = nc.HostnamePath
   354  	container.HostsPath = nc.HostsPath
   355  	container.ResolvConfPath = nc.ResolvConfPath
   356  }