container.go 32 KB

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