container.go 25 KB

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