container.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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/docker/swarmkit/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: The returned path is *only* safely scoped inside the container's BaseFS
  261. // if no component of the returned path changes (such as a component
  262. // symlinking to a different path) between using this method and using the
  263. // path. See symlink.FollowSymlinkInScope for more details.
  264. func (container *Container) GetResourcePath(path string) (string, error) {
  265. if container.BaseFS == nil {
  266. return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly nil")
  267. }
  268. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  269. // any filepath operations must be done in an OS agnostic way.
  270. r, e := container.BaseFS.ResolveScopedPath(path, false)
  271. // Log this here on the daemon side as there's otherwise no indication apart
  272. // from the error being propagated all the way back to the client. This makes
  273. // debugging significantly easier and clearly indicates the error comes from the daemon.
  274. if e != nil {
  275. logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", container.BaseFS.Path(), path, e)
  276. }
  277. return r, e
  278. }
  279. // GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
  280. // sanitisation. Symlinks are all scoped to the root of the container, as
  281. // though the container's root was `/`.
  282. //
  283. // The root of a container is the host-facing configuration metadata directory.
  284. // Only use this method to safely access the container's `container.json` or
  285. // other metadata files. If in doubt, use container.GetResourcePath.
  286. //
  287. // NOTE: The returned path is *only* safely scoped inside the container's root
  288. // if no component of the returned path changes (such as a component
  289. // symlinking to a different path) between using this method and using the
  290. // path. See symlink.FollowSymlinkInScope for more details.
  291. func (container *Container) GetRootResourcePath(path string) (string, error) {
  292. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  293. // any filepath operations must be done in an OS agnostic way.
  294. cleanPath := filepath.Join(string(os.PathSeparator), path)
  295. return symlink.FollowSymlinkInScope(filepath.Join(container.Root, cleanPath), container.Root)
  296. }
  297. // ExitOnNext signals to the monitor that it should not restart the container
  298. // after we send the kill signal.
  299. func (container *Container) ExitOnNext() {
  300. container.RestartManager().Cancel()
  301. }
  302. // HostConfigPath returns the path to the container's JSON hostconfig
  303. func (container *Container) HostConfigPath() (string, error) {
  304. return container.GetRootResourcePath(hostConfigFileName)
  305. }
  306. // ConfigPath returns the path to the container's JSON config
  307. func (container *Container) ConfigPath() (string, error) {
  308. return container.GetRootResourcePath(configFileName)
  309. }
  310. // CheckpointDir returns the directory checkpoints are stored in
  311. func (container *Container) CheckpointDir() string {
  312. return filepath.Join(container.Root, "checkpoints")
  313. }
  314. // StartLogger starts a new logger driver for the container.
  315. func (container *Container) StartLogger() (logger.Logger, error) {
  316. cfg := container.HostConfig.LogConfig
  317. initDriver, err := logger.GetLogDriver(cfg.Type)
  318. if err != nil {
  319. return nil, errors.Wrap(err, "failed to get logging factory")
  320. }
  321. info := logger.Info{
  322. Config: cfg.Config,
  323. ContainerID: container.ID,
  324. ContainerName: container.Name,
  325. ContainerEntrypoint: container.Path,
  326. ContainerArgs: container.Args,
  327. ContainerImageID: container.ImageID.String(),
  328. ContainerImageName: container.Config.Image,
  329. ContainerCreated: container.Created,
  330. ContainerEnv: container.Config.Env,
  331. ContainerLabels: container.Config.Labels,
  332. DaemonName: "docker",
  333. }
  334. // Set logging file for "json-logger"
  335. // TODO(@cpuguy83): Setup here based on log driver is a little weird.
  336. switch cfg.Type {
  337. case jsonfilelog.Name:
  338. info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  339. if err != nil {
  340. return nil, err
  341. }
  342. container.LogPath = info.LogPath
  343. case local.Name:
  344. // Do not set container.LogPath for the local driver
  345. // This would expose the value to the API, which should not be done as it means
  346. // that the log file implementation would become a stable API that cannot change.
  347. logDir, err := container.GetRootResourcePath("local-logs")
  348. if err != nil {
  349. return nil, err
  350. }
  351. if err := os.MkdirAll(logDir, 0700); err != nil {
  352. return nil, errdefs.System(errors.Wrap(err, "error creating local logs dir"))
  353. }
  354. info.LogPath = filepath.Join(logDir, "container.log")
  355. }
  356. l, err := initDriver(info)
  357. if err != nil {
  358. return nil, err
  359. }
  360. if containertypes.LogMode(cfg.Config["mode"]) == containertypes.LogModeNonBlock {
  361. bufferSize := int64(-1)
  362. if s, exists := cfg.Config["max-buffer-size"]; exists {
  363. bufferSize, err = units.RAMInBytes(s)
  364. if err != nil {
  365. return nil, err
  366. }
  367. }
  368. l = logger.NewRingLogger(l, info, bufferSize)
  369. }
  370. if _, ok := l.(logger.LogReader); !ok {
  371. if cache.ShouldUseCache(cfg.Config) {
  372. logPath, err := container.GetRootResourcePath("container-cached.log")
  373. if err != nil {
  374. return nil, err
  375. }
  376. if !container.LocalLogCacheMeta.HaveNotifyEnabled {
  377. 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")
  378. container.LocalLogCacheMeta.HaveNotifyEnabled = true
  379. }
  380. info.LogPath = logPath
  381. l, err = cache.WithLocalCache(l, info)
  382. if err != nil {
  383. return nil, errors.Wrap(err, "error setting up local container log cache")
  384. }
  385. }
  386. }
  387. return l, nil
  388. }
  389. // GetProcessLabel returns the process label for the container.
  390. func (container *Container) GetProcessLabel() string {
  391. // even if we have a process label return "" if we are running
  392. // in privileged mode
  393. if container.HostConfig.Privileged {
  394. return ""
  395. }
  396. return container.ProcessLabel
  397. }
  398. // GetMountLabel returns the mounting label for the container.
  399. // This label is empty if the container is privileged.
  400. func (container *Container) GetMountLabel() string {
  401. return container.MountLabel
  402. }
  403. // GetExecIDs returns the list of exec commands running on the container.
  404. func (container *Container) GetExecIDs() []string {
  405. return container.ExecCommands.List()
  406. }
  407. // ShouldRestart decides whether the daemon should restart the container or not.
  408. // This is based on the container's restart policy.
  409. func (container *Container) ShouldRestart() bool {
  410. shouldRestart, _, _ := container.RestartManager().ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
  411. return shouldRestart
  412. }
  413. // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
  414. func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  415. volumeParser := volumemounts.NewParser()
  416. container.MountPoints[destination] = &volumemounts.MountPoint{
  417. Type: mounttypes.TypeVolume,
  418. Name: vol.Name(),
  419. Driver: vol.DriverName(),
  420. Destination: destination,
  421. RW: rw,
  422. Volume: vol,
  423. CopyData: volumeParser.DefaultCopyMode(),
  424. }
  425. }
  426. // UnmountVolumes unmounts all volumes
  427. func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
  428. var errors []string
  429. for _, volumeMount := range container.MountPoints {
  430. if volumeMount.Volume == nil {
  431. continue
  432. }
  433. if err := volumeMount.Cleanup(); err != nil {
  434. errors = append(errors, err.Error())
  435. continue
  436. }
  437. attributes := map[string]string{
  438. "driver": volumeMount.Volume.DriverName(),
  439. "container": container.ID,
  440. }
  441. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  442. }
  443. if len(errors) > 0 {
  444. return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
  445. }
  446. return nil
  447. }
  448. // IsDestinationMounted checks whether a path is mounted on the container or not.
  449. func (container *Container) IsDestinationMounted(destination string) bool {
  450. return container.MountPoints[destination] != nil
  451. }
  452. // StopSignal returns the signal used to stop the container.
  453. func (container *Container) StopSignal() int {
  454. var stopSignal syscall.Signal
  455. if container.Config.StopSignal != "" {
  456. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  457. }
  458. if int(stopSignal) == 0 {
  459. stopSignal, _ = signal.ParseSignal(defaultStopSignal)
  460. }
  461. return int(stopSignal)
  462. }
  463. // StopTimeout returns the timeout (in seconds) used to stop the container.
  464. func (container *Container) StopTimeout() int {
  465. if container.Config.StopTimeout != nil {
  466. return *container.Config.StopTimeout
  467. }
  468. return defaultStopTimeout
  469. }
  470. // InitDNSHostConfig ensures that the dns fields are never nil.
  471. // New containers don't ever have those fields nil,
  472. // but pre created containers can still have those nil values.
  473. // The non-recommended host configuration in the start api can
  474. // make these fields nil again, this corrects that issue until
  475. // we remove that behavior for good.
  476. // See https://github.com/docker/docker/pull/17779
  477. // for a more detailed explanation on why we don't want that.
  478. func (container *Container) InitDNSHostConfig() {
  479. container.Lock()
  480. defer container.Unlock()
  481. if container.HostConfig.DNS == nil {
  482. container.HostConfig.DNS = make([]string, 0)
  483. }
  484. if container.HostConfig.DNSSearch == nil {
  485. container.HostConfig.DNSSearch = make([]string, 0)
  486. }
  487. if container.HostConfig.DNSOptions == nil {
  488. container.HostConfig.DNSOptions = make([]string, 0)
  489. }
  490. }
  491. // UpdateMonitor updates monitor configure for running container
  492. func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
  493. type policySetter interface {
  494. SetPolicy(containertypes.RestartPolicy)
  495. }
  496. if rm, ok := container.RestartManager().(policySetter); ok {
  497. rm.SetPolicy(restartPolicy)
  498. }
  499. }
  500. // FullHostname returns hostname and optional domain appended to it.
  501. func (container *Container) FullHostname() string {
  502. fullHostname := container.Config.Hostname
  503. if container.Config.Domainname != "" {
  504. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  505. }
  506. return fullHostname
  507. }
  508. // RestartManager returns the current restartmanager instance connected to container.
  509. func (container *Container) RestartManager() restartmanager.RestartManager {
  510. if container.restartManager == nil {
  511. container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
  512. }
  513. return container.restartManager
  514. }
  515. // ResetRestartManager initializes new restartmanager based on container config
  516. func (container *Container) ResetRestartManager(resetCount bool) {
  517. if container.restartManager != nil {
  518. container.restartManager.Cancel()
  519. }
  520. if resetCount {
  521. container.RestartCount = 0
  522. }
  523. container.restartManager = nil
  524. }
  525. type attachContext struct {
  526. ctx context.Context
  527. cancel context.CancelFunc
  528. mu sync.Mutex
  529. }
  530. // InitAttachContext initializes or returns existing context for attach calls to
  531. // track container liveness.
  532. func (container *Container) InitAttachContext() context.Context {
  533. container.attachContext.mu.Lock()
  534. defer container.attachContext.mu.Unlock()
  535. if container.attachContext.ctx == nil {
  536. container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
  537. }
  538. return container.attachContext.ctx
  539. }
  540. // CancelAttachContext cancels attach context. All attach calls should detach
  541. // after this call.
  542. func (container *Container) CancelAttachContext() {
  543. container.attachContext.mu.Lock()
  544. if container.attachContext.ctx != nil {
  545. container.attachContext.cancel()
  546. container.attachContext.ctx = nil
  547. }
  548. container.attachContext.mu.Unlock()
  549. }
  550. func (container *Container) startLogging() error {
  551. if container.HostConfig.LogConfig.Type == "none" {
  552. return nil // do not start logging routines
  553. }
  554. l, err := container.StartLogger()
  555. if err != nil {
  556. return fmt.Errorf("failed to initialize logging driver: %v", err)
  557. }
  558. copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  559. container.LogCopier = copier
  560. copier.Run()
  561. container.LogDriver = l
  562. return nil
  563. }
  564. // StdinPipe gets the stdin stream of the container
  565. func (container *Container) StdinPipe() io.WriteCloser {
  566. return container.StreamConfig.StdinPipe()
  567. }
  568. // StdoutPipe gets the stdout stream of the container
  569. func (container *Container) StdoutPipe() io.ReadCloser {
  570. return container.StreamConfig.StdoutPipe()
  571. }
  572. // StderrPipe gets the stderr stream of the container
  573. func (container *Container) StderrPipe() io.ReadCloser {
  574. return container.StreamConfig.StderrPipe()
  575. }
  576. // CloseStreams closes the container's stdio streams
  577. func (container *Container) CloseStreams() error {
  578. return container.StreamConfig.CloseStreams()
  579. }
  580. // InitializeStdio is called by libcontainerd to connect the stdio.
  581. func (container *Container) InitializeStdio(iop *cio.DirectIO) (cio.IO, error) {
  582. if err := container.startLogging(); err != nil {
  583. container.Reset(false)
  584. return nil, err
  585. }
  586. container.StreamConfig.CopyToPipe(iop)
  587. if container.StreamConfig.Stdin() == nil && !container.Config.Tty {
  588. if iop.Stdin != nil {
  589. if err := iop.Stdin.Close(); err != nil {
  590. logrus.Warnf("error closing stdin: %+v", err)
  591. }
  592. }
  593. }
  594. return &rio{IO: iop, sc: container.StreamConfig}, nil
  595. }
  596. // MountsResourcePath returns the path where mounts are stored for the given mount
  597. func (container *Container) MountsResourcePath(mount string) (string, error) {
  598. return container.GetRootResourcePath(filepath.Join("mounts", mount))
  599. }
  600. // SecretMountPath returns the path of the secret mount for the container
  601. func (container *Container) SecretMountPath() (string, error) {
  602. return container.MountsResourcePath("secrets")
  603. }
  604. // SecretFilePath returns the path to the location of a secret on the host.
  605. func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) (string, error) {
  606. secrets, err := container.SecretMountPath()
  607. if err != nil {
  608. return "", err
  609. }
  610. return filepath.Join(secrets, secretRef.SecretID), nil
  611. }
  612. func getSecretTargetPath(r *swarmtypes.SecretReference) string {
  613. if filepath.IsAbs(r.File.Name) {
  614. return r.File.Name
  615. }
  616. return filepath.Join(containerSecretMountPath, r.File.Name)
  617. }
  618. // getConfigTargetPath makes sure that config paths inside the container are
  619. // absolute, as required by the runtime spec, and enforced by runc >= 1.0.0-rc94.
  620. // see https://github.com/opencontainers/runc/issues/2928
  621. func getConfigTargetPath(r *swarmtypes.ConfigReference) string {
  622. if filepath.IsAbs(r.File.Name) {
  623. return r.File.Name
  624. }
  625. return filepath.Join(containerConfigMountPath, r.File.Name)
  626. }
  627. // CreateDaemonEnvironment creates a new environment variable slice for this container.
  628. func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string {
  629. // Setup environment
  630. ctrOS := container.OS
  631. if ctrOS == "" {
  632. ctrOS = runtime.GOOS
  633. }
  634. // Figure out what size slice we need so we can allocate this all at once.
  635. envSize := len(container.Config.Env)
  636. if runtime.GOOS != "windows" {
  637. envSize += 2 + len(linkedEnv)
  638. }
  639. if tty {
  640. envSize++
  641. }
  642. env := make([]string, 0, envSize)
  643. if runtime.GOOS != "windows" {
  644. env = append(env, "PATH="+system.DefaultPathEnv(ctrOS))
  645. env = append(env, "HOSTNAME="+container.Config.Hostname)
  646. if tty {
  647. env = append(env, "TERM=xterm")
  648. }
  649. env = append(env, linkedEnv...)
  650. }
  651. // because the env on the container can override certain default values
  652. // we need to replace the 'env' keys where they match and append anything
  653. // else.
  654. env = ReplaceOrAppendEnvValues(env, container.Config.Env)
  655. return env
  656. }
  657. type rio struct {
  658. cio.IO
  659. sc *stream.Config
  660. }
  661. func (i *rio) Close() error {
  662. i.IO.Close()
  663. return i.sc.CloseStreams()
  664. }
  665. func (i *rio) Wait() {
  666. i.sc.Wait(context.Background())
  667. i.IO.Wait()
  668. }