container.go 33 KB

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