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