container.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. package container
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "syscall"
  15. "time"
  16. "github.com/containerd/containerd/cio"
  17. containertypes "github.com/docker/docker/api/types/container"
  18. mounttypes "github.com/docker/docker/api/types/mount"
  19. networktypes "github.com/docker/docker/api/types/network"
  20. swarmtypes "github.com/docker/docker/api/types/swarm"
  21. "github.com/docker/docker/container/stream"
  22. "github.com/docker/docker/daemon/exec"
  23. "github.com/docker/docker/daemon/logger"
  24. "github.com/docker/docker/daemon/logger/jsonfilelog"
  25. "github.com/docker/docker/daemon/network"
  26. "github.com/docker/docker/image"
  27. "github.com/docker/docker/layer"
  28. "github.com/docker/docker/opts"
  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/signal"
  33. "github.com/docker/docker/pkg/symlink"
  34. "github.com/docker/docker/pkg/system"
  35. "github.com/docker/docker/restartmanager"
  36. "github.com/docker/docker/runconfig"
  37. "github.com/docker/docker/volume"
  38. "github.com/docker/go-connections/nat"
  39. "github.com/docker/go-units"
  40. "github.com/docker/libnetwork"
  41. "github.com/docker/libnetwork/netlabel"
  42. "github.com/docker/libnetwork/options"
  43. "github.com/docker/libnetwork/types"
  44. agentexec "github.com/docker/swarmkit/agent/exec"
  45. "github.com/pkg/errors"
  46. "github.com/sirupsen/logrus"
  47. "golang.org/x/net/context"
  48. )
  49. const configFileName = "config.v2.json"
  50. var (
  51. errInvalidEndpoint = errors.New("invalid endpoint while building port map info")
  52. errInvalidNetwork = errors.New("invalid network settings while building port map info")
  53. )
  54. // ExitStatus provides exit reasons for a container.
  55. type ExitStatus struct {
  56. // The exit code with which the container exited.
  57. ExitCode int
  58. // Whether the container encountered an OOM.
  59. OOMKilled bool
  60. // Time at which the container died
  61. ExitedAt time.Time
  62. }
  63. // Container holds the structure defining a container object.
  64. type Container struct {
  65. StreamConfig *stream.Config
  66. // embed for Container to support states directly.
  67. *State `json:"State"` // Needed for Engine API version <= 1.11
  68. Root string `json:"-"` // Path to the "home" of the container, including metadata.
  69. BaseFS containerfs.ContainerFS `json:"-"` // interface containing graphdriver mount
  70. RWLayer layer.RWLayer `json:"-"`
  71. ID string
  72. Created time.Time
  73. Managed bool
  74. Path string
  75. Args []string
  76. Config *containertypes.Config
  77. ImageID image.ID `json:"Image"`
  78. NetworkSettings *network.Settings
  79. LogPath string
  80. Name string
  81. Driver string
  82. OS string
  83. // MountLabel contains the options for the 'mount' command
  84. MountLabel string
  85. ProcessLabel string
  86. RestartCount int
  87. HasBeenStartedBefore bool
  88. HasBeenManuallyStopped bool // used for unless-stopped restart policy
  89. MountPoints map[string]*volume.MountPoint
  90. HostConfig *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
  91. ExecCommands *exec.Store `json:"-"`
  92. DependencyStore agentexec.DependencyGetter `json:"-"`
  93. SecretReferences []*swarmtypes.SecretReference
  94. ConfigReferences []*swarmtypes.ConfigReference
  95. // logDriver for closing
  96. LogDriver logger.Logger `json:"-"`
  97. LogCopier *logger.Copier `json:"-"`
  98. restartManager restartmanager.RestartManager
  99. attachContext *attachContext
  100. // Fields here are specific to Unix platforms
  101. AppArmorProfile string
  102. HostnamePath string
  103. HostsPath string
  104. ShmPath string
  105. ResolvConfPath string
  106. SeccompProfile string
  107. NoNewPrivileges bool
  108. // Fields here are specific to Windows
  109. NetworkSharedContainerID string `json:"-"`
  110. SharedEndpointList []string `json:"-"`
  111. }
  112. // NewBaseContainer creates a new container with its
  113. // basic configuration.
  114. func NewBaseContainer(id, root string) *Container {
  115. return &Container{
  116. ID: id,
  117. State: NewState(),
  118. ExecCommands: exec.NewStore(),
  119. Root: root,
  120. MountPoints: make(map[string]*volume.MountPoint),
  121. StreamConfig: stream.NewConfig(),
  122. attachContext: &attachContext{},
  123. }
  124. }
  125. // FromDisk loads the container configuration stored in the host.
  126. func (container *Container) FromDisk() error {
  127. pth, err := container.ConfigPath()
  128. if err != nil {
  129. return err
  130. }
  131. jsonSource, err := os.Open(pth)
  132. if err != nil {
  133. return err
  134. }
  135. defer jsonSource.Close()
  136. dec := json.NewDecoder(jsonSource)
  137. // Load container settings
  138. if err := dec.Decode(container); err != nil {
  139. return err
  140. }
  141. // Ensure the operating system is set if blank. Assume it is the OS of the
  142. // host OS if not, to ensure containers created before multiple-OS
  143. // support are migrated
  144. if container.OS == "" {
  145. container.OS = runtime.GOOS
  146. }
  147. return container.readHostConfig()
  148. }
  149. // toDisk saves the container configuration on disk and returns a deep copy.
  150. func (container *Container) toDisk() (*Container, error) {
  151. var (
  152. buf bytes.Buffer
  153. deepCopy Container
  154. )
  155. pth, err := container.ConfigPath()
  156. if err != nil {
  157. return nil, err
  158. }
  159. // Save container settings
  160. f, err := ioutils.NewAtomicFileWriter(pth, 0600)
  161. if err != nil {
  162. return nil, err
  163. }
  164. defer f.Close()
  165. w := io.MultiWriter(&buf, f)
  166. if err := json.NewEncoder(w).Encode(container); err != nil {
  167. return nil, err
  168. }
  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, 0644)
  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(rootIDs idtools.IDPair) error {
  238. // TODO @jhowardmsft, @gupta-ak LCOW Support. This will need revisiting.
  239. // We will need to do remote filesystem operations here.
  240. if container.OS != runtime.GOOS {
  241. return nil
  242. }
  243. if container.Config.WorkingDir == "" {
  244. return nil
  245. }
  246. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  247. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  248. if err != nil {
  249. return err
  250. }
  251. if err := idtools.MkdirAllAndChownNew(pth, 0755, rootIDs); err != nil {
  252. pthInfo, err2 := os.Stat(pth)
  253. if err2 == nil && pthInfo != nil && !pthInfo.IsDir() {
  254. return errors.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  255. }
  256. return err
  257. }
  258. return nil
  259. }
  260. // GetResourcePath evaluates `path` in the scope of the container's BaseFS, with proper path
  261. // sanitisation. Symlinks are all scoped to the BaseFS of the container, as
  262. // though the container's BaseFS was `/`.
  263. //
  264. // The BaseFS of a container is the host-facing path which is bind-mounted as
  265. // `/` inside the container. This method is essentially used to access a
  266. // particular path inside the container as though you were a process in that
  267. // container.
  268. //
  269. // NOTE: The returned path is *only* safely scoped inside the container's BaseFS
  270. // if no component of the returned path changes (such as a component
  271. // symlinking to a different path) between using this method and using the
  272. // path. See symlink.FollowSymlinkInScope for more details.
  273. func (container *Container) GetResourcePath(path string) (string, error) {
  274. // IMPORTANT - These are paths on the OS where the daemon is running, hence
  275. // any filepath operations must be done in an OS agnostic way.
  276. r, e := container.BaseFS.ResolveScopedPath(path, false)
  277. // Log this here on the daemon side as there's otherwise no indication apart
  278. // from the error being propagated all the way back to the client. This makes
  279. // debugging significantly easier and clearly indicates the error comes from the daemon.
  280. if e != nil {
  281. logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", container.BaseFS.Path(), path, e)
  282. }
  283. return r, e
  284. }
  285. // GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
  286. // sanitisation. Symlinks are all scoped to the root of the container, as
  287. // though the container's root was `/`.
  288. //
  289. // The root of a container is the host-facing configuration metadata directory.
  290. // Only use this method to safely access the container's `container.json` or
  291. // other metadata files. If in doubt, use container.GetResourcePath.
  292. //
  293. // NOTE: 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("hostconfig.json")
  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. if cfg.Type == jsonfilelog.Name {
  342. info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
  343. if err != nil {
  344. return nil, err
  345. }
  346. }
  347. l, err := initDriver(info)
  348. if err != nil {
  349. return nil, err
  350. }
  351. if containertypes.LogMode(cfg.Config["mode"]) == containertypes.LogModeNonBlock {
  352. bufferSize := int64(-1)
  353. if s, exists := cfg.Config["max-buffer-size"]; exists {
  354. bufferSize, err = units.RAMInBytes(s)
  355. if err != nil {
  356. return nil, err
  357. }
  358. }
  359. l = logger.NewRingLogger(l, info, bufferSize)
  360. }
  361. return l, nil
  362. }
  363. // GetProcessLabel returns the process label for the container.
  364. func (container *Container) GetProcessLabel() string {
  365. // even if we have a process label return "" if we are running
  366. // in privileged mode
  367. if container.HostConfig.Privileged {
  368. return ""
  369. }
  370. return container.ProcessLabel
  371. }
  372. // GetMountLabel returns the mounting label for the container.
  373. // This label is empty if the container is privileged.
  374. func (container *Container) GetMountLabel() string {
  375. return container.MountLabel
  376. }
  377. // GetExecIDs returns the list of exec commands running on the container.
  378. func (container *Container) GetExecIDs() []string {
  379. return container.ExecCommands.List()
  380. }
  381. // ShouldRestart decides whether the daemon should restart the container or not.
  382. // This is based on the container's restart policy.
  383. func (container *Container) ShouldRestart() bool {
  384. shouldRestart, _, _ := container.RestartManager().ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
  385. return shouldRestart
  386. }
  387. // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
  388. func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  389. operatingSystem := container.OS
  390. if operatingSystem == "" {
  391. operatingSystem = runtime.GOOS
  392. }
  393. volumeParser := volume.NewParser(operatingSystem)
  394. container.MountPoints[destination] = &volume.MountPoint{
  395. Type: mounttypes.TypeVolume,
  396. Name: vol.Name(),
  397. Driver: vol.DriverName(),
  398. Destination: destination,
  399. RW: rw,
  400. Volume: vol,
  401. CopyData: volumeParser.DefaultCopyMode(),
  402. }
  403. }
  404. // UnmountVolumes unmounts all volumes
  405. func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
  406. var errors []string
  407. for _, volumeMount := range container.MountPoints {
  408. if volumeMount.Volume == nil {
  409. continue
  410. }
  411. if err := volumeMount.Cleanup(); err != nil {
  412. errors = append(errors, err.Error())
  413. continue
  414. }
  415. attributes := map[string]string{
  416. "driver": volumeMount.Volume.DriverName(),
  417. "container": container.ID,
  418. }
  419. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  420. }
  421. if len(errors) > 0 {
  422. return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
  423. }
  424. return nil
  425. }
  426. // IsDestinationMounted checks whether a path is mounted on the container or not.
  427. func (container *Container) IsDestinationMounted(destination string) bool {
  428. return container.MountPoints[destination] != nil
  429. }
  430. // StopSignal returns the signal used to stop the container.
  431. func (container *Container) StopSignal() int {
  432. var stopSignal syscall.Signal
  433. if container.Config.StopSignal != "" {
  434. stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
  435. }
  436. if int(stopSignal) == 0 {
  437. stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
  438. }
  439. return int(stopSignal)
  440. }
  441. // StopTimeout returns the timeout (in seconds) used to stop the container.
  442. func (container *Container) StopTimeout() int {
  443. if container.Config.StopTimeout != nil {
  444. return *container.Config.StopTimeout
  445. }
  446. return DefaultStopTimeout
  447. }
  448. // InitDNSHostConfig ensures that the dns fields are never nil.
  449. // New containers don't ever have those fields nil,
  450. // but pre created containers can still have those nil values.
  451. // The non-recommended host configuration in the start api can
  452. // make these fields nil again, this corrects that issue until
  453. // we remove that behavior for good.
  454. // See https://github.com/docker/docker/pull/17779
  455. // for a more detailed explanation on why we don't want that.
  456. func (container *Container) InitDNSHostConfig() {
  457. container.Lock()
  458. defer container.Unlock()
  459. if container.HostConfig.DNS == nil {
  460. container.HostConfig.DNS = make([]string, 0)
  461. }
  462. if container.HostConfig.DNSSearch == nil {
  463. container.HostConfig.DNSSearch = make([]string, 0)
  464. }
  465. if container.HostConfig.DNSOptions == nil {
  466. container.HostConfig.DNSOptions = make([]string, 0)
  467. }
  468. }
  469. // GetEndpointInNetwork returns the container's endpoint to the provided network.
  470. func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  471. endpointName := strings.TrimPrefix(container.Name, "/")
  472. return n.EndpointByName(endpointName)
  473. }
  474. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
  475. if ep == nil {
  476. return errInvalidEndpoint
  477. }
  478. networkSettings := container.NetworkSettings
  479. if networkSettings == nil {
  480. return errInvalidNetwork
  481. }
  482. if len(networkSettings.Ports) == 0 {
  483. pm, err := getEndpointPortMapInfo(ep)
  484. if err != nil {
  485. return err
  486. }
  487. networkSettings.Ports = pm
  488. }
  489. return nil
  490. }
  491. func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) {
  492. pm := nat.PortMap{}
  493. driverInfo, err := ep.DriverInfo()
  494. if err != nil {
  495. return pm, err
  496. }
  497. if driverInfo == nil {
  498. // It is not an error for epInfo to be nil
  499. return pm, nil
  500. }
  501. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  502. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  503. for _, tp := range exposedPorts {
  504. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  505. if err != nil {
  506. return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  507. }
  508. pm[natPort] = nil
  509. }
  510. }
  511. }
  512. mapData, ok := driverInfo[netlabel.PortMap]
  513. if !ok {
  514. return pm, nil
  515. }
  516. if portMapping, ok := mapData.([]types.PortBinding); ok {
  517. for _, pp := range portMapping {
  518. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  519. if err != nil {
  520. return pm, err
  521. }
  522. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  523. pm[natPort] = append(pm[natPort], natBndg)
  524. }
  525. }
  526. return pm, nil
  527. }
  528. // GetSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox
  529. func GetSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap {
  530. pm := nat.PortMap{}
  531. if sb == nil {
  532. return pm
  533. }
  534. for _, ep := range sb.Endpoints() {
  535. pm, _ = getEndpointPortMapInfo(ep)
  536. if len(pm) > 0 {
  537. break
  538. }
  539. }
  540. return pm
  541. }
  542. // BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  543. func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  544. if ep == nil {
  545. return errInvalidEndpoint
  546. }
  547. networkSettings := container.NetworkSettings
  548. if networkSettings == nil {
  549. return errInvalidNetwork
  550. }
  551. epInfo := ep.Info()
  552. if epInfo == nil {
  553. // It is not an error to get an empty endpoint info
  554. return nil
  555. }
  556. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  557. networkSettings.Networks[n.Name()] = &network.EndpointSettings{
  558. EndpointSettings: &networktypes.EndpointSettings{},
  559. }
  560. }
  561. networkSettings.Networks[n.Name()].NetworkID = n.ID()
  562. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  563. iface := epInfo.Iface()
  564. if iface == nil {
  565. return nil
  566. }
  567. if iface.MacAddress() != nil {
  568. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  569. }
  570. if iface.Address() != nil {
  571. ones, _ := iface.Address().Mask.Size()
  572. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  573. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  574. }
  575. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  576. onesv6, _ := iface.AddressIPv6().Mask.Size()
  577. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  578. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  579. }
  580. return nil
  581. }
  582. type named interface {
  583. Name() string
  584. }
  585. // UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
  586. func (container *Container) UpdateJoinInfo(n named, ep libnetwork.Endpoint) error {
  587. if err := container.buildPortMapInfo(ep); err != nil {
  588. return err
  589. }
  590. epInfo := ep.Info()
  591. if epInfo == nil {
  592. // It is not an error to get an empty endpoint info
  593. return nil
  594. }
  595. if epInfo.Gateway() != nil {
  596. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  597. }
  598. if epInfo.GatewayIPv6().To16() != nil {
  599. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  600. }
  601. return nil
  602. }
  603. // UpdateSandboxNetworkSettings updates the sandbox ID and Key.
  604. func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  605. container.NetworkSettings.SandboxID = sb.ID()
  606. container.NetworkSettings.SandboxKey = sb.Key()
  607. return nil
  608. }
  609. // BuildJoinOptions builds endpoint Join options from a given network.
  610. func (container *Container) BuildJoinOptions(n named) ([]libnetwork.EndpointOption, error) {
  611. var joinOptions []libnetwork.EndpointOption
  612. if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  613. for _, str := range epConfig.Links {
  614. name, alias, err := opts.ParseLink(str)
  615. if err != nil {
  616. return nil, err
  617. }
  618. joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias))
  619. }
  620. for k, v := range epConfig.DriverOpts {
  621. joinOptions = append(joinOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  622. }
  623. }
  624. return joinOptions, nil
  625. }
  626. // BuildCreateEndpointOptions builds endpoint options from a given network.
  627. func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network, epConfig *networktypes.EndpointSettings, sb libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) {
  628. var (
  629. bindings = make(nat.PortMap)
  630. pbList []types.PortBinding
  631. exposeList []types.TransportPort
  632. createOptions []libnetwork.EndpointOption
  633. )
  634. defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
  635. if (!container.EnableServiceDiscoveryOnDefaultNetwork() && n.Name() == defaultNetName) ||
  636. container.NetworkSettings.IsAnonymousEndpoint {
  637. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  638. }
  639. if epConfig != nil {
  640. ipam := epConfig.IPAMConfig
  641. if ipam != nil {
  642. var (
  643. ipList []net.IP
  644. ip, ip6, linkip net.IP
  645. )
  646. for _, ips := range ipam.LinkLocalIPs {
  647. if linkip = net.ParseIP(ips); linkip == nil && ips != "" {
  648. return nil, errors.Errorf("Invalid link-local IP address: %s", ipam.LinkLocalIPs)
  649. }
  650. ipList = append(ipList, linkip)
  651. }
  652. if ip = net.ParseIP(ipam.IPv4Address); ip == nil && ipam.IPv4Address != "" {
  653. return nil, errors.Errorf("Invalid IPv4 address: %s)", ipam.IPv4Address)
  654. }
  655. if ip6 = net.ParseIP(ipam.IPv6Address); ip6 == nil && ipam.IPv6Address != "" {
  656. return nil, errors.Errorf("Invalid IPv6 address: %s)", ipam.IPv6Address)
  657. }
  658. createOptions = append(createOptions,
  659. libnetwork.CreateOptionIpam(ip, ip6, ipList, nil))
  660. }
  661. for _, alias := range epConfig.Aliases {
  662. createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias))
  663. }
  664. for k, v := range epConfig.DriverOpts {
  665. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  666. }
  667. }
  668. if container.NetworkSettings.Service != nil {
  669. svcCfg := container.NetworkSettings.Service
  670. var vip string
  671. if svcCfg.VirtualAddresses[n.ID()] != nil {
  672. vip = svcCfg.VirtualAddresses[n.ID()].IPv4
  673. }
  674. var portConfigs []*libnetwork.PortConfig
  675. for _, portConfig := range svcCfg.ExposedPorts {
  676. portConfigs = append(portConfigs, &libnetwork.PortConfig{
  677. Name: portConfig.Name,
  678. Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol),
  679. TargetPort: portConfig.TargetPort,
  680. PublishedPort: portConfig.PublishedPort,
  681. })
  682. }
  683. createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()]))
  684. }
  685. if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
  686. createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution())
  687. }
  688. // configs that are applicable only for the endpoint in the network
  689. // to which container was connected to on docker run.
  690. // Ideally all these network-specific endpoint configurations must be moved under
  691. // container.NetworkSettings.Networks[n.Name()]
  692. if n.Name() == container.HostConfig.NetworkMode.NetworkName() ||
  693. (n.Name() == defaultNetName && container.HostConfig.NetworkMode.IsDefault()) {
  694. if container.Config.MacAddress != "" {
  695. mac, err := net.ParseMAC(container.Config.MacAddress)
  696. if err != nil {
  697. return nil, err
  698. }
  699. genericOption := options.Generic{
  700. netlabel.MacAddress: mac,
  701. }
  702. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  703. }
  704. }
  705. // Port-mapping rules belong to the container & applicable only to non-internal networks
  706. portmaps := GetSandboxPortMapInfo(sb)
  707. if n.Info().Internal() || len(portmaps) > 0 {
  708. return createOptions, nil
  709. }
  710. if container.HostConfig.PortBindings != nil {
  711. for p, b := range container.HostConfig.PortBindings {
  712. bindings[p] = []nat.PortBinding{}
  713. for _, bb := range b {
  714. bindings[p] = append(bindings[p], nat.PortBinding{
  715. HostIP: bb.HostIP,
  716. HostPort: bb.HostPort,
  717. })
  718. }
  719. }
  720. }
  721. portSpecs := container.Config.ExposedPorts
  722. ports := make([]nat.Port, len(portSpecs))
  723. var i int
  724. for p := range portSpecs {
  725. ports[i] = p
  726. i++
  727. }
  728. nat.SortPortMap(ports, bindings)
  729. for _, port := range ports {
  730. expose := types.TransportPort{}
  731. expose.Proto = types.ParseProtocol(port.Proto())
  732. expose.Port = uint16(port.Int())
  733. exposeList = append(exposeList, expose)
  734. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  735. binding := bindings[port]
  736. for i := 0; i < len(binding); i++ {
  737. pbCopy := pb.GetCopy()
  738. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  739. var portStart, portEnd int
  740. if err == nil {
  741. portStart, portEnd, err = newP.Range()
  742. }
  743. if err != nil {
  744. return nil, errors.Wrapf(err, "Error parsing HostPort value (%s)", binding[i].HostPort)
  745. }
  746. pbCopy.HostPort = uint16(portStart)
  747. pbCopy.HostPortEnd = uint16(portEnd)
  748. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  749. pbList = append(pbList, pbCopy)
  750. }
  751. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  752. pbList = append(pbList, pb)
  753. }
  754. }
  755. var dns []string
  756. if len(container.HostConfig.DNS) > 0 {
  757. dns = container.HostConfig.DNS
  758. } else if len(daemonDNS) > 0 {
  759. dns = daemonDNS
  760. }
  761. if len(dns) > 0 {
  762. createOptions = append(createOptions,
  763. libnetwork.CreateOptionDNS(dns))
  764. }
  765. createOptions = append(createOptions,
  766. libnetwork.CreateOptionPortMapping(pbList),
  767. libnetwork.CreateOptionExposedPorts(exposeList))
  768. return createOptions, nil
  769. }
  770. // UpdateMonitor updates monitor configure for running container
  771. func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
  772. type policySetter interface {
  773. SetPolicy(containertypes.RestartPolicy)
  774. }
  775. if rm, ok := container.RestartManager().(policySetter); ok {
  776. rm.SetPolicy(restartPolicy)
  777. }
  778. }
  779. // FullHostname returns hostname and optional domain appended to it.
  780. func (container *Container) FullHostname() string {
  781. fullHostname := container.Config.Hostname
  782. if container.Config.Domainname != "" {
  783. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  784. }
  785. return fullHostname
  786. }
  787. // RestartManager returns the current restartmanager instance connected to container.
  788. func (container *Container) RestartManager() restartmanager.RestartManager {
  789. if container.restartManager == nil {
  790. container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
  791. }
  792. return container.restartManager
  793. }
  794. // ResetRestartManager initializes new restartmanager based on container config
  795. func (container *Container) ResetRestartManager(resetCount bool) {
  796. if container.restartManager != nil {
  797. container.restartManager.Cancel()
  798. }
  799. if resetCount {
  800. container.RestartCount = 0
  801. }
  802. container.restartManager = nil
  803. }
  804. type attachContext struct {
  805. ctx context.Context
  806. cancel context.CancelFunc
  807. mu sync.Mutex
  808. }
  809. // InitAttachContext initializes or returns existing context for attach calls to
  810. // track container liveness.
  811. func (container *Container) InitAttachContext() context.Context {
  812. container.attachContext.mu.Lock()
  813. defer container.attachContext.mu.Unlock()
  814. if container.attachContext.ctx == nil {
  815. container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
  816. }
  817. return container.attachContext.ctx
  818. }
  819. // CancelAttachContext cancels attach context. All attach calls should detach
  820. // after this call.
  821. func (container *Container) CancelAttachContext() {
  822. container.attachContext.mu.Lock()
  823. if container.attachContext.ctx != nil {
  824. container.attachContext.cancel()
  825. container.attachContext.ctx = nil
  826. }
  827. container.attachContext.mu.Unlock()
  828. }
  829. func (container *Container) startLogging() error {
  830. if container.HostConfig.LogConfig.Type == "none" {
  831. return nil // do not start logging routines
  832. }
  833. l, err := container.StartLogger()
  834. if err != nil {
  835. return fmt.Errorf("failed to initialize logging driver: %v", err)
  836. }
  837. copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  838. container.LogCopier = copier
  839. copier.Run()
  840. container.LogDriver = l
  841. // set LogPath field only for json-file logdriver
  842. if jl, ok := l.(*jsonfilelog.JSONFileLogger); ok {
  843. container.LogPath = jl.LogPath()
  844. }
  845. return nil
  846. }
  847. // StdinPipe gets the stdin stream of the container
  848. func (container *Container) StdinPipe() io.WriteCloser {
  849. return container.StreamConfig.StdinPipe()
  850. }
  851. // StdoutPipe gets the stdout stream of the container
  852. func (container *Container) StdoutPipe() io.ReadCloser {
  853. return container.StreamConfig.StdoutPipe()
  854. }
  855. // StderrPipe gets the stderr stream of the container
  856. func (container *Container) StderrPipe() io.ReadCloser {
  857. return container.StreamConfig.StderrPipe()
  858. }
  859. // CloseStreams closes the container's stdio streams
  860. func (container *Container) CloseStreams() error {
  861. return container.StreamConfig.CloseStreams()
  862. }
  863. // InitializeStdio is called by libcontainerd to connect the stdio.
  864. func (container *Container) InitializeStdio(iop *cio.DirectIO) (cio.IO, error) {
  865. if err := container.startLogging(); err != nil {
  866. container.Reset(false)
  867. return nil, err
  868. }
  869. container.StreamConfig.CopyToPipe(iop)
  870. if container.StreamConfig.Stdin() == nil && !container.Config.Tty {
  871. if iop.Stdin != nil {
  872. if err := iop.Stdin.Close(); err != nil {
  873. logrus.Warnf("error closing stdin: %+v", err)
  874. }
  875. }
  876. }
  877. return &rio{IO: iop, sc: container.StreamConfig}, nil
  878. }
  879. // SecretMountPath returns the path of the secret mount for the container
  880. func (container *Container) SecretMountPath() string {
  881. return filepath.Join(container.Root, "secrets")
  882. }
  883. // SecretFilePath returns the path to the location of a secret on the host.
  884. func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) string {
  885. return filepath.Join(container.SecretMountPath(), secretRef.SecretID)
  886. }
  887. func getSecretTargetPath(r *swarmtypes.SecretReference) string {
  888. if filepath.IsAbs(r.File.Name) {
  889. return r.File.Name
  890. }
  891. return filepath.Join(containerSecretMountPath, r.File.Name)
  892. }
  893. // ConfigsDirPath returns the path to the directory where configs are stored on
  894. // disk.
  895. func (container *Container) ConfigsDirPath() string {
  896. return filepath.Join(container.Root, "configs")
  897. }
  898. // ConfigFilePath returns the path to the on-disk location of a config.
  899. func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) string {
  900. return filepath.Join(container.ConfigsDirPath(), configRef.ConfigID)
  901. }
  902. // CreateDaemonEnvironment creates a new environment variable slice for this container.
  903. func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string {
  904. // Setup environment
  905. os := container.OS
  906. if os == "" {
  907. os = runtime.GOOS
  908. }
  909. env := []string{}
  910. if runtime.GOOS != "windows" || (runtime.GOOS == "windows" && os == "linux") {
  911. env = []string{
  912. "PATH=" + system.DefaultPathEnv(os),
  913. "HOSTNAME=" + container.Config.Hostname,
  914. }
  915. if tty {
  916. env = append(env, "TERM=xterm")
  917. }
  918. env = append(env, linkedEnv...)
  919. }
  920. // because the env on the container can override certain default values
  921. // we need to replace the 'env' keys where they match and append anything
  922. // else.
  923. env = ReplaceOrAppendEnvValues(env, container.Config.Env)
  924. return env
  925. }
  926. type rio struct {
  927. cio.IO
  928. sc *stream.Config
  929. }
  930. func (i *rio) Close() error {
  931. i.IO.Close()
  932. return i.sc.CloseStreams()
  933. }
  934. func (i *rio) Wait() {
  935. i.sc.Wait()
  936. i.IO.Wait()
  937. }