container.go 33 KB

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