2015-11-12 14:55:17 -05:00
|
|
|
package container
|
2013-01-18 19:13:39 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2013-03-21 03:25:00 -04:00
|
|
|
"fmt"
|
2014-04-28 17:36:04 -04:00
|
|
|
"io"
|
2016-03-09 23:33:21 -05:00
|
|
|
"net"
|
2014-04-28 17:36:04 -04:00
|
|
|
"os"
|
2014-05-11 16:49:46 -04:00
|
|
|
"path/filepath"
|
2016-03-09 23:33:21 -05:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2015-05-05 16:25:05 -04:00
|
|
|
"sync"
|
2014-04-28 17:36:04 -04:00
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
|
2016-03-08 19:54:33 -05:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
|
2015-03-26 18:22:04 -04:00
|
|
|
"github.com/Sirupsen/logrus"
|
2015-11-20 17:35:16 -05:00
|
|
|
"github.com/docker/docker/daemon/exec"
|
2015-02-04 14:04:58 -05:00
|
|
|
"github.com/docker/docker/daemon/logger"
|
|
|
|
"github.com/docker/docker/daemon/logger/jsonfilelog"
|
2015-04-04 00:06:48 -04:00
|
|
|
"github.com/docker/docker/daemon/network"
|
2015-11-18 17:20:54 -05:00
|
|
|
"github.com/docker/docker/image"
|
|
|
|
"github.com/docker/docker/layer"
|
2016-03-08 10:40:30 -05:00
|
|
|
"github.com/docker/docker/pkg/idtools"
|
2016-04-20 20:08:47 -04:00
|
|
|
"github.com/docker/docker/pkg/ioutils"
|
2014-09-30 02:16:27 -04:00
|
|
|
"github.com/docker/docker/pkg/promise"
|
2015-08-04 16:51:48 -04:00
|
|
|
"github.com/docker/docker/pkg/signal"
|
2014-07-24 18:19:50 -04:00
|
|
|
"github.com/docker/docker/pkg/symlink"
|
2016-03-18 14:50:19 -04:00
|
|
|
"github.com/docker/docker/restartmanager"
|
2014-07-24 18:19:50 -04:00
|
|
|
"github.com/docker/docker/runconfig"
|
2016-03-09 23:33:21 -05:00
|
|
|
runconfigopts "github.com/docker/docker/runconfig/opts"
|
2015-05-19 16:05:25 -04:00
|
|
|
"github.com/docker/docker/volume"
|
2016-01-04 19:05:26 -05:00
|
|
|
containertypes "github.com/docker/engine-api/types/container"
|
2016-03-09 23:33:21 -05:00
|
|
|
networktypes "github.com/docker/engine-api/types/network"
|
2015-12-18 12:58:48 -05:00
|
|
|
"github.com/docker/go-connections/nat"
|
2016-03-09 23:33:21 -05:00
|
|
|
"github.com/docker/libnetwork"
|
|
|
|
"github.com/docker/libnetwork/netlabel"
|
|
|
|
"github.com/docker/libnetwork/options"
|
|
|
|
"github.com/docker/libnetwork/types"
|
2015-11-12 14:55:17 -05:00
|
|
|
"github.com/opencontainers/runc/libcontainer/label"
|
2013-01-18 19:13:39 -05:00
|
|
|
)
|
|
|
|
|
2015-11-18 17:20:54 -05:00
|
|
|
const configFileName = "config.v2.json"
|
|
|
|
|
2016-03-09 23:33:21 -05:00
|
|
|
var (
|
|
|
|
errInvalidEndpoint = fmt.Errorf("invalid endpoint while building port map info")
|
|
|
|
errInvalidNetwork = fmt.Errorf("invalid network settings while building port map info")
|
|
|
|
)
|
|
|
|
|
2016-06-03 13:11:52 -04:00
|
|
|
// DetachError is special error which returned in case of container detach.
|
|
|
|
type DetachError struct{}
|
2016-05-22 10:04:39 -04:00
|
|
|
|
2016-06-03 13:11:52 -04:00
|
|
|
func (DetachError) Error() string {
|
2016-05-22 10:04:39 -04:00
|
|
|
return "detached from container"
|
|
|
|
}
|
|
|
|
|
2015-07-30 17:01:53 -04:00
|
|
|
// CommonContainer holds the fields for a container which are
|
|
|
|
// applicable across all platforms supported by the daemon.
|
2015-04-29 18:53:35 -04:00
|
|
|
type CommonContainer struct {
|
2015-11-17 19:21:44 -05:00
|
|
|
*runconfig.StreamConfig
|
2015-07-30 17:01:53 -04:00
|
|
|
// embed for Container to support states directly.
|
|
|
|
*State `json:"State"` // Needed for remote api version <= 1.11
|
2015-11-12 14:55:17 -05:00
|
|
|
Root string `json:"-"` // Path to the "home" of the container, including metadata.
|
|
|
|
BaseFS string `json:"-"` // Path to the graphdriver mountpoint
|
|
|
|
RWLayer layer.RWLayer `json:"-"`
|
2015-07-30 17:01:53 -04:00
|
|
|
ID string
|
|
|
|
Created time.Time
|
2016-06-13 22:52:49 -04:00
|
|
|
Managed bool
|
2015-07-30 17:01:53 -04:00
|
|
|
Path string
|
|
|
|
Args []string
|
2015-12-18 13:36:17 -05:00
|
|
|
Config *containertypes.Config
|
2015-11-18 17:20:54 -05:00
|
|
|
ImageID image.ID `json:"Image"`
|
2015-07-30 17:01:53 -04:00
|
|
|
NetworkSettings *network.Settings
|
|
|
|
LogPath string
|
|
|
|
Name string
|
|
|
|
Driver string
|
|
|
|
// MountLabel contains the options for the 'mount' command
|
|
|
|
MountLabel string
|
|
|
|
ProcessLabel string
|
|
|
|
RestartCount int
|
|
|
|
HasBeenStartedBefore bool
|
|
|
|
HasBeenManuallyStopped bool // used for unless-stopped restart policy
|
2015-09-09 22:23:06 -04:00
|
|
|
MountPoints map[string]*volume.MountPoint
|
2015-12-18 13:36:17 -05:00
|
|
|
HostConfig *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
|
2016-03-18 14:50:19 -04:00
|
|
|
ExecCommands *exec.Store `json:"-"`
|
2015-02-04 14:04:58 -05:00
|
|
|
// logDriver for closing
|
2016-03-18 14:50:19 -04:00
|
|
|
LogDriver logger.Logger `json:"-"`
|
|
|
|
LogCopier *logger.Copier `json:"-"`
|
|
|
|
restartManager restartmanager.RestartManager
|
|
|
|
attachContext *attachContext
|
2013-01-18 19:13:39 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// NewBaseContainer creates a new container with its
|
2015-11-18 05:04:23 -05:00
|
|
|
// basic configuration.
|
2015-11-12 14:55:17 -05:00
|
|
|
func NewBaseContainer(id, root string) *Container {
|
2015-11-18 05:04:23 -05:00
|
|
|
return &Container{
|
|
|
|
CommonContainer: CommonContainer{
|
2016-03-08 19:54:33 -05:00
|
|
|
ID: id,
|
|
|
|
State: NewState(),
|
|
|
|
ExecCommands: exec.NewStore(),
|
|
|
|
Root: root,
|
|
|
|
MountPoints: make(map[string]*volume.MountPoint),
|
|
|
|
StreamConfig: runconfig.NewStreamConfig(),
|
|
|
|
attachContext: &attachContext{},
|
2015-11-18 05:04:23 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// FromDisk loads the container configuration stored in the host.
|
|
|
|
func (container *Container) FromDisk() error {
|
|
|
|
pth, err := container.ConfigPath()
|
2014-05-27 22:15:42 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-11-04 08:43:58 -05:00
|
|
|
jsonSource, err := os.Open(pth)
|
2013-01-25 17:39:02 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-11-04 08:43:58 -05:00
|
|
|
defer jsonSource.Close()
|
|
|
|
|
|
|
|
dec := json.NewDecoder(jsonSource)
|
|
|
|
|
2013-03-21 03:25:00 -04:00
|
|
|
// Load container settings
|
2015-09-03 05:01:55 -04:00
|
|
|
if err := dec.Decode(container); err != nil {
|
2013-01-25 17:39:02 -05:00
|
|
|
return err
|
|
|
|
}
|
2014-04-28 17:36:04 -04:00
|
|
|
|
|
|
|
if err := label.ReserveLabel(container.ProcessLabel); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-10-31 17:58:43 -04:00
|
|
|
return container.readHostConfig()
|
2013-01-25 17:39:02 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// ToDisk saves the container configuration on disk.
|
|
|
|
func (container *Container) ToDisk() error {
|
|
|
|
pth, err := container.ConfigPath()
|
2013-01-18 19:13:39 -05:00
|
|
|
if err != nil {
|
2014-05-27 22:15:42 -04:00
|
|
|
return err
|
2013-01-18 19:13:39 -05:00
|
|
|
}
|
2014-05-27 22:15:42 -04:00
|
|
|
|
2016-04-20 20:08:47 -04:00
|
|
|
jsonSource, err := ioutils.NewAtomicFileWriter(pth, 0666)
|
2013-10-31 17:58:43 -04:00
|
|
|
if err != nil {
|
2014-05-27 22:15:42 -04:00
|
|
|
return err
|
|
|
|
}
|
2015-10-30 12:04:25 -04:00
|
|
|
defer jsonSource.Close()
|
|
|
|
|
|
|
|
enc := json.NewEncoder(jsonSource)
|
2014-05-27 22:15:42 -04:00
|
|
|
|
2015-10-30 12:04:25 -04:00
|
|
|
// Save container settings
|
|
|
|
if err := enc.Encode(container); err != nil {
|
2014-05-27 22:15:42 -04:00
|
|
|
return err
|
2013-10-31 17:58:43 -04:00
|
|
|
}
|
2014-05-27 22:15:42 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
return container.WriteHostConfig()
|
2013-01-18 19:13:39 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// ToDiskLocking saves the container configuration on disk in a thread safe way.
|
|
|
|
func (container *Container) ToDiskLocking() error {
|
2014-07-11 13:49:24 -04:00
|
|
|
container.Lock()
|
2015-11-12 14:55:17 -05:00
|
|
|
err := container.ToDisk()
|
2014-07-11 13:49:24 -04:00
|
|
|
container.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// readHostConfig reads the host configuration from disk for the container.
|
2013-10-31 17:58:43 -04:00
|
|
|
func (container *Container) readHostConfig() error {
|
2015-12-18 13:36:17 -05:00
|
|
|
container.HostConfig = &containertypes.HostConfig{}
|
2013-10-31 17:58:43 -04:00
|
|
|
// If the hostconfig file does not exist, do not read it.
|
2015-11-12 14:55:17 -05:00
|
|
|
// (We still have to initialize container.HostConfig,
|
2013-10-31 17:58:43 -04:00
|
|
|
// but that's OK, since we just did that above.)
|
2015-11-12 14:55:17 -05:00
|
|
|
pth, err := container.HostConfigPath()
|
2014-05-27 22:15:42 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-04-21 15:59:59 -04:00
|
|
|
f, err := os.Open(pth)
|
2013-07-02 08:19:25 -04:00
|
|
|
if err != nil {
|
2015-10-30 17:54:09 -04:00
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
2013-10-31 17:58:43 -04:00
|
|
|
return err
|
2013-07-02 08:19:25 -04:00
|
|
|
}
|
2015-04-21 15:59:59 -04:00
|
|
|
defer f.Close()
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if err := json.NewDecoder(f).Decode(&container.HostConfig); err != nil {
|
2015-11-06 17:22:48 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
container.InitDNSHostConfig()
|
2015-11-06 17:22:48 -05:00
|
|
|
|
|
|
|
return nil
|
2013-07-02 08:19:25 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// WriteHostConfig saves the host configuration on disk for the container.
|
|
|
|
func (container *Container) WriteHostConfig() error {
|
|
|
|
pth, err := container.HostConfigPath()
|
2013-07-02 08:19:25 -04:00
|
|
|
if err != nil {
|
2014-05-27 22:15:42 -04:00
|
|
|
return err
|
2013-07-02 08:19:25 -04:00
|
|
|
}
|
2014-05-27 22:15:42 -04:00
|
|
|
|
2016-04-20 20:08:47 -04:00
|
|
|
f, err := ioutils.NewAtomicFileWriter(pth, 0666)
|
2014-05-27 22:15:42 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-10-30 17:45:35 -04:00
|
|
|
defer f.Close()
|
2014-05-27 22:15:42 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
return json.NewEncoder(f).Encode(&container.HostConfig)
|
2013-07-02 08:19:25 -04:00
|
|
|
}
|
|
|
|
|
2016-01-27 16:03:09 -05:00
|
|
|
// SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
|
2016-03-08 10:40:30 -05:00
|
|
|
func (container *Container) SetupWorkingDirectory(rootUID, rootGID int) error {
|
2016-01-27 16:03:09 -05:00
|
|
|
if container.Config.WorkingDir == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2016-03-01 13:23:43 -05:00
|
|
|
|
2016-05-26 16:24:22 -04:00
|
|
|
container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
|
|
|
|
|
2016-03-01 13:23:43 -05:00
|
|
|
// If can't mount container FS at this point (eg Hyper-V Containers on
|
|
|
|
// Windows) bail out now with no action.
|
|
|
|
if !container.canMountFS() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-01-27 16:03:09 -05:00
|
|
|
pth, err := container.GetResourcePath(container.Config.WorkingDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-03-08 10:40:30 -05:00
|
|
|
if err := idtools.MkdirAllNewAs(pth, 0755, rootUID, rootGID); err != nil {
|
2016-01-27 16:03:09 -05:00
|
|
|
pthInfo, err2 := os.Stat(pth)
|
|
|
|
if err2 == nil && pthInfo != nil && !pthInfo.IsDir() {
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
|
2016-01-27 16:03:09 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// GetResourcePath evaluates `path` in the scope of the container's BaseFS, with proper path
|
|
|
|
// sanitisation. Symlinks are all scoped to the BaseFS of the container, as
|
|
|
|
// though the container's BaseFS was `/`.
|
2015-03-05 20:53:06 -05:00
|
|
|
//
|
2015-11-12 14:55:17 -05:00
|
|
|
// The BaseFS of a container is the host-facing path which is bind-mounted as
|
2015-03-05 20:53:06 -05:00
|
|
|
// `/` inside the container. This method is essentially used to access a
|
|
|
|
// particular path inside the container as though you were a process in that
|
|
|
|
// container.
|
|
|
|
//
|
2015-11-12 14:55:17 -05:00
|
|
|
// NOTE: The returned path is *only* safely scoped inside the container's BaseFS
|
2015-03-05 20:53:06 -05:00
|
|
|
// if no component of the returned path changes (such as a component
|
|
|
|
// symlinking to a different path) between using this method and using the
|
|
|
|
// path. See symlink.FollowSymlinkInScope for more details.
|
|
|
|
func (container *Container) GetResourcePath(path string) (string, error) {
|
2015-06-01 19:42:27 -04:00
|
|
|
// IMPORTANT - These are paths on the OS where the daemon is running, hence
|
|
|
|
// any filepath operations must be done in an OS agnostic way.
|
2016-01-27 16:03:09 -05:00
|
|
|
|
|
|
|
cleanPath := cleanResourcePath(path)
|
2015-11-12 14:55:17 -05:00
|
|
|
r, e := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, cleanPath), container.BaseFS)
|
2016-04-19 23:55:30 -04:00
|
|
|
|
|
|
|
// Log this here on the daemon side as there's otherwise no indication apart
|
|
|
|
// from the error being propagated all the way back to the client. This makes
|
|
|
|
// debugging significantly easier and clearly indicates the error comes from the daemon.
|
|
|
|
if e != nil {
|
|
|
|
logrus.Errorf("Failed to FollowSymlinkInScope BaseFS %s cleanPath %s path %s %s\n", container.BaseFS, cleanPath, path, e)
|
|
|
|
}
|
2015-06-01 19:42:27 -04:00
|
|
|
return r, e
|
2014-05-11 16:49:46 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
|
2015-03-05 20:53:06 -05:00
|
|
|
// sanitisation. Symlinks are all scoped to the root of the container, as
|
|
|
|
// though the container's root was `/`.
|
|
|
|
//
|
|
|
|
// The root of a container is the host-facing configuration metadata directory.
|
|
|
|
// Only use this method to safely access the container's `container.json` or
|
|
|
|
// other metadata files. If in doubt, use container.GetResourcePath.
|
|
|
|
//
|
|
|
|
// NOTE: The returned path is *only* safely scoped inside the container's root
|
|
|
|
// if no component of the returned path changes (such as a component
|
|
|
|
// symlinking to a different path) between using this method and using the
|
|
|
|
// path. See symlink.FollowSymlinkInScope for more details.
|
2015-11-12 14:55:17 -05:00
|
|
|
func (container *Container) GetRootResourcePath(path string) (string, error) {
|
2015-06-01 19:42:27 -04:00
|
|
|
// IMPORTANT - These are paths on the OS where the daemon is running, hence
|
|
|
|
// any filepath operations must be done in an OS agnostic way.
|
|
|
|
cleanPath := filepath.Join(string(os.PathSeparator), path)
|
2015-11-12 14:55:17 -05:00
|
|
|
return symlink.FollowSymlinkInScope(filepath.Join(container.Root, cleanPath), container.Root)
|
2014-05-11 16:49:46 -04:00
|
|
|
}
|
|
|
|
|
2015-11-02 18:25:26 -05:00
|
|
|
// ExitOnNext signals to the monitor that it should not restart the container
|
|
|
|
// after we send the kill signal.
|
|
|
|
func (container *Container) ExitOnNext() {
|
2016-03-18 14:50:19 -04:00
|
|
|
if container.restartManager != nil {
|
|
|
|
container.restartManager.Cancel()
|
2015-05-24 14:19:39 -04:00
|
|
|
}
|
2013-05-23 22:33:28 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// HostConfigPath returns the path to the container's JSON hostconfig
|
|
|
|
func (container *Container) HostConfigPath() (string, error) {
|
|
|
|
return container.GetRootResourcePath("hostconfig.json")
|
2013-03-21 03:25:00 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// ConfigPath returns the path to the container's JSON config
|
|
|
|
func (container *Container) ConfigPath() (string, error) {
|
|
|
|
return container.GetRootResourcePath(configFileName)
|
2013-03-21 03:25:00 -04:00
|
|
|
}
|
|
|
|
|
2015-11-03 13:45:12 -05:00
|
|
|
// StartLogger starts a new logger driver for the container.
|
2015-12-18 13:36:17 -05:00
|
|
|
func (container *Container) StartLogger(cfg containertypes.LogConfig) (logger.Logger, error) {
|
2015-04-09 00:23:30 -04:00
|
|
|
c, err := logger.GetLogDriver(cfg.Type)
|
|
|
|
if err != nil {
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
return nil, fmt.Errorf("Failed to get logging factory: %v", err)
|
2015-04-09 00:23:30 -04:00
|
|
|
}
|
|
|
|
ctx := logger.Context{
|
2015-05-29 17:00:46 -04:00
|
|
|
Config: cfg.Config,
|
|
|
|
ContainerID: container.ID,
|
|
|
|
ContainerName: container.Name,
|
|
|
|
ContainerEntrypoint: container.Path,
|
|
|
|
ContainerArgs: container.Args,
|
2015-11-18 17:20:54 -05:00
|
|
|
ContainerImageID: container.ImageID.String(),
|
2015-05-29 17:00:46 -04:00
|
|
|
ContainerImageName: container.Config.Image,
|
|
|
|
ContainerCreated: container.Created,
|
2015-08-11 07:27:19 -04:00
|
|
|
ContainerEnv: container.Config.Env,
|
|
|
|
ContainerLabels: container.Config.Labels,
|
2016-04-27 22:46:54 -04:00
|
|
|
DaemonName: "docker",
|
2015-04-09 00:23:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set logging file for "json-logger"
|
|
|
|
if cfg.Type == jsonfilelog.Name {
|
2015-11-12 14:55:17 -05:00
|
|
|
ctx.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
|
2015-04-20 14:26:39 -04:00
|
|
|
if err != nil {
|
2015-04-09 00:23:30 -04:00
|
|
|
return nil, err
|
2015-04-20 14:26:39 -04:00
|
|
|
}
|
2015-04-09 00:23:30 -04:00
|
|
|
}
|
|
|
|
return c(ctx)
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// GetProcessLabel returns the process label for the container.
|
|
|
|
func (container *Container) GetProcessLabel() string {
|
2014-04-29 04:08:19 -04:00
|
|
|
// even if we have a process label return "" if we are running
|
|
|
|
// in privileged mode
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.HostConfig.Privileged {
|
2014-04-29 04:08:19 -04:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return container.ProcessLabel
|
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// GetMountLabel returns the mounting label for the container.
|
|
|
|
// This label is empty if the container is privileged.
|
|
|
|
func (container *Container) GetMountLabel() string {
|
2014-04-29 04:08:19 -04:00
|
|
|
return container.MountLabel
|
|
|
|
}
|
2014-05-02 19:59:28 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// GetExecIDs returns the list of exec commands running on the container.
|
|
|
|
func (container *Container) GetExecIDs() []string {
|
|
|
|
return container.ExecCommands.List()
|
2015-05-04 08:39:51 -04:00
|
|
|
}
|
|
|
|
|
2015-07-30 17:01:53 -04:00
|
|
|
// Attach connects to the container's TTY, delegating to standard
|
|
|
|
// streams or websockets depending on the configuration.
|
2016-01-03 17:03:39 -05:00
|
|
|
func (container *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer, keys []byte) chan error {
|
2016-03-08 19:54:33 -05:00
|
|
|
ctx := container.InitAttachContext()
|
|
|
|
return AttachStreams(ctx, container.StreamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, stdin, stdout, stderr, keys)
|
2015-05-05 16:25:05 -04:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// AttachStreams connects streams to a TTY.
|
|
|
|
// Used by exec too. Should this move somewhere else?
|
2016-03-08 19:54:33 -05:00
|
|
|
func AttachStreams(ctx context.Context, streamConfig *runconfig.StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer, keys []byte) chan error {
|
2015-05-05 16:25:05 -04:00
|
|
|
var (
|
|
|
|
cStdout, cStderr io.ReadCloser
|
|
|
|
cStdin io.WriteCloser
|
|
|
|
wg sync.WaitGroup
|
|
|
|
errors = make(chan error, 3)
|
|
|
|
)
|
|
|
|
|
|
|
|
if stdin != nil && openStdin {
|
|
|
|
cStdin = streamConfig.StdinPipe()
|
|
|
|
wg.Add(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
if stdout != nil {
|
|
|
|
cStdout = streamConfig.StdoutPipe()
|
|
|
|
wg.Add(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
if stderr != nil {
|
|
|
|
cStderr = streamConfig.StderrPipe()
|
|
|
|
wg.Add(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect stdin of container to the http conn.
|
|
|
|
go func() {
|
|
|
|
if stdin == nil || !openStdin {
|
|
|
|
return
|
|
|
|
}
|
2016-06-11 16:16:55 -04:00
|
|
|
logrus.Debug("attach: stdin: begin")
|
2015-05-05 16:25:05 -04:00
|
|
|
|
|
|
|
var err error
|
|
|
|
if tty {
|
2016-01-03 17:03:39 -05:00
|
|
|
_, err = copyEscapable(cStdin, stdin, keys)
|
2015-05-05 16:25:05 -04:00
|
|
|
} else {
|
|
|
|
_, err = io.Copy(cStdin, stdin)
|
|
|
|
}
|
|
|
|
if err == io.ErrClosedPipe {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("attach: stdin: %s", err)
|
|
|
|
errors <- err
|
|
|
|
}
|
2016-03-08 19:54:33 -05:00
|
|
|
if stdinOnce && !tty {
|
|
|
|
cStdin.Close()
|
|
|
|
} else {
|
|
|
|
// No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
|
|
|
|
if cStdout != nil {
|
|
|
|
cStdout.Close()
|
|
|
|
}
|
|
|
|
if cStderr != nil {
|
|
|
|
cStderr.Close()
|
|
|
|
}
|
|
|
|
}
|
2016-06-11 16:16:55 -04:00
|
|
|
logrus.Debug("attach: stdin: end")
|
2016-03-08 19:54:33 -05:00
|
|
|
wg.Done()
|
2015-05-05 16:25:05 -04:00
|
|
|
}()
|
|
|
|
|
|
|
|
attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) {
|
|
|
|
if stream == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.Debugf("attach: %s: begin", name)
|
|
|
|
_, err := io.Copy(stream, streamPipe)
|
|
|
|
if err == io.ErrClosedPipe {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("attach: %s: %v", name, err)
|
|
|
|
errors <- err
|
|
|
|
}
|
2016-03-08 19:54:33 -05:00
|
|
|
// Make sure stdin gets closed
|
|
|
|
if stdin != nil {
|
|
|
|
stdin.Close()
|
|
|
|
}
|
|
|
|
streamPipe.Close()
|
|
|
|
logrus.Debugf("attach: %s: end", name)
|
|
|
|
wg.Done()
|
2015-05-05 16:25:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
go attachStream("stdout", stdout, cStdout)
|
|
|
|
go attachStream("stderr", stderr, cStderr)
|
|
|
|
|
|
|
|
return promise.Go(func() error {
|
2016-03-08 19:54:33 -05:00
|
|
|
done := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
wg.Wait()
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
case <-ctx.Done():
|
|
|
|
// close all pipes
|
|
|
|
if cStdin != nil {
|
|
|
|
cStdin.Close()
|
|
|
|
}
|
|
|
|
if cStdout != nil {
|
|
|
|
cStdout.Close()
|
|
|
|
}
|
|
|
|
if cStderr != nil {
|
|
|
|
cStderr.Close()
|
|
|
|
}
|
|
|
|
<-done
|
|
|
|
}
|
2015-05-05 16:25:05 -04:00
|
|
|
close(errors)
|
|
|
|
for err := range errors {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Code c/c from io.Copy() modified to handle escape sequence
|
2016-01-03 17:03:39 -05:00
|
|
|
func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64, err error) {
|
|
|
|
if len(keys) == 0 {
|
|
|
|
// Default keys : ctrl-p ctrl-q
|
|
|
|
keys = []byte{16, 17}
|
|
|
|
}
|
2015-05-05 16:25:05 -04:00
|
|
|
buf := make([]byte, 32*1024)
|
|
|
|
for {
|
|
|
|
nr, er := src.Read(buf)
|
|
|
|
if nr > 0 {
|
|
|
|
// ---- Docker addition
|
2016-05-24 11:14:48 -04:00
|
|
|
preservBuf := []byte{}
|
2016-01-03 17:03:39 -05:00
|
|
|
for i, key := range keys {
|
2016-05-24 11:14:48 -04:00
|
|
|
preservBuf = append(preservBuf, buf[0:nr]...)
|
2016-01-03 17:03:39 -05:00
|
|
|
if nr != 1 || buf[0] != key {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if i == len(keys)-1 {
|
2016-05-22 10:04:39 -04:00
|
|
|
src.Close()
|
2016-06-03 13:11:52 -04:00
|
|
|
return 0, DetachError{}
|
2015-05-05 16:25:05 -04:00
|
|
|
}
|
2016-01-03 17:03:39 -05:00
|
|
|
nr, er = src.Read(buf)
|
2015-05-05 16:25:05 -04:00
|
|
|
}
|
2016-05-24 11:14:48 -04:00
|
|
|
var nw int
|
|
|
|
var ew error
|
|
|
|
if len(preservBuf) > 0 {
|
|
|
|
nw, ew = dst.Write(preservBuf)
|
|
|
|
nr = len(preservBuf)
|
|
|
|
} else {
|
|
|
|
// ---- End of docker
|
|
|
|
nw, ew = dst.Write(buf[0:nr])
|
|
|
|
}
|
2015-05-05 16:25:05 -04:00
|
|
|
if nw > 0 {
|
|
|
|
written += int64(nw)
|
|
|
|
}
|
|
|
|
if ew != nil {
|
|
|
|
err = ew
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if nr != nw {
|
|
|
|
err = io.ErrShortWrite
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if er == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if er != nil {
|
|
|
|
err = er
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return written, err
|
|
|
|
}
|
2015-05-19 16:05:25 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// ShouldRestart decides whether the daemon should restart the container or not.
|
|
|
|
// This is based on the container's restart policy.
|
|
|
|
func (container *Container) ShouldRestart() bool {
|
2016-06-14 14:11:43 -04:00
|
|
|
shouldRestart, _, _ := container.restartManager.ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
|
2016-03-22 11:46:40 -04:00
|
|
|
return shouldRestart
|
2015-05-19 16:05:25 -04:00
|
|
|
}
|
2015-05-22 13:37:00 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// AddMountPointWithVolume adds a new mount point configured with a volume to the container.
|
|
|
|
func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
|
2015-09-09 22:23:06 -04:00
|
|
|
container.MountPoints[destination] = &volume.MountPoint{
|
|
|
|
Name: vol.Name(),
|
|
|
|
Driver: vol.DriverName(),
|
|
|
|
Destination: destination,
|
|
|
|
RW: rw,
|
|
|
|
Volume: vol,
|
2016-03-14 23:31:42 -04:00
|
|
|
CopyData: volume.DefaultCopyMode,
|
2015-09-09 22:23:06 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-13 11:00:39 -05:00
|
|
|
// IsDestinationMounted checks whether a path is mounted on the container or not.
|
2015-11-12 14:55:17 -05:00
|
|
|
func (container *Container) IsDestinationMounted(destination string) bool {
|
2015-09-09 22:23:06 -04:00
|
|
|
return container.MountPoints[destination] != nil
|
2015-05-22 13:37:00 -04:00
|
|
|
}
|
2015-08-04 16:51:48 -04:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// StopSignal returns the signal used to stop the container.
|
|
|
|
func (container *Container) StopSignal() int {
|
2015-08-04 16:51:48 -04:00
|
|
|
var stopSignal syscall.Signal
|
|
|
|
if container.Config.StopSignal != "" {
|
|
|
|
stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
|
|
|
|
}
|
|
|
|
|
|
|
|
if int(stopSignal) == 0 {
|
|
|
|
stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
|
|
|
|
}
|
|
|
|
return int(stopSignal)
|
|
|
|
}
|
2015-11-30 17:44:34 -05:00
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
// InitDNSHostConfig ensures that the dns fields are never nil.
|
2015-11-30 17:44:34 -05:00
|
|
|
// New containers don't ever have those fields nil,
|
|
|
|
// but pre created containers can still have those nil values.
|
|
|
|
// The non-recommended host configuration in the start api can
|
|
|
|
// make these fields nil again, this corrects that issue until
|
|
|
|
// we remove that behavior for good.
|
|
|
|
// See https://github.com/docker/docker/pull/17779
|
|
|
|
// for a more detailed explanation on why we don't want that.
|
2015-11-12 14:55:17 -05:00
|
|
|
func (container *Container) InitDNSHostConfig() {
|
2015-12-10 21:33:13 -05:00
|
|
|
container.Lock()
|
|
|
|
defer container.Unlock()
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.HostConfig.DNS == nil {
|
|
|
|
container.HostConfig.DNS = make([]string, 0)
|
2015-11-30 17:44:34 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.HostConfig.DNSSearch == nil {
|
|
|
|
container.HostConfig.DNSSearch = make([]string, 0)
|
2015-11-30 17:44:34 -05:00
|
|
|
}
|
|
|
|
|
2015-11-12 14:55:17 -05:00
|
|
|
if container.HostConfig.DNSOptions == nil {
|
|
|
|
container.HostConfig.DNSOptions = make([]string, 0)
|
2015-11-30 17:44:34 -05:00
|
|
|
}
|
|
|
|
}
|
2016-01-04 10:58:20 -05:00
|
|
|
|
2016-03-09 23:33:21 -05:00
|
|
|
// GetEndpointInNetwork returns the container's endpoint to the provided network.
|
|
|
|
func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
|
|
|
|
endpointName := strings.TrimPrefix(container.Name, "/")
|
|
|
|
return n.EndpointByName(endpointName)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
|
|
|
|
if ep == nil {
|
|
|
|
return errInvalidEndpoint
|
|
|
|
}
|
|
|
|
|
|
|
|
networkSettings := container.NetworkSettings
|
|
|
|
if networkSettings == nil {
|
|
|
|
return errInvalidNetwork
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(networkSettings.Ports) == 0 {
|
|
|
|
pm, err := getEndpointPortMapInfo(ep)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
networkSettings.Ports = pm
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) {
|
|
|
|
pm := nat.PortMap{}
|
|
|
|
driverInfo, err := ep.DriverInfo()
|
|
|
|
if err != nil {
|
|
|
|
return pm, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if driverInfo == nil {
|
|
|
|
// It is not an error for epInfo to be nil
|
|
|
|
return pm, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
|
|
|
|
if exposedPorts, ok := expData.([]types.TransportPort); ok {
|
|
|
|
for _, tp := range exposedPorts {
|
|
|
|
natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
|
|
|
|
if err != nil {
|
|
|
|
return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
|
|
|
|
}
|
|
|
|
pm[natPort] = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
mapData, ok := driverInfo[netlabel.PortMap]
|
|
|
|
if !ok {
|
|
|
|
return pm, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if portMapping, ok := mapData.([]types.PortBinding); ok {
|
|
|
|
for _, pp := range portMapping {
|
|
|
|
natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
|
|
|
|
if err != nil {
|
|
|
|
return pm, err
|
|
|
|
}
|
|
|
|
natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
|
|
|
|
pm[natPort] = append(pm[natPort], natBndg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return pm, nil
|
|
|
|
}
|
|
|
|
|
2016-05-25 16:47:38 -04:00
|
|
|
// GetSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox
|
|
|
|
func GetSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap {
|
2016-03-09 23:33:21 -05:00
|
|
|
pm := nat.PortMap{}
|
|
|
|
if sb == nil {
|
|
|
|
return pm
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ep := range sb.Endpoints() {
|
|
|
|
pm, _ = getEndpointPortMapInfo(ep)
|
|
|
|
if len(pm) > 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return pm
|
|
|
|
}
|
|
|
|
|
|
|
|
// BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
|
|
|
|
func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
|
|
|
|
if ep == nil {
|
|
|
|
return errInvalidEndpoint
|
|
|
|
}
|
|
|
|
|
|
|
|
networkSettings := container.NetworkSettings
|
|
|
|
if networkSettings == nil {
|
|
|
|
return errInvalidNetwork
|
|
|
|
}
|
|
|
|
|
|
|
|
epInfo := ep.Info()
|
|
|
|
if epInfo == nil {
|
|
|
|
// It is not an error to get an empty endpoint info
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := networkSettings.Networks[n.Name()]; !ok {
|
|
|
|
networkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
|
|
|
|
}
|
|
|
|
networkSettings.Networks[n.Name()].NetworkID = n.ID()
|
|
|
|
networkSettings.Networks[n.Name()].EndpointID = ep.ID()
|
|
|
|
|
|
|
|
iface := epInfo.Iface()
|
|
|
|
if iface == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if iface.MacAddress() != nil {
|
|
|
|
networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
if iface.Address() != nil {
|
|
|
|
ones, _ := iface.Address().Mask.Size()
|
|
|
|
networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
|
|
|
|
networkSettings.Networks[n.Name()].IPPrefixLen = ones
|
|
|
|
}
|
|
|
|
|
|
|
|
if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
|
|
|
|
onesv6, _ := iface.AddressIPv6().Mask.Size()
|
|
|
|
networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
|
|
|
|
networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
|
|
|
|
func (container *Container) UpdateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
|
|
|
|
if err := container.buildPortMapInfo(ep); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
epInfo := ep.Info()
|
|
|
|
if epInfo == nil {
|
|
|
|
// It is not an error to get an empty endpoint info
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if epInfo.Gateway() != nil {
|
|
|
|
container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
|
|
|
|
}
|
|
|
|
if epInfo.GatewayIPv6().To16() != nil {
|
|
|
|
container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateSandboxNetworkSettings updates the sandbox ID and Key.
|
|
|
|
func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
|
|
|
|
container.NetworkSettings.SandboxID = sb.ID()
|
|
|
|
container.NetworkSettings.SandboxKey = sb.Key()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// BuildJoinOptions builds endpoint Join options from a given network.
|
|
|
|
func (container *Container) BuildJoinOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
|
|
|
|
var joinOptions []libnetwork.EndpointOption
|
|
|
|
if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok {
|
|
|
|
for _, str := range epConfig.Links {
|
|
|
|
name, alias, err := runconfigopts.ParseLink(str)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return joinOptions, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// BuildCreateEndpointOptions builds endpoint options from a given network.
|
|
|
|
func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network, epConfig *networktypes.EndpointSettings, sb libnetwork.Sandbox) ([]libnetwork.EndpointOption, error) {
|
|
|
|
var (
|
|
|
|
bindings = make(nat.PortMap)
|
|
|
|
pbList []types.PortBinding
|
|
|
|
exposeList []types.TransportPort
|
|
|
|
createOptions []libnetwork.EndpointOption
|
|
|
|
)
|
|
|
|
|
|
|
|
defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
|
|
|
|
|
|
|
|
if n.Name() == defaultNetName || container.NetworkSettings.IsAnonymousEndpoint {
|
|
|
|
createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
|
|
|
|
}
|
|
|
|
|
|
|
|
if epConfig != nil {
|
|
|
|
ipam := epConfig.IPAMConfig
|
2016-06-09 18:10:59 -04:00
|
|
|
if ipam != nil && (ipam.IPv4Address != "" || ipam.IPv6Address != "" || len(ipam.LinkLocalIPs) > 0) {
|
|
|
|
var ipList []net.IP
|
|
|
|
for _, ips := range ipam.LinkLocalIPs {
|
|
|
|
if ip := net.ParseIP(ips); ip != nil {
|
|
|
|
ipList = append(ipList, ip)
|
|
|
|
}
|
|
|
|
}
|
2016-03-09 23:33:21 -05:00
|
|
|
createOptions = append(createOptions,
|
2016-06-09 18:10:59 -04:00
|
|
|
libnetwork.CreateOptionIpam(net.ParseIP(ipam.IPv4Address), net.ParseIP(ipam.IPv6Address), ipList, nil))
|
2016-03-09 23:33:21 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, alias := range epConfig.Aliases {
|
|
|
|
createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-13 22:52:49 -04:00
|
|
|
if container.NetworkSettings.Service != nil {
|
|
|
|
svcCfg := container.NetworkSettings.Service
|
|
|
|
|
|
|
|
var vip string
|
|
|
|
if svcCfg.VirtualAddresses[n.ID()] != nil {
|
|
|
|
vip = svcCfg.VirtualAddresses[n.ID()].IPv4
|
|
|
|
}
|
|
|
|
|
|
|
|
var portConfigs []*libnetwork.PortConfig
|
|
|
|
for _, portConfig := range svcCfg.ExposedPorts {
|
|
|
|
portConfigs = append(portConfigs, &libnetwork.PortConfig{
|
|
|
|
Name: portConfig.Name,
|
|
|
|
Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol),
|
|
|
|
TargetPort: portConfig.TargetPort,
|
|
|
|
PublishedPort: portConfig.PublishedPort,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-06-14 17:55:05 -04:00
|
|
|
createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()]))
|
2016-06-13 22:52:49 -04:00
|
|
|
}
|
|
|
|
|
2016-03-09 23:33:21 -05:00
|
|
|
if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
|
|
|
|
createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution())
|
|
|
|
}
|
|
|
|
|
|
|
|
// configs that are applicable only for the endpoint in the network
|
|
|
|
// to which container was connected to on docker run.
|
|
|
|
// Ideally all these network-specific endpoint configurations must be moved under
|
|
|
|
// container.NetworkSettings.Networks[n.Name()]
|
|
|
|
if n.Name() == container.HostConfig.NetworkMode.NetworkName() ||
|
|
|
|
(n.Name() == defaultNetName && container.HostConfig.NetworkMode.IsDefault()) {
|
|
|
|
if container.Config.MacAddress != "" {
|
|
|
|
mac, err := net.ParseMAC(container.Config.MacAddress)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
genericOption := options.Generic{
|
|
|
|
netlabel.MacAddress: mac,
|
|
|
|
}
|
|
|
|
|
|
|
|
createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Port-mapping rules belong to the container & applicable only to non-internal networks
|
2016-05-25 16:47:38 -04:00
|
|
|
portmaps := GetSandboxPortMapInfo(sb)
|
2016-03-09 23:33:21 -05:00
|
|
|
if n.Info().Internal() || len(portmaps) > 0 {
|
|
|
|
return createOptions, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if container.HostConfig.PortBindings != nil {
|
|
|
|
for p, b := range container.HostConfig.PortBindings {
|
|
|
|
bindings[p] = []nat.PortBinding{}
|
|
|
|
for _, bb := range b {
|
|
|
|
bindings[p] = append(bindings[p], nat.PortBinding{
|
|
|
|
HostIP: bb.HostIP,
|
|
|
|
HostPort: bb.HostPort,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
portSpecs := container.Config.ExposedPorts
|
|
|
|
ports := make([]nat.Port, len(portSpecs))
|
|
|
|
var i int
|
|
|
|
for p := range portSpecs {
|
|
|
|
ports[i] = p
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
nat.SortPortMap(ports, bindings)
|
|
|
|
for _, port := range ports {
|
|
|
|
expose := types.TransportPort{}
|
|
|
|
expose.Proto = types.ParseProtocol(port.Proto())
|
|
|
|
expose.Port = uint16(port.Int())
|
|
|
|
exposeList = append(exposeList, expose)
|
|
|
|
|
|
|
|
pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
|
|
|
|
binding := bindings[port]
|
|
|
|
for i := 0; i < len(binding); i++ {
|
|
|
|
pbCopy := pb.GetCopy()
|
|
|
|
newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
|
|
|
|
var portStart, portEnd int
|
|
|
|
if err == nil {
|
|
|
|
portStart, portEnd, err = newP.Range()
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
|
|
|
|
}
|
|
|
|
pbCopy.HostPort = uint16(portStart)
|
|
|
|
pbCopy.HostPortEnd = uint16(portEnd)
|
|
|
|
pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
|
|
|
|
pbList = append(pbList, pbCopy)
|
|
|
|
}
|
|
|
|
|
|
|
|
if container.HostConfig.PublishAllPorts && len(binding) == 0 {
|
|
|
|
pbList = append(pbList, pb)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
createOptions = append(createOptions,
|
|
|
|
libnetwork.CreateOptionPortMapping(pbList),
|
|
|
|
libnetwork.CreateOptionExposedPorts(exposeList))
|
|
|
|
|
|
|
|
return createOptions, nil
|
|
|
|
}
|
|
|
|
|
2016-01-04 10:58:20 -05:00
|
|
|
// UpdateMonitor updates monitor configure for running container
|
|
|
|
func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
|
2016-03-18 14:50:19 -04:00
|
|
|
type policySetter interface {
|
|
|
|
SetPolicy(containertypes.RestartPolicy)
|
|
|
|
}
|
|
|
|
|
|
|
|
if rm, ok := container.RestartManager(false).(policySetter); ok {
|
|
|
|
rm.SetPolicy(restartPolicy)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FullHostname returns hostname and optional domain appended to it.
|
|
|
|
func (container *Container) FullHostname() string {
|
|
|
|
fullHostname := container.Config.Hostname
|
|
|
|
if container.Config.Domainname != "" {
|
|
|
|
fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
|
2016-01-04 10:58:20 -05:00
|
|
|
}
|
2016-03-18 14:50:19 -04:00
|
|
|
return fullHostname
|
|
|
|
}
|
2016-01-04 10:58:20 -05:00
|
|
|
|
2016-04-08 10:08:58 -04:00
|
|
|
// RestartManager returns the current restartmanager instance connected to container.
|
2016-03-18 14:50:19 -04:00
|
|
|
func (container *Container) RestartManager(reset bool) restartmanager.RestartManager {
|
|
|
|
if reset {
|
|
|
|
container.RestartCount = 0
|
2016-04-07 19:12:05 -04:00
|
|
|
container.restartManager = nil
|
2016-03-18 14:50:19 -04:00
|
|
|
}
|
|
|
|
if container.restartManager == nil {
|
2016-03-22 11:46:40 -04:00
|
|
|
container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
|
2016-01-04 10:58:20 -05:00
|
|
|
}
|
2016-03-22 11:46:40 -04:00
|
|
|
|
2016-03-18 14:50:19 -04:00
|
|
|
return container.restartManager
|
2016-01-04 10:58:20 -05:00
|
|
|
}
|
2016-03-08 19:54:33 -05:00
|
|
|
|
|
|
|
type attachContext struct {
|
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// InitAttachContext initialize or returns existing context for attach calls to
|
|
|
|
// track container liveness.
|
|
|
|
func (container *Container) InitAttachContext() context.Context {
|
|
|
|
container.attachContext.mu.Lock()
|
|
|
|
defer container.attachContext.mu.Unlock()
|
|
|
|
if container.attachContext.ctx == nil {
|
|
|
|
container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
|
|
|
|
}
|
|
|
|
return container.attachContext.ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
// CancelAttachContext cancel attach context. All attach calls should detach
|
|
|
|
// after this call.
|
|
|
|
func (container *Container) CancelAttachContext() {
|
|
|
|
container.attachContext.mu.Lock()
|
|
|
|
if container.attachContext.ctx != nil {
|
|
|
|
container.attachContext.cancel()
|
|
|
|
container.attachContext.ctx = nil
|
|
|
|
}
|
|
|
|
container.attachContext.mu.Unlock()
|
|
|
|
}
|