container.go 29 KB

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