container.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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. // CommonContainer holds the fields for a container which are
  46. // applicable across all platforms supported by the daemon.
  47. type CommonContainer struct {
  48. *runconfig.StreamConfig
  49. // embed for Container to support states directly.
  50. *State `json:"State"` // Needed for remote api version <= 1.11
  51. Root string `json:"-"` // Path to the "home" of the container, including metadata.
  52. BaseFS string `json:"-"` // Path to the graphdriver mountpoint
  53. RWLayer layer.RWLayer `json:"-"`
  54. ID string
  55. Created time.Time
  56. Path string
  57. Args []string
  58. Config *containertypes.Config
  59. ImageID image.ID `json:"Image"`
  60. NetworkSettings *network.Settings
  61. LogPath string
  62. Name string
  63. Driver string
  64. // MountLabel contains the options for the 'mount' command
  65. MountLabel string
  66. ProcessLabel string
  67. RestartCount int
  68. HasBeenStartedBefore bool
  69. HasBeenManuallyStopped bool // used for unless-stopped restart policy
  70. MountPoints map[string]*volume.MountPoint
  71. HostConfig *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
  72. ExecCommands *exec.Store `json:"-"`
  73. // logDriver for closing
  74. LogDriver logger.Logger `json:"-"`
  75. LogCopier *logger.Copier `json:"-"`
  76. restartManager restartmanager.RestartManager
  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 := ioutils.NewAtomicFileWriter(pth, 0666)
  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 := ioutils.NewAtomicFileWriter(pth, 0666)
  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. if container.restartManager != nil {
  243. container.restartManager.Cancel()
  244. }
  245. }
  246. // HostConfigPath returns the path to the container's JSON hostconfig
  247. func (container *Container) HostConfigPath() (string, error) {
  248. return container.GetRootResourcePath("hostconfig.json")
  249. }
  250. // ConfigPath returns the path to the container's JSON config
  251. func (container *Container) ConfigPath() (string, error) {
  252. return container.GetRootResourcePath(configFileName)
  253. }
  254. // StartLogger starts a new logger driver for the container.
  255. func (container *Container) StartLogger(cfg containertypes.LogConfig) (logger.Logger, error) {
  256. c, err := logger.GetLogDriver(cfg.Type)
  257. if err != nil {
  258. return nil, fmt.Errorf("Failed to get logging factory: %v", err)
  259. }
  260. ctx := logger.Context{
  261. Config: cfg.Config,
  262. ContainerID: container.ID,
  263. ContainerName: container.Name,
  264. ContainerEntrypoint: container.Path,
  265. ContainerArgs: container.Args,
  266. ContainerImageID: container.ImageID.String(),
  267. ContainerImageName: container.Config.Image,
  268. ContainerCreated: container.Created,
  269. ContainerEnv: container.Config.Env,
  270. ContainerLabels: container.Config.Labels,
  271. }
  272. // Set logging file for "json-logger"
  273. if cfg.Type == jsonfilelog.Name {
  274. ctx.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  275. if err != nil {
  276. return nil, err
  277. }
  278. }
  279. return c(ctx)
  280. }
  281. // GetProcessLabel returns the process label for the container.
  282. func (container *Container) GetProcessLabel() string {
  283. // even if we have a process label return "" if we are running
  284. // in privileged mode
  285. if container.HostConfig.Privileged {
  286. return ""
  287. }
  288. return container.ProcessLabel
  289. }
  290. // GetMountLabel returns the mounting label for the container.
  291. // This label is empty if the container is privileged.
  292. func (container *Container) GetMountLabel() string {
  293. if container.HostConfig.Privileged {
  294. return ""
  295. }
  296. return container.MountLabel
  297. }
  298. // GetExecIDs returns the list of exec commands running on the container.
  299. func (container *Container) GetExecIDs() []string {
  300. return container.ExecCommands.List()
  301. }
  302. // Attach connects to the container's TTY, delegating to standard
  303. // streams or websockets depending on the configuration.
  304. func (container *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer, keys []byte) chan error {
  305. ctx := container.InitAttachContext()
  306. return AttachStreams(ctx, container.StreamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, stdin, stdout, stderr, keys)
  307. }
  308. // AttachStreams connects streams to a TTY.
  309. // Used by exec too. Should this move somewhere else?
  310. 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 {
  311. var (
  312. cStdout, cStderr io.ReadCloser
  313. cStdin io.WriteCloser
  314. wg sync.WaitGroup
  315. errors = make(chan error, 3)
  316. )
  317. if stdin != nil && openStdin {
  318. cStdin = streamConfig.StdinPipe()
  319. wg.Add(1)
  320. }
  321. if stdout != nil {
  322. cStdout = streamConfig.StdoutPipe()
  323. wg.Add(1)
  324. }
  325. if stderr != nil {
  326. cStderr = streamConfig.StderrPipe()
  327. wg.Add(1)
  328. }
  329. // Connect stdin of container to the http conn.
  330. go func() {
  331. if stdin == nil || !openStdin {
  332. return
  333. }
  334. logrus.Debugf("attach: stdin: begin")
  335. var err error
  336. if tty {
  337. _, err = copyEscapable(cStdin, stdin, keys)
  338. } else {
  339. _, err = io.Copy(cStdin, stdin)
  340. }
  341. if err == io.ErrClosedPipe {
  342. err = nil
  343. }
  344. if err != nil {
  345. logrus.Errorf("attach: stdin: %s", err)
  346. errors <- err
  347. }
  348. if stdinOnce && !tty {
  349. cStdin.Close()
  350. } else {
  351. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  352. if cStdout != nil {
  353. cStdout.Close()
  354. }
  355. if cStderr != nil {
  356. cStderr.Close()
  357. }
  358. }
  359. logrus.Debugf("attach: stdin: end")
  360. wg.Done()
  361. }()
  362. attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) {
  363. if stream == nil {
  364. return
  365. }
  366. logrus.Debugf("attach: %s: begin", name)
  367. _, err := io.Copy(stream, streamPipe)
  368. if err == io.ErrClosedPipe {
  369. err = nil
  370. }
  371. if err != nil {
  372. logrus.Errorf("attach: %s: %v", name, err)
  373. errors <- err
  374. }
  375. // Make sure stdin gets closed
  376. if stdin != nil {
  377. stdin.Close()
  378. }
  379. streamPipe.Close()
  380. logrus.Debugf("attach: %s: end", name)
  381. wg.Done()
  382. }
  383. go attachStream("stdout", stdout, cStdout)
  384. go attachStream("stderr", stderr, cStderr)
  385. return promise.Go(func() error {
  386. done := make(chan struct{})
  387. go func() {
  388. wg.Wait()
  389. close(done)
  390. }()
  391. select {
  392. case <-done:
  393. case <-ctx.Done():
  394. // close all pipes
  395. if cStdin != nil {
  396. cStdin.Close()
  397. }
  398. if cStdout != nil {
  399. cStdout.Close()
  400. }
  401. if cStderr != nil {
  402. cStderr.Close()
  403. }
  404. <-done
  405. }
  406. close(errors)
  407. for err := range errors {
  408. if err != nil {
  409. return err
  410. }
  411. }
  412. return nil
  413. })
  414. }
  415. // Code c/c from io.Copy() modified to handle escape sequence
  416. func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64, err error) {
  417. if len(keys) == 0 {
  418. // Default keys : ctrl-p ctrl-q
  419. keys = []byte{16, 17}
  420. }
  421. buf := make([]byte, 32*1024)
  422. for {
  423. nr, er := src.Read(buf)
  424. if nr > 0 {
  425. // ---- Docker addition
  426. for i, key := range keys {
  427. if nr != 1 || buf[0] != key {
  428. break
  429. }
  430. if i == len(keys)-1 {
  431. if err := src.Close(); err != nil {
  432. return 0, err
  433. }
  434. return 0, nil
  435. }
  436. nr, er = src.Read(buf)
  437. }
  438. // ---- End of docker
  439. nw, ew := dst.Write(buf[0:nr])
  440. if nw > 0 {
  441. written += int64(nw)
  442. }
  443. if ew != nil {
  444. err = ew
  445. break
  446. }
  447. if nr != nw {
  448. err = io.ErrShortWrite
  449. break
  450. }
  451. }
  452. if er == io.EOF {
  453. break
  454. }
  455. if er != nil {
  456. err = er
  457. break
  458. }
  459. }
  460. return written, err
  461. }
  462. // ShouldRestart decides whether the daemon should restart the container or not.
  463. // This is based on the container's restart policy.
  464. func (container *Container) ShouldRestart() bool {
  465. shouldRestart, _, _ := container.restartManager.ShouldRestart(uint32(container.ExitCode), container.HasBeenManuallyStopped)
  466. return shouldRestart
  467. }
  468. // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
  469. func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  470. container.MountPoints[destination] = &volume.MountPoint{
  471. Name: vol.Name(),
  472. Driver: vol.DriverName(),
  473. Destination: destination,
  474. RW: rw,
  475. Volume: vol,
  476. CopyData: volume.DefaultCopyMode,
  477. }
  478. }
  479. // IsDestinationMounted checks whether a path is mounted on the container or not.
  480. func (container *Container) IsDestinationMounted(destination string) bool {
  481. return container.MountPoints[destination] != nil
  482. }
  483. // StopSignal returns the signal used to stop the container.
  484. func (container *Container) StopSignal() int {
  485. var stopSignal syscall.Signal
  486. if container.Config.StopSignal != "" {
  487. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  488. }
  489. if int(stopSignal) == 0 {
  490. stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
  491. }
  492. return int(stopSignal)
  493. }
  494. // InitDNSHostConfig ensures that the dns fields are never nil.
  495. // New containers don't ever have those fields nil,
  496. // but pre created containers can still have those nil values.
  497. // The non-recommended host configuration in the start api can
  498. // make these fields nil again, this corrects that issue until
  499. // we remove that behavior for good.
  500. // See https://github.com/docker/docker/pull/17779
  501. // for a more detailed explanation on why we don't want that.
  502. func (container *Container) InitDNSHostConfig() {
  503. container.Lock()
  504. defer container.Unlock()
  505. if container.HostConfig.DNS == nil {
  506. container.HostConfig.DNS = make([]string, 0)
  507. }
  508. if container.HostConfig.DNSSearch == nil {
  509. container.HostConfig.DNSSearch = make([]string, 0)
  510. }
  511. if container.HostConfig.DNSOptions == nil {
  512. container.HostConfig.DNSOptions = make([]string, 0)
  513. }
  514. }
  515. // GetEndpointInNetwork returns the container's endpoint to the provided network.
  516. func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  517. endpointName := strings.TrimPrefix(container.Name, "/")
  518. return n.EndpointByName(endpointName)
  519. }
  520. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
  521. if ep == nil {
  522. return errInvalidEndpoint
  523. }
  524. networkSettings := container.NetworkSettings
  525. if networkSettings == nil {
  526. return errInvalidNetwork
  527. }
  528. if len(networkSettings.Ports) == 0 {
  529. pm, err := getEndpointPortMapInfo(ep)
  530. if err != nil {
  531. return err
  532. }
  533. networkSettings.Ports = pm
  534. }
  535. return nil
  536. }
  537. func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) {
  538. pm := nat.PortMap{}
  539. driverInfo, err := ep.DriverInfo()
  540. if err != nil {
  541. return pm, err
  542. }
  543. if driverInfo == nil {
  544. // It is not an error for epInfo to be nil
  545. return pm, nil
  546. }
  547. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  548. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  549. for _, tp := range exposedPorts {
  550. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  551. if err != nil {
  552. return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  553. }
  554. pm[natPort] = nil
  555. }
  556. }
  557. }
  558. mapData, ok := driverInfo[netlabel.PortMap]
  559. if !ok {
  560. return pm, nil
  561. }
  562. if portMapping, ok := mapData.([]types.PortBinding); ok {
  563. for _, pp := range portMapping {
  564. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  565. if err != nil {
  566. return pm, err
  567. }
  568. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  569. pm[natPort] = append(pm[natPort], natBndg)
  570. }
  571. }
  572. return pm, nil
  573. }
  574. func getSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap {
  575. pm := nat.PortMap{}
  576. if sb == nil {
  577. return pm
  578. }
  579. for _, ep := range sb.Endpoints() {
  580. pm, _ = getEndpointPortMapInfo(ep)
  581. if len(pm) > 0 {
  582. break
  583. }
  584. }
  585. return pm
  586. }
  587. // BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  588. func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  589. if ep == nil {
  590. return errInvalidEndpoint
  591. }
  592. networkSettings := container.NetworkSettings
  593. if networkSettings == nil {
  594. return errInvalidNetwork
  595. }
  596. epInfo := ep.Info()
  597. if epInfo == nil {
  598. // It is not an error to get an empty endpoint info
  599. return nil
  600. }
  601. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  602. networkSettings.Networks[n.Name()] = new(networktypes.EndpointSettings)
  603. }
  604. networkSettings.Networks[n.Name()].NetworkID = n.ID()
  605. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  606. iface := epInfo.Iface()
  607. if iface == nil {
  608. return nil
  609. }
  610. if iface.MacAddress() != nil {
  611. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  612. }
  613. if iface.Address() != nil {
  614. ones, _ := iface.Address().Mask.Size()
  615. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  616. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  617. }
  618. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  619. onesv6, _ := iface.AddressIPv6().Mask.Size()
  620. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  621. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  622. }
  623. return nil
  624. }
  625. // UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
  626. func (container *Container) UpdateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  627. if err := container.buildPortMapInfo(ep); err != nil {
  628. return err
  629. }
  630. epInfo := ep.Info()
  631. if epInfo == nil {
  632. // It is not an error to get an empty endpoint info
  633. return nil
  634. }
  635. if epInfo.Gateway() != nil {
  636. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  637. }
  638. if epInfo.GatewayIPv6().To16() != nil {
  639. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  640. }
  641. return nil
  642. }
  643. // UpdateSandboxNetworkSettings updates the sandbox ID and Key.
  644. func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  645. container.NetworkSettings.SandboxID = sb.ID()
  646. container.NetworkSettings.SandboxKey = sb.Key()
  647. return nil
  648. }
  649. // BuildJoinOptions builds endpoint Join options from a given network.
  650. func (container *Container) BuildJoinOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  651. var joinOptions []libnetwork.EndpointOption
  652. if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  653. for _, str := range epConfig.Links {
  654. name, alias, err := runconfigopts.ParseLink(str)
  655. if err != nil {
  656. return nil, err
  657. }
  658. joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias))
  659. }
  660. }
  661. return joinOptions, nil
  662. }
  663. // BuildCreateEndpointOptions builds endpoint options from a given network.
  664. func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network, epConfig *networktypes.EndpointSettings, sb libnetwork.Sandbox) ([]libnetwork.EndpointOption, error) {
  665. var (
  666. bindings = make(nat.PortMap)
  667. pbList []types.PortBinding
  668. exposeList []types.TransportPort
  669. createOptions []libnetwork.EndpointOption
  670. )
  671. defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
  672. if n.Name() == defaultNetName || container.NetworkSettings.IsAnonymousEndpoint {
  673. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  674. }
  675. if epConfig != nil {
  676. ipam := epConfig.IPAMConfig
  677. if ipam != nil && (ipam.IPv4Address != "" || ipam.IPv6Address != "") {
  678. createOptions = append(createOptions,
  679. libnetwork.CreateOptionIpam(net.ParseIP(ipam.IPv4Address), net.ParseIP(ipam.IPv6Address), nil))
  680. }
  681. for _, alias := range epConfig.Aliases {
  682. createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias))
  683. }
  684. }
  685. if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
  686. createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution())
  687. }
  688. // configs that are applicable only for the endpoint in the network
  689. // to which container was connected to on docker run.
  690. // Ideally all these network-specific endpoint configurations must be moved under
  691. // container.NetworkSettings.Networks[n.Name()]
  692. if n.Name() == container.HostConfig.NetworkMode.NetworkName() ||
  693. (n.Name() == defaultNetName && container.HostConfig.NetworkMode.IsDefault()) {
  694. if container.Config.MacAddress != "" {
  695. mac, err := net.ParseMAC(container.Config.MacAddress)
  696. if err != nil {
  697. return nil, err
  698. }
  699. genericOption := options.Generic{
  700. netlabel.MacAddress: mac,
  701. }
  702. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  703. }
  704. }
  705. // Port-mapping rules belong to the container & applicable only to non-internal networks
  706. portmaps := getSandboxPortMapInfo(sb)
  707. if n.Info().Internal() || len(portmaps) > 0 {
  708. return createOptions, nil
  709. }
  710. if container.HostConfig.PortBindings != nil {
  711. for p, b := range container.HostConfig.PortBindings {
  712. bindings[p] = []nat.PortBinding{}
  713. for _, bb := range b {
  714. bindings[p] = append(bindings[p], nat.PortBinding{
  715. HostIP: bb.HostIP,
  716. HostPort: bb.HostPort,
  717. })
  718. }
  719. }
  720. }
  721. portSpecs := container.Config.ExposedPorts
  722. ports := make([]nat.Port, len(portSpecs))
  723. var i int
  724. for p := range portSpecs {
  725. ports[i] = p
  726. i++
  727. }
  728. nat.SortPortMap(ports, bindings)
  729. for _, port := range ports {
  730. expose := types.TransportPort{}
  731. expose.Proto = types.ParseProtocol(port.Proto())
  732. expose.Port = uint16(port.Int())
  733. exposeList = append(exposeList, expose)
  734. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  735. binding := bindings[port]
  736. for i := 0; i < len(binding); i++ {
  737. pbCopy := pb.GetCopy()
  738. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  739. var portStart, portEnd int
  740. if err == nil {
  741. portStart, portEnd, err = newP.Range()
  742. }
  743. if err != nil {
  744. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  745. }
  746. pbCopy.HostPort = uint16(portStart)
  747. pbCopy.HostPortEnd = uint16(portEnd)
  748. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  749. pbList = append(pbList, pbCopy)
  750. }
  751. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  752. pbList = append(pbList, pb)
  753. }
  754. }
  755. createOptions = append(createOptions,
  756. libnetwork.CreateOptionPortMapping(pbList),
  757. libnetwork.CreateOptionExposedPorts(exposeList))
  758. return createOptions, nil
  759. }
  760. // UpdateMonitor updates monitor configure for running container
  761. func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
  762. type policySetter interface {
  763. SetPolicy(containertypes.RestartPolicy)
  764. }
  765. if rm, ok := container.RestartManager(false).(policySetter); ok {
  766. rm.SetPolicy(restartPolicy)
  767. }
  768. }
  769. // FullHostname returns hostname and optional domain appended to it.
  770. func (container *Container) FullHostname() string {
  771. fullHostname := container.Config.Hostname
  772. if container.Config.Domainname != "" {
  773. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  774. }
  775. return fullHostname
  776. }
  777. // RestartManager returns the current restartmanager instance connected to container.
  778. func (container *Container) RestartManager(reset bool) restartmanager.RestartManager {
  779. if reset {
  780. container.RestartCount = 0
  781. container.restartManager = nil
  782. }
  783. if container.restartManager == nil {
  784. container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
  785. }
  786. return container.restartManager
  787. }
  788. type attachContext struct {
  789. ctx context.Context
  790. cancel context.CancelFunc
  791. mu sync.Mutex
  792. }
  793. // InitAttachContext initialize or returns existing context for attach calls to
  794. // track container liveness.
  795. func (container *Container) InitAttachContext() context.Context {
  796. container.attachContext.mu.Lock()
  797. defer container.attachContext.mu.Unlock()
  798. if container.attachContext.ctx == nil {
  799. container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
  800. }
  801. return container.attachContext.ctx
  802. }
  803. // CancelAttachContext cancel attach context. All attach calls should detach
  804. // after this call.
  805. func (container *Container) CancelAttachContext() {
  806. container.attachContext.mu.Lock()
  807. if container.attachContext.ctx != nil {
  808. container.attachContext.cancel()
  809. container.attachContext.ctx = nil
  810. }
  811. container.attachContext.mu.Unlock()
  812. }