container_unix.go 31 KB

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