container.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. package container // import "github.com/docker/docker/container"
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. "github.com/containerd/containerd/cio"
  16. containertypes "github.com/docker/docker/api/types/container"
  17. mounttypes "github.com/docker/docker/api/types/mount"
  18. swarmtypes "github.com/docker/docker/api/types/swarm"
  19. "github.com/docker/docker/container/stream"
  20. "github.com/docker/docker/daemon/exec"
  21. "github.com/docker/docker/daemon/logger"
  22. "github.com/docker/docker/daemon/logger/jsonfilelog"
  23. "github.com/docker/docker/daemon/logger/local"
  24. "github.com/docker/docker/daemon/logger/loggerutils/cache"
  25. "github.com/docker/docker/daemon/network"
  26. "github.com/docker/docker/errdefs"
  27. "github.com/docker/docker/image"
  28. "github.com/docker/docker/layer"
  29. "github.com/docker/docker/pkg/containerfs"
  30. "github.com/docker/docker/pkg/idtools"
  31. "github.com/docker/docker/pkg/ioutils"
  32. "github.com/docker/docker/pkg/signal"
  33. "github.com/docker/docker/pkg/system"
  34. "github.com/docker/docker/restartmanager"
  35. "github.com/docker/docker/volume"
  36. volumemounts "github.com/docker/docker/volume/mounts"
  37. units "github.com/docker/go-units"
  38. agentexec "github.com/docker/swarmkit/agent/exec"
  39. "github.com/moby/sys/symlink"
  40. "github.com/pkg/errors"
  41. "github.com/sirupsen/logrus"
  42. )
  43. const configFileName = "config.v2.json"
  44. // ExitStatus provides exit reasons for a container.
  45. type ExitStatus struct {
  46. // The exit code with which the container exited.
  47. ExitCode int
  48. // Whether the container encountered an OOM.
  49. OOMKilled bool
  50. // Time at which the container died
  51. ExitedAt time.Time
  52. }
  53. // Container holds the structure defining a container object.
  54. type Container struct {
  55. StreamConfig *stream.Config
  56. // embed for Container to support states directly.
  57. *State `json:"State"` // Needed for Engine API version <= 1.11
  58. Root string `json:"-"` // Path to the "home" of the container, including metadata.
  59. BaseFS containerfs.ContainerFS `json:"-"` // interface containing graphdriver mount
  60. RWLayer layer.RWLayer `json:"-"`
  61. ID string
  62. Created time.Time
  63. Managed bool
  64. Path string
  65. Args []string
  66. Config *containertypes.Config
  67. ImageID image.ID `json:"Image"`
  68. NetworkSettings *network.Settings
  69. LogPath string
  70. Name string
  71. Driver string
  72. OS string
  73. // MountLabel contains the options for the 'mount' command
  74. MountLabel string
  75. ProcessLabel string
  76. RestartCount int
  77. HasBeenStartedBefore bool
  78. HasBeenManuallyStopped bool // used for unless-stopped restart policy
  79. MountPoints map[string]*volumemounts.MountPoint
  80. HostConfig *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
  81. ExecCommands *exec.Store `json:"-"`
  82. DependencyStore agentexec.DependencyGetter `json:"-"`
  83. SecretReferences []*swarmtypes.SecretReference
  84. ConfigReferences []*swarmtypes.ConfigReference
  85. // logDriver for closing
  86. LogDriver logger.Logger `json:"-"`
  87. LogCopier *logger.Copier `json:"-"`
  88. restartManager restartmanager.RestartManager
  89. attachContext *attachContext
  90. // Fields here are specific to Unix platforms
  91. AppArmorProfile string
  92. HostnamePath string
  93. HostsPath string
  94. ShmPath string
  95. ResolvConfPath string
  96. SeccompProfile string
  97. NoNewPrivileges bool
  98. // Fields here are specific to Windows
  99. NetworkSharedContainerID string `json:"-"`
  100. SharedEndpointList []string `json:"-"`
  101. LocalLogCacheMeta localLogCacheMeta `json:",omitempty"`
  102. }
  103. type localLogCacheMeta struct {
  104. HaveNotifyEnabled bool
  105. }
  106. // NewBaseContainer creates a new container with its
  107. // basic configuration.
  108. func NewBaseContainer(id, root string) *Container {
  109. return &Container{
  110. ID: id,
  111. State: NewState(),
  112. ExecCommands: exec.NewStore(),
  113. Root: root,
  114. MountPoints: make(map[string]*volumemounts.MountPoint),
  115. StreamConfig: stream.NewConfig(),
  116. attachContext: &attachContext{},
  117. }
  118. }
  119. // FromDisk loads the container configuration stored in the host.
  120. func (container *Container) FromDisk() error {
  121. pth, err := container.ConfigPath()
  122. if err != nil {
  123. return err
  124. }
  125. jsonSource, err := os.Open(pth)
  126. if err != nil {
  127. return err
  128. }
  129. defer jsonSource.Close()
  130. dec := json.NewDecoder(jsonSource)
  131. // Load container settings
  132. if err := dec.Decode(container); err != nil {
  133. return err
  134. }
  135. // Ensure the operating system is set if blank. Assume it is the OS of the
  136. // host OS if not, to ensure containers created before multiple-OS
  137. // support are migrated
  138. if container.OS == "" {
  139. container.OS = runtime.GOOS
  140. }
  141. return container.readHostConfig()
  142. }
  143. // toDisk saves the container configuration on disk and returns a deep copy.
  144. func (container *Container) toDisk() (*Container, error) {
  145. var (
  146. buf bytes.Buffer
  147. deepCopy Container
  148. )
  149. pth, err := container.ConfigPath()
  150. if err != nil {
  151. return nil, err
  152. }
  153. // Save container settings
  154. f, err := ioutils.NewAtomicFileWriter(pth, 0600)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer f.Close()
  159. w := io.MultiWriter(&buf, f)
  160. if err := json.NewEncoder(w).Encode(container); err != nil {
  161. return nil, err
  162. }
  163. if err := json.NewDecoder(&buf).Decode(&deepCopy); err != nil {
  164. return nil, err
  165. }
  166. deepCopy.HostConfig, err = container.WriteHostConfig()
  167. if err != nil {
  168. return nil, err
  169. }
  170. return &deepCopy, nil
  171. }
  172. // CheckpointTo makes the Container's current state visible to queries, and persists state.
  173. // Callers must hold a Container lock.
  174. func (container *Container) CheckpointTo(store ViewDB) error {
  175. deepCopy, err := container.toDisk()
  176. if err != nil {
  177. return err
  178. }
  179. return store.Save(deepCopy)
  180. }
  181. // readHostConfig reads the host configuration from disk for the container.
  182. func (container *Container) readHostConfig() error {
  183. container.HostConfig = &containertypes.HostConfig{}
  184. // If the hostconfig file does not exist, do not read it.
  185. // (We still have to initialize container.HostConfig,
  186. // but that's OK, since we just did that above.)
  187. pth, err := container.HostConfigPath()
  188. if err != nil {
  189. return err
  190. }
  191. f, err := os.Open(pth)
  192. if err != nil {
  193. if os.IsNotExist(err) {
  194. return nil
  195. }
  196. return err
  197. }
  198. defer f.Close()
  199. if err := json.NewDecoder(f).Decode(&container.HostConfig); err != nil {
  200. return err
  201. }
  202. container.InitDNSHostConfig()
  203. return nil
  204. }
  205. // WriteHostConfig saves the host configuration on disk for the container,
  206. // and returns a deep copy of the saved object. Callers must hold a Container lock.
  207. func (container *Container) WriteHostConfig() (*containertypes.HostConfig, error) {
  208. var (
  209. buf bytes.Buffer
  210. deepCopy containertypes.HostConfig
  211. )
  212. pth, err := container.HostConfigPath()
  213. if err != nil {
  214. return nil, err
  215. }
  216. f, err := ioutils.NewAtomicFileWriter(pth, 0644)
  217. if err != nil {
  218. return nil, err
  219. }
  220. defer f.Close()
  221. w := io.MultiWriter(&buf, f)
  222. if err := json.NewEncoder(w).Encode(&container.HostConfig); err != nil {
  223. return nil, err
  224. }
  225. if err := json.NewDecoder(&buf).Decode(&deepCopy); err != nil {
  226. return nil, err
  227. }
  228. return &deepCopy, nil
  229. }
  230. // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
  231. func (container *Container) SetupWorkingDirectory(rootIdentity idtools.Identity) error {
  232. // TODO: LCOW Support. This will need revisiting.
  233. // We will need to do remote filesystem operations here.
  234. if container.OS != runtime.GOOS {
  235. return nil
  236. }
  237. if container.Config.WorkingDir == "" {
  238. return nil
  239. }
  240. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  241. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  242. if err != nil {
  243. return err
  244. }
  245. if err := idtools.MkdirAllAndChownNew(pth, 0755, rootIdentity); err != nil {
  246. pthInfo, err2 := os.Stat(pth)
  247. if err2 == nil && pthInfo != nil && !pthInfo.IsDir() {
  248. return errors.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  249. }
  250. return err
  251. }
  252. return nil
  253. }
  254. // GetResourcePath evaluates `path` in the scope of the container's BaseFS, with proper path
  255. // sanitisation. Symlinks are all scoped to the BaseFS of the container, as
  256. // though the container's BaseFS was `/`.
  257. //
  258. // The BaseFS of a container is the host-facing path which is bind-mounted as
  259. // `/` inside the container. This method is essentially used to access a
  260. // particular path inside the container as though you were a process in that
  261. // container.
  262. //
  263. // NOTE: The returned path is *only* safely scoped inside the container's BaseFS
  264. // if no component of the returned path changes (such as a component
  265. // symlinking to a different path) between using this method and using the
  266. // path. See symlink.FollowSymlinkInScope for more details.
  267. func (container *Container) GetResourcePath(path string) (string, error) {
  268. if container.BaseFS == nil {
  269. return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly nil")
  270. }
  271. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  272. // any filepath operations must be done in an OS agnostic way.
  273. r, e := container.BaseFS.ResolveScopedPath(path, false)
  274. // Log this here on the daemon side as there's otherwise no indication apart
  275. // from the error being propagated all the way back to the client. This makes
  276. // debugging significantly easier and clearly indicates the error comes from the daemon.
  277. if e != nil {
  278. logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", container.BaseFS.Path(), path, e)
  279. }
  280. return r, e
  281. }
  282. // GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
  283. // sanitisation. Symlinks are all scoped to the root of the container, as
  284. // though the container's root was `/`.
  285. //
  286. // The root of a container is the host-facing configuration metadata directory.
  287. // Only use this method to safely access the container's `container.json` or
  288. // other metadata files. If in doubt, use container.GetResourcePath.
  289. //
  290. // NOTE: The returned path is *only* safely scoped inside the container's root
  291. // if no component of the returned path changes (such as a component
  292. // symlinking to a different path) between using this method and using the
  293. // path. See symlink.FollowSymlinkInScope for more details.
  294. func (container *Container) GetRootResourcePath(path string) (string, error) {
  295. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  296. // any filepath operations must be done in an OS agnostic way.
  297. cleanPath := filepath.Join(string(os.PathSeparator), path)
  298. return symlink.FollowSymlinkInScope(filepath.Join(container.Root, cleanPath), container.Root)
  299. }
  300. // ExitOnNext signals to the monitor that it should not restart the container
  301. // after we send the kill signal.
  302. func (container *Container) ExitOnNext() {
  303. container.RestartManager().Cancel()
  304. }
  305. // HostConfigPath returns the path to the container's JSON hostconfig
  306. func (container *Container) HostConfigPath() (string, error) {
  307. return container.GetRootResourcePath("hostconfig.json")
  308. }
  309. // ConfigPath returns the path to the container's JSON config
  310. func (container *Container) ConfigPath() (string, error) {
  311. return container.GetRootResourcePath(configFileName)
  312. }
  313. // CheckpointDir returns the directory checkpoints are stored in
  314. func (container *Container) CheckpointDir() string {
  315. return filepath.Join(container.Root, "checkpoints")
  316. }
  317. // StartLogger starts a new logger driver for the container.
  318. func (container *Container) StartLogger() (logger.Logger, error) {
  319. cfg := container.HostConfig.LogConfig
  320. initDriver, err := logger.GetLogDriver(cfg.Type)
  321. if err != nil {
  322. return nil, errors.Wrap(err, "failed to get logging factory")
  323. }
  324. info := logger.Info{
  325. Config: cfg.Config,
  326. ContainerID: container.ID,
  327. ContainerName: container.Name,
  328. ContainerEntrypoint: container.Path,
  329. ContainerArgs: container.Args,
  330. ContainerImageID: container.ImageID.String(),
  331. ContainerImageName: container.Config.Image,
  332. ContainerCreated: container.Created,
  333. ContainerEnv: container.Config.Env,
  334. ContainerLabels: container.Config.Labels,
  335. DaemonName: "docker",
  336. }
  337. // Set logging file for "json-logger"
  338. // TODO(@cpuguy83): Setup here based on log driver is a little weird.
  339. switch cfg.Type {
  340. case jsonfilelog.Name:
  341. info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  342. if err != nil {
  343. return nil, err
  344. }
  345. container.LogPath = info.LogPath
  346. case local.Name:
  347. // Do not set container.LogPath for the local driver
  348. // This would expose the value to the API, which should not be done as it means
  349. // that the log file implementation would become a stable API that cannot change.
  350. logDir, err := container.GetRootResourcePath("local-logs")
  351. if err != nil {
  352. return nil, err
  353. }
  354. if err := os.MkdirAll(logDir, 0700); err != nil {
  355. return nil, errdefs.System(errors.Wrap(err, "error creating local logs dir"))
  356. }
  357. info.LogPath = filepath.Join(logDir, "container.log")
  358. }
  359. l, err := initDriver(info)
  360. if err != nil {
  361. return nil, err
  362. }
  363. if containertypes.LogMode(cfg.Config["mode"]) == containertypes.LogModeNonBlock {
  364. bufferSize := int64(-1)
  365. if s, exists := cfg.Config["max-buffer-size"]; exists {
  366. bufferSize, err = units.RAMInBytes(s)
  367. if err != nil {
  368. return nil, err
  369. }
  370. }
  371. l = logger.NewRingLogger(l, info, bufferSize)
  372. }
  373. if _, ok := l.(logger.LogReader); !ok {
  374. if cache.ShouldUseCache(cfg.Config) {
  375. logPath, err := container.GetRootResourcePath("container-cached.log")
  376. if err != nil {
  377. return nil, err
  378. }
  379. if !container.LocalLogCacheMeta.HaveNotifyEnabled {
  380. logrus.WithField("container", container.ID).WithField("driver", container.HostConfig.LogConfig.Type).Info("Configured log driver does not support reads, enabling local file cache for container logs")
  381. container.LocalLogCacheMeta.HaveNotifyEnabled = true
  382. }
  383. info.LogPath = logPath
  384. l, err = cache.WithLocalCache(l, info)
  385. if err != nil {
  386. return nil, errors.Wrap(err, "error setting up local container log cache")
  387. }
  388. }
  389. }
  390. return l, nil
  391. }
  392. // GetProcessLabel returns the process label for the container.
  393. func (container *Container) GetProcessLabel() string {
  394. // even if we have a process label return "" if we are running
  395. // in privileged mode
  396. if container.HostConfig.Privileged {
  397. return ""
  398. }
  399. return container.ProcessLabel
  400. }
  401. // GetMountLabel returns the mounting label for the container.
  402. // This label is empty if the container is privileged.
  403. func (container *Container) GetMountLabel() string {
  404. return container.MountLabel
  405. }
  406. // GetExecIDs returns the list of exec commands running on the container.
  407. func (container *Container) GetExecIDs() []string {
  408. return container.ExecCommands.List()
  409. }
  410. // ShouldRestart decides whether the daemon should restart the container or not.
  411. // This is based on the container's restart policy.
  412. func (container *Container) ShouldRestart() bool {
  413. shouldRestart, _, _ := container.RestartManager().ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
  414. return shouldRestart
  415. }
  416. // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
  417. func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  418. operatingSystem := container.OS
  419. if operatingSystem == "" {
  420. operatingSystem = runtime.GOOS
  421. }
  422. volumeParser := volumemounts.NewParser(operatingSystem)
  423. container.MountPoints[destination] = &volumemounts.MountPoint{
  424. Type: mounttypes.TypeVolume,
  425. Name: vol.Name(),
  426. Driver: vol.DriverName(),
  427. Destination: destination,
  428. RW: rw,
  429. Volume: vol,
  430. CopyData: volumeParser.DefaultCopyMode(),
  431. }
  432. }
  433. // UnmountVolumes unmounts all volumes
  434. func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
  435. var errors []string
  436. for _, volumeMount := range container.MountPoints {
  437. if volumeMount.Volume == nil {
  438. continue
  439. }
  440. if err := volumeMount.Cleanup(); err != nil {
  441. errors = append(errors, err.Error())
  442. continue
  443. }
  444. attributes := map[string]string{
  445. "driver": volumeMount.Volume.DriverName(),
  446. "container": container.ID,
  447. }
  448. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  449. }
  450. if len(errors) > 0 {
  451. return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
  452. }
  453. return nil
  454. }
  455. // IsDestinationMounted checks whether a path is mounted on the container or not.
  456. func (container *Container) IsDestinationMounted(destination string) bool {
  457. return container.MountPoints[destination] != nil
  458. }
  459. // StopSignal returns the signal used to stop the container.
  460. func (container *Container) StopSignal() int {
  461. var stopSignal syscall.Signal
  462. if container.Config.StopSignal != "" {
  463. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  464. }
  465. if int(stopSignal) == 0 {
  466. stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
  467. }
  468. return int(stopSignal)
  469. }
  470. // StopTimeout returns the timeout (in seconds) used to stop the container.
  471. func (container *Container) StopTimeout() int {
  472. if container.Config.StopTimeout != nil {
  473. return *container.Config.StopTimeout
  474. }
  475. return DefaultStopTimeout
  476. }
  477. // InitDNSHostConfig ensures that the dns fields are never nil.
  478. // New containers don't ever have those fields nil,
  479. // but pre created containers can still have those nil values.
  480. // The non-recommended host configuration in the start api can
  481. // make these fields nil again, this corrects that issue until
  482. // we remove that behavior for good.
  483. // See https://github.com/docker/docker/pull/17779
  484. // for a more detailed explanation on why we don't want that.
  485. func (container *Container) InitDNSHostConfig() {
  486. container.Lock()
  487. defer container.Unlock()
  488. if container.HostConfig.DNS == nil {
  489. container.HostConfig.DNS = make([]string, 0)
  490. }
  491. if container.HostConfig.DNSSearch == nil {
  492. container.HostConfig.DNSSearch = make([]string, 0)
  493. }
  494. if container.HostConfig.DNSOptions == nil {
  495. container.HostConfig.DNSOptions = make([]string, 0)
  496. }
  497. }
  498. // UpdateMonitor updates monitor configure for running container
  499. func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
  500. type policySetter interface {
  501. SetPolicy(containertypes.RestartPolicy)
  502. }
  503. if rm, ok := container.RestartManager().(policySetter); ok {
  504. rm.SetPolicy(restartPolicy)
  505. }
  506. }
  507. // FullHostname returns hostname and optional domain appended to it.
  508. func (container *Container) FullHostname() string {
  509. fullHostname := container.Config.Hostname
  510. if container.Config.Domainname != "" {
  511. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  512. }
  513. return fullHostname
  514. }
  515. // RestartManager returns the current restartmanager instance connected to container.
  516. func (container *Container) RestartManager() restartmanager.RestartManager {
  517. if container.restartManager == nil {
  518. container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
  519. }
  520. return container.restartManager
  521. }
  522. // ResetRestartManager initializes new restartmanager based on container config
  523. func (container *Container) ResetRestartManager(resetCount bool) {
  524. if container.restartManager != nil {
  525. container.restartManager.Cancel()
  526. }
  527. if resetCount {
  528. container.RestartCount = 0
  529. }
  530. container.restartManager = nil
  531. }
  532. type attachContext struct {
  533. ctx context.Context
  534. cancel context.CancelFunc
  535. mu sync.Mutex
  536. }
  537. // InitAttachContext initializes or returns existing context for attach calls to
  538. // track container liveness.
  539. func (container *Container) InitAttachContext() context.Context {
  540. container.attachContext.mu.Lock()
  541. defer container.attachContext.mu.Unlock()
  542. if container.attachContext.ctx == nil {
  543. container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
  544. }
  545. return container.attachContext.ctx
  546. }
  547. // CancelAttachContext cancels attach context. All attach calls should detach
  548. // after this call.
  549. func (container *Container) CancelAttachContext() {
  550. container.attachContext.mu.Lock()
  551. if container.attachContext.ctx != nil {
  552. container.attachContext.cancel()
  553. container.attachContext.ctx = nil
  554. }
  555. container.attachContext.mu.Unlock()
  556. }
  557. func (container *Container) startLogging() error {
  558. if container.HostConfig.LogConfig.Type == "none" {
  559. return nil // do not start logging routines
  560. }
  561. l, err := container.StartLogger()
  562. if err != nil {
  563. return fmt.Errorf("failed to initialize logging driver: %v", err)
  564. }
  565. copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  566. container.LogCopier = copier
  567. copier.Run()
  568. container.LogDriver = l
  569. return nil
  570. }
  571. // StdinPipe gets the stdin stream of the container
  572. func (container *Container) StdinPipe() io.WriteCloser {
  573. return container.StreamConfig.StdinPipe()
  574. }
  575. // StdoutPipe gets the stdout stream of the container
  576. func (container *Container) StdoutPipe() io.ReadCloser {
  577. return container.StreamConfig.StdoutPipe()
  578. }
  579. // StderrPipe gets the stderr stream of the container
  580. func (container *Container) StderrPipe() io.ReadCloser {
  581. return container.StreamConfig.StderrPipe()
  582. }
  583. // CloseStreams closes the container's stdio streams
  584. func (container *Container) CloseStreams() error {
  585. return container.StreamConfig.CloseStreams()
  586. }
  587. // InitializeStdio is called by libcontainerd to connect the stdio.
  588. func (container *Container) InitializeStdio(iop *cio.DirectIO) (cio.IO, error) {
  589. if err := container.startLogging(); err != nil {
  590. container.Reset(false)
  591. return nil, err
  592. }
  593. container.StreamConfig.CopyToPipe(iop)
  594. if container.StreamConfig.Stdin() == nil && !container.Config.Tty {
  595. if iop.Stdin != nil {
  596. if err := iop.Stdin.Close(); err != nil {
  597. logrus.Warnf("error closing stdin: %+v", err)
  598. }
  599. }
  600. }
  601. return &rio{IO: iop, sc: container.StreamConfig}, nil
  602. }
  603. // MountsResourcePath returns the path where mounts are stored for the given mount
  604. func (container *Container) MountsResourcePath(mount string) (string, error) {
  605. return container.GetRootResourcePath(filepath.Join("mounts", mount))
  606. }
  607. // SecretMountPath returns the path of the secret mount for the container
  608. func (container *Container) SecretMountPath() (string, error) {
  609. return container.MountsResourcePath("secrets")
  610. }
  611. // SecretFilePath returns the path to the location of a secret on the host.
  612. func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) (string, error) {
  613. secrets, err := container.SecretMountPath()
  614. if err != nil {
  615. return "", err
  616. }
  617. return filepath.Join(secrets, secretRef.SecretID), nil
  618. }
  619. func getSecretTargetPath(r *swarmtypes.SecretReference) string {
  620. if filepath.IsAbs(r.File.Name) {
  621. return r.File.Name
  622. }
  623. return filepath.Join(containerSecretMountPath, r.File.Name)
  624. }
  625. // CreateDaemonEnvironment creates a new environment variable slice for this container.
  626. func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string {
  627. // Setup environment
  628. os := container.OS
  629. if os == "" {
  630. os = runtime.GOOS
  631. }
  632. // Figure out what size slice we need so we can allocate this all at once.
  633. envSize := len(container.Config.Env)
  634. if runtime.GOOS != "windows" || (runtime.GOOS == "windows" && os == "linux") {
  635. envSize += 2 + len(linkedEnv)
  636. }
  637. if tty {
  638. envSize++
  639. }
  640. env := make([]string, 0, envSize)
  641. if runtime.GOOS != "windows" || (runtime.GOOS == "windows" && os == "linux") {
  642. env = append(env, "PATH="+system.DefaultPathEnv(os))
  643. env = append(env, "HOSTNAME="+container.Config.Hostname)
  644. if tty {
  645. env = append(env, "TERM=xterm")
  646. }
  647. env = append(env, linkedEnv...)
  648. }
  649. // because the env on the container can override certain default values
  650. // we need to replace the 'env' keys where they match and append anything
  651. // else.
  652. env = ReplaceOrAppendEnvValues(env, container.Config.Env)
  653. return env
  654. }
  655. type rio struct {
  656. cio.IO
  657. sc *stream.Config
  658. }
  659. func (i *rio) Close() error {
  660. i.IO.Close()
  661. return i.sc.CloseStreams()
  662. }
  663. func (i *rio) Wait() {
  664. i.sc.Wait(context.Background())
  665. i.IO.Wait()
  666. }