container.go 29 KB

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