github.com/squaremo/docker@v1.3.2-0.20150516120342-42cfc9554972/daemon/daemon.go (about)

     1  package daemon
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"path"
    10  	"path/filepath"
    11  	"regexp"
    12  	"runtime"
    13  	"strings"
    14  	"sync"
    15  	"time"
    16  
    17  	"github.com/docker/libcontainer/label"
    18  
    19  	"github.com/Sirupsen/logrus"
    20  	"github.com/docker/docker/api"
    21  	"github.com/docker/docker/autogen/dockerversion"
    22  	"github.com/docker/docker/daemon/events"
    23  	"github.com/docker/docker/daemon/execdriver"
    24  	"github.com/docker/docker/daemon/execdriver/execdrivers"
    25  	"github.com/docker/docker/daemon/graphdriver"
    26  	_ "github.com/docker/docker/daemon/graphdriver/vfs"
    27  	"github.com/docker/docker/daemon/logger"
    28  	"github.com/docker/docker/daemon/network"
    29  	"github.com/docker/docker/daemon/networkdriver/bridge"
    30  	"github.com/docker/docker/graph"
    31  	"github.com/docker/docker/image"
    32  	"github.com/docker/docker/pkg/archive"
    33  	"github.com/docker/docker/pkg/broadcastwriter"
    34  	"github.com/docker/docker/pkg/fileutils"
    35  	"github.com/docker/docker/pkg/graphdb"
    36  	"github.com/docker/docker/pkg/ioutils"
    37  	"github.com/docker/docker/pkg/namesgenerator"
    38  	"github.com/docker/docker/pkg/parsers"
    39  	"github.com/docker/docker/pkg/parsers/kernel"
    40  	"github.com/docker/docker/pkg/resolvconf"
    41  	"github.com/docker/docker/pkg/stringid"
    42  	"github.com/docker/docker/pkg/sysinfo"
    43  	"github.com/docker/docker/pkg/truncindex"
    44  	"github.com/docker/docker/registry"
    45  	"github.com/docker/docker/runconfig"
    46  	"github.com/docker/docker/trust"
    47  	"github.com/docker/docker/utils"
    48  	"github.com/docker/docker/volumes"
    49  
    50  	"github.com/go-fsnotify/fsnotify"
    51  )
    52  
    53  var (
    54  	validContainerNameChars   = `[a-zA-Z0-9][a-zA-Z0-9_.-]`
    55  	validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
    56  )
    57  
    58  type contStore struct {
    59  	s map[string]*Container
    60  	sync.Mutex
    61  }
    62  
    63  func (c *contStore) Add(id string, cont *Container) {
    64  	c.Lock()
    65  	c.s[id] = cont
    66  	c.Unlock()
    67  }
    68  
    69  func (c *contStore) Get(id string) *Container {
    70  	c.Lock()
    71  	res := c.s[id]
    72  	c.Unlock()
    73  	return res
    74  }
    75  
    76  func (c *contStore) Delete(id string) {
    77  	c.Lock()
    78  	delete(c.s, id)
    79  	c.Unlock()
    80  }
    81  
    82  func (c *contStore) List() []*Container {
    83  	containers := new(History)
    84  	c.Lock()
    85  	for _, cont := range c.s {
    86  		containers.Add(cont)
    87  	}
    88  	c.Unlock()
    89  	containers.Sort()
    90  	return *containers
    91  }
    92  
    93  type Daemon struct {
    94  	ID               string
    95  	repository       string
    96  	sysInitPath      string
    97  	containers       *contStore
    98  	execCommands     *execStore
    99  	graph            *graph.Graph
   100  	repositories     *graph.TagStore
   101  	idIndex          *truncindex.TruncIndex
   102  	sysInfo          *sysinfo.SysInfo
   103  	volumes          *volumes.Repository
   104  	config           *Config
   105  	containerGraph   *graphdb.Database
   106  	driver           graphdriver.Driver
   107  	execDriver       execdriver.Driver
   108  	statsCollector   *statsCollector
   109  	defaultLogConfig runconfig.LogConfig
   110  	RegistryService  *registry.Service
   111  	EventsService    *events.Events
   112  }
   113  
   114  // Get looks for a container using the provided information, which could be
   115  // one of the following inputs from the caller:
   116  //  - A full container ID, which will exact match a container in daemon's list
   117  //  - A container name, which will only exact match via the GetByName() function
   118  //  - A partial container ID prefix (e.g. short ID) of any length that is
   119  //    unique enough to only return a single container object
   120  //  If none of these searches succeed, an error is returned
   121  func (daemon *Daemon) Get(prefixOrName string) (*Container, error) {
   122  	if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
   123  		// prefix is an exact match to a full container ID
   124  		return containerByID, nil
   125  	}
   126  
   127  	// GetByName will match only an exact name provided; we ignore errors
   128  	containerByName, _ := daemon.GetByName(prefixOrName)
   129  	containerId, indexError := daemon.idIndex.Get(prefixOrName)
   130  
   131  	if containerByName != nil {
   132  		// prefix is an exact match to a full container Name
   133  		return containerByName, nil
   134  	}
   135  
   136  	if containerId != "" {
   137  		// prefix is a fuzzy match to a container ID
   138  		return daemon.containers.Get(containerId), nil
   139  	}
   140  	return nil, indexError
   141  }
   142  
   143  // Exists returns a true if a container of the specified ID or name exists,
   144  // false otherwise.
   145  func (daemon *Daemon) Exists(id string) bool {
   146  	c, _ := daemon.Get(id)
   147  	return c != nil
   148  }
   149  
   150  func (daemon *Daemon) containerRoot(id string) string {
   151  	return path.Join(daemon.repository, id)
   152  }
   153  
   154  // Load reads the contents of a container from disk
   155  // This is typically done at startup.
   156  func (daemon *Daemon) load(id string) (*Container, error) {
   157  	container := &Container{
   158  		root:         daemon.containerRoot(id),
   159  		State:        NewState(),
   160  		execCommands: newExecStore(),
   161  	}
   162  	if err := container.FromDisk(); err != nil {
   163  		return nil, err
   164  	}
   165  
   166  	if container.ID != id {
   167  		return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
   168  	}
   169  
   170  	return container, nil
   171  }
   172  
   173  // Register makes a container object usable by the daemon as <container.ID>
   174  // This is a wrapper for register
   175  func (daemon *Daemon) Register(container *Container) error {
   176  	return daemon.register(container, true)
   177  }
   178  
   179  // register makes a container object usable by the daemon as <container.ID>
   180  func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error {
   181  	if container.daemon != nil || daemon.Exists(container.ID) {
   182  		return fmt.Errorf("Container is already loaded")
   183  	}
   184  	if err := validateID(container.ID); err != nil {
   185  		return err
   186  	}
   187  	if err := daemon.ensureName(container); err != nil {
   188  		return err
   189  	}
   190  
   191  	container.daemon = daemon
   192  
   193  	// Attach to stdout and stderr
   194  	container.stderr = broadcastwriter.New()
   195  	container.stdout = broadcastwriter.New()
   196  	// Attach to stdin
   197  	if container.Config.OpenStdin {
   198  		container.stdin, container.stdinPipe = io.Pipe()
   199  	} else {
   200  		container.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
   201  	}
   202  	// done
   203  	daemon.containers.Add(container.ID, container)
   204  
   205  	// don't update the Suffixarray if we're starting up
   206  	// we'll waste time if we update it for every container
   207  	daemon.idIndex.Add(container.ID)
   208  
   209  	container.registerVolumes()
   210  
   211  	if container.IsRunning() {
   212  		logrus.Debugf("killing old running container %s", container.ID)
   213  
   214  		container.SetStopped(&execdriver.ExitStatus{ExitCode: 0})
   215  
   216  		// use the current driver and ensure that the container is dead x.x
   217  		cmd := &execdriver.Command{
   218  			ID: container.ID,
   219  		}
   220  		daemon.execDriver.Terminate(cmd)
   221  
   222  		if err := container.Unmount(); err != nil {
   223  			logrus.Debugf("unmount error %s", err)
   224  		}
   225  		if err := container.ToDisk(); err != nil {
   226  			logrus.Debugf("saving stopped state to disk %s", err)
   227  		}
   228  	}
   229  
   230  	return nil
   231  }
   232  
   233  func (daemon *Daemon) ensureName(container *Container) error {
   234  	if container.Name == "" {
   235  		name, err := daemon.generateNewName(container.ID)
   236  		if err != nil {
   237  			return err
   238  		}
   239  		container.Name = name
   240  
   241  		if err := container.ToDisk(); err != nil {
   242  			logrus.Debugf("Error saving container name %s", err)
   243  		}
   244  	}
   245  	return nil
   246  }
   247  
   248  func (daemon *Daemon) restore() error {
   249  	var (
   250  		debug         = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "")
   251  		containers    = make(map[string]*Container)
   252  		currentDriver = daemon.driver.String()
   253  	)
   254  
   255  	if !debug {
   256  		logrus.Info("Loading containers: start.")
   257  	}
   258  	dir, err := ioutil.ReadDir(daemon.repository)
   259  	if err != nil {
   260  		return err
   261  	}
   262  
   263  	for _, v := range dir {
   264  		id := v.Name()
   265  		container, err := daemon.load(id)
   266  		if !debug && logrus.GetLevel() == logrus.InfoLevel {
   267  			fmt.Print(".")
   268  		}
   269  		if err != nil {
   270  			logrus.Errorf("Failed to load container %v: %v", id, err)
   271  			continue
   272  		}
   273  
   274  		// Ignore the container if it does not support the current driver being used by the graph
   275  		if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
   276  			logrus.Debugf("Loaded container %v", container.ID)
   277  
   278  			containers[container.ID] = container
   279  		} else {
   280  			logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
   281  		}
   282  	}
   283  
   284  	registeredContainers := []*Container{}
   285  
   286  	if entities := daemon.containerGraph.List("/", -1); entities != nil {
   287  		for _, p := range entities.Paths() {
   288  			if !debug && logrus.GetLevel() == logrus.InfoLevel {
   289  				fmt.Print(".")
   290  			}
   291  
   292  			e := entities[p]
   293  
   294  			if container, ok := containers[e.ID()]; ok {
   295  				if err := daemon.register(container, false); err != nil {
   296  					logrus.Debugf("Failed to register container %s: %s", container.ID, err)
   297  				}
   298  
   299  				registeredContainers = append(registeredContainers, container)
   300  
   301  				// delete from the map so that a new name is not automatically generated
   302  				delete(containers, e.ID())
   303  			}
   304  		}
   305  	}
   306  
   307  	// Any containers that are left over do not exist in the graph
   308  	for _, container := range containers {
   309  		// Try to set the default name for a container if it exists prior to links
   310  		container.Name, err = daemon.generateNewName(container.ID)
   311  		if err != nil {
   312  			logrus.Debugf("Setting default id - %s", err)
   313  		}
   314  
   315  		if err := daemon.register(container, false); err != nil {
   316  			logrus.Debugf("Failed to register container %s: %s", container.ID, err)
   317  		}
   318  
   319  		registeredContainers = append(registeredContainers, container)
   320  	}
   321  
   322  	// check the restart policy on the containers and restart any container with
   323  	// the restart policy of "always"
   324  	if daemon.config.AutoRestart {
   325  		logrus.Debug("Restarting containers...")
   326  
   327  		for _, container := range registeredContainers {
   328  			if container.hostConfig.RestartPolicy.Name == "always" ||
   329  				(container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) {
   330  				logrus.Debugf("Starting container %s", container.ID)
   331  
   332  				if err := container.Start(); err != nil {
   333  					logrus.Debugf("Failed to start container %s: %s", container.ID, err)
   334  				}
   335  			}
   336  		}
   337  	}
   338  
   339  	if !debug {
   340  		if logrus.GetLevel() == logrus.InfoLevel {
   341  			fmt.Println()
   342  		}
   343  		logrus.Info("Loading containers: done.")
   344  	}
   345  
   346  	return nil
   347  }
   348  
   349  // set up the watch on the host's /etc/resolv.conf so that we can update container's
   350  // live resolv.conf when the network changes on the host
   351  func (daemon *Daemon) setupResolvconfWatcher() error {
   352  
   353  	watcher, err := fsnotify.NewWatcher()
   354  	if err != nil {
   355  		return err
   356  	}
   357  
   358  	//this goroutine listens for the events on the watch we add
   359  	//on the resolv.conf file on the host
   360  	go func() {
   361  		for {
   362  			select {
   363  			case event := <-watcher.Events:
   364  				if event.Name == "/etc/resolv.conf" &&
   365  					(event.Op&(fsnotify.Write|fsnotify.Create) != 0) {
   366  					// verify a real change happened before we go further--a file write may have happened
   367  					// without an actual change to the file
   368  					updatedResolvConf, newResolvConfHash, err := resolvconf.GetIfChanged()
   369  					if err != nil {
   370  						logrus.Debugf("Error retrieving updated host resolv.conf: %v", err)
   371  					} else if updatedResolvConf != nil {
   372  						// because the new host resolv.conf might have localhost nameservers..
   373  						updatedResolvConf, modified := resolvconf.FilterResolvDns(updatedResolvConf, daemon.config.Bridge.EnableIPv6)
   374  						if modified {
   375  							// changes have occurred during localhost cleanup: generate an updated hash
   376  							newHash, err := ioutils.HashData(bytes.NewReader(updatedResolvConf))
   377  							if err != nil {
   378  								logrus.Debugf("Error generating hash of new resolv.conf: %v", err)
   379  							} else {
   380  								newResolvConfHash = newHash
   381  							}
   382  						}
   383  						logrus.Debug("host network resolv.conf changed--walking container list for updates")
   384  						contList := daemon.containers.List()
   385  						for _, container := range contList {
   386  							if err := container.updateResolvConf(updatedResolvConf, newResolvConfHash); err != nil {
   387  								logrus.Debugf("Error on resolv.conf update check for container ID: %s: %v", container.ID, err)
   388  							}
   389  						}
   390  					}
   391  				}
   392  			case err := <-watcher.Errors:
   393  				logrus.Debugf("host resolv.conf notify error: %v", err)
   394  			}
   395  		}
   396  	}()
   397  
   398  	if err := watcher.Add("/etc"); err != nil {
   399  		return err
   400  	}
   401  	return nil
   402  }
   403  
   404  func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool {
   405  	if config != nil {
   406  		if config.PortSpecs != nil {
   407  			for _, p := range config.PortSpecs {
   408  				if strings.Contains(p, ":") {
   409  					return true
   410  				}
   411  			}
   412  		}
   413  	}
   414  	return false
   415  }
   416  
   417  func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) {
   418  	warnings := []string{}
   419  	if (img != nil && daemon.checkDeprecatedExpose(img.Config)) || daemon.checkDeprecatedExpose(config) {
   420  		warnings = append(warnings, "The mapping to public ports on your host via Dockerfile EXPOSE (host:port:port) has been deprecated. Use -p to publish the ports.")
   421  	}
   422  	if img != nil && img.Config != nil {
   423  		if err := runconfig.Merge(config, img.Config); err != nil {
   424  			return nil, err
   425  		}
   426  	}
   427  	if config.Entrypoint.Len() == 0 && config.Cmd.Len() == 0 {
   428  		return nil, fmt.Errorf("No command specified")
   429  	}
   430  	return warnings, nil
   431  }
   432  
   433  func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
   434  	var (
   435  		err error
   436  		id  = stringid.GenerateRandomID()
   437  	)
   438  
   439  	if name == "" {
   440  		if name, err = daemon.generateNewName(id); err != nil {
   441  			return "", "", err
   442  		}
   443  		return id, name, nil
   444  	}
   445  
   446  	if name, err = daemon.reserveName(id, name); err != nil {
   447  		return "", "", err
   448  	}
   449  
   450  	return id, name, nil
   451  }
   452  
   453  func (daemon *Daemon) reserveName(id, name string) (string, error) {
   454  	if !validContainerNamePattern.MatchString(name) {
   455  		return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
   456  	}
   457  
   458  	if name[0] != '/' {
   459  		name = "/" + name
   460  	}
   461  
   462  	if _, err := daemon.containerGraph.Set(name, id); err != nil {
   463  		if !graphdb.IsNonUniqueNameError(err) {
   464  			return "", err
   465  		}
   466  
   467  		conflictingContainer, err := daemon.GetByName(name)
   468  		if err != nil {
   469  			if strings.Contains(err.Error(), "Could not find entity") {
   470  				return "", err
   471  			}
   472  
   473  			// Remove name and continue starting the container
   474  			if err := daemon.containerGraph.Delete(name); err != nil {
   475  				return "", err
   476  			}
   477  		} else {
   478  			nameAsKnownByUser := strings.TrimPrefix(name, "/")
   479  			return "", fmt.Errorf(
   480  				"Conflict. The name %q is already in use by container %s. You have to delete (or rename) that container to be able to reuse that name.", nameAsKnownByUser,
   481  				stringid.TruncateID(conflictingContainer.ID))
   482  		}
   483  	}
   484  	return name, nil
   485  }
   486  
   487  func (daemon *Daemon) generateNewName(id string) (string, error) {
   488  	var name string
   489  	for i := 0; i < 6; i++ {
   490  		name = namesgenerator.GetRandomName(i)
   491  		if name[0] != '/' {
   492  			name = "/" + name
   493  		}
   494  
   495  		if _, err := daemon.containerGraph.Set(name, id); err != nil {
   496  			if !graphdb.IsNonUniqueNameError(err) {
   497  				return "", err
   498  			}
   499  			continue
   500  		}
   501  		return name, nil
   502  	}
   503  
   504  	name = "/" + stringid.TruncateID(id)
   505  	if _, err := daemon.containerGraph.Set(name, id); err != nil {
   506  		return "", err
   507  	}
   508  	return name, nil
   509  }
   510  
   511  func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
   512  	// Generate default hostname
   513  	// FIXME: the lxc template no longer needs to set a default hostname
   514  	if config.Hostname == "" {
   515  		config.Hostname = id[:12]
   516  	}
   517  }
   518  
   519  func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *runconfig.Entrypoint, configCmd *runconfig.Command) (string, []string) {
   520  	var (
   521  		entrypoint string
   522  		args       []string
   523  	)
   524  
   525  	cmdSlice := configCmd.Slice()
   526  	if configEntrypoint.Len() != 0 {
   527  		eSlice := configEntrypoint.Slice()
   528  		entrypoint = eSlice[0]
   529  		args = append(eSlice[1:], cmdSlice...)
   530  	} else {
   531  		entrypoint = cmdSlice[0]
   532  		args = cmdSlice[1:]
   533  	}
   534  	return entrypoint, args
   535  }
   536  
   537  func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
   538  	var (
   539  		labelOpts []string
   540  		err       error
   541  	)
   542  
   543  	for _, opt := range config.SecurityOpt {
   544  		con := strings.SplitN(opt, ":", 2)
   545  		if len(con) == 1 {
   546  			return fmt.Errorf("Invalid --security-opt: %q", opt)
   547  		}
   548  		switch con[0] {
   549  		case "label":
   550  			labelOpts = append(labelOpts, con[1])
   551  		case "apparmor":
   552  			container.AppArmorProfile = con[1]
   553  		default:
   554  			return fmt.Errorf("Invalid --security-opt: %q", opt)
   555  		}
   556  	}
   557  
   558  	container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
   559  	return err
   560  }
   561  
   562  func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) {
   563  	var (
   564  		id  string
   565  		err error
   566  	)
   567  	id, name, err = daemon.generateIdAndName(name)
   568  	if err != nil {
   569  		return nil, err
   570  	}
   571  
   572  	daemon.generateHostname(id, config)
   573  	entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
   574  
   575  	container := &Container{
   576  		// FIXME: we should generate the ID here instead of receiving it as an argument
   577  		ID:              id,
   578  		Created:         time.Now().UTC(),
   579  		Path:            entrypoint,
   580  		Args:            args, //FIXME: de-duplicate from config
   581  		Config:          config,
   582  		hostConfig:      &runconfig.HostConfig{},
   583  		ImageID:         imgID,
   584  		NetworkSettings: &network.Settings{},
   585  		Name:            name,
   586  		Driver:          daemon.driver.String(),
   587  		ExecDriver:      daemon.execDriver.Name(),
   588  		State:           NewState(),
   589  		execCommands:    newExecStore(),
   590  	}
   591  	container.root = daemon.containerRoot(container.ID)
   592  	return container, err
   593  }
   594  
   595  func (daemon *Daemon) createRootfs(container *Container) error {
   596  	// Step 1: create the container directory.
   597  	// This doubles as a barrier to avoid race conditions.
   598  	if err := os.Mkdir(container.root, 0700); err != nil {
   599  		return err
   600  	}
   601  	initID := fmt.Sprintf("%s-init", container.ID)
   602  	if err := daemon.driver.Create(initID, container.ImageID); err != nil {
   603  		return err
   604  	}
   605  	initPath, err := daemon.driver.Get(initID, "")
   606  	if err != nil {
   607  		return err
   608  	}
   609  	defer daemon.driver.Put(initID)
   610  
   611  	if err := graph.SetupInitLayer(initPath); err != nil {
   612  		return err
   613  	}
   614  
   615  	if err := daemon.driver.Create(container.ID, initID); err != nil {
   616  		return err
   617  	}
   618  	return nil
   619  }
   620  
   621  func GetFullContainerName(name string) (string, error) {
   622  	if name == "" {
   623  		return "", fmt.Errorf("Container name cannot be empty")
   624  	}
   625  	if name[0] != '/' {
   626  		name = "/" + name
   627  	}
   628  	return name, nil
   629  }
   630  
   631  func (daemon *Daemon) GetByName(name string) (*Container, error) {
   632  	fullName, err := GetFullContainerName(name)
   633  	if err != nil {
   634  		return nil, err
   635  	}
   636  	entity := daemon.containerGraph.Get(fullName)
   637  	if entity == nil {
   638  		return nil, fmt.Errorf("Could not find entity for %s", name)
   639  	}
   640  	e := daemon.containers.Get(entity.ID())
   641  	if e == nil {
   642  		return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
   643  	}
   644  	return e, nil
   645  }
   646  
   647  func (daemon *Daemon) Children(name string) (map[string]*Container, error) {
   648  	name, err := GetFullContainerName(name)
   649  	if err != nil {
   650  		return nil, err
   651  	}
   652  	children := make(map[string]*Container)
   653  
   654  	err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
   655  		c, err := daemon.Get(e.ID())
   656  		if err != nil {
   657  			return err
   658  		}
   659  		children[p] = c
   660  		return nil
   661  	}, 0)
   662  
   663  	if err != nil {
   664  		return nil, err
   665  	}
   666  	return children, nil
   667  }
   668  
   669  func (daemon *Daemon) Parents(name string) ([]string, error) {
   670  	name, err := GetFullContainerName(name)
   671  	if err != nil {
   672  		return nil, err
   673  	}
   674  
   675  	return daemon.containerGraph.Parents(name)
   676  }
   677  
   678  func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error {
   679  	fullName := path.Join(parent.Name, alias)
   680  	if !daemon.containerGraph.Exists(fullName) {
   681  		_, err := daemon.containerGraph.Set(fullName, child.ID)
   682  		return err
   683  	}
   684  	return nil
   685  }
   686  
   687  func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
   688  	if hostConfig != nil && hostConfig.Links != nil {
   689  		for _, l := range hostConfig.Links {
   690  			name, alias, err := parsers.ParseLink(l)
   691  			if err != nil {
   692  				return err
   693  			}
   694  			child, err := daemon.Get(name)
   695  			if err != nil {
   696  				//An error from daemon.Get() means this name could not be found
   697  				return fmt.Errorf("Could not get container for %s", name)
   698  			}
   699  			for child.hostConfig.NetworkMode.IsContainer() {
   700  				parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
   701  				child, err = daemon.Get(parts[1])
   702  				if err != nil {
   703  					return fmt.Errorf("Could not get container for %s", parts[1])
   704  				}
   705  			}
   706  			if child.hostConfig.NetworkMode.IsHost() {
   707  				return runconfig.ErrConflictHostNetworkAndLinks
   708  			}
   709  			if err := daemon.RegisterLink(container, child, alias); err != nil {
   710  				return err
   711  			}
   712  		}
   713  
   714  		// After we load all the links into the daemon
   715  		// set them to nil on the hostconfig
   716  		hostConfig.Links = nil
   717  		if err := container.WriteHostConfig(); err != nil {
   718  			return err
   719  		}
   720  	}
   721  	return nil
   722  }
   723  
   724  func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
   725  	if config.Mtu == 0 {
   726  		config.Mtu = getDefaultNetworkMtu()
   727  	}
   728  	// Check for mutually incompatible config options
   729  	if config.Bridge.Iface != "" && config.Bridge.IP != "" {
   730  		return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
   731  	}
   732  	if !config.Bridge.EnableIptables && !config.Bridge.InterContainerCommunication {
   733  		return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
   734  	}
   735  	if !config.Bridge.EnableIptables && config.Bridge.EnableIpMasq {
   736  		config.Bridge.EnableIpMasq = false
   737  	}
   738  	config.DisableNetwork = config.Bridge.Iface == disableNetworkBridge
   739  
   740  	// Check that the system is supported and we have sufficient privileges
   741  	if runtime.GOOS != "linux" {
   742  		return nil, fmt.Errorf("The Docker daemon is only supported on linux")
   743  	}
   744  	if os.Geteuid() != 0 {
   745  		return nil, fmt.Errorf("The Docker daemon needs to be run as root")
   746  	}
   747  	if err := checkKernel(); err != nil {
   748  		return nil, err
   749  	}
   750  
   751  	// set up SIGUSR1 handler to dump Go routine stacks
   752  	setupSigusr1Trap()
   753  
   754  	// set up the tmpDir to use a canonical path
   755  	tmp, err := tempDir(config.Root)
   756  	if err != nil {
   757  		return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
   758  	}
   759  	realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
   760  	if err != nil {
   761  		return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
   762  	}
   763  	os.Setenv("TMPDIR", realTmp)
   764  
   765  	// get the canonical path to the Docker root directory
   766  	var realRoot string
   767  	if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
   768  		realRoot = config.Root
   769  	} else {
   770  		realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
   771  		if err != nil {
   772  			return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
   773  		}
   774  	}
   775  	config.Root = realRoot
   776  	// Create the root directory if it doesn't exists
   777  	if err := os.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) {
   778  		return nil, err
   779  	}
   780  
   781  	// Set the default driver
   782  	graphdriver.DefaultDriver = config.GraphDriver
   783  
   784  	// Load storage driver
   785  	driver, err := graphdriver.New(config.Root, config.GraphOptions)
   786  	if err != nil {
   787  		return nil, fmt.Errorf("error initializing graphdriver: %v", err)
   788  	}
   789  	logrus.Debugf("Using graph driver %s", driver)
   790  
   791  	d := &Daemon{}
   792  	d.driver = driver
   793  
   794  	defer func() {
   795  		if err != nil {
   796  			if err := d.Shutdown(); err != nil {
   797  				logrus.Error(err)
   798  			}
   799  		}
   800  	}()
   801  
   802  	// Verify logging driver type
   803  	if config.LogConfig.Type != "none" {
   804  		if _, err := logger.GetLogDriver(config.LogConfig.Type); err != nil {
   805  			return nil, fmt.Errorf("error finding the logging driver: %v", err)
   806  		}
   807  	}
   808  	logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
   809  
   810  	if config.EnableSelinuxSupport {
   811  		if selinuxEnabled() {
   812  			// As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
   813  			if d.driver.String() == "btrfs" {
   814  				return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
   815  			}
   816  			logrus.Debug("SELinux enabled successfully")
   817  		} else {
   818  			logrus.Warn("Docker could not enable SELinux on the host system")
   819  		}
   820  	} else {
   821  		selinuxSetDisabled()
   822  	}
   823  
   824  	daemonRepo := path.Join(config.Root, "containers")
   825  
   826  	if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) {
   827  		return nil, err
   828  	}
   829  
   830  	// Migrate the container if it is aufs and aufs is enabled
   831  	if err := migrateIfAufs(d.driver, config.Root); err != nil {
   832  		return nil, err
   833  	}
   834  
   835  	logrus.Debug("Creating images graph")
   836  	g, err := graph.NewGraph(path.Join(config.Root, "graph"), d.driver)
   837  	if err != nil {
   838  		return nil, err
   839  	}
   840  
   841  	volumesDriver, err := graphdriver.GetDriver("vfs", config.Root, config.GraphOptions)
   842  	if err != nil {
   843  		return nil, err
   844  	}
   845  
   846  	volumes, err := volumes.NewRepository(filepath.Join(config.Root, "volumes"), volumesDriver)
   847  	if err != nil {
   848  		return nil, err
   849  	}
   850  
   851  	trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
   852  	if err != nil {
   853  		return nil, err
   854  	}
   855  
   856  	trustDir := path.Join(config.Root, "trust")
   857  	if err := os.MkdirAll(trustDir, 0700); err != nil && !os.IsExist(err) {
   858  		return nil, err
   859  	}
   860  	trustService, err := trust.NewTrustStore(trustDir)
   861  	if err != nil {
   862  		return nil, fmt.Errorf("could not create trust store: %s", err)
   863  	}
   864  
   865  	eventsService := events.New()
   866  	logrus.Debug("Creating repository list")
   867  	tagCfg := &graph.TagStoreConfig{
   868  		Graph:    g,
   869  		Key:      trustKey,
   870  		Registry: registryService,
   871  		Events:   eventsService,
   872  		Trust:    trustService,
   873  	}
   874  	repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+d.driver.String()), tagCfg)
   875  	if err != nil {
   876  		return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
   877  	}
   878  
   879  	if !config.DisableNetwork {
   880  		if err := bridge.InitDriver(&config.Bridge); err != nil {
   881  			return nil, fmt.Errorf("Error initializing Bridge: %v", err)
   882  		}
   883  	}
   884  
   885  	graphdbPath := path.Join(config.Root, "linkgraph.db")
   886  	graph, err := graphdb.NewSqliteConn(graphdbPath)
   887  	if err != nil {
   888  		return nil, err
   889  	}
   890  
   891  	d.containerGraph = graph
   892  
   893  	localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
   894  	sysInitPath := utils.DockerInitPath(localCopy)
   895  	if sysInitPath == "" {
   896  		return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See https://docs.docker.com/contributing/devenvironment for official build instructions.")
   897  	}
   898  
   899  	if sysInitPath != localCopy {
   900  		// When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade).
   901  		if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
   902  			return nil, err
   903  		}
   904  		if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
   905  			return nil, err
   906  		}
   907  		if err := os.Chmod(localCopy, 0700); err != nil {
   908  			return nil, err
   909  		}
   910  		sysInitPath = localCopy
   911  	}
   912  
   913  	sysInfo := sysinfo.New(false)
   914  	ed, err := execdrivers.NewDriver(config.ExecDriver, config.ExecOptions, config.ExecRoot, config.Root, sysInitPath, sysInfo)
   915  	if err != nil {
   916  		return nil, err
   917  	}
   918  
   919  	d.ID = trustKey.PublicKey().KeyID()
   920  	d.repository = daemonRepo
   921  	d.containers = &contStore{s: make(map[string]*Container)}
   922  	d.execCommands = newExecStore()
   923  	d.graph = g
   924  	d.repositories = repositories
   925  	d.idIndex = truncindex.NewTruncIndex([]string{})
   926  	d.sysInfo = sysInfo
   927  	d.volumes = volumes
   928  	d.config = config
   929  	d.sysInitPath = sysInitPath
   930  	d.execDriver = ed
   931  	d.statsCollector = newStatsCollector(1 * time.Second)
   932  	d.defaultLogConfig = config.LogConfig
   933  	d.RegistryService = registryService
   934  	d.EventsService = eventsService
   935  
   936  	if err := d.restore(); err != nil {
   937  		return nil, err
   938  	}
   939  
   940  	// set up filesystem watch on resolv.conf for network changes
   941  	if err := d.setupResolvconfWatcher(); err != nil {
   942  		return nil, err
   943  	}
   944  
   945  	return d, nil
   946  }
   947  
   948  func (daemon *Daemon) Shutdown() error {
   949  	if daemon.containerGraph != nil {
   950  		if err := daemon.containerGraph.Close(); err != nil {
   951  			logrus.Errorf("Error during container graph.Close(): %v", err)
   952  		}
   953  	}
   954  	if daemon.driver != nil {
   955  		if err := daemon.driver.Cleanup(); err != nil {
   956  			logrus.Errorf("Error during graph storage driver.Cleanup(): %v", err)
   957  		}
   958  	}
   959  	if daemon.containers != nil {
   960  		group := sync.WaitGroup{}
   961  		logrus.Debug("starting clean shutdown of all containers...")
   962  		for _, container := range daemon.List() {
   963  			c := container
   964  			if c.IsRunning() {
   965  				logrus.Debugf("stopping %s", c.ID)
   966  				group.Add(1)
   967  
   968  				go func() {
   969  					defer group.Done()
   970  					if err := c.KillSig(15); err != nil {
   971  						logrus.Debugf("kill 15 error for %s - %s", c.ID, err)
   972  					}
   973  					c.WaitStop(-1 * time.Second)
   974  					logrus.Debugf("container stopped %s", c.ID)
   975  				}()
   976  			}
   977  		}
   978  		group.Wait()
   979  	}
   980  
   981  	return nil
   982  }
   983  
   984  func (daemon *Daemon) Mount(container *Container) error {
   985  	dir, err := daemon.driver.Get(container.ID, container.GetMountLabel())
   986  	if err != nil {
   987  		return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
   988  	}
   989  	if container.basefs == "" {
   990  		container.basefs = dir
   991  	} else if container.basefs != dir {
   992  		daemon.driver.Put(container.ID)
   993  		return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
   994  			daemon.driver, container.ID, container.basefs, dir)
   995  	}
   996  	return nil
   997  }
   998  
   999  func (daemon *Daemon) Unmount(container *Container) error {
  1000  	daemon.driver.Put(container.ID)
  1001  	return nil
  1002  }
  1003  
  1004  func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  1005  	initID := fmt.Sprintf("%s-init", container.ID)
  1006  	return daemon.driver.Changes(container.ID, initID)
  1007  }
  1008  
  1009  func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  1010  	initID := fmt.Sprintf("%s-init", container.ID)
  1011  	return daemon.driver.Diff(container.ID, initID)
  1012  }
  1013  
  1014  func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  1015  	return daemon.execDriver.Run(c.command, pipes, startCallback)
  1016  }
  1017  
  1018  func (daemon *Daemon) Kill(c *Container, sig int) error {
  1019  	return daemon.execDriver.Kill(c.command, sig)
  1020  }
  1021  
  1022  func (daemon *Daemon) Stats(c *Container) (*execdriver.ResourceStats, error) {
  1023  	return daemon.execDriver.Stats(c.ID)
  1024  }
  1025  
  1026  func (daemon *Daemon) SubscribeToContainerStats(name string) (chan interface{}, error) {
  1027  	c, err := daemon.Get(name)
  1028  	if err != nil {
  1029  		return nil, err
  1030  	}
  1031  	ch := daemon.statsCollector.collect(c)
  1032  	return ch, nil
  1033  }
  1034  
  1035  func (daemon *Daemon) UnsubscribeToContainerStats(name string, ch chan interface{}) error {
  1036  	c, err := daemon.Get(name)
  1037  	if err != nil {
  1038  		return err
  1039  	}
  1040  	daemon.statsCollector.unsubscribe(c, ch)
  1041  	return nil
  1042  }
  1043  
  1044  // FIXME: this is a convenience function for integration tests
  1045  // which need direct access to daemon.graph.
  1046  // Once the tests switch to using engine and jobs, this method
  1047  // can go away.
  1048  func (daemon *Daemon) Graph() *graph.Graph {
  1049  	return daemon.graph
  1050  }
  1051  
  1052  func (daemon *Daemon) Repositories() *graph.TagStore {
  1053  	return daemon.repositories
  1054  }
  1055  
  1056  func (daemon *Daemon) Config() *Config {
  1057  	return daemon.config
  1058  }
  1059  
  1060  func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo {
  1061  	return daemon.sysInfo
  1062  }
  1063  
  1064  func (daemon *Daemon) SystemInitPath() string {
  1065  	return daemon.sysInitPath
  1066  }
  1067  
  1068  func (daemon *Daemon) GraphDriver() graphdriver.Driver {
  1069  	return daemon.driver
  1070  }
  1071  
  1072  func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
  1073  	return daemon.execDriver
  1074  }
  1075  
  1076  func (daemon *Daemon) ContainerGraph() *graphdb.Database {
  1077  	return daemon.containerGraph
  1078  }
  1079  
  1080  func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
  1081  	// Retrieve all images
  1082  	images, err := daemon.Graph().Map()
  1083  	if err != nil {
  1084  		return nil, err
  1085  	}
  1086  
  1087  	// Store the tree in a map of map (map[parentId][childId])
  1088  	imageMap := make(map[string]map[string]struct{})
  1089  	for _, img := range images {
  1090  		if _, exists := imageMap[img.Parent]; !exists {
  1091  			imageMap[img.Parent] = make(map[string]struct{})
  1092  		}
  1093  		imageMap[img.Parent][img.ID] = struct{}{}
  1094  	}
  1095  
  1096  	// Loop on the children of the given image and check the config
  1097  	var match *image.Image
  1098  	for elem := range imageMap[imgID] {
  1099  		img, ok := images[elem]
  1100  		if !ok {
  1101  			return nil, fmt.Errorf("unable to find image %q", elem)
  1102  		}
  1103  		if runconfig.Compare(&img.ContainerConfig, config) {
  1104  			if match == nil || match.Created.Before(img.Created) {
  1105  				match = img
  1106  			}
  1107  		}
  1108  	}
  1109  	return match, nil
  1110  }
  1111  
  1112  // tempDir returns the default directory to use for temporary files.
  1113  func tempDir(rootDir string) (string, error) {
  1114  	var tmpDir string
  1115  	if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  1116  		tmpDir = filepath.Join(rootDir, "tmp")
  1117  	}
  1118  	return tmpDir, os.MkdirAll(tmpDir, 0700)
  1119  }
  1120  
  1121  func checkKernel() error {
  1122  	// Check for unsupported kernel versions
  1123  	// FIXME: it would be cleaner to not test for specific versions, but rather
  1124  	// test for specific functionalities.
  1125  	// Unfortunately we can't test for the feature "does not cause a kernel panic"
  1126  	// without actually causing a kernel panic, so we need this workaround until
  1127  	// the circumstances of pre-3.10 crashes are clearer.
  1128  	// For details see https://github.com/docker/docker/issues/407
  1129  	if k, err := kernel.GetKernelVersion(); err != nil {
  1130  		logrus.Warnf("%s", err)
  1131  	} else {
  1132  		if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 {
  1133  			if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  1134  				logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.10.0.", k.String())
  1135  			}
  1136  		}
  1137  	}
  1138  	return nil
  1139  }
  1140  
  1141  func (daemon *Daemon) verifyHostConfig(hostConfig *runconfig.HostConfig) ([]string, error) {
  1142  	var warnings []string
  1143  
  1144  	if hostConfig == nil {
  1145  		return warnings, nil
  1146  	}
  1147  
  1148  	if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  1149  		return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  1150  	}
  1151  	if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  1152  		return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  1153  	}
  1154  	if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  1155  		warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  1156  		hostConfig.Memory = 0
  1157  	}
  1158  	if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  1159  		warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  1160  		hostConfig.MemorySwap = -1
  1161  	}
  1162  	if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  1163  		return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  1164  	}
  1165  	if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  1166  		return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  1167  	}
  1168  	if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  1169  		warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  1170  		hostConfig.CpuPeriod = 0
  1171  	}
  1172  	if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  1173  		warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  1174  		hostConfig.CpuQuota = 0
  1175  	}
  1176  	if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  1177  		return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  1178  	}
  1179  	if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  1180  		hostConfig.OomKillDisable = false
  1181  		return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  1182  	}
  1183  
  1184  	return warnings, nil
  1185  }
  1186  
  1187  func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error {
  1188  	container.Lock()
  1189  	defer container.Unlock()
  1190  	if err := parseSecurityOpt(container, hostConfig); err != nil {
  1191  		return err
  1192  	}
  1193  
  1194  	// Register any links from the host config before starting the container
  1195  	if err := daemon.RegisterLinks(container, hostConfig); err != nil {
  1196  		return err
  1197  	}
  1198  
  1199  	container.hostConfig = hostConfig
  1200  	container.toDisk()
  1201  
  1202  	return nil
  1203  }