container.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. package daemon
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "sync"
  11. "syscall"
  12. "time"
  13. "github.com/opencontainers/runc/libcontainer/label"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/context"
  16. "github.com/docker/docker/daemon/execdriver"
  17. "github.com/docker/docker/daemon/logger"
  18. "github.com/docker/docker/daemon/logger/jsonfilelog"
  19. "github.com/docker/docker/daemon/network"
  20. derr "github.com/docker/docker/errors"
  21. "github.com/docker/docker/image"
  22. "github.com/docker/docker/pkg/archive"
  23. "github.com/docker/docker/pkg/broadcastwriter"
  24. "github.com/docker/docker/pkg/fileutils"
  25. "github.com/docker/docker/pkg/ioutils"
  26. "github.com/docker/docker/pkg/mount"
  27. "github.com/docker/docker/pkg/nat"
  28. "github.com/docker/docker/pkg/promise"
  29. "github.com/docker/docker/pkg/signal"
  30. "github.com/docker/docker/pkg/symlink"
  31. "github.com/docker/docker/runconfig"
  32. "github.com/docker/docker/volume"
  33. )
  34. var (
  35. // ErrRootFSReadOnly is returned when a container
  36. // rootfs is marked readonly.
  37. ErrRootFSReadOnly = errors.New("container rootfs is marked read-only")
  38. )
  39. type streamConfig struct {
  40. stdout *broadcastwriter.BroadcastWriter
  41. stderr *broadcastwriter.BroadcastWriter
  42. stdin io.ReadCloser
  43. stdinPipe io.WriteCloser
  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. streamConfig
  49. // embed for Container to support states directly.
  50. *State `json:"State"` // Needed for remote api version <= 1.11
  51. root string // Path to the "home" of the container, including metadata.
  52. basefs string // Path to the graphdriver mountpoint
  53. ID string
  54. Created time.Time
  55. Path string
  56. Args []string
  57. Config *runconfig.Config
  58. ImageID string `json:"Image"`
  59. NetworkSettings *network.Settings
  60. LogPath string
  61. Name string
  62. Driver string
  63. ExecDriver 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. hostConfig *runconfig.HostConfig
  71. command *execdriver.Command
  72. monitor *containerMonitor
  73. execCommands *execStore
  74. daemon *Daemon
  75. // logDriver for closing
  76. logDriver logger.Logger
  77. logCopier *logger.Copier
  78. }
  79. func (container *Container) fromDisk() error {
  80. pth, err := container.jsonPath()
  81. if err != nil {
  82. return err
  83. }
  84. jsonSource, err := os.Open(pth)
  85. if err != nil {
  86. return err
  87. }
  88. defer jsonSource.Close()
  89. dec := json.NewDecoder(jsonSource)
  90. // Load container settings
  91. if err := dec.Decode(container); err != nil {
  92. return err
  93. }
  94. if err := label.ReserveLabel(container.ProcessLabel); err != nil {
  95. return err
  96. }
  97. return container.readHostConfig()
  98. }
  99. func (container *Container) toDisk() error {
  100. data, err := json.Marshal(container)
  101. if err != nil {
  102. return err
  103. }
  104. pth, err := container.jsonPath()
  105. if err != nil {
  106. return err
  107. }
  108. if err := ioutil.WriteFile(pth, data, 0666); err != nil {
  109. return err
  110. }
  111. return container.writeHostConfig()
  112. }
  113. func (container *Container) toDiskLocking() error {
  114. container.Lock()
  115. err := container.toDisk()
  116. container.Unlock()
  117. return err
  118. }
  119. func (container *Container) readHostConfig() error {
  120. container.hostConfig = &runconfig.HostConfig{}
  121. // If the hostconfig file does not exist, do not read it.
  122. // (We still have to initialize container.hostConfig,
  123. // but that's OK, since we just did that above.)
  124. pth, err := container.hostConfigPath()
  125. if err != nil {
  126. return err
  127. }
  128. _, err = os.Stat(pth)
  129. if os.IsNotExist(err) {
  130. return nil
  131. }
  132. f, err := os.Open(pth)
  133. if err != nil {
  134. return err
  135. }
  136. defer f.Close()
  137. return json.NewDecoder(f).Decode(&container.hostConfig)
  138. }
  139. func (container *Container) writeHostConfig() error {
  140. data, err := json.Marshal(container.hostConfig)
  141. if err != nil {
  142. return err
  143. }
  144. pth, err := container.hostConfigPath()
  145. if err != nil {
  146. return err
  147. }
  148. return ioutil.WriteFile(pth, data, 0666)
  149. }
  150. func (container *Container) logEvent(ctx context.Context, action string) {
  151. d := container.daemon
  152. d.EventsService.Log(
  153. ctx,
  154. action,
  155. container.ID,
  156. container.Config.Image,
  157. )
  158. }
  159. // GetResourcePath evaluates `path` in the scope of the container's basefs, with proper path
  160. // sanitisation. Symlinks are all scoped to the basefs of the container, as
  161. // though the container's basefs was `/`.
  162. //
  163. // The basefs of a container is the host-facing path which is bind-mounted as
  164. // `/` inside the container. This method is essentially used to access a
  165. // particular path inside the container as though you were a process in that
  166. // container.
  167. //
  168. // NOTE: The returned path is *only* safely scoped inside the container's basefs
  169. // if no component of the returned path changes (such as a component
  170. // symlinking to a different path) between using this method and using the
  171. // path. See symlink.FollowSymlinkInScope for more details.
  172. func (container *Container) GetResourcePath(path string) (string, error) {
  173. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  174. // any filepath operations must be done in an OS agnostic way.
  175. cleanPath := filepath.Join(string(os.PathSeparator), path)
  176. r, e := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, cleanPath), container.basefs)
  177. return r, e
  178. }
  179. // Evaluates `path` in the scope of the container's root, with proper path
  180. // sanitisation. Symlinks are all scoped to the root of the container, as
  181. // though the container's root was `/`.
  182. //
  183. // The root of a container is the host-facing configuration metadata directory.
  184. // Only use this method to safely access the container's `container.json` or
  185. // other metadata files. If in doubt, use container.GetResourcePath.
  186. //
  187. // NOTE: The returned path is *only* safely scoped inside the container's root
  188. // if no component of the returned path changes (such as a component
  189. // symlinking to a different path) between using this method and using the
  190. // path. See symlink.FollowSymlinkInScope for more details.
  191. func (container *Container) getRootResourcePath(path string) (string, error) {
  192. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  193. // any filepath operations must be done in an OS agnostic way.
  194. cleanPath := filepath.Join(string(os.PathSeparator), path)
  195. return symlink.FollowSymlinkInScope(filepath.Join(container.root, cleanPath), container.root)
  196. }
  197. func (container *Container) exportContainerRw() (archive.Archive, error) {
  198. if container.daemon == nil {
  199. return nil, derr.ErrorCodeUnregisteredContainer.WithArgs(container.ID)
  200. }
  201. archive, err := container.daemon.diff(container)
  202. if err != nil {
  203. return nil, err
  204. }
  205. return ioutils.NewReadCloserWrapper(archive, func() error {
  206. err := archive.Close()
  207. return err
  208. }),
  209. nil
  210. }
  211. // Start prepares the container to run by setting up everything the
  212. // container needs, such as storage and networking, as well as links
  213. // between containers. The container is left waiting for a signal to
  214. // begin running.
  215. func (container *Container) Start(ctx context.Context) (err error) {
  216. container.Lock()
  217. defer container.Unlock()
  218. if container.Running {
  219. return nil
  220. }
  221. if container.removalInProgress || container.Dead {
  222. return derr.ErrorCodeContainerBeingRemoved
  223. }
  224. // if we encounter an error during start we need to ensure that any other
  225. // setup has been cleaned up properly
  226. defer func() {
  227. if err != nil {
  228. container.setError(err)
  229. // if no one else has set it, make sure we don't leave it at zero
  230. if container.ExitCode == 0 {
  231. container.ExitCode = 128
  232. }
  233. container.toDisk()
  234. container.cleanup(ctx)
  235. container.logEvent(ctx, "die")
  236. }
  237. }()
  238. if err := container.Mount(ctx); err != nil {
  239. return err
  240. }
  241. // Make sure NetworkMode has an acceptable value. We do this to ensure
  242. // backwards API compatibility.
  243. container.hostConfig = runconfig.SetDefaultNetModeIfBlank(container.hostConfig)
  244. if err := container.initializeNetworking(ctx); err != nil {
  245. return err
  246. }
  247. linkedEnv, err := container.setupLinkedContainers(ctx)
  248. if err != nil {
  249. return err
  250. }
  251. if err := container.setupWorkingDirectory(); err != nil {
  252. return err
  253. }
  254. env := container.createDaemonEnvironment(linkedEnv)
  255. if err := populateCommand(ctx, container, env); err != nil {
  256. return err
  257. }
  258. if !container.hostConfig.IpcMode.IsContainer() && !container.hostConfig.IpcMode.IsHost() {
  259. if err := container.setupIpcDirs(); err != nil {
  260. return err
  261. }
  262. }
  263. mounts, err := container.setupMounts()
  264. if err != nil {
  265. return err
  266. }
  267. mounts = append(mounts, container.ipcMounts()...)
  268. container.command.Mounts = mounts
  269. return container.waitForStart(ctx)
  270. }
  271. // streamConfig.StdinPipe returns a WriteCloser which can be used to feed data
  272. // to the standard input of the container's active process.
  273. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser
  274. // which can be used to retrieve the standard output (and error) generated
  275. // by the container's active process. The output (and error) are actually
  276. // copied and delivered to all StdoutPipe and StderrPipe consumers, using
  277. // a kind of "broadcaster".
  278. func (streamConfig *streamConfig) StdinPipe() io.WriteCloser {
  279. return streamConfig.stdinPipe
  280. }
  281. func (streamConfig *streamConfig) StdoutPipe() io.ReadCloser {
  282. reader, writer := io.Pipe()
  283. streamConfig.stdout.AddWriter(writer)
  284. return ioutils.NewBufReader(reader)
  285. }
  286. func (streamConfig *streamConfig) StderrPipe() io.ReadCloser {
  287. reader, writer := io.Pipe()
  288. streamConfig.stderr.AddWriter(writer)
  289. return ioutils.NewBufReader(reader)
  290. }
  291. func (container *Container) isNetworkAllocated() bool {
  292. return container.NetworkSettings.IPAddress != ""
  293. }
  294. // cleanup releases any network resources allocated to the container along with any rules
  295. // around how containers are linked together. It also unmounts the container's root filesystem.
  296. func (container *Container) cleanup(ctx context.Context) {
  297. container.releaseNetwork()
  298. if err := container.unmountIpcMounts(); err != nil {
  299. logrus.Errorf("%s: Failed to umount ipc filesystems: %v", container.ID, err)
  300. }
  301. if err := container.Unmount(ctx); err != nil {
  302. logrus.Errorf("%s: Failed to umount filesystem: %v", container.ID, err)
  303. }
  304. for _, eConfig := range container.execCommands.s {
  305. container.daemon.unregisterExecCommand(eConfig)
  306. }
  307. container.unmountVolumes(false)
  308. }
  309. // killSig sends the container the given signal. This wrapper for the
  310. // host specific kill command prepares the container before attempting
  311. // to send the signal. An error is returned if the container is paused
  312. // or not running, or if there is a problem returned from the
  313. // underlying kill command.
  314. func (container *Container) killSig(ctx context.Context, sig int) error {
  315. logrus.Debugf("Sending %d to %s", sig, container.ID)
  316. container.Lock()
  317. defer container.Unlock()
  318. // We could unpause the container for them rather than returning this error
  319. if container.Paused {
  320. return derr.ErrorCodeUnpauseContainer.WithArgs(container.ID)
  321. }
  322. if !container.Running {
  323. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  324. }
  325. // signal to the monitor that it should not restart the container
  326. // after we send the kill signal
  327. container.monitor.ExitOnNext()
  328. // if the container is currently restarting we do not need to send the signal
  329. // to the process. Telling the monitor that it should exit on it's next event
  330. // loop is enough
  331. if container.Restarting {
  332. return nil
  333. }
  334. if err := container.daemon.kill(container, sig); err != nil {
  335. return err
  336. }
  337. container.logEvent(ctx, "kill")
  338. return nil
  339. }
  340. // Wrapper aroung killSig() suppressing "no such process" error.
  341. func (container *Container) killPossiblyDeadProcess(ctx context.Context, sig int) error {
  342. err := container.killSig(ctx, sig)
  343. if err == syscall.ESRCH {
  344. logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.getPID(), sig)
  345. return nil
  346. }
  347. return err
  348. }
  349. func (container *Container) pause(ctx context.Context) error {
  350. container.Lock()
  351. defer container.Unlock()
  352. // We cannot Pause the container which is not running
  353. if !container.Running {
  354. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  355. }
  356. // We cannot Pause the container which is already paused
  357. if container.Paused {
  358. return derr.ErrorCodeAlreadyPaused.WithArgs(container.ID)
  359. }
  360. if err := container.daemon.execDriver.Pause(container.command); err != nil {
  361. return err
  362. }
  363. container.Paused = true
  364. container.logEvent(ctx, "pause")
  365. return nil
  366. }
  367. func (container *Container) unpause(ctx context.Context) error {
  368. container.Lock()
  369. defer container.Unlock()
  370. // We cannot unpause the container which is not running
  371. if !container.Running {
  372. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  373. }
  374. // We cannot unpause the container which is not paused
  375. if !container.Paused {
  376. return derr.ErrorCodeNotPaused.WithArgs(container.ID)
  377. }
  378. if err := container.daemon.execDriver.Unpause(container.command); err != nil {
  379. return err
  380. }
  381. container.Paused = false
  382. container.logEvent(ctx, "unpause")
  383. return nil
  384. }
  385. // Kill forcefully terminates a container.
  386. func (container *Container) Kill(ctx context.Context) error {
  387. if !container.IsRunning() {
  388. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  389. }
  390. // 1. Send SIGKILL
  391. if err := container.killPossiblyDeadProcess(ctx, int(syscall.SIGKILL)); err != nil {
  392. // While normally we might "return err" here we're not going to
  393. // because if we can't stop the container by this point then
  394. // its probably because its already stopped. Meaning, between
  395. // the time of the IsRunning() call above and now it stopped.
  396. // Also, since the err return will be exec driver specific we can't
  397. // look for any particular (common) error that would indicate
  398. // that the process is already dead vs something else going wrong.
  399. // So, instead we'll give it up to 2 more seconds to complete and if
  400. // by that time the container is still running, then the error
  401. // we got is probably valid and so we return it to the caller.
  402. if container.IsRunning() {
  403. container.WaitStop(2 * time.Second)
  404. if container.IsRunning() {
  405. return err
  406. }
  407. }
  408. }
  409. // 2. Wait for the process to die, in last resort, try to kill the process directly
  410. if err := killProcessDirectly(container); err != nil {
  411. return err
  412. }
  413. container.WaitStop(-1 * time.Second)
  414. return nil
  415. }
  416. // Stop halts a container by sending a stop signal, waiting for the given
  417. // duration in seconds, and then calling SIGKILL and waiting for the
  418. // process to exit. If a negative duration is given, Stop will wait
  419. // for the initial signal forever. If the container is not running Stop returns
  420. // immediately.
  421. func (container *Container) Stop(ctx context.Context, seconds int) error {
  422. if !container.IsRunning() {
  423. return nil
  424. }
  425. // 1. Send a SIGTERM
  426. if err := container.killPossiblyDeadProcess(ctx, container.stopSignal()); err != nil {
  427. logrus.Infof("Failed to send SIGTERM to the process, force killing")
  428. if err := container.killPossiblyDeadProcess(ctx, 9); err != nil {
  429. return err
  430. }
  431. }
  432. // 2. Wait for the process to exit on its own
  433. if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil {
  434. logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  435. // 3. If it doesn't, then send SIGKILL
  436. if err := container.Kill(ctx); err != nil {
  437. container.WaitStop(-1 * time.Second)
  438. return err
  439. }
  440. }
  441. container.logEvent(ctx, "stop")
  442. return nil
  443. }
  444. // Restart attempts to gracefully stop and then start the
  445. // container. When stopping, wait for the given duration in seconds to
  446. // gracefully stop, before forcefully terminating the container. If
  447. // given a negative duration, wait forever for a graceful stop.
  448. func (container *Container) Restart(ctx context.Context, seconds int) error {
  449. // Avoid unnecessarily unmounting and then directly mounting
  450. // the container when the container stops and then starts
  451. // again
  452. if err := container.Mount(ctx); err == nil {
  453. defer container.Unmount(ctx)
  454. }
  455. if err := container.Stop(ctx, seconds); err != nil {
  456. return err
  457. }
  458. if err := container.Start(ctx); err != nil {
  459. return err
  460. }
  461. container.logEvent(ctx, "restart")
  462. return nil
  463. }
  464. // Resize changes the TTY of the process running inside the container
  465. // to the given height and width. The container must be running.
  466. func (container *Container) Resize(ctx context.Context, h, w int) error {
  467. if !container.IsRunning() {
  468. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  469. }
  470. if err := container.command.ProcessConfig.Terminal.Resize(h, w); err != nil {
  471. return err
  472. }
  473. container.logEvent(ctx, "resize")
  474. return nil
  475. }
  476. func (container *Container) export(ctx context.Context) (archive.Archive, error) {
  477. if err := container.Mount(ctx); err != nil {
  478. return nil, err
  479. }
  480. archive, err := archive.Tar(container.basefs, archive.Uncompressed)
  481. if err != nil {
  482. container.Unmount(ctx)
  483. return nil, err
  484. }
  485. arch := ioutils.NewReadCloserWrapper(archive, func() error {
  486. err := archive.Close()
  487. container.Unmount(ctx)
  488. return err
  489. })
  490. container.logEvent(ctx, "export")
  491. return arch, err
  492. }
  493. // Mount sets container.basefs
  494. func (container *Container) Mount(ctx context.Context) error {
  495. return container.daemon.Mount(ctx, container)
  496. }
  497. func (container *Container) changes() ([]archive.Change, error) {
  498. container.Lock()
  499. defer container.Unlock()
  500. return container.daemon.changes(container)
  501. }
  502. func (container *Container) getImage(ctx context.Context) (*image.Image, error) {
  503. if container.daemon == nil {
  504. return nil, derr.ErrorCodeImageUnregContainer
  505. }
  506. return container.daemon.graph.Get(container.ImageID)
  507. }
  508. // Unmount asks the daemon to release the layered filesystems that are
  509. // mounted by the container.
  510. func (container *Container) Unmount(ctx context.Context) error {
  511. return container.daemon.unmount(container)
  512. }
  513. func (container *Container) hostConfigPath() (string, error) {
  514. return container.getRootResourcePath("hostconfig.json")
  515. }
  516. func (container *Container) jsonPath() (string, error) {
  517. return container.getRootResourcePath("config.json")
  518. }
  519. // This method must be exported to be used from the lxc template
  520. // This directory is only usable when the container is running
  521. func (container *Container) rootfsPath() string {
  522. return container.basefs
  523. }
  524. func validateID(id string) error {
  525. if id == "" {
  526. return derr.ErrorCodeEmptyID
  527. }
  528. return nil
  529. }
  530. func (container *Container) copy(ctx context.Context, resource string) (rc io.ReadCloser, err error) {
  531. container.Lock()
  532. defer func() {
  533. if err != nil {
  534. // Wait to unlock the container until the archive is fully read
  535. // (see the ReadCloseWrapper func below) or if there is an error
  536. // before that occurs.
  537. container.Unlock()
  538. }
  539. }()
  540. if err := container.Mount(ctx); err != nil {
  541. return nil, err
  542. }
  543. defer func() {
  544. if err != nil {
  545. // unmount any volumes
  546. container.unmountVolumes(true)
  547. // unmount the container's rootfs
  548. container.Unmount(ctx)
  549. }
  550. }()
  551. if err := container.mountVolumes(); err != nil {
  552. return nil, err
  553. }
  554. basePath, err := container.GetResourcePath(resource)
  555. if err != nil {
  556. return nil, err
  557. }
  558. stat, err := os.Stat(basePath)
  559. if err != nil {
  560. return nil, err
  561. }
  562. var filter []string
  563. if !stat.IsDir() {
  564. d, f := filepath.Split(basePath)
  565. basePath = d
  566. filter = []string{f}
  567. } else {
  568. filter = []string{filepath.Base(basePath)}
  569. basePath = filepath.Dir(basePath)
  570. }
  571. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  572. Compression: archive.Uncompressed,
  573. IncludeFiles: filter,
  574. })
  575. if err != nil {
  576. return nil, err
  577. }
  578. reader := ioutils.NewReadCloserWrapper(archive, func() error {
  579. err := archive.Close()
  580. container.unmountVolumes(true)
  581. container.Unmount(ctx)
  582. container.Unlock()
  583. return err
  584. })
  585. container.logEvent(ctx, "copy")
  586. return reader, nil
  587. }
  588. // Returns true if the container exposes a certain port
  589. func (container *Container) exposes(p nat.Port) bool {
  590. _, exists := container.Config.ExposedPorts[p]
  591. return exists
  592. }
  593. func (container *Container) getLogConfig() runconfig.LogConfig {
  594. cfg := container.hostConfig.LogConfig
  595. if cfg.Type != "" || len(cfg.Config) > 0 { // container has log driver configured
  596. if cfg.Type == "" {
  597. cfg.Type = jsonfilelog.Name
  598. }
  599. return cfg
  600. }
  601. // Use daemon's default log config for containers
  602. return container.daemon.defaultLogConfig
  603. }
  604. func (container *Container) getLogger() (logger.Logger, error) {
  605. if container.logDriver != nil && container.IsRunning() {
  606. return container.logDriver, nil
  607. }
  608. cfg := container.getLogConfig()
  609. if err := logger.ValidateLogOpts(cfg.Type, cfg.Config); err != nil {
  610. return nil, err
  611. }
  612. c, err := logger.GetLogDriver(cfg.Type)
  613. if err != nil {
  614. return nil, derr.ErrorCodeLoggingFactory.WithArgs(err)
  615. }
  616. ctx := logger.Context{
  617. Config: cfg.Config,
  618. ContainerID: container.ID,
  619. ContainerName: container.Name,
  620. ContainerEntrypoint: container.Path,
  621. ContainerArgs: container.Args,
  622. ContainerImageID: container.ImageID,
  623. ContainerImageName: container.Config.Image,
  624. ContainerCreated: container.Created,
  625. }
  626. // Set logging file for "json-logger"
  627. if cfg.Type == jsonfilelog.Name {
  628. ctx.LogPath, err = container.getRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  629. if err != nil {
  630. return nil, err
  631. }
  632. }
  633. return c(ctx)
  634. }
  635. func (container *Container) startLogging() error {
  636. cfg := container.getLogConfig()
  637. if cfg.Type == "none" {
  638. return nil // do not start logging routines
  639. }
  640. l, err := container.getLogger()
  641. if err != nil {
  642. return derr.ErrorCodeInitLogger.WithArgs(err)
  643. }
  644. copier := logger.NewCopier(container.ID, map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  645. container.logCopier = copier
  646. copier.Run()
  647. container.logDriver = l
  648. // set LogPath field only for json-file logdriver
  649. if jl, ok := l.(*jsonfilelog.JSONFileLogger); ok {
  650. container.LogPath = jl.LogPath()
  651. }
  652. return nil
  653. }
  654. func (container *Container) waitForStart(ctx context.Context) error {
  655. container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy)
  656. // block until we either receive an error from the initial start of the container's
  657. // process or until the process is running in the container
  658. select {
  659. case <-container.monitor.startSignal:
  660. case err := <-promise.Go(func() error { return container.monitor.Start(ctx) }):
  661. return err
  662. }
  663. return nil
  664. }
  665. func (container *Container) getProcessLabel() string {
  666. // even if we have a process label return "" if we are running
  667. // in privileged mode
  668. if container.hostConfig.Privileged {
  669. return ""
  670. }
  671. return container.ProcessLabel
  672. }
  673. func (container *Container) getMountLabel() string {
  674. if container.hostConfig.Privileged {
  675. return ""
  676. }
  677. return container.MountLabel
  678. }
  679. func (container *Container) stats() (*execdriver.ResourceStats, error) {
  680. return container.daemon.stats(container)
  681. }
  682. func (container *Container) getExecIDs() []string {
  683. return container.execCommands.List()
  684. }
  685. func (container *Container) exec(ctx context.Context, ExecConfig *ExecConfig) error {
  686. container.Lock()
  687. defer container.Unlock()
  688. callback := func(ctx context.Context, processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error {
  689. if processConfig.Tty {
  690. // The callback is called after the process Start()
  691. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
  692. // which we close here.
  693. if c, ok := processConfig.Stdout.(io.Closer); ok {
  694. c.Close()
  695. }
  696. }
  697. close(ExecConfig.waitStart)
  698. return nil
  699. }
  700. // We use a callback here instead of a goroutine and an chan for
  701. // synchronization purposes
  702. cErr := promise.Go(func() error { return container.monitorExec(ctx, ExecConfig, callback) })
  703. // Exec should not return until the process is actually running
  704. select {
  705. case <-ExecConfig.waitStart:
  706. case err := <-cErr:
  707. return err
  708. }
  709. return nil
  710. }
  711. func (container *Container) monitorExec(ctx context.Context, ExecConfig *ExecConfig, callback execdriver.DriverCallback) error {
  712. var (
  713. err error
  714. exitCode int
  715. )
  716. pipes := execdriver.NewPipes(ExecConfig.streamConfig.stdin, ExecConfig.streamConfig.stdout, ExecConfig.streamConfig.stderr, ExecConfig.OpenStdin)
  717. exitCode, err = container.daemon.Exec(ctx, container, ExecConfig, pipes, callback)
  718. if err != nil {
  719. logrus.Errorf("Error running command in existing container %s: %s", container.ID, err)
  720. }
  721. logrus.Debugf("Exec task in container %s exited with code %d", container.ID, exitCode)
  722. if ExecConfig.OpenStdin {
  723. if err := ExecConfig.streamConfig.stdin.Close(); err != nil {
  724. logrus.Errorf("Error closing stdin while running in %s: %s", container.ID, err)
  725. }
  726. }
  727. if err := ExecConfig.streamConfig.stdout.Clean(); err != nil {
  728. logrus.Errorf("Error closing stdout while running in %s: %s", container.ID, err)
  729. }
  730. if err := ExecConfig.streamConfig.stderr.Clean(); err != nil {
  731. logrus.Errorf("Error closing stderr while running in %s: %s", container.ID, err)
  732. }
  733. if ExecConfig.ProcessConfig.Terminal != nil {
  734. if err := ExecConfig.ProcessConfig.Terminal.Close(); err != nil {
  735. logrus.Errorf("Error closing terminal while running in container %s: %s", container.ID, err)
  736. }
  737. }
  738. // remove the exec command from the container's store only and not the
  739. // daemon's store so that the exec command can be inspected.
  740. container.execCommands.Delete(ExecConfig.ID)
  741. return err
  742. }
  743. // Attach connects to the container's TTY, delegating to standard
  744. // streams or websockets depending on the configuration.
  745. func (container *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
  746. return attach(&container.streamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, stdin, stdout, stderr)
  747. }
  748. func (container *Container) attachWithLogs(ctx context.Context, stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error {
  749. if logs {
  750. logDriver, err := container.getLogger()
  751. if err != nil {
  752. return err
  753. }
  754. cLog, ok := logDriver.(logger.LogReader)
  755. if !ok {
  756. return logger.ErrReadLogsNotSupported
  757. }
  758. logs := cLog.ReadLogs(logger.ReadConfig{Tail: -1})
  759. LogLoop:
  760. for {
  761. select {
  762. case msg, ok := <-logs.Msg:
  763. if !ok {
  764. break LogLoop
  765. }
  766. if msg.Source == "stdout" && stdout != nil {
  767. stdout.Write(msg.Line)
  768. }
  769. if msg.Source == "stderr" && stderr != nil {
  770. stderr.Write(msg.Line)
  771. }
  772. case err := <-logs.Err:
  773. logrus.Errorf("Error streaming logs: %v", err)
  774. break LogLoop
  775. }
  776. }
  777. }
  778. container.logEvent(ctx, "attach")
  779. //stream
  780. if stream {
  781. var stdinPipe io.ReadCloser
  782. if stdin != nil {
  783. r, w := io.Pipe()
  784. go func() {
  785. defer w.Close()
  786. defer logrus.Debugf("Closing buffered stdin pipe")
  787. io.Copy(w, stdin)
  788. }()
  789. stdinPipe = r
  790. }
  791. <-container.Attach(stdinPipe, stdout, stderr)
  792. // If we are in stdinonce mode, wait for the process to end
  793. // otherwise, simply return
  794. if container.Config.StdinOnce && !container.Config.Tty {
  795. container.WaitStop(-1 * time.Second)
  796. }
  797. }
  798. return nil
  799. }
  800. func attach(streamConfig *streamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
  801. var (
  802. cStdout, cStderr io.ReadCloser
  803. cStdin io.WriteCloser
  804. wg sync.WaitGroup
  805. errors = make(chan error, 3)
  806. )
  807. if stdin != nil && openStdin {
  808. cStdin = streamConfig.StdinPipe()
  809. wg.Add(1)
  810. }
  811. if stdout != nil {
  812. cStdout = streamConfig.StdoutPipe()
  813. wg.Add(1)
  814. }
  815. if stderr != nil {
  816. cStderr = streamConfig.StderrPipe()
  817. wg.Add(1)
  818. }
  819. // Connect stdin of container to the http conn.
  820. go func() {
  821. if stdin == nil || !openStdin {
  822. return
  823. }
  824. logrus.Debugf("attach: stdin: begin")
  825. defer func() {
  826. if stdinOnce && !tty {
  827. cStdin.Close()
  828. } else {
  829. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  830. if cStdout != nil {
  831. cStdout.Close()
  832. }
  833. if cStderr != nil {
  834. cStderr.Close()
  835. }
  836. }
  837. wg.Done()
  838. logrus.Debugf("attach: stdin: end")
  839. }()
  840. var err error
  841. if tty {
  842. _, err = copyEscapable(cStdin, stdin)
  843. } else {
  844. _, err = io.Copy(cStdin, stdin)
  845. }
  846. if err == io.ErrClosedPipe {
  847. err = nil
  848. }
  849. if err != nil {
  850. logrus.Errorf("attach: stdin: %s", err)
  851. errors <- err
  852. return
  853. }
  854. }()
  855. attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) {
  856. if stream == nil {
  857. return
  858. }
  859. defer func() {
  860. // Make sure stdin gets closed
  861. if stdin != nil {
  862. stdin.Close()
  863. }
  864. streamPipe.Close()
  865. wg.Done()
  866. logrus.Debugf("attach: %s: end", name)
  867. }()
  868. logrus.Debugf("attach: %s: begin", name)
  869. _, err := io.Copy(stream, streamPipe)
  870. if err == io.ErrClosedPipe {
  871. err = nil
  872. }
  873. if err != nil {
  874. logrus.Errorf("attach: %s: %v", name, err)
  875. errors <- err
  876. }
  877. }
  878. go attachStream("stdout", stdout, cStdout)
  879. go attachStream("stderr", stderr, cStderr)
  880. return promise.Go(func() error {
  881. wg.Wait()
  882. close(errors)
  883. for err := range errors {
  884. if err != nil {
  885. return err
  886. }
  887. }
  888. return nil
  889. })
  890. }
  891. // Code c/c from io.Copy() modified to handle escape sequence
  892. func copyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  893. buf := make([]byte, 32*1024)
  894. for {
  895. nr, er := src.Read(buf)
  896. if nr > 0 {
  897. // ---- Docker addition
  898. // char 16 is C-p
  899. if nr == 1 && buf[0] == 16 {
  900. nr, er = src.Read(buf)
  901. // char 17 is C-q
  902. if nr == 1 && buf[0] == 17 {
  903. if err := src.Close(); err != nil {
  904. return 0, err
  905. }
  906. return 0, nil
  907. }
  908. }
  909. // ---- End of docker
  910. nw, ew := dst.Write(buf[0:nr])
  911. if nw > 0 {
  912. written += int64(nw)
  913. }
  914. if ew != nil {
  915. err = ew
  916. break
  917. }
  918. if nr != nw {
  919. err = io.ErrShortWrite
  920. break
  921. }
  922. }
  923. if er == io.EOF {
  924. break
  925. }
  926. if er != nil {
  927. err = er
  928. break
  929. }
  930. }
  931. return written, err
  932. }
  933. func (container *Container) shouldRestart() bool {
  934. return container.hostConfig.RestartPolicy.Name == "always" ||
  935. (container.hostConfig.RestartPolicy.Name == "unless-stopped" && !container.HasBeenManuallyStopped) ||
  936. (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0)
  937. }
  938. func (container *Container) mountVolumes() error {
  939. mounts, err := container.setupMounts()
  940. if err != nil {
  941. return err
  942. }
  943. for _, m := range mounts {
  944. dest, err := container.GetResourcePath(m.Destination)
  945. if err != nil {
  946. return err
  947. }
  948. var stat os.FileInfo
  949. stat, err = os.Stat(m.Source)
  950. if err != nil {
  951. return err
  952. }
  953. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  954. return err
  955. }
  956. opts := "rbind,ro"
  957. if m.Writable {
  958. opts = "rbind,rw"
  959. }
  960. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  961. return err
  962. }
  963. }
  964. return nil
  965. }
  966. func (container *Container) copyImagePathContent(v volume.Volume, destination string) error {
  967. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs)
  968. if err != nil {
  969. return err
  970. }
  971. if _, err = ioutil.ReadDir(rootfs); err != nil {
  972. if os.IsNotExist(err) {
  973. return nil
  974. }
  975. return err
  976. }
  977. path, err := v.Mount()
  978. if err != nil {
  979. return err
  980. }
  981. if err := copyExistingContents(rootfs, path); err != nil {
  982. return err
  983. }
  984. return v.Unmount()
  985. }
  986. func (container *Container) stopSignal() int {
  987. var stopSignal syscall.Signal
  988. if container.Config.StopSignal != "" {
  989. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  990. }
  991. if int(stopSignal) == 0 {
  992. stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
  993. }
  994. return int(stopSignal)
  995. }