container.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. package container
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. "golang.org/x/net/context"
  15. "github.com/Sirupsen/logrus"
  16. containertypes "github.com/docker/docker/api/types/container"
  17. mounttypes "github.com/docker/docker/api/types/mount"
  18. networktypes "github.com/docker/docker/api/types/network"
  19. swarmtypes "github.com/docker/docker/api/types/swarm"
  20. "github.com/docker/docker/container/stream"
  21. "github.com/docker/docker/daemon/exec"
  22. "github.com/docker/docker/daemon/logger"
  23. "github.com/docker/docker/daemon/logger/jsonfilelog"
  24. "github.com/docker/docker/daemon/network"
  25. "github.com/docker/docker/image"
  26. "github.com/docker/docker/layer"
  27. "github.com/docker/docker/libcontainerd"
  28. "github.com/docker/docker/opts"
  29. "github.com/docker/docker/pkg/idtools"
  30. "github.com/docker/docker/pkg/ioutils"
  31. "github.com/docker/docker/pkg/signal"
  32. "github.com/docker/docker/pkg/symlink"
  33. "github.com/docker/docker/restartmanager"
  34. "github.com/docker/docker/runconfig"
  35. "github.com/docker/docker/volume"
  36. "github.com/docker/go-connections/nat"
  37. "github.com/docker/go-units"
  38. "github.com/docker/libnetwork"
  39. "github.com/docker/libnetwork/netlabel"
  40. "github.com/docker/libnetwork/options"
  41. "github.com/docker/libnetwork/types"
  42. agentexec "github.com/docker/swarmkit/agent/exec"
  43. "github.com/opencontainers/selinux/go-selinux/label"
  44. )
  45. const configFileName = "config.v2.json"
  46. const (
  47. // DefaultStopTimeout is the timeout (in seconds) for the syscall signal used to stop a container.
  48. DefaultStopTimeout = 10
  49. )
  50. var (
  51. errInvalidEndpoint = fmt.Errorf("invalid endpoint while building port map info")
  52. errInvalidNetwork = fmt.Errorf("invalid network settings while building port map info")
  53. )
  54. // CommonContainer holds the fields for a container which are
  55. // applicable across all platforms supported by the daemon.
  56. type CommonContainer struct {
  57. StreamConfig *stream.Config
  58. // embed for Container to support states directly.
  59. *State `json:"State"` // Needed for Engine API version <= 1.11
  60. Root string `json:"-"` // Path to the "home" of the container, including metadata.
  61. BaseFS string `json:"-"` // Path to the graphdriver mountpoint
  62. RWLayer layer.RWLayer `json:"-"`
  63. ID string
  64. Created time.Time
  65. Managed bool
  66. Path string
  67. Args []string
  68. Config *containertypes.Config
  69. ImageID image.ID `json:"Image"`
  70. NetworkSettings *network.Settings
  71. LogPath string
  72. Name string
  73. Driver string
  74. // MountLabel contains the options for the 'mount' command
  75. MountLabel string
  76. ProcessLabel string
  77. RestartCount int
  78. HasBeenStartedBefore bool
  79. HasBeenManuallyStopped bool // used for unless-stopped restart policy
  80. MountPoints map[string]*volume.MountPoint
  81. HostConfig *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
  82. ExecCommands *exec.Store `json:"-"`
  83. DependencyStore agentexec.DependencyGetter `json:"-"`
  84. SecretReferences []*swarmtypes.SecretReference
  85. ConfigReferences []*swarmtypes.ConfigReference
  86. // logDriver for closing
  87. LogDriver logger.Logger `json:"-"`
  88. LogCopier *logger.Copier `json:"-"`
  89. restartManager restartmanager.RestartManager
  90. attachContext *attachContext
  91. }
  92. // NewBaseContainer creates a new container with its
  93. // basic configuration.
  94. func NewBaseContainer(id, root string) *Container {
  95. return &Container{
  96. CommonContainer: CommonContainer{
  97. ID: id,
  98. State: NewState(),
  99. ExecCommands: exec.NewStore(),
  100. Root: root,
  101. MountPoints: make(map[string]*volume.MountPoint),
  102. StreamConfig: stream.NewConfig(),
  103. attachContext: &attachContext{},
  104. },
  105. }
  106. }
  107. // FromDisk loads the container configuration stored in the host.
  108. func (container *Container) FromDisk() error {
  109. pth, err := container.ConfigPath()
  110. if err != nil {
  111. return err
  112. }
  113. jsonSource, err := os.Open(pth)
  114. if err != nil {
  115. return err
  116. }
  117. defer jsonSource.Close()
  118. dec := json.NewDecoder(jsonSource)
  119. // Load container settings
  120. if err := dec.Decode(container); err != nil {
  121. return err
  122. }
  123. if err := label.ReserveLabel(container.ProcessLabel); err != nil {
  124. return err
  125. }
  126. return container.readHostConfig()
  127. }
  128. // ToDisk saves the container configuration on disk.
  129. func (container *Container) ToDisk() error {
  130. pth, err := container.ConfigPath()
  131. if err != nil {
  132. return err
  133. }
  134. jsonSource, err := ioutils.NewAtomicFileWriter(pth, 0644)
  135. if err != nil {
  136. return err
  137. }
  138. defer jsonSource.Close()
  139. enc := json.NewEncoder(jsonSource)
  140. // Save container settings
  141. if err := enc.Encode(container); err != nil {
  142. return err
  143. }
  144. return container.WriteHostConfig()
  145. }
  146. // ToDiskLocking saves the container configuration on disk in a thread safe way.
  147. func (container *Container) ToDiskLocking() error {
  148. container.Lock()
  149. err := container.ToDisk()
  150. container.Unlock()
  151. return err
  152. }
  153. // readHostConfig reads the host configuration from disk for the container.
  154. func (container *Container) readHostConfig() error {
  155. container.HostConfig = &containertypes.HostConfig{}
  156. // If the hostconfig file does not exist, do not read it.
  157. // (We still have to initialize container.HostConfig,
  158. // but that's OK, since we just did that above.)
  159. pth, err := container.HostConfigPath()
  160. if err != nil {
  161. return err
  162. }
  163. f, err := os.Open(pth)
  164. if err != nil {
  165. if os.IsNotExist(err) {
  166. return nil
  167. }
  168. return err
  169. }
  170. defer f.Close()
  171. if err := json.NewDecoder(f).Decode(&container.HostConfig); err != nil {
  172. return err
  173. }
  174. container.InitDNSHostConfig()
  175. return nil
  176. }
  177. // WriteHostConfig saves the host configuration on disk for the container.
  178. func (container *Container) WriteHostConfig() error {
  179. pth, err := container.HostConfigPath()
  180. if err != nil {
  181. return err
  182. }
  183. f, err := ioutils.NewAtomicFileWriter(pth, 0644)
  184. if err != nil {
  185. return err
  186. }
  187. defer f.Close()
  188. return json.NewEncoder(f).Encode(&container.HostConfig)
  189. }
  190. // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
  191. func (container *Container) SetupWorkingDirectory(rootUID, rootGID int) error {
  192. if container.Config.WorkingDir == "" {
  193. return nil
  194. }
  195. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  196. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  197. if err != nil {
  198. return err
  199. }
  200. if err := idtools.MkdirAllNewAs(pth, 0755, rootUID, rootGID); err != nil {
  201. pthInfo, err2 := os.Stat(pth)
  202. if err2 == nil && pthInfo != nil && !pthInfo.IsDir() {
  203. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  204. }
  205. return err
  206. }
  207. return nil
  208. }
  209. // GetResourcePath evaluates `path` in the scope of the container's BaseFS, with proper path
  210. // sanitisation. Symlinks are all scoped to the BaseFS of the container, as
  211. // though the container's BaseFS was `/`.
  212. //
  213. // The BaseFS of a container is the host-facing path which is bind-mounted as
  214. // `/` inside the container. This method is essentially used to access a
  215. // particular path inside the container as though you were a process in that
  216. // container.
  217. //
  218. // NOTE: The returned path is *only* safely scoped inside the container's BaseFS
  219. // if no component of the returned path changes (such as a component
  220. // symlinking to a different path) between using this method and using the
  221. // path. See symlink.FollowSymlinkInScope for more details.
  222. func (container *Container) GetResourcePath(path string) (string, error) {
  223. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  224. // any filepath operations must be done in an OS agnostic way.
  225. cleanPath := cleanResourcePath(path)
  226. r, e := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, cleanPath), container.BaseFS)
  227. // Log this here on the daemon side as there's otherwise no indication apart
  228. // from the error being propagated all the way back to the client. This makes
  229. // debugging significantly easier and clearly indicates the error comes from the daemon.
  230. if e != nil {
  231. logrus.Errorf("Failed to FollowSymlinkInScope BaseFS %s cleanPath %s path %s %s\n", container.BaseFS, cleanPath, path, e)
  232. }
  233. return r, e
  234. }
  235. // GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
  236. // sanitisation. Symlinks are all scoped to the root of the container, as
  237. // though the container's root was `/`.
  238. //
  239. // The root of a container is the host-facing configuration metadata directory.
  240. // Only use this method to safely access the container's `container.json` or
  241. // other metadata files. If in doubt, use container.GetResourcePath.
  242. //
  243. // NOTE: The returned path is *only* safely scoped inside the container's root
  244. // if no component of the returned path changes (such as a component
  245. // symlinking to a different path) between using this method and using the
  246. // path. See symlink.FollowSymlinkInScope for more details.
  247. func (container *Container) GetRootResourcePath(path string) (string, error) {
  248. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  249. // any filepath operations must be done in an OS agnostic way.
  250. cleanPath := filepath.Join(string(os.PathSeparator), path)
  251. return symlink.FollowSymlinkInScope(filepath.Join(container.Root, cleanPath), container.Root)
  252. }
  253. // ExitOnNext signals to the monitor that it should not restart the container
  254. // after we send the kill signal.
  255. func (container *Container) ExitOnNext() {
  256. container.RestartManager().Cancel()
  257. }
  258. // HostConfigPath returns the path to the container's JSON hostconfig
  259. func (container *Container) HostConfigPath() (string, error) {
  260. return container.GetRootResourcePath("hostconfig.json")
  261. }
  262. // ConfigPath returns the path to the container's JSON config
  263. func (container *Container) ConfigPath() (string, error) {
  264. return container.GetRootResourcePath(configFileName)
  265. }
  266. // CheckpointDir returns the directory checkpoints are stored in
  267. func (container *Container) CheckpointDir() string {
  268. return filepath.Join(container.Root, "checkpoints")
  269. }
  270. // StartLogger starts a new logger driver for the container.
  271. func (container *Container) StartLogger() (logger.Logger, error) {
  272. cfg := container.HostConfig.LogConfig
  273. initDriver, err := logger.GetLogDriver(cfg.Type)
  274. if err != nil {
  275. return nil, fmt.Errorf("failed to get logging factory: %v", err)
  276. }
  277. info := logger.Info{
  278. Config: cfg.Config,
  279. ContainerID: container.ID,
  280. ContainerName: container.Name,
  281. ContainerEntrypoint: container.Path,
  282. ContainerArgs: container.Args,
  283. ContainerImageID: container.ImageID.String(),
  284. ContainerImageName: container.Config.Image,
  285. ContainerCreated: container.Created,
  286. ContainerEnv: container.Config.Env,
  287. ContainerLabels: container.Config.Labels,
  288. DaemonName: "docker",
  289. }
  290. // Set logging file for "json-logger"
  291. if cfg.Type == jsonfilelog.Name {
  292. info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  293. if err != nil {
  294. return nil, err
  295. }
  296. }
  297. l, err := initDriver(info)
  298. if err != nil {
  299. return nil, err
  300. }
  301. if containertypes.LogMode(cfg.Config["mode"]) == containertypes.LogModeNonBlock {
  302. bufferSize := int64(-1)
  303. if s, exists := cfg.Config["max-buffer-size"]; exists {
  304. bufferSize, err = units.RAMInBytes(s)
  305. if err != nil {
  306. return nil, err
  307. }
  308. }
  309. l = logger.NewRingLogger(l, info, bufferSize)
  310. }
  311. return l, nil
  312. }
  313. // GetProcessLabel returns the process label for the container.
  314. func (container *Container) GetProcessLabel() string {
  315. // even if we have a process label return "" if we are running
  316. // in privileged mode
  317. if container.HostConfig.Privileged {
  318. return ""
  319. }
  320. return container.ProcessLabel
  321. }
  322. // GetMountLabel returns the mounting label for the container.
  323. // This label is empty if the container is privileged.
  324. func (container *Container) GetMountLabel() string {
  325. return container.MountLabel
  326. }
  327. // GetExecIDs returns the list of exec commands running on the container.
  328. func (container *Container) GetExecIDs() []string {
  329. return container.ExecCommands.List()
  330. }
  331. // ShouldRestart decides whether the daemon should restart the container or not.
  332. // This is based on the container's restart policy.
  333. func (container *Container) ShouldRestart() bool {
  334. shouldRestart, _, _ := container.RestartManager().ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
  335. return shouldRestart
  336. }
  337. // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
  338. func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  339. container.MountPoints[destination] = &volume.MountPoint{
  340. Type: mounttypes.TypeVolume,
  341. Name: vol.Name(),
  342. Driver: vol.DriverName(),
  343. Destination: destination,
  344. RW: rw,
  345. Volume: vol,
  346. CopyData: volume.DefaultCopyMode,
  347. }
  348. }
  349. // UnmountVolumes unmounts all volumes
  350. func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
  351. var errors []string
  352. for _, volumeMount := range container.MountPoints {
  353. if volumeMount.Volume == nil {
  354. continue
  355. }
  356. if err := volumeMount.Cleanup(); err != nil {
  357. errors = append(errors, err.Error())
  358. continue
  359. }
  360. attributes := map[string]string{
  361. "driver": volumeMount.Volume.DriverName(),
  362. "container": container.ID,
  363. }
  364. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  365. }
  366. if len(errors) > 0 {
  367. return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
  368. }
  369. return nil
  370. }
  371. // IsDestinationMounted checks whether a path is mounted on the container or not.
  372. func (container *Container) IsDestinationMounted(destination string) bool {
  373. return container.MountPoints[destination] != nil
  374. }
  375. // StopSignal returns the signal used to stop the container.
  376. func (container *Container) StopSignal() int {
  377. var stopSignal syscall.Signal
  378. if container.Config.StopSignal != "" {
  379. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  380. }
  381. if int(stopSignal) == 0 {
  382. stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
  383. }
  384. return int(stopSignal)
  385. }
  386. // StopTimeout returns the timeout (in seconds) used to stop the container.
  387. func (container *Container) StopTimeout() int {
  388. if container.Config.StopTimeout != nil {
  389. return *container.Config.StopTimeout
  390. }
  391. return DefaultStopTimeout
  392. }
  393. // InitDNSHostConfig ensures that the dns fields are never nil.
  394. // New containers don't ever have those fields nil,
  395. // but pre created containers can still have those nil values.
  396. // The non-recommended host configuration in the start api can
  397. // make these fields nil again, this corrects that issue until
  398. // we remove that behavior for good.
  399. // See https://github.com/docker/docker/pull/17779
  400. // for a more detailed explanation on why we don't want that.
  401. func (container *Container) InitDNSHostConfig() {
  402. container.Lock()
  403. defer container.Unlock()
  404. if container.HostConfig.DNS == nil {
  405. container.HostConfig.DNS = make([]string, 0)
  406. }
  407. if container.HostConfig.DNSSearch == nil {
  408. container.HostConfig.DNSSearch = make([]string, 0)
  409. }
  410. if container.HostConfig.DNSOptions == nil {
  411. container.HostConfig.DNSOptions = make([]string, 0)
  412. }
  413. }
  414. // GetEndpointInNetwork returns the container's endpoint to the provided network.
  415. func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  416. endpointName := strings.TrimPrefix(container.Name, "/")
  417. return n.EndpointByName(endpointName)
  418. }
  419. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
  420. if ep == nil {
  421. return errInvalidEndpoint
  422. }
  423. networkSettings := container.NetworkSettings
  424. if networkSettings == nil {
  425. return errInvalidNetwork
  426. }
  427. if len(networkSettings.Ports) == 0 {
  428. pm, err := getEndpointPortMapInfo(ep)
  429. if err != nil {
  430. return err
  431. }
  432. networkSettings.Ports = pm
  433. }
  434. return nil
  435. }
  436. func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) {
  437. pm := nat.PortMap{}
  438. driverInfo, err := ep.DriverInfo()
  439. if err != nil {
  440. return pm, err
  441. }
  442. if driverInfo == nil {
  443. // It is not an error for epInfo to be nil
  444. return pm, nil
  445. }
  446. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  447. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  448. for _, tp := range exposedPorts {
  449. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  450. if err != nil {
  451. return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  452. }
  453. pm[natPort] = nil
  454. }
  455. }
  456. }
  457. mapData, ok := driverInfo[netlabel.PortMap]
  458. if !ok {
  459. return pm, nil
  460. }
  461. if portMapping, ok := mapData.([]types.PortBinding); ok {
  462. for _, pp := range portMapping {
  463. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  464. if err != nil {
  465. return pm, err
  466. }
  467. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  468. pm[natPort] = append(pm[natPort], natBndg)
  469. }
  470. }
  471. return pm, nil
  472. }
  473. // GetSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox
  474. func GetSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap {
  475. pm := nat.PortMap{}
  476. if sb == nil {
  477. return pm
  478. }
  479. for _, ep := range sb.Endpoints() {
  480. pm, _ = getEndpointPortMapInfo(ep)
  481. if len(pm) > 0 {
  482. break
  483. }
  484. }
  485. return pm
  486. }
  487. // BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  488. func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  489. if ep == nil {
  490. return errInvalidEndpoint
  491. }
  492. networkSettings := container.NetworkSettings
  493. if networkSettings == nil {
  494. return errInvalidNetwork
  495. }
  496. epInfo := ep.Info()
  497. if epInfo == nil {
  498. // It is not an error to get an empty endpoint info
  499. return nil
  500. }
  501. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  502. networkSettings.Networks[n.Name()] = &network.EndpointSettings{
  503. EndpointSettings: &networktypes.EndpointSettings{},
  504. }
  505. }
  506. networkSettings.Networks[n.Name()].NetworkID = n.ID()
  507. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  508. iface := epInfo.Iface()
  509. if iface == nil {
  510. return nil
  511. }
  512. if iface.MacAddress() != nil {
  513. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  514. }
  515. if iface.Address() != nil {
  516. ones, _ := iface.Address().Mask.Size()
  517. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  518. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  519. }
  520. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  521. onesv6, _ := iface.AddressIPv6().Mask.Size()
  522. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  523. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  524. }
  525. return nil
  526. }
  527. // UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
  528. func (container *Container) UpdateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  529. if err := container.buildPortMapInfo(ep); err != nil {
  530. return err
  531. }
  532. epInfo := ep.Info()
  533. if epInfo == nil {
  534. // It is not an error to get an empty endpoint info
  535. return nil
  536. }
  537. if epInfo.Gateway() != nil {
  538. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  539. }
  540. if epInfo.GatewayIPv6().To16() != nil {
  541. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  542. }
  543. return nil
  544. }
  545. // UpdateSandboxNetworkSettings updates the sandbox ID and Key.
  546. func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  547. container.NetworkSettings.SandboxID = sb.ID()
  548. container.NetworkSettings.SandboxKey = sb.Key()
  549. return nil
  550. }
  551. // BuildJoinOptions builds endpoint Join options from a given network.
  552. func (container *Container) BuildJoinOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  553. var joinOptions []libnetwork.EndpointOption
  554. if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  555. for _, str := range epConfig.Links {
  556. name, alias, err := opts.ParseLink(str)
  557. if err != nil {
  558. return nil, err
  559. }
  560. joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias))
  561. }
  562. for k, v := range epConfig.DriverOpts {
  563. joinOptions = append(joinOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  564. }
  565. }
  566. return joinOptions, nil
  567. }
  568. // BuildCreateEndpointOptions builds endpoint options from a given network.
  569. func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network, epConfig *networktypes.EndpointSettings, sb libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) {
  570. var (
  571. bindings = make(nat.PortMap)
  572. pbList []types.PortBinding
  573. exposeList []types.TransportPort
  574. createOptions []libnetwork.EndpointOption
  575. )
  576. defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
  577. if (!container.EnableServiceDiscoveryOnDefaultNetwork() && n.Name() == defaultNetName) ||
  578. container.NetworkSettings.IsAnonymousEndpoint {
  579. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  580. }
  581. if epConfig != nil {
  582. ipam := epConfig.IPAMConfig
  583. if ipam != nil {
  584. var (
  585. ipList []net.IP
  586. ip, ip6, linkip net.IP
  587. )
  588. for _, ips := range ipam.LinkLocalIPs {
  589. if linkip = net.ParseIP(ips); linkip == nil && ips != "" {
  590. return nil, fmt.Errorf("Invalid link-local IP address:%s", ipam.LinkLocalIPs)
  591. }
  592. ipList = append(ipList, linkip)
  593. }
  594. if ip = net.ParseIP(ipam.IPv4Address); ip == nil && ipam.IPv4Address != "" {
  595. return nil, fmt.Errorf("Invalid IPv4 address:%s)", ipam.IPv4Address)
  596. }
  597. if ip6 = net.ParseIP(ipam.IPv6Address); ip6 == nil && ipam.IPv6Address != "" {
  598. return nil, fmt.Errorf("Invalid IPv6 address:%s)", ipam.IPv6Address)
  599. }
  600. createOptions = append(createOptions,
  601. libnetwork.CreateOptionIpam(ip, ip6, ipList, nil))
  602. }
  603. for _, alias := range epConfig.Aliases {
  604. createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias))
  605. }
  606. }
  607. if container.NetworkSettings.Service != nil {
  608. svcCfg := container.NetworkSettings.Service
  609. var vip string
  610. if svcCfg.VirtualAddresses[n.ID()] != nil {
  611. vip = svcCfg.VirtualAddresses[n.ID()].IPv4
  612. }
  613. var portConfigs []*libnetwork.PortConfig
  614. for _, portConfig := range svcCfg.ExposedPorts {
  615. portConfigs = append(portConfigs, &libnetwork.PortConfig{
  616. Name: portConfig.Name,
  617. Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol),
  618. TargetPort: portConfig.TargetPort,
  619. PublishedPort: portConfig.PublishedPort,
  620. })
  621. }
  622. createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()]))
  623. }
  624. if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
  625. createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution())
  626. }
  627. // configs that are applicable only for the endpoint in the network
  628. // to which container was connected to on docker run.
  629. // Ideally all these network-specific endpoint configurations must be moved under
  630. // container.NetworkSettings.Networks[n.Name()]
  631. if n.Name() == container.HostConfig.NetworkMode.NetworkName() ||
  632. (n.Name() == defaultNetName && container.HostConfig.NetworkMode.IsDefault()) {
  633. if container.Config.MacAddress != "" {
  634. mac, err := net.ParseMAC(container.Config.MacAddress)
  635. if err != nil {
  636. return nil, err
  637. }
  638. genericOption := options.Generic{
  639. netlabel.MacAddress: mac,
  640. }
  641. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  642. }
  643. for k, v := range epConfig.DriverOpts {
  644. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  645. }
  646. }
  647. // Port-mapping rules belong to the container & applicable only to non-internal networks
  648. portmaps := GetSandboxPortMapInfo(sb)
  649. if n.Info().Internal() || len(portmaps) > 0 {
  650. return createOptions, nil
  651. }
  652. if container.HostConfig.PortBindings != nil {
  653. for p, b := range container.HostConfig.PortBindings {
  654. bindings[p] = []nat.PortBinding{}
  655. for _, bb := range b {
  656. bindings[p] = append(bindings[p], nat.PortBinding{
  657. HostIP: bb.HostIP,
  658. HostPort: bb.HostPort,
  659. })
  660. }
  661. }
  662. }
  663. portSpecs := container.Config.ExposedPorts
  664. ports := make([]nat.Port, len(portSpecs))
  665. var i int
  666. for p := range portSpecs {
  667. ports[i] = p
  668. i++
  669. }
  670. nat.SortPortMap(ports, bindings)
  671. for _, port := range ports {
  672. expose := types.TransportPort{}
  673. expose.Proto = types.ParseProtocol(port.Proto())
  674. expose.Port = uint16(port.Int())
  675. exposeList = append(exposeList, expose)
  676. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  677. binding := bindings[port]
  678. for i := 0; i < len(binding); i++ {
  679. pbCopy := pb.GetCopy()
  680. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  681. var portStart, portEnd int
  682. if err == nil {
  683. portStart, portEnd, err = newP.Range()
  684. }
  685. if err != nil {
  686. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  687. }
  688. pbCopy.HostPort = uint16(portStart)
  689. pbCopy.HostPortEnd = uint16(portEnd)
  690. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  691. pbList = append(pbList, pbCopy)
  692. }
  693. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  694. pbList = append(pbList, pb)
  695. }
  696. }
  697. var dns []string
  698. if len(container.HostConfig.DNS) > 0 {
  699. dns = container.HostConfig.DNS
  700. } else if len(daemonDNS) > 0 {
  701. dns = daemonDNS
  702. }
  703. if len(dns) > 0 {
  704. createOptions = append(createOptions,
  705. libnetwork.CreateOptionDNS(dns))
  706. }
  707. createOptions = append(createOptions,
  708. libnetwork.CreateOptionPortMapping(pbList),
  709. libnetwork.CreateOptionExposedPorts(exposeList))
  710. return createOptions, nil
  711. }
  712. // UpdateMonitor updates monitor configure for running container
  713. func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
  714. type policySetter interface {
  715. SetPolicy(containertypes.RestartPolicy)
  716. }
  717. if rm, ok := container.RestartManager().(policySetter); ok {
  718. rm.SetPolicy(restartPolicy)
  719. }
  720. }
  721. // FullHostname returns hostname and optional domain appended to it.
  722. func (container *Container) FullHostname() string {
  723. fullHostname := container.Config.Hostname
  724. if container.Config.Domainname != "" {
  725. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  726. }
  727. return fullHostname
  728. }
  729. // RestartManager returns the current restartmanager instance connected to container.
  730. func (container *Container) RestartManager() restartmanager.RestartManager {
  731. if container.restartManager == nil {
  732. container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
  733. }
  734. return container.restartManager
  735. }
  736. // ResetRestartManager initializes new restartmanager based on container config
  737. func (container *Container) ResetRestartManager(resetCount bool) {
  738. if container.restartManager != nil {
  739. container.restartManager.Cancel()
  740. }
  741. if resetCount {
  742. container.RestartCount = 0
  743. }
  744. container.restartManager = nil
  745. }
  746. type attachContext struct {
  747. ctx context.Context
  748. cancel context.CancelFunc
  749. mu sync.Mutex
  750. }
  751. // InitAttachContext initializes or returns existing context for attach calls to
  752. // track container liveness.
  753. func (container *Container) InitAttachContext() context.Context {
  754. container.attachContext.mu.Lock()
  755. defer container.attachContext.mu.Unlock()
  756. if container.attachContext.ctx == nil {
  757. container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
  758. }
  759. return container.attachContext.ctx
  760. }
  761. // CancelAttachContext cancels attach context. All attach calls should detach
  762. // after this call.
  763. func (container *Container) CancelAttachContext() {
  764. container.attachContext.mu.Lock()
  765. if container.attachContext.ctx != nil {
  766. container.attachContext.cancel()
  767. container.attachContext.ctx = nil
  768. }
  769. container.attachContext.mu.Unlock()
  770. }
  771. func (container *Container) startLogging() error {
  772. if container.HostConfig.LogConfig.Type == "none" {
  773. return nil // do not start logging routines
  774. }
  775. l, err := container.StartLogger()
  776. if err != nil {
  777. return fmt.Errorf("failed to initialize logging driver: %v", err)
  778. }
  779. copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  780. container.LogCopier = copier
  781. copier.Run()
  782. container.LogDriver = l
  783. // set LogPath field only for json-file logdriver
  784. if jl, ok := l.(*jsonfilelog.JSONFileLogger); ok {
  785. container.LogPath = jl.LogPath()
  786. }
  787. return nil
  788. }
  789. // StdinPipe gets the stdin stream of the container
  790. func (container *Container) StdinPipe() io.WriteCloser {
  791. return container.StreamConfig.StdinPipe()
  792. }
  793. // StdoutPipe gets the stdout stream of the container
  794. func (container *Container) StdoutPipe() io.ReadCloser {
  795. return container.StreamConfig.StdoutPipe()
  796. }
  797. // StderrPipe gets the stderr stream of the container
  798. func (container *Container) StderrPipe() io.ReadCloser {
  799. return container.StreamConfig.StderrPipe()
  800. }
  801. // CloseStreams closes the container's stdio streams
  802. func (container *Container) CloseStreams() error {
  803. return container.StreamConfig.CloseStreams()
  804. }
  805. // InitializeStdio is called by libcontainerd to connect the stdio.
  806. func (container *Container) InitializeStdio(iop libcontainerd.IOPipe) error {
  807. if err := container.startLogging(); err != nil {
  808. container.Reset(false)
  809. return err
  810. }
  811. container.StreamConfig.CopyToPipe(iop)
  812. if container.StreamConfig.Stdin() == nil && !container.Config.Tty {
  813. if iop.Stdin != nil {
  814. if err := iop.Stdin.Close(); err != nil {
  815. logrus.Warnf("error closing stdin: %+v", err)
  816. }
  817. }
  818. }
  819. return nil
  820. }
  821. // SecretMountPath returns the path of the secret mount for the container
  822. func (container *Container) SecretMountPath() string {
  823. return filepath.Join(container.Root, "secrets")
  824. }
  825. // SecretFilePath returns the path to the location of a secret on the host.
  826. func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) string {
  827. return filepath.Join(container.SecretMountPath(), secretRef.SecretID)
  828. }
  829. func getSecretTargetPath(r *swarmtypes.SecretReference) string {
  830. if filepath.IsAbs(r.File.Name) {
  831. return r.File.Name
  832. }
  833. return filepath.Join(containerSecretMountPath, r.File.Name)
  834. }
  835. // ConfigsDirPath returns the path to the directory where configs are stored on
  836. // disk.
  837. func (container *Container) ConfigsDirPath() string {
  838. return filepath.Join(container.Root, "configs")
  839. }
  840. // ConfigFilePath returns the path to the on-disk location of a config.
  841. func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) string {
  842. return filepath.Join(container.ConfigsDirPath(), configRef.ConfigID)
  843. }