github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/daemon/start.go (about)

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