container_unix.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/daemon/network"
  18. "github.com/docker/docker/pkg/directory"
  19. "github.com/docker/docker/pkg/nat"
  20. "github.com/docker/docker/pkg/stringid"
  21. "github.com/docker/docker/pkg/system"
  22. "github.com/docker/docker/pkg/ulimit"
  23. "github.com/docker/docker/runconfig"
  24. "github.com/docker/docker/utils"
  25. "github.com/docker/docker/volume"
  26. "github.com/docker/libnetwork"
  27. "github.com/docker/libnetwork/netlabel"
  28. "github.com/docker/libnetwork/options"
  29. "github.com/docker/libnetwork/types"
  30. "github.com/opencontainers/runc/libcontainer/configs"
  31. "github.com/opencontainers/runc/libcontainer/devices"
  32. "github.com/opencontainers/runc/libcontainer/label"
  33. )
  34. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  35. type Container struct {
  36. CommonContainer
  37. // Fields below here are platform specific.
  38. activeLinks map[string]*links.Link
  39. AppArmorProfile string
  40. HostnamePath string
  41. HostsPath string
  42. MountPoints map[string]*mountPoint
  43. ResolvConfPath string
  44. UpdateDns bool
  45. Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
  46. VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility
  47. }
  48. func killProcessDirectly(container *Container) error {
  49. if _, err := container.WaitStop(10 * time.Second); err != nil {
  50. // Ensure that we don't kill ourselves
  51. if pid := container.GetPid(); pid != 0 {
  52. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  53. if err := syscall.Kill(pid, 9); err != nil {
  54. if err != syscall.ESRCH {
  55. return err
  56. }
  57. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  58. }
  59. }
  60. }
  61. return nil
  62. }
  63. func (container *Container) setupLinkedContainers() ([]string, error) {
  64. var (
  65. env []string
  66. daemon = container.daemon
  67. )
  68. children, err := daemon.Children(container.Name)
  69. if err != nil {
  70. return nil, err
  71. }
  72. if len(children) > 0 {
  73. for linkAlias, child := range children {
  74. if !child.IsRunning() {
  75. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  76. }
  77. link := links.NewLink(
  78. container.NetworkSettings.IPAddress,
  79. child.NetworkSettings.IPAddress,
  80. linkAlias,
  81. child.Config.Env,
  82. child.Config.ExposedPorts,
  83. )
  84. for _, envVar := range link.ToEnv() {
  85. env = append(env, envVar)
  86. }
  87. }
  88. }
  89. return env, nil
  90. }
  91. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  92. // if a domain name was specified, append it to the hostname (see #7851)
  93. fullHostname := container.Config.Hostname
  94. if container.Config.Domainname != "" {
  95. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  96. }
  97. // Setup environment
  98. env := []string{
  99. "PATH=" + DefaultPathEnv,
  100. "HOSTNAME=" + fullHostname,
  101. // Note: we don't set HOME here because it'll get autoset intelligently
  102. // based on the value of USER inside dockerinit, but only if it isn't
  103. // set already (ie, that can be overridden by setting HOME via -e or ENV
  104. // in a Dockerfile).
  105. }
  106. if container.Config.Tty {
  107. env = append(env, "TERM=xterm")
  108. }
  109. env = append(env, linkedEnv...)
  110. // because the env on the container can override certain default values
  111. // we need to replace the 'env' keys where they match and append anything
  112. // else.
  113. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  114. return env
  115. }
  116. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  117. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  118. // if there was no error, return the device
  119. if err == nil {
  120. device.Path = deviceMapping.PathInContainer
  121. return append(devs, device), nil
  122. }
  123. // if the device is not a device node
  124. // try to see if it's a directory holding many devices
  125. if err == devices.ErrNotADevice {
  126. // check if it is a directory
  127. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  128. // mount the internal devices recursively
  129. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  130. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  131. if e != nil {
  132. // ignore the device
  133. return nil
  134. }
  135. // add the device to userSpecified devices
  136. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  137. devs = append(devs, childDevice)
  138. return nil
  139. })
  140. }
  141. }
  142. if len(devs) > 0 {
  143. return devs, nil
  144. }
  145. return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  146. }
  147. func populateCommand(c *Container, env []string) error {
  148. var en *execdriver.Network
  149. if !c.Config.NetworkDisabled {
  150. en = &execdriver.Network{
  151. NamespacePath: c.NetworkSettings.SandboxKey,
  152. }
  153. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  154. if parts[0] == "container" {
  155. nc, err := c.getNetworkedContainer()
  156. if err != nil {
  157. return err
  158. }
  159. en.ContainerID = nc.ID
  160. }
  161. }
  162. ipc := &execdriver.Ipc{}
  163. if c.hostConfig.IpcMode.IsContainer() {
  164. ic, err := c.getIpcContainer()
  165. if err != nil {
  166. return err
  167. }
  168. ipc.ContainerID = ic.ID
  169. } else {
  170. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  171. }
  172. pid := &execdriver.Pid{}
  173. pid.HostPid = c.hostConfig.PidMode.IsHost()
  174. uts := &execdriver.UTS{
  175. HostUTS: c.hostConfig.UTSMode.IsHost(),
  176. }
  177. // Build lists of devices allowed and created within the container.
  178. var userSpecifiedDevices []*configs.Device
  179. for _, deviceMapping := range c.hostConfig.Devices {
  180. devs, err := getDevicesFromPath(deviceMapping)
  181. if err != nil {
  182. return err
  183. }
  184. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  185. }
  186. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  187. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  188. // TODO: this can be removed after lxc-conf is fully deprecated
  189. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  190. if err != nil {
  191. return err
  192. }
  193. var rlimits []*ulimit.Rlimit
  194. ulimits := c.hostConfig.Ulimits
  195. // Merge ulimits with daemon defaults
  196. ulIdx := make(map[string]*ulimit.Ulimit)
  197. for _, ul := range ulimits {
  198. ulIdx[ul.Name] = ul
  199. }
  200. for name, ul := range c.daemon.config.Ulimits {
  201. if _, exists := ulIdx[name]; !exists {
  202. ulimits = append(ulimits, ul)
  203. }
  204. }
  205. for _, limit := range ulimits {
  206. rl, err := limit.GetRlimit()
  207. if err != nil {
  208. return err
  209. }
  210. rlimits = append(rlimits, rl)
  211. }
  212. resources := &execdriver.Resources{
  213. Memory: c.hostConfig.Memory,
  214. MemorySwap: c.hostConfig.MemorySwap,
  215. CPUShares: c.hostConfig.CPUShares,
  216. CpusetCpus: c.hostConfig.CpusetCpus,
  217. CpusetMems: c.hostConfig.CpusetMems,
  218. CPUPeriod: c.hostConfig.CPUPeriod,
  219. CPUQuota: c.hostConfig.CPUQuota,
  220. BlkioWeight: c.hostConfig.BlkioWeight,
  221. Rlimits: rlimits,
  222. OomKillDisable: c.hostConfig.OomKillDisable,
  223. MemorySwappiness: -1,
  224. }
  225. if c.hostConfig.MemorySwappiness != nil {
  226. resources.MemorySwappiness = *c.hostConfig.MemorySwappiness
  227. }
  228. processConfig := execdriver.ProcessConfig{
  229. Privileged: c.hostConfig.Privileged,
  230. Entrypoint: c.Path,
  231. Arguments: c.Args,
  232. Tty: c.Config.Tty,
  233. User: c.Config.User,
  234. }
  235. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  236. processConfig.Env = env
  237. c.command = &execdriver.Command{
  238. ID: c.ID,
  239. Rootfs: c.RootfsPath(),
  240. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  241. InitPath: "/.dockerinit",
  242. WorkingDir: c.Config.WorkingDir,
  243. Network: en,
  244. Ipc: ipc,
  245. Pid: pid,
  246. UTS: uts,
  247. Resources: resources,
  248. AllowedDevices: allowedDevices,
  249. AutoCreatedDevices: autoCreatedDevices,
  250. CapAdd: c.hostConfig.CapAdd.Slice(),
  251. CapDrop: c.hostConfig.CapDrop.Slice(),
  252. GroupAdd: c.hostConfig.GroupAdd,
  253. ProcessConfig: processConfig,
  254. ProcessLabel: c.GetProcessLabel(),
  255. MountLabel: c.GetMountLabel(),
  256. LxcConfig: lxcConfig,
  257. AppArmorProfile: c.AppArmorProfile,
  258. CgroupParent: c.hostConfig.CgroupParent,
  259. }
  260. return nil
  261. }
  262. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  263. if len(userDevices) == 0 {
  264. return defaultDevices
  265. }
  266. paths := map[string]*configs.Device{}
  267. for _, d := range userDevices {
  268. paths[d.Path] = d
  269. }
  270. var devs []*configs.Device
  271. for _, d := range defaultDevices {
  272. if _, defined := paths[d.Path]; !defined {
  273. devs = append(devs, d)
  274. }
  275. }
  276. return append(devs, userDevices...)
  277. }
  278. // GetSize, return real size, virtual size
  279. func (container *Container) GetSize() (int64, int64) {
  280. var (
  281. sizeRw, sizeRootfs int64
  282. err error
  283. driver = container.daemon.driver
  284. )
  285. if err := container.Mount(); err != nil {
  286. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  287. return sizeRw, sizeRootfs
  288. }
  289. defer container.Unmount()
  290. initID := fmt.Sprintf("%s-init", container.ID)
  291. sizeRw, err = driver.DiffSize(container.ID, initID)
  292. if err != nil {
  293. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  294. // FIXME: GetSize should return an error. Not changing it now in case
  295. // there is a side-effect.
  296. sizeRw = -1
  297. }
  298. if _, err = os.Stat(container.basefs); err == nil {
  299. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  300. sizeRootfs = -1
  301. }
  302. }
  303. return sizeRw, sizeRootfs
  304. }
  305. // Attempt to set the network mounts given a provided destination and
  306. // the path to use for it; return true if the given destination was a
  307. // network mount file
  308. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  309. if destination == "/etc/resolv.conf" {
  310. container.ResolvConfPath = path
  311. return true
  312. }
  313. if destination == "/etc/hostname" {
  314. container.HostnamePath = path
  315. return true
  316. }
  317. if destination == "/etc/hosts" {
  318. container.HostsPath = path
  319. return true
  320. }
  321. return false
  322. }
  323. func (container *Container) buildHostnameFile() error {
  324. hostnamePath, err := container.GetRootResourcePath("hostname")
  325. if err != nil {
  326. return err
  327. }
  328. container.HostnamePath = hostnamePath
  329. if container.Config.Domainname != "" {
  330. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  331. }
  332. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  333. }
  334. func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  335. var (
  336. joinOptions []libnetwork.EndpointOption
  337. err error
  338. dns []string
  339. dnsSearch []string
  340. )
  341. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  342. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  343. if container.hostConfig.NetworkMode.IsHost() {
  344. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  345. }
  346. container.HostsPath, err = container.GetRootResourcePath("hosts")
  347. if err != nil {
  348. return nil, err
  349. }
  350. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  351. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  352. if err != nil {
  353. return nil, err
  354. }
  355. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  356. if len(container.hostConfig.DNS) > 0 {
  357. dns = container.hostConfig.DNS
  358. } else if len(container.daemon.config.Dns) > 0 {
  359. dns = container.daemon.config.Dns
  360. }
  361. for _, d := range dns {
  362. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  363. }
  364. if len(container.hostConfig.DNSSearch) > 0 {
  365. dnsSearch = container.hostConfig.DNSSearch
  366. } else if len(container.daemon.config.DnsSearch) > 0 {
  367. dnsSearch = container.daemon.config.DnsSearch
  368. }
  369. for _, ds := range dnsSearch {
  370. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  371. }
  372. if container.NetworkSettings.SecondaryIPAddresses != nil {
  373. name := container.Config.Hostname
  374. if container.Config.Domainname != "" {
  375. name = name + "." + container.Config.Domainname
  376. }
  377. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  378. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  379. }
  380. }
  381. var childEndpoints, parentEndpoints []string
  382. children, err := container.daemon.Children(container.Name)
  383. if err != nil {
  384. return nil, err
  385. }
  386. for linkAlias, child := range children {
  387. _, alias := path.Split(linkAlias)
  388. // allow access to the linked container via the alias, real name, and container hostname
  389. aliasList := alias + " " + child.Config.Hostname
  390. // only add the name if alias isn't equal to the name
  391. if alias != child.Name[1:] {
  392. aliasList = aliasList + " " + child.Name[1:]
  393. }
  394. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  395. if child.NetworkSettings.EndpointID != "" {
  396. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  397. }
  398. }
  399. for _, extraHost := range container.hostConfig.ExtraHosts {
  400. // allow IPv6 addresses in extra hosts; only split on first ":"
  401. parts := strings.SplitN(extraHost, ":", 2)
  402. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  403. }
  404. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  405. for _, ref := range refs {
  406. if ref.ParentID == "0" {
  407. continue
  408. }
  409. c, err := container.daemon.Get(ref.ParentID)
  410. if err != nil {
  411. logrus.Error(err)
  412. }
  413. if c != nil && !container.daemon.config.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  414. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  415. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  416. if c.NetworkSettings.EndpointID != "" {
  417. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  418. }
  419. }
  420. }
  421. linkOptions := options.Generic{
  422. netlabel.GenericData: options.Generic{
  423. "ParentEndpoints": parentEndpoints,
  424. "ChildEndpoints": childEndpoints,
  425. },
  426. }
  427. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  428. return joinOptions, nil
  429. }
  430. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  431. if ep == nil {
  432. return nil, fmt.Errorf("invalid endpoint while building port map info")
  433. }
  434. if networkSettings == nil {
  435. return nil, fmt.Errorf("invalid networksettings while building port map info")
  436. }
  437. driverInfo, err := ep.DriverInfo()
  438. if err != nil {
  439. return nil, err
  440. }
  441. if driverInfo == nil {
  442. // It is not an error for epInfo to be nil
  443. return networkSettings, nil
  444. }
  445. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  446. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  447. }
  448. networkSettings.Ports = nat.PortMap{}
  449. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  450. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  451. for _, tp := range exposedPorts {
  452. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  453. if err != nil {
  454. return nil, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  455. }
  456. networkSettings.Ports[natPort] = nil
  457. }
  458. }
  459. }
  460. mapData, ok := driverInfo[netlabel.PortMap]
  461. if !ok {
  462. return networkSettings, nil
  463. }
  464. if portMapping, ok := mapData.([]types.PortBinding); ok {
  465. for _, pp := range portMapping {
  466. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  467. if err != nil {
  468. return nil, err
  469. }
  470. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  471. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  472. }
  473. }
  474. return networkSettings, nil
  475. }
  476. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  477. if ep == nil {
  478. return nil, fmt.Errorf("invalid endpoint while building port map info")
  479. }
  480. if networkSettings == nil {
  481. return nil, fmt.Errorf("invalid networksettings while building port map info")
  482. }
  483. epInfo := ep.Info()
  484. if epInfo == nil {
  485. // It is not an error to get an empty endpoint info
  486. return networkSettings, nil
  487. }
  488. ifaceList := epInfo.InterfaceList()
  489. if len(ifaceList) == 0 {
  490. return networkSettings, nil
  491. }
  492. iface := ifaceList[0]
  493. ones, _ := iface.Address().Mask.Size()
  494. networkSettings.IPAddress = iface.Address().IP.String()
  495. networkSettings.IPPrefixLen = ones
  496. if iface.AddressIPv6().IP.To16() != nil {
  497. onesv6, _ := iface.AddressIPv6().Mask.Size()
  498. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  499. networkSettings.GlobalIPv6PrefixLen = onesv6
  500. }
  501. if len(ifaceList) == 1 {
  502. return networkSettings, nil
  503. }
  504. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  505. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  506. for _, iface := range ifaceList[1:] {
  507. ones, _ := iface.Address().Mask.Size()
  508. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  509. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  510. if iface.AddressIPv6().IP.To16() != nil {
  511. onesv6, _ := iface.AddressIPv6().Mask.Size()
  512. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  513. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  514. }
  515. }
  516. return networkSettings, nil
  517. }
  518. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  519. epInfo := ep.Info()
  520. if epInfo == nil {
  521. // It is not an error to get an empty endpoint info
  522. return nil
  523. }
  524. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  525. if epInfo.GatewayIPv6().To16() != nil {
  526. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  527. }
  528. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  529. return nil
  530. }
  531. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  532. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  533. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  534. if err != nil {
  535. return err
  536. }
  537. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  538. if err != nil {
  539. return err
  540. }
  541. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  542. networkSettings.Bridge = container.daemon.config.Bridge.Iface
  543. }
  544. container.NetworkSettings = networkSettings
  545. return nil
  546. }
  547. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  548. // get removed/unlinked).
  549. func (container *Container) UpdateNetwork() error {
  550. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  551. if err != nil {
  552. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  553. }
  554. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  555. if err != nil {
  556. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  557. }
  558. if err := ep.Leave(container.ID); err != nil {
  559. return fmt.Errorf("endpoint leave failed: %v", err)
  560. }
  561. joinOptions, err := container.buildJoinOptions()
  562. if err != nil {
  563. return fmt.Errorf("Update network failed: %v", err)
  564. }
  565. if err := ep.Join(container.ID, joinOptions...); err != nil {
  566. return fmt.Errorf("endpoint join failed: %v", err)
  567. }
  568. if err := container.updateJoinInfo(ep); err != nil {
  569. return fmt.Errorf("Updating join info failed: %v", err)
  570. }
  571. return nil
  572. }
  573. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  574. var (
  575. portSpecs = make(nat.PortSet)
  576. bindings = make(nat.PortMap)
  577. pbList []types.PortBinding
  578. exposeList []types.TransportPort
  579. createOptions []libnetwork.EndpointOption
  580. )
  581. if container.Config.ExposedPorts != nil {
  582. portSpecs = container.Config.ExposedPorts
  583. }
  584. if container.hostConfig.PortBindings != nil {
  585. for p, b := range container.hostConfig.PortBindings {
  586. bindings[p] = []nat.PortBinding{}
  587. for _, bb := range b {
  588. bindings[p] = append(bindings[p], nat.PortBinding{
  589. HostIP: bb.HostIP,
  590. HostPort: bb.HostPort,
  591. })
  592. }
  593. }
  594. }
  595. container.NetworkSettings.PortMapping = nil
  596. ports := make([]nat.Port, len(portSpecs))
  597. var i int
  598. for p := range portSpecs {
  599. ports[i] = p
  600. i++
  601. }
  602. nat.SortPortMap(ports, bindings)
  603. for _, port := range ports {
  604. expose := types.TransportPort{}
  605. expose.Proto = types.ParseProtocol(port.Proto())
  606. expose.Port = uint16(port.Int())
  607. exposeList = append(exposeList, expose)
  608. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  609. binding := bindings[port]
  610. for i := 0; i < len(binding); i++ {
  611. pbCopy := pb.GetCopy()
  612. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  613. var portStart, portEnd int
  614. if err == nil {
  615. portStart, portEnd, err = newP.Range()
  616. }
  617. if err != nil {
  618. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  619. }
  620. pbCopy.HostPort = uint16(portStart)
  621. pbCopy.HostPortEnd = uint16(portEnd)
  622. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  623. pbList = append(pbList, pbCopy)
  624. }
  625. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  626. pbList = append(pbList, pb)
  627. }
  628. }
  629. createOptions = append(createOptions,
  630. libnetwork.CreateOptionPortMapping(pbList),
  631. libnetwork.CreateOptionExposedPorts(exposeList))
  632. if container.Config.MacAddress != "" {
  633. mac, err := net.ParseMAC(container.Config.MacAddress)
  634. if err != nil {
  635. return nil, err
  636. }
  637. genericOption := options.Generic{
  638. netlabel.MacAddress: mac,
  639. }
  640. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  641. }
  642. return createOptions, nil
  643. }
  644. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  645. dn := controller.Config().Daemon.DefaultNetwork
  646. dd := controller.Config().Daemon.DefaultDriver
  647. snd := strings.Split(service, ".")
  648. if len(snd) > 2 {
  649. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  650. }
  651. if len(snd) > 1 {
  652. return snd[0], snd[1], dd
  653. }
  654. return snd[0], dn, dd
  655. }
  656. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  657. createOptions := []libnetwork.NetworkOption{}
  658. genericOption := options.Generic{}
  659. // Bridge driver is special due to legacy reasons
  660. if runconfig.NetworkMode(driver).IsBridge() {
  661. genericOption[netlabel.GenericData] = map[string]interface{}{
  662. "BridgeName": dnet,
  663. "AllowNonDefaultBridge": "true",
  664. }
  665. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  666. createOptions = append(createOptions, networkOption)
  667. }
  668. return controller.NewNetwork(driver, dnet, createOptions...)
  669. }
  670. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  671. switch primaryNetworkType {
  672. case "bridge", "none", "host", "container":
  673. return false
  674. }
  675. if container.daemon.config.DisableBridge {
  676. return false
  677. }
  678. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  679. return true
  680. }
  681. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  682. return true
  683. }
  684. return false
  685. }
  686. func (container *Container) AllocateNetwork() error {
  687. mode := container.hostConfig.NetworkMode
  688. controller := container.daemon.netController
  689. if container.Config.NetworkDisabled || mode.IsContainer() {
  690. return nil
  691. }
  692. networkDriver := string(mode)
  693. service := container.Config.PublishService
  694. networkName := mode.NetworkName()
  695. if mode.IsDefault() {
  696. if service != "" {
  697. service, networkName, networkDriver = parseService(controller, service)
  698. } else {
  699. networkName = controller.Config().Daemon.DefaultNetwork
  700. networkDriver = controller.Config().Daemon.DefaultDriver
  701. }
  702. } else if service != "" {
  703. return fmt.Errorf("conflicting options: publishing a service and network mode")
  704. }
  705. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.config.DisableBridge {
  706. container.Config.NetworkDisabled = true
  707. return nil
  708. }
  709. if service == "" {
  710. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  711. // For backward compatibility, replacing "." with "-", instead of failing
  712. service = strings.Replace(container.Name, ".", "-", -1)
  713. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  714. service = strings.Replace(service, "/", "", -1)
  715. }
  716. if container.secondaryNetworkRequired(networkDriver) {
  717. // Configure Bridge as secondary network for port binding purposes
  718. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  719. return err
  720. }
  721. }
  722. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  723. return err
  724. }
  725. return container.WriteHostConfig()
  726. }
  727. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  728. controller := container.daemon.netController
  729. n, err := controller.NetworkByName(networkName)
  730. if err != nil {
  731. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  732. return err
  733. }
  734. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  735. return err
  736. }
  737. }
  738. ep, err := n.EndpointByName(service)
  739. if err != nil {
  740. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  741. return err
  742. }
  743. createOptions, err := container.buildCreateEndpointOptions()
  744. if err != nil {
  745. return err
  746. }
  747. ep, err = n.CreateEndpoint(service, createOptions...)
  748. if err != nil {
  749. return err
  750. }
  751. }
  752. if err := container.updateNetworkSettings(n, ep); err != nil {
  753. return err
  754. }
  755. joinOptions, err := container.buildJoinOptions()
  756. if err != nil {
  757. return err
  758. }
  759. if err := ep.Join(container.ID, joinOptions...); err != nil {
  760. return err
  761. }
  762. if err := container.updateJoinInfo(ep); err != nil {
  763. return fmt.Errorf("Updating join info failed: %v", err)
  764. }
  765. return nil
  766. }
  767. func (container *Container) initializeNetworking() error {
  768. var err error
  769. if container.hostConfig.NetworkMode.IsContainer() {
  770. // we need to get the hosts files from the container to join
  771. nc, err := container.getNetworkedContainer()
  772. if err != nil {
  773. return err
  774. }
  775. container.HostnamePath = nc.HostnamePath
  776. container.HostsPath = nc.HostsPath
  777. container.ResolvConfPath = nc.ResolvConfPath
  778. container.Config.Hostname = nc.Config.Hostname
  779. container.Config.Domainname = nc.Config.Domainname
  780. return nil
  781. }
  782. if container.hostConfig.NetworkMode.IsHost() {
  783. container.Config.Hostname, err = os.Hostname()
  784. if err != nil {
  785. return err
  786. }
  787. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  788. if len(parts) > 1 {
  789. container.Config.Hostname = parts[0]
  790. container.Config.Domainname = parts[1]
  791. }
  792. }
  793. if err := container.AllocateNetwork(); err != nil {
  794. return err
  795. }
  796. return container.buildHostnameFile()
  797. }
  798. func (container *Container) getIpcContainer() (*Container, error) {
  799. containerID := container.hostConfig.IpcMode.Container()
  800. c, err := container.daemon.Get(containerID)
  801. if err != nil {
  802. return nil, err
  803. }
  804. if !c.IsRunning() {
  805. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  806. }
  807. return c, nil
  808. }
  809. func (container *Container) setupWorkingDirectory() error {
  810. if container.Config.WorkingDir != "" {
  811. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  812. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  813. if err != nil {
  814. return err
  815. }
  816. pthInfo, err := os.Stat(pth)
  817. if err != nil {
  818. if !os.IsNotExist(err) {
  819. return err
  820. }
  821. if err := system.MkdirAll(pth, 0755); err != nil {
  822. return err
  823. }
  824. }
  825. if pthInfo != nil && !pthInfo.IsDir() {
  826. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  827. }
  828. }
  829. return nil
  830. }
  831. func (container *Container) getNetworkedContainer() (*Container, error) {
  832. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  833. switch parts[0] {
  834. case "container":
  835. if len(parts) != 2 {
  836. return nil, fmt.Errorf("no container specified to join network")
  837. }
  838. nc, err := container.daemon.Get(parts[1])
  839. if err != nil {
  840. return nil, err
  841. }
  842. if container == nc {
  843. return nil, fmt.Errorf("cannot join own network")
  844. }
  845. if !nc.IsRunning() {
  846. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  847. }
  848. return nc, nil
  849. default:
  850. return nil, fmt.Errorf("network mode not set to container")
  851. }
  852. }
  853. func (container *Container) ReleaseNetwork() {
  854. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  855. return
  856. }
  857. eid := container.NetworkSettings.EndpointID
  858. nid := container.NetworkSettings.NetworkID
  859. container.NetworkSettings = &network.Settings{}
  860. if nid == "" || eid == "" {
  861. return
  862. }
  863. n, err := container.daemon.netController.NetworkByID(nid)
  864. if err != nil {
  865. logrus.Errorf("error locating network id %s: %v", nid, err)
  866. return
  867. }
  868. ep, err := n.EndpointByID(eid)
  869. if err != nil {
  870. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  871. return
  872. }
  873. switch {
  874. case container.hostConfig.NetworkMode.IsHost():
  875. if err := ep.Leave(container.ID); err != nil {
  876. logrus.Errorf("Error leaving endpoint id %s for container %s: %v", eid, container.ID, err)
  877. return
  878. }
  879. default:
  880. if err := container.daemon.netController.LeaveAll(container.ID); err != nil {
  881. logrus.Errorf("Leave all failed for %s: %v", container.ID, err)
  882. return
  883. }
  884. }
  885. // In addition to leaving all endpoints, delete implicitly created endpoint
  886. if container.Config.PublishService == "" {
  887. if err := ep.Delete(); err != nil {
  888. logrus.Errorf("deleting endpoint failed: %v", err)
  889. }
  890. }
  891. }
  892. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  893. var volumeMounts []mountPoint
  894. for _, mntPoint := range container.MountPoints {
  895. dest, err := container.GetResourcePath(mntPoint.Destination)
  896. if err != nil {
  897. return err
  898. }
  899. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  900. }
  901. for _, mnt := range container.networkMounts() {
  902. dest, err := container.GetResourcePath(mnt.Destination)
  903. if err != nil {
  904. return err
  905. }
  906. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  907. }
  908. for _, volumeMount := range volumeMounts {
  909. if forceSyscall {
  910. syscall.Unmount(volumeMount.Destination, 0)
  911. }
  912. if volumeMount.Volume != nil {
  913. if err := volumeMount.Volume.Unmount(); err != nil {
  914. return err
  915. }
  916. }
  917. }
  918. return nil
  919. }
  920. func (container *Container) networkMounts() []execdriver.Mount {
  921. var mounts []execdriver.Mount
  922. mode := "Z"
  923. if container.hostConfig.NetworkMode.IsContainer() {
  924. mode = "z"
  925. }
  926. if container.ResolvConfPath != "" {
  927. label.Relabel(container.ResolvConfPath, container.MountLabel, mode)
  928. writable := !container.hostConfig.ReadonlyRootfs
  929. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  930. writable = m.RW
  931. }
  932. mounts = append(mounts, execdriver.Mount{
  933. Source: container.ResolvConfPath,
  934. Destination: "/etc/resolv.conf",
  935. Writable: writable,
  936. Private: true,
  937. })
  938. }
  939. if container.HostnamePath != "" {
  940. label.Relabel(container.HostnamePath, container.MountLabel, mode)
  941. writable := !container.hostConfig.ReadonlyRootfs
  942. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  943. writable = m.RW
  944. }
  945. mounts = append(mounts, execdriver.Mount{
  946. Source: container.HostnamePath,
  947. Destination: "/etc/hostname",
  948. Writable: writable,
  949. Private: true,
  950. })
  951. }
  952. if container.HostsPath != "" {
  953. label.Relabel(container.HostsPath, container.MountLabel, mode)
  954. writable := !container.hostConfig.ReadonlyRootfs
  955. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  956. writable = m.RW
  957. }
  958. mounts = append(mounts, execdriver.Mount{
  959. Source: container.HostsPath,
  960. Destination: "/etc/hosts",
  961. Writable: writable,
  962. Private: true,
  963. })
  964. }
  965. return mounts
  966. }
  967. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  968. container.MountPoints[destination] = &mountPoint{
  969. Name: name,
  970. Source: source,
  971. Destination: destination,
  972. RW: rw,
  973. }
  974. }
  975. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  976. container.MountPoints[destination] = &mountPoint{
  977. Name: name,
  978. Driver: volume.DefaultDriverName,
  979. Destination: destination,
  980. RW: rw,
  981. }
  982. }
  983. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  984. container.MountPoints[destination] = &mountPoint{
  985. Name: vol.Name(),
  986. Driver: vol.DriverName(),
  987. Destination: destination,
  988. RW: rw,
  989. Volume: vol,
  990. }
  991. }
  992. func (container *Container) isDestinationMounted(destination string) bool {
  993. return container.MountPoints[destination] != nil
  994. }
  995. func (container *Container) prepareMountPoints() error {
  996. for _, config := range container.MountPoints {
  997. if len(config.Driver) > 0 {
  998. v, err := createVolume(config.Name, config.Driver)
  999. if err != nil {
  1000. return err
  1001. }
  1002. config.Volume = v
  1003. }
  1004. }
  1005. return nil
  1006. }
  1007. func (container *Container) removeMountPoints() error {
  1008. for _, m := range container.MountPoints {
  1009. if m.Volume != nil {
  1010. if err := removeVolume(m.Volume); err != nil {
  1011. return err
  1012. }
  1013. }
  1014. }
  1015. return nil
  1016. }