github.com/brahmaroutu/docker@v1.2.1-0.20160809185609-eb28dde01f16/daemon/start.go (about)

     1  package daemon
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"runtime"
     7  	"strings"
     8  	"syscall"
     9  
    10  	"google.golang.org/grpc"
    11  
    12  	"github.com/Sirupsen/logrus"
    13  	"github.com/docker/docker/container"
    14  	"github.com/docker/docker/errors"
    15  	"github.com/docker/docker/libcontainerd"
    16  	"github.com/docker/docker/runconfig"
    17  	"github.com/docker/engine-api/types"
    18  	containertypes "github.com/docker/engine-api/types/container"
    19  )
    20  
    21  // ContainerStart starts a container.
    22  func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, validateHostname bool) error {
    23  	container, err := daemon.GetContainer(name)
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	if container.IsPaused() {
    29  		return fmt.Errorf("Cannot start a paused container, try unpause instead.")
    30  	}
    31  
    32  	if container.IsRunning() {
    33  		err := fmt.Errorf("Container already started")
    34  		return errors.NewErrorWithStatusCode(err, http.StatusNotModified)
    35  	}
    36  
    37  	// Windows does not have the backwards compatibility issue here.
    38  	if runtime.GOOS != "windows" {
    39  		// This is kept for backward compatibility - hostconfig should be passed when
    40  		// creating a container, not during start.
    41  		if hostConfig != nil {
    42  			logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and will be removed in Docker 1.12")
    43  			oldNetworkMode := container.HostConfig.NetworkMode
    44  			if err := daemon.setSecurityOptions(container, hostConfig); err != nil {
    45  				return err
    46  			}
    47  			if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil {
    48  				return err
    49  			}
    50  			if err := daemon.setHostConfig(container, hostConfig); err != nil {
    51  				return err
    52  			}
    53  			newNetworkMode := container.HostConfig.NetworkMode
    54  			if string(oldNetworkMode) != string(newNetworkMode) {
    55  				// if user has change the network mode on starting, clean up the
    56  				// old networks. It is a deprecated feature and will be removed in Docker 1.12
    57  				container.NetworkSettings.Networks = nil
    58  				if err := container.ToDisk(); err != nil {
    59  					return err
    60  				}
    61  			}
    62  			container.InitDNSHostConfig()
    63  		}
    64  	} else {
    65  		if hostConfig != nil {
    66  			return fmt.Errorf("Supplying a hostconfig on start is not supported. It should be supplied on create")
    67  		}
    68  	}
    69  
    70  	// check if hostConfig is in line with the current system settings.
    71  	// It may happen cgroups are umounted or the like.
    72  	if _, err = daemon.verifyContainerSettings(container.HostConfig, nil, false, validateHostname); err != nil {
    73  		return err
    74  	}
    75  	// Adapt for old containers in case we have updates in this function and
    76  	// old containers never have chance to call the new function in create stage.
    77  	if err := daemon.adaptContainerSettings(container.HostConfig, false); err != nil {
    78  		return err
    79  	}
    80  
    81  	return daemon.containerStart(container)
    82  }
    83  
    84  // Start starts a container
    85  func (daemon *Daemon) Start(container *container.Container) error {
    86  	return daemon.containerStart(container)
    87  }
    88  
    89  // containerStart prepares the container to run by setting up everything the
    90  // container needs, such as storage and networking, as well as links
    91  // between containers. The container is left waiting for a signal to
    92  // begin running.
    93  func (daemon *Daemon) containerStart(container *container.Container) (err error) {
    94  	container.Lock()
    95  	defer container.Unlock()
    96  
    97  	if container.Running {
    98  		return nil
    99  	}
   100  
   101  	if container.RemovalInProgress || container.Dead {
   102  		return fmt.Errorf("Container is marked for removal and cannot be started.")
   103  	}
   104  
   105  	// if we encounter an error during start we need to ensure that any other
   106  	// setup has been cleaned up properly
   107  	defer func() {
   108  		if err != nil {
   109  			container.SetError(err)
   110  			// if no one else has set it, make sure we don't leave it at zero
   111  			if container.ExitCode() == 0 {
   112  				container.SetExitCode(128)
   113  			}
   114  			container.ToDisk()
   115  			daemon.Cleanup(container)
   116  			// if containers AutoRemove flag is set, remove it after clean up
   117  			if container.HostConfig.AutoRemove {
   118  				container.Unlock()
   119  				if err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
   120  					logrus.Errorf("can't remove container %s: %v", container.ID, err)
   121  				}
   122  				container.Lock()
   123  			}
   124  		}
   125  	}()
   126  
   127  	if err := daemon.conditionalMountOnStart(container); err != nil {
   128  		return err
   129  	}
   130  
   131  	// Make sure NetworkMode has an acceptable value. We do this to ensure
   132  	// backwards API compatibility.
   133  	container.HostConfig = runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
   134  
   135  	if err := daemon.initializeNetworking(container); err != nil {
   136  		return err
   137  	}
   138  
   139  	spec, err := daemon.createSpec(container)
   140  	if err != nil {
   141  		return err
   142  	}
   143  
   144  	createOptions := []libcontainerd.CreateOption{libcontainerd.WithRestartManager(container.RestartManager(true))}
   145  	copts, err := daemon.getLibcontainerdCreateOptions(container)
   146  	if err != nil {
   147  		return err
   148  	}
   149  	if copts != nil {
   150  		createOptions = append(createOptions, *copts...)
   151  	}
   152  
   153  	if err := daemon.containerd.Create(container.ID, *spec, createOptions...); err != nil {
   154  		errDesc := grpc.ErrorDesc(err)
   155  		logrus.Errorf("Create container failed with error: %s", errDesc)
   156  		// if we receive an internal error from the initial start of a container then lets
   157  		// return it instead of entering the restart loop
   158  		// set to 127 for container cmd not found/does not exist)
   159  		if strings.Contains(errDesc, container.Path) &&
   160  			(strings.Contains(errDesc, "executable file not found") ||
   161  				strings.Contains(errDesc, "no such file or directory") ||
   162  				strings.Contains(errDesc, "system cannot find the file specified")) {
   163  			container.SetExitCode(127)
   164  		}
   165  		// set to 126 for container cmd can't be invoked errors
   166  		if strings.Contains(errDesc, syscall.EACCES.Error()) {
   167  			container.SetExitCode(126)
   168  		}
   169  
   170  		// attempted to mount a file onto a directory, or a directory onto a file, maybe from user specified bind mounts
   171  		if strings.Contains(errDesc, syscall.ENOTDIR.Error()) {
   172  			errDesc += ": Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type"
   173  			container.SetExitCode(127)
   174  		}
   175  
   176  		container.Reset(false)
   177  
   178  		return fmt.Errorf("%s", errDesc)
   179  	}
   180  
   181  	return nil
   182  }
   183  
   184  // Cleanup releases any network resources allocated to the container along with any rules
   185  // around how containers are linked together.  It also unmounts the container's root filesystem.
   186  func (daemon *Daemon) Cleanup(container *container.Container) {
   187  	daemon.releaseNetwork(container)
   188  
   189  	container.UnmountIpcMounts(detachMounted)
   190  
   191  	if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
   192  		// FIXME: remove once reference counting for graphdrivers has been refactored
   193  		// Ensure that all the mounts are gone
   194  		if mountid, err := daemon.layerStore.GetMountID(container.ID); err == nil {
   195  			daemon.cleanupMountsByID(mountid)
   196  		}
   197  	}
   198  
   199  	for _, eConfig := range container.ExecCommands.Commands() {
   200  		daemon.unregisterExecCommand(container, eConfig)
   201  	}
   202  
   203  	if container.BaseFS != "" {
   204  		if err := container.UnmountVolumes(false, daemon.LogVolumeEvent); err != nil {
   205  			logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
   206  		}
   207  	}
   208  	container.CancelAttachContext()
   209  }