container.go 33 KB

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