container.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. if err := container.CleanupStorage(); err != nil {
  297. logrus.Errorf("%v: Failed to cleanup storage: %v", container.ID, err)
  298. }
  299. if err := container.Unmount(); err != nil {
  300. logrus.Errorf("%v: 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. func (container *Container) KillSig(sig int) error {
  308. logrus.Debugf("Sending %d to %s", sig, container.ID)
  309. container.Lock()
  310. defer container.Unlock()
  311. // We could unpause the container for them rather than returning this error
  312. if container.Paused {
  313. return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID)
  314. }
  315. if !container.Running {
  316. return ErrContainerNotRunning{container.ID}
  317. }
  318. // signal to the monitor that it should not restart the container
  319. // after we send the kill signal
  320. container.monitor.ExitOnNext()
  321. // if the container is currently restarting we do not need to send the signal
  322. // to the process. Telling the monitor that it should exit on it's next event
  323. // loop is enough
  324. if container.Restarting {
  325. return nil
  326. }
  327. if err := container.daemon.Kill(container, sig); err != nil {
  328. return err
  329. }
  330. container.LogEvent("kill")
  331. return nil
  332. }
  333. // Wrapper aroung KillSig() suppressing "no such process" error.
  334. func (container *Container) killPossiblyDeadProcess(sig int) error {
  335. err := container.KillSig(sig)
  336. if err == syscall.ESRCH {
  337. logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPid(), sig)
  338. return nil
  339. }
  340. return err
  341. }
  342. func (container *Container) Pause() error {
  343. container.Lock()
  344. defer container.Unlock()
  345. // We cannot Pause the container which is not running
  346. if !container.Running {
  347. return ErrContainerNotRunning{container.ID}
  348. }
  349. // We cannot Pause the container which is already paused
  350. if container.Paused {
  351. return fmt.Errorf("Container %s is already paused", container.ID)
  352. }
  353. if err := container.daemon.execDriver.Pause(container.command); err != nil {
  354. return err
  355. }
  356. container.Paused = true
  357. container.LogEvent("pause")
  358. return nil
  359. }
  360. func (container *Container) Unpause() error {
  361. container.Lock()
  362. defer container.Unlock()
  363. // We cannot unpause the container which is not running
  364. if !container.Running {
  365. return ErrContainerNotRunning{container.ID}
  366. }
  367. // We cannot unpause the container which is not paused
  368. if !container.Paused {
  369. return fmt.Errorf("Container %s is not paused", container.ID)
  370. }
  371. if err := container.daemon.execDriver.Unpause(container.command); err != nil {
  372. return err
  373. }
  374. container.Paused = false
  375. container.LogEvent("unpause")
  376. return nil
  377. }
  378. func (container *Container) Kill() error {
  379. if !container.IsRunning() {
  380. return ErrContainerNotRunning{container.ID}
  381. }
  382. // 1. Send SIGKILL
  383. if err := container.killPossiblyDeadProcess(9); err != nil {
  384. // While normally we might "return err" here we're not going to
  385. // because if we can't stop the container by this point then
  386. // its probably because its already stopped. Meaning, between
  387. // the time of the IsRunning() call above and now it stopped.
  388. // Also, since the err return will be exec driver specific we can't
  389. // look for any particular (common) error that would indicate
  390. // that the process is already dead vs something else going wrong.
  391. // So, instead we'll give it up to 2 more seconds to complete and if
  392. // by that time the container is still running, then the error
  393. // we got is probably valid and so we return it to the caller.
  394. if container.IsRunning() {
  395. container.WaitStop(2 * time.Second)
  396. if container.IsRunning() {
  397. return err
  398. }
  399. }
  400. }
  401. // 2. Wait for the process to die, in last resort, try to kill the process directly
  402. if err := killProcessDirectly(container); err != nil {
  403. return err
  404. }
  405. container.WaitStop(-1 * time.Second)
  406. return nil
  407. }
  408. func (container *Container) Stop(seconds int) error {
  409. if !container.IsRunning() {
  410. return nil
  411. }
  412. // 1. Send a SIGTERM
  413. if err := container.killPossiblyDeadProcess(15); err != nil {
  414. logrus.Infof("Failed to send SIGTERM to the process, force killing")
  415. if err := container.killPossiblyDeadProcess(9); err != nil {
  416. return err
  417. }
  418. }
  419. // 2. Wait for the process to exit on its own
  420. if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil {
  421. logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  422. // 3. If it doesn't, then send SIGKILL
  423. if err := container.Kill(); err != nil {
  424. container.WaitStop(-1 * time.Second)
  425. return err
  426. }
  427. }
  428. container.LogEvent("stop")
  429. return nil
  430. }
  431. func (container *Container) Restart(seconds int) error {
  432. // Avoid unnecessarily unmounting and then directly mounting
  433. // the container when the container stops and then starts
  434. // again
  435. if err := container.Mount(); err == nil {
  436. defer container.Unmount()
  437. }
  438. if err := container.Stop(seconds); err != nil {
  439. return err
  440. }
  441. if err := container.Start(); err != nil {
  442. return err
  443. }
  444. container.LogEvent("restart")
  445. return nil
  446. }
  447. func (container *Container) Resize(h, w int) error {
  448. if !container.IsRunning() {
  449. return ErrContainerNotRunning{container.ID}
  450. }
  451. if err := container.command.ProcessConfig.Terminal.Resize(h, w); err != nil {
  452. return err
  453. }
  454. container.LogEvent("resize")
  455. return nil
  456. }
  457. func (container *Container) Export() (archive.Archive, error) {
  458. if err := container.Mount(); err != nil {
  459. return nil, err
  460. }
  461. archive, err := archive.Tar(container.basefs, archive.Uncompressed)
  462. if err != nil {
  463. container.Unmount()
  464. return nil, err
  465. }
  466. arch := ioutils.NewReadCloserWrapper(archive, func() error {
  467. err := archive.Close()
  468. container.Unmount()
  469. return err
  470. })
  471. container.LogEvent("export")
  472. return arch, err
  473. }
  474. func (container *Container) Mount() error {
  475. return container.daemon.Mount(container)
  476. }
  477. func (container *Container) changes() ([]archive.Change, error) {
  478. return container.daemon.Changes(container)
  479. }
  480. func (container *Container) Changes() ([]archive.Change, error) {
  481. container.Lock()
  482. defer container.Unlock()
  483. return container.changes()
  484. }
  485. func (container *Container) GetImage() (*image.Image, error) {
  486. if container.daemon == nil {
  487. return nil, fmt.Errorf("Can't get image of unregistered container")
  488. }
  489. return container.daemon.graph.Get(container.ImageID)
  490. }
  491. func (container *Container) Unmount() error {
  492. return container.daemon.Unmount(container)
  493. }
  494. func (container *Container) hostConfigPath() (string, error) {
  495. return container.GetRootResourcePath("hostconfig.json")
  496. }
  497. func (container *Container) jsonPath() (string, error) {
  498. return container.GetRootResourcePath("config.json")
  499. }
  500. // This method must be exported to be used from the lxc template
  501. // This directory is only usable when the container is running
  502. func (container *Container) RootfsPath() string {
  503. return container.basefs
  504. }
  505. func validateID(id string) error {
  506. if id == "" {
  507. return fmt.Errorf("Invalid empty id")
  508. }
  509. return nil
  510. }
  511. func (container *Container) Copy(resource string) (rc io.ReadCloser, err error) {
  512. container.Lock()
  513. defer func() {
  514. if err != nil {
  515. // Wait to unlock the container until the archive is fully read
  516. // (see the ReadCloseWrapper func below) or if there is an error
  517. // before that occurs.
  518. container.Unlock()
  519. }
  520. }()
  521. if err := container.Mount(); err != nil {
  522. return nil, err
  523. }
  524. defer func() {
  525. if err != nil {
  526. // unmount any volumes
  527. container.UnmountVolumes(true)
  528. // unmount the container's rootfs
  529. container.Unmount()
  530. }
  531. }()
  532. if err := container.mountVolumes(); err != nil {
  533. return nil, err
  534. }
  535. basePath, err := container.GetResourcePath(resource)
  536. if err != nil {
  537. return nil, err
  538. }
  539. stat, err := os.Stat(basePath)
  540. if err != nil {
  541. return nil, err
  542. }
  543. var filter []string
  544. if !stat.IsDir() {
  545. d, f := filepath.Split(basePath)
  546. basePath = d
  547. filter = []string{f}
  548. } else {
  549. filter = []string{filepath.Base(basePath)}
  550. basePath = filepath.Dir(basePath)
  551. }
  552. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  553. Compression: archive.Uncompressed,
  554. IncludeFiles: filter,
  555. })
  556. if err != nil {
  557. return nil, err
  558. }
  559. if err := container.PrepareStorage(); err != nil {
  560. container.Unmount()
  561. return nil, err
  562. }
  563. reader := ioutils.NewReadCloserWrapper(archive, func() error {
  564. err := archive.Close()
  565. container.CleanupStorage()
  566. container.UnmountVolumes(true)
  567. container.Unmount()
  568. container.Unlock()
  569. return err
  570. })
  571. container.LogEvent("copy")
  572. return reader, nil
  573. }
  574. // Returns true if the container exposes a certain port
  575. func (container *Container) Exposes(p nat.Port) bool {
  576. _, exists := container.Config.ExposedPorts[p]
  577. return exists
  578. }
  579. func (container *Container) HostConfig() *runconfig.HostConfig {
  580. return container.hostConfig
  581. }
  582. func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) {
  583. container.hostConfig = hostConfig
  584. }
  585. func (container *Container) getLogConfig() runconfig.LogConfig {
  586. cfg := container.hostConfig.LogConfig
  587. if cfg.Type != "" || len(cfg.Config) > 0 { // container has log driver configured
  588. if cfg.Type == "" {
  589. cfg.Type = jsonfilelog.Name
  590. }
  591. return cfg
  592. }
  593. // Use daemon's default log config for containers
  594. return container.daemon.defaultLogConfig
  595. }
  596. func (container *Container) getLogger() (logger.Logger, error) {
  597. if container.logDriver != nil && container.IsRunning() {
  598. return container.logDriver, nil
  599. }
  600. cfg := container.getLogConfig()
  601. if err := logger.ValidateLogOpts(cfg.Type, cfg.Config); err != nil {
  602. return nil, err
  603. }
  604. c, err := logger.GetLogDriver(cfg.Type)
  605. if err != nil {
  606. return nil, fmt.Errorf("Failed to get logging factory: %v", err)
  607. }
  608. ctx := logger.Context{
  609. Config: cfg.Config,
  610. ContainerID: container.ID,
  611. ContainerName: container.Name,
  612. ContainerEntrypoint: container.Path,
  613. ContainerArgs: container.Args,
  614. ContainerImageID: container.ImageID,
  615. ContainerImageName: container.Config.Image,
  616. ContainerCreated: container.Created,
  617. }
  618. // Set logging file for "json-logger"
  619. if cfg.Type == jsonfilelog.Name {
  620. ctx.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  621. if err != nil {
  622. return nil, err
  623. }
  624. }
  625. return c(ctx)
  626. }
  627. func (container *Container) startLogging() error {
  628. cfg := container.getLogConfig()
  629. if cfg.Type == "none" {
  630. return nil // do not start logging routines
  631. }
  632. l, err := container.getLogger()
  633. if err != nil {
  634. return fmt.Errorf("Failed to initialize logging driver: %v", err)
  635. }
  636. copier := logger.NewCopier(container.ID, map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  637. container.logCopier = copier
  638. copier.Run()
  639. container.logDriver = l
  640. // set LogPath field only for json-file logdriver
  641. if jl, ok := l.(*jsonfilelog.JSONFileLogger); ok {
  642. container.LogPath = jl.LogPath()
  643. }
  644. return nil
  645. }
  646. func (container *Container) waitForStart() error {
  647. container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy)
  648. // block until we either receive an error from the initial start of the container's
  649. // process or until the process is running in the container
  650. select {
  651. case <-container.monitor.startSignal:
  652. case err := <-promise.Go(container.monitor.Start):
  653. return err
  654. }
  655. return nil
  656. }
  657. func (container *Container) GetProcessLabel() string {
  658. // even if we have a process label return "" if we are running
  659. // in privileged mode
  660. if container.hostConfig.Privileged {
  661. return ""
  662. }
  663. return container.ProcessLabel
  664. }
  665. func (container *Container) GetMountLabel() string {
  666. if container.hostConfig.Privileged {
  667. return ""
  668. }
  669. return container.MountLabel
  670. }
  671. func (container *Container) Stats() (*execdriver.ResourceStats, error) {
  672. return container.daemon.Stats(container)
  673. }
  674. func (c *Container) LogDriverType() string {
  675. c.Lock()
  676. defer c.Unlock()
  677. if c.hostConfig.LogConfig.Type == "" {
  678. return c.daemon.defaultLogConfig.Type
  679. }
  680. return c.hostConfig.LogConfig.Type
  681. }
  682. func (container *Container) GetExecIDs() []string {
  683. return container.execCommands.List()
  684. }
  685. func (container *Container) Exec(execConfig *execConfig) error {
  686. container.Lock()
  687. defer container.Unlock()
  688. callback := func(processConfig *execdriver.ProcessConfig, pid int) {
  689. if processConfig.Tty {
  690. // The callback is called after the process Start()
  691. // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave
  692. // which we close here.
  693. if c, ok := processConfig.Stdout.(io.Closer); ok {
  694. c.Close()
  695. }
  696. }
  697. close(execConfig.waitStart)
  698. }
  699. // We use a callback here instead of a goroutine and an chan for
  700. // syncronization purposes
  701. cErr := promise.Go(func() error { return container.monitorExec(execConfig, callback) })
  702. // Exec should not return until the process is actually running
  703. select {
  704. case <-execConfig.waitStart:
  705. case err := <-cErr:
  706. return err
  707. }
  708. return nil
  709. }
  710. func (container *Container) monitorExec(execConfig *execConfig, callback execdriver.StartCallback) error {
  711. var (
  712. err error
  713. exitCode int
  714. )
  715. pipes := execdriver.NewPipes(execConfig.StreamConfig.stdin, execConfig.StreamConfig.stdout, execConfig.StreamConfig.stderr, execConfig.OpenStdin)
  716. exitCode, err = container.daemon.Exec(container, execConfig, pipes, callback)
  717. if err != nil {
  718. logrus.Errorf("Error running command in existing container %s: %s", container.ID, err)
  719. }
  720. logrus.Debugf("Exec task in container %s exited with code %d", container.ID, exitCode)
  721. if execConfig.OpenStdin {
  722. if err := execConfig.StreamConfig.stdin.Close(); err != nil {
  723. logrus.Errorf("Error closing stdin while running in %s: %s", container.ID, err)
  724. }
  725. }
  726. if err := execConfig.StreamConfig.stdout.Clean(); err != nil {
  727. logrus.Errorf("Error closing stdout while running in %s: %s", container.ID, err)
  728. }
  729. if err := execConfig.StreamConfig.stderr.Clean(); err != nil {
  730. logrus.Errorf("Error closing stderr while running in %s: %s", container.ID, err)
  731. }
  732. if execConfig.ProcessConfig.Terminal != nil {
  733. if err := execConfig.ProcessConfig.Terminal.Close(); err != nil {
  734. logrus.Errorf("Error closing terminal while running in container %s: %s", container.ID, err)
  735. }
  736. }
  737. // remove the exec command from the container's store only and not the
  738. // daemon's store so that the exec command can be inspected.
  739. container.execCommands.Delete(execConfig.ID)
  740. return err
  741. }
  742. func (c *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
  743. return attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, stdin, stdout, stderr)
  744. }
  745. func (c *Container) AttachWithLogs(stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error {
  746. if logs {
  747. logDriver, err := c.getLogger()
  748. if err != nil {
  749. return err
  750. }
  751. cLog, ok := logDriver.(logger.LogReader)
  752. if !ok {
  753. return logger.ErrReadLogsNotSupported
  754. }
  755. logs := cLog.ReadLogs(logger.ReadConfig{Tail: -1})
  756. LogLoop:
  757. for {
  758. select {
  759. case msg, ok := <-logs.Msg:
  760. if !ok {
  761. break LogLoop
  762. }
  763. if msg.Source == "stdout" && stdout != nil {
  764. stdout.Write(msg.Line)
  765. }
  766. if msg.Source == "stderr" && stderr != nil {
  767. stderr.Write(msg.Line)
  768. }
  769. case err := <-logs.Err:
  770. logrus.Errorf("Error streaming logs: %v", err)
  771. break LogLoop
  772. }
  773. }
  774. }
  775. c.LogEvent("attach")
  776. //stream
  777. if stream {
  778. var stdinPipe io.ReadCloser
  779. if stdin != nil {
  780. r, w := io.Pipe()
  781. go func() {
  782. defer w.Close()
  783. defer logrus.Debugf("Closing buffered stdin pipe")
  784. io.Copy(w, stdin)
  785. }()
  786. stdinPipe = r
  787. }
  788. <-c.Attach(stdinPipe, stdout, stderr)
  789. // If we are in stdinonce mode, wait for the process to end
  790. // otherwise, simply return
  791. if c.Config.StdinOnce && !c.Config.Tty {
  792. c.WaitStop(-1 * time.Second)
  793. }
  794. }
  795. return nil
  796. }
  797. func attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error {
  798. var (
  799. cStdout, cStderr io.ReadCloser
  800. cStdin io.WriteCloser
  801. wg sync.WaitGroup
  802. errors = make(chan error, 3)
  803. )
  804. if stdin != nil && openStdin {
  805. cStdin = streamConfig.StdinPipe()
  806. wg.Add(1)
  807. }
  808. if stdout != nil {
  809. cStdout = streamConfig.StdoutPipe()
  810. wg.Add(1)
  811. }
  812. if stderr != nil {
  813. cStderr = streamConfig.StderrPipe()
  814. wg.Add(1)
  815. }
  816. // Connect stdin of container to the http conn.
  817. go func() {
  818. if stdin == nil || !openStdin {
  819. return
  820. }
  821. logrus.Debugf("attach: stdin: begin")
  822. defer func() {
  823. if stdinOnce && !tty {
  824. cStdin.Close()
  825. } else {
  826. // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
  827. if cStdout != nil {
  828. cStdout.Close()
  829. }
  830. if cStderr != nil {
  831. cStderr.Close()
  832. }
  833. }
  834. wg.Done()
  835. logrus.Debugf("attach: stdin: end")
  836. }()
  837. var err error
  838. if tty {
  839. _, err = copyEscapable(cStdin, stdin)
  840. } else {
  841. _, err = io.Copy(cStdin, stdin)
  842. }
  843. if err == io.ErrClosedPipe {
  844. err = nil
  845. }
  846. if err != nil {
  847. logrus.Errorf("attach: stdin: %s", err)
  848. errors <- err
  849. return
  850. }
  851. }()
  852. attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) {
  853. if stream == nil {
  854. return
  855. }
  856. defer func() {
  857. // Make sure stdin gets closed
  858. if stdin != nil {
  859. stdin.Close()
  860. }
  861. streamPipe.Close()
  862. wg.Done()
  863. logrus.Debugf("attach: %s: end", name)
  864. }()
  865. logrus.Debugf("attach: %s: begin", name)
  866. _, err := io.Copy(stream, streamPipe)
  867. if err == io.ErrClosedPipe {
  868. err = nil
  869. }
  870. if err != nil {
  871. logrus.Errorf("attach: %s: %v", name, err)
  872. errors <- err
  873. }
  874. }
  875. go attachStream("stdout", stdout, cStdout)
  876. go attachStream("stderr", stderr, cStderr)
  877. return promise.Go(func() error {
  878. wg.Wait()
  879. close(errors)
  880. for err := range errors {
  881. if err != nil {
  882. return err
  883. }
  884. }
  885. return nil
  886. })
  887. }
  888. // Code c/c from io.Copy() modified to handle escape sequence
  889. func copyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  890. buf := make([]byte, 32*1024)
  891. for {
  892. nr, er := src.Read(buf)
  893. if nr > 0 {
  894. // ---- Docker addition
  895. // char 16 is C-p
  896. if nr == 1 && buf[0] == 16 {
  897. nr, er = src.Read(buf)
  898. // char 17 is C-q
  899. if nr == 1 && buf[0] == 17 {
  900. if err := src.Close(); err != nil {
  901. return 0, err
  902. }
  903. return 0, nil
  904. }
  905. }
  906. // ---- End of docker
  907. nw, ew := dst.Write(buf[0:nr])
  908. if nw > 0 {
  909. written += int64(nw)
  910. }
  911. if ew != nil {
  912. err = ew
  913. break
  914. }
  915. if nr != nw {
  916. err = io.ErrShortWrite
  917. break
  918. }
  919. }
  920. if er == io.EOF {
  921. break
  922. }
  923. if er != nil {
  924. err = er
  925. break
  926. }
  927. }
  928. return written, err
  929. }
  930. func (container *Container) shouldRestart() bool {
  931. return container.hostConfig.RestartPolicy.Name == "always" ||
  932. (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0)
  933. }
  934. func (container *Container) mountVolumes() error {
  935. mounts, err := container.setupMounts()
  936. if err != nil {
  937. return err
  938. }
  939. for _, m := range mounts {
  940. dest, err := container.GetResourcePath(m.Destination)
  941. if err != nil {
  942. return err
  943. }
  944. var stat os.FileInfo
  945. stat, err = os.Stat(m.Source)
  946. if err != nil {
  947. return err
  948. }
  949. if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {
  950. return err
  951. }
  952. opts := "rbind,ro"
  953. if m.Writable {
  954. opts = "rbind,rw"
  955. }
  956. if err := mount.Mount(m.Source, dest, "bind", opts); err != nil {
  957. return err
  958. }
  959. }
  960. return nil
  961. }
  962. func (container *Container) copyImagePathContent(v volume.Volume, destination string) error {
  963. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs)
  964. if err != nil {
  965. return err
  966. }
  967. if _, err = ioutil.ReadDir(rootfs); err != nil {
  968. if os.IsNotExist(err) {
  969. return nil
  970. }
  971. return err
  972. }
  973. path, err := v.Mount()
  974. if err != nil {
  975. return err
  976. }
  977. if err := copyExistingContents(rootfs, path); err != nil {
  978. return err
  979. }
  980. return v.Unmount()
  981. }