container.go 26 KB

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