container.go 31 KB

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