container.go 27 KB

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