container.go 33 KB

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