container.go 23 KB

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