container.go 24 KB

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