container.go 29 KB

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