container.go 27 KB

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