container_unix.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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/libcontainer/configs"
  28. "github.com/docker/libcontainer/devices"
  29. "github.com/docker/libnetwork"
  30. "github.com/docker/libnetwork/netlabel"
  31. "github.com/docker/libnetwork/options"
  32. "github.com/docker/libnetwork/types"
  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. ProcessConfig: processConfig,
  261. ProcessLabel: c.GetProcessLabel(),
  262. MountLabel: c.GetMountLabel(),
  263. LxcConfig: lxcConfig,
  264. AppArmorProfile: c.AppArmorProfile,
  265. CgroupParent: c.hostConfig.CgroupParent,
  266. }
  267. return nil
  268. }
  269. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  270. if len(userDevices) == 0 {
  271. return defaultDevices
  272. }
  273. paths := map[string]*configs.Device{}
  274. for _, d := range userDevices {
  275. paths[d.Path] = d
  276. }
  277. var devs []*configs.Device
  278. for _, d := range defaultDevices {
  279. if _, defined := paths[d.Path]; !defined {
  280. devs = append(devs, d)
  281. }
  282. }
  283. return append(devs, userDevices...)
  284. }
  285. // GetSize, return real size, virtual size
  286. func (container *Container) GetSize() (int64, int64) {
  287. var (
  288. sizeRw, sizeRootfs int64
  289. err error
  290. driver = container.daemon.driver
  291. )
  292. if err := container.Mount(); err != nil {
  293. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  294. return sizeRw, sizeRootfs
  295. }
  296. defer container.Unmount()
  297. initID := fmt.Sprintf("%s-init", container.ID)
  298. sizeRw, err = driver.DiffSize(container.ID, initID)
  299. if err != nil {
  300. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  301. // FIXME: GetSize should return an error. Not changing it now in case
  302. // there is a side-effect.
  303. sizeRw = -1
  304. }
  305. if _, err = os.Stat(container.basefs); err == nil {
  306. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  307. sizeRootfs = -1
  308. }
  309. }
  310. return sizeRw, sizeRootfs
  311. }
  312. func (container *Container) buildHostnameFile() error {
  313. hostnamePath, err := container.GetRootResourcePath("hostname")
  314. if err != nil {
  315. return err
  316. }
  317. container.HostnamePath = hostnamePath
  318. if container.Config.Domainname != "" {
  319. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  320. }
  321. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  322. }
  323. func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  324. var (
  325. joinOptions []libnetwork.EndpointOption
  326. err error
  327. dns []string
  328. dnsSearch []string
  329. )
  330. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  331. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  332. if container.hostConfig.NetworkMode.IsHost() {
  333. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  334. }
  335. container.HostsPath, err = container.GetRootResourcePath("hosts")
  336. if err != nil {
  337. return nil, err
  338. }
  339. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  340. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  341. if err != nil {
  342. return nil, err
  343. }
  344. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  345. if len(container.hostConfig.Dns) > 0 {
  346. dns = container.hostConfig.Dns
  347. } else if len(container.daemon.config.Dns) > 0 {
  348. dns = container.daemon.config.Dns
  349. }
  350. for _, d := range dns {
  351. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  352. }
  353. if len(container.hostConfig.DnsSearch) > 0 {
  354. dnsSearch = container.hostConfig.DnsSearch
  355. } else if len(container.daemon.config.DnsSearch) > 0 {
  356. dnsSearch = container.daemon.config.DnsSearch
  357. }
  358. for _, ds := range dnsSearch {
  359. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  360. }
  361. if container.NetworkSettings.SecondaryIPAddresses != nil {
  362. name := container.Config.Hostname
  363. if container.Config.Domainname != "" {
  364. name = name + "." + container.Config.Domainname
  365. }
  366. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  367. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  368. }
  369. }
  370. var childEndpoints, parentEndpoints []string
  371. children, err := container.daemon.Children(container.Name)
  372. if err != nil {
  373. return nil, err
  374. }
  375. for linkAlias, child := range children {
  376. _, alias := path.Split(linkAlias)
  377. // allow access to the linked container via the alias, real name, and container hostname
  378. aliasList := alias + " " + child.Config.Hostname
  379. // only add the name if alias isn't equal to the name
  380. if alias != child.Name[1:] {
  381. aliasList = aliasList + " " + child.Name[1:]
  382. }
  383. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  384. if child.NetworkSettings.EndpointID != "" {
  385. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  386. }
  387. }
  388. for _, extraHost := range container.hostConfig.ExtraHosts {
  389. // allow IPv6 addresses in extra hosts; only split on first ":"
  390. parts := strings.SplitN(extraHost, ":", 2)
  391. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  392. }
  393. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  394. for _, ref := range refs {
  395. if ref.ParentID == "0" {
  396. continue
  397. }
  398. c, err := container.daemon.Get(ref.ParentID)
  399. if err != nil {
  400. logrus.Error(err)
  401. }
  402. if c != nil && !container.daemon.config.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  403. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  404. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  405. if c.NetworkSettings.EndpointID != "" {
  406. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  407. }
  408. }
  409. }
  410. linkOptions := options.Generic{
  411. netlabel.GenericData: options.Generic{
  412. "ParentEndpoints": parentEndpoints,
  413. "ChildEndpoints": childEndpoints,
  414. },
  415. }
  416. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  417. return joinOptions, nil
  418. }
  419. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  420. if ep == nil {
  421. return nil, fmt.Errorf("invalid endpoint while building port map info")
  422. }
  423. if networkSettings == nil {
  424. return nil, fmt.Errorf("invalid networksettings while building port map info")
  425. }
  426. driverInfo, err := ep.DriverInfo()
  427. if err != nil {
  428. return nil, err
  429. }
  430. if driverInfo == nil {
  431. // It is not an error for epInfo to be nil
  432. return networkSettings, nil
  433. }
  434. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  435. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  436. }
  437. networkSettings.Ports = nat.PortMap{}
  438. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  439. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  440. for _, tp := range exposedPorts {
  441. natPort := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  442. networkSettings.Ports[natPort] = nil
  443. }
  444. }
  445. }
  446. mapData, ok := driverInfo[netlabel.PortMap]
  447. if !ok {
  448. return networkSettings, nil
  449. }
  450. if portMapping, ok := mapData.([]types.PortBinding); ok {
  451. for _, pp := range portMapping {
  452. natPort := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  453. natBndg := nat.PortBinding{HostIp: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  454. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  455. }
  456. }
  457. return networkSettings, nil
  458. }
  459. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  460. if ep == nil {
  461. return nil, fmt.Errorf("invalid endpoint while building port map info")
  462. }
  463. if networkSettings == nil {
  464. return nil, fmt.Errorf("invalid networksettings while building port map info")
  465. }
  466. epInfo := ep.Info()
  467. if epInfo == nil {
  468. // It is not an error to get an empty endpoint info
  469. return networkSettings, nil
  470. }
  471. ifaceList := epInfo.InterfaceList()
  472. if len(ifaceList) == 0 {
  473. return networkSettings, nil
  474. }
  475. iface := ifaceList[0]
  476. ones, _ := iface.Address().Mask.Size()
  477. networkSettings.IPAddress = iface.Address().IP.String()
  478. networkSettings.IPPrefixLen = ones
  479. if iface.AddressIPv6().IP.To16() != nil {
  480. onesv6, _ := iface.AddressIPv6().Mask.Size()
  481. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  482. networkSettings.GlobalIPv6PrefixLen = onesv6
  483. }
  484. if len(ifaceList) == 1 {
  485. return networkSettings, nil
  486. }
  487. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  488. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  489. for _, iface := range ifaceList[1:] {
  490. ones, _ := iface.Address().Mask.Size()
  491. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  492. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  493. if iface.AddressIPv6().IP.To16() != nil {
  494. onesv6, _ := iface.AddressIPv6().Mask.Size()
  495. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  496. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  497. }
  498. }
  499. return networkSettings, nil
  500. }
  501. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  502. epInfo := ep.Info()
  503. if epInfo == nil {
  504. // It is not an error to get an empty endpoint info
  505. return nil
  506. }
  507. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  508. if epInfo.GatewayIPv6().To16() != nil {
  509. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  510. }
  511. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  512. return nil
  513. }
  514. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  515. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  516. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  517. if err != nil {
  518. return err
  519. }
  520. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  521. if err != nil {
  522. return err
  523. }
  524. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  525. networkSettings.Bridge = container.daemon.config.Bridge.Iface
  526. }
  527. container.NetworkSettings = networkSettings
  528. return nil
  529. }
  530. func (container *Container) UpdateNetwork() error {
  531. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  532. if err != nil {
  533. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  534. }
  535. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  536. if err != nil {
  537. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  538. }
  539. if err := ep.Leave(container.ID); err != nil {
  540. return fmt.Errorf("endpoint leave failed: %v", err)
  541. }
  542. joinOptions, err := container.buildJoinOptions()
  543. if err != nil {
  544. return fmt.Errorf("Update network failed: %v", err)
  545. }
  546. if err := ep.Join(container.ID, joinOptions...); err != nil {
  547. return fmt.Errorf("endpoint join failed: %v", err)
  548. }
  549. if err := container.updateJoinInfo(ep); err != nil {
  550. return fmt.Errorf("Updating join info failed: %v", err)
  551. }
  552. return nil
  553. }
  554. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  555. var (
  556. portSpecs = make(nat.PortSet)
  557. bindings = make(nat.PortMap)
  558. pbList []types.PortBinding
  559. exposeList []types.TransportPort
  560. createOptions []libnetwork.EndpointOption
  561. )
  562. if container.Config.ExposedPorts != nil {
  563. portSpecs = container.Config.ExposedPorts
  564. }
  565. if container.hostConfig.PortBindings != nil {
  566. for p, b := range container.hostConfig.PortBindings {
  567. bindings[p] = []nat.PortBinding{}
  568. for _, bb := range b {
  569. bindings[p] = append(bindings[p], nat.PortBinding{
  570. HostIp: bb.HostIp,
  571. HostPort: bb.HostPort,
  572. })
  573. }
  574. }
  575. }
  576. container.NetworkSettings.PortMapping = nil
  577. ports := make([]nat.Port, len(portSpecs))
  578. var i int
  579. for p := range portSpecs {
  580. ports[i] = p
  581. i++
  582. }
  583. nat.SortPortMap(ports, bindings)
  584. for _, port := range ports {
  585. expose := types.TransportPort{}
  586. expose.Proto = types.ParseProtocol(port.Proto())
  587. expose.Port = uint16(port.Int())
  588. exposeList = append(exposeList, expose)
  589. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  590. binding := bindings[port]
  591. for i := 0; i < len(binding); i++ {
  592. pbCopy := pb.GetCopy()
  593. pbCopy.HostPort = uint16(nat.Port(binding[i].HostPort).Int())
  594. pbCopy.HostIP = net.ParseIP(binding[i].HostIp)
  595. pbList = append(pbList, pbCopy)
  596. }
  597. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  598. pbList = append(pbList, pb)
  599. }
  600. }
  601. createOptions = append(createOptions,
  602. libnetwork.CreateOptionPortMapping(pbList),
  603. libnetwork.CreateOptionExposedPorts(exposeList))
  604. if container.Config.MacAddress != "" {
  605. mac, err := net.ParseMAC(container.Config.MacAddress)
  606. if err != nil {
  607. return nil, err
  608. }
  609. genericOption := options.Generic{
  610. netlabel.MacAddress: mac,
  611. }
  612. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  613. }
  614. return createOptions, nil
  615. }
  616. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  617. dn := controller.Config().Daemon.DefaultNetwork
  618. dd := controller.Config().Daemon.DefaultDriver
  619. snd := strings.Split(service, ".")
  620. if len(snd) > 2 {
  621. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  622. }
  623. if len(snd) > 1 {
  624. return snd[0], snd[1], dd
  625. }
  626. return snd[0], dn, dd
  627. }
  628. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  629. createOptions := []libnetwork.NetworkOption{}
  630. genericOption := options.Generic{}
  631. // Bridge driver is special due to legacy reasons
  632. if runconfig.NetworkMode(driver).IsBridge() {
  633. genericOption[netlabel.GenericData] = map[string]interface{}{
  634. "BridgeName": dnet,
  635. "AllowNonDefaultBridge": "true",
  636. }
  637. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  638. createOptions = append(createOptions, networkOption)
  639. }
  640. return controller.NewNetwork(driver, dnet, createOptions...)
  641. }
  642. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  643. switch primaryNetworkType {
  644. case "bridge", "none", "host", "container":
  645. return false
  646. }
  647. if container.daemon.config.DisableBridge {
  648. return false
  649. }
  650. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  651. return true
  652. }
  653. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  654. return true
  655. }
  656. return false
  657. }
  658. func (container *Container) AllocateNetwork() error {
  659. mode := container.hostConfig.NetworkMode
  660. controller := container.daemon.netController
  661. if container.Config.NetworkDisabled || mode.IsContainer() {
  662. return nil
  663. }
  664. networkDriver := string(mode)
  665. service := container.Config.PublishService
  666. networkName := mode.NetworkName()
  667. if mode.IsDefault() {
  668. if service != "" {
  669. service, networkName, networkDriver = parseService(controller, service)
  670. } else {
  671. networkName = controller.Config().Daemon.DefaultNetwork
  672. networkDriver = controller.Config().Daemon.DefaultDriver
  673. }
  674. } else if service != "" {
  675. return fmt.Errorf("conflicting options: publishing a service and network mode")
  676. }
  677. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.config.DisableBridge {
  678. container.Config.NetworkDisabled = true
  679. return nil
  680. }
  681. if service == "" {
  682. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  683. // For backward compatiblity, replacing "." with "-", instead of failing
  684. service = strings.Replace(container.Name, ".", "-", -1)
  685. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  686. service = strings.Replace(service, "/", "", -1)
  687. }
  688. if container.secondaryNetworkRequired(networkDriver) {
  689. // Configure Bridge as secondary network for port binding purposes
  690. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  691. return err
  692. }
  693. }
  694. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  695. return err
  696. }
  697. return container.WriteHostConfig()
  698. }
  699. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  700. controller := container.daemon.netController
  701. n, err := controller.NetworkByName(networkName)
  702. if err != nil {
  703. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  704. return err
  705. }
  706. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  707. return err
  708. }
  709. }
  710. ep, err := n.EndpointByName(service)
  711. if err != nil {
  712. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  713. return err
  714. }
  715. createOptions, err := container.buildCreateEndpointOptions()
  716. if err != nil {
  717. return err
  718. }
  719. ep, err = n.CreateEndpoint(service, createOptions...)
  720. if err != nil {
  721. return err
  722. }
  723. }
  724. if err := container.updateNetworkSettings(n, ep); err != nil {
  725. return err
  726. }
  727. joinOptions, err := container.buildJoinOptions()
  728. if err != nil {
  729. return err
  730. }
  731. if err := ep.Join(container.ID, joinOptions...); err != nil {
  732. return err
  733. }
  734. if err := container.updateJoinInfo(ep); err != nil {
  735. return fmt.Errorf("Updating join info failed: %v", err)
  736. }
  737. return nil
  738. }
  739. func (container *Container) initializeNetworking() error {
  740. var err error
  741. // Make sure NetworkMode has an acceptable value before
  742. // initializing networking.
  743. if container.hostConfig.NetworkMode == runconfig.NetworkMode("") {
  744. container.hostConfig.NetworkMode = runconfig.NetworkMode("default")
  745. }
  746. if container.hostConfig.NetworkMode.IsContainer() {
  747. // we need to get the hosts files from the container to join
  748. nc, err := container.getNetworkedContainer()
  749. if err != nil {
  750. return err
  751. }
  752. container.HostnamePath = nc.HostnamePath
  753. container.HostsPath = nc.HostsPath
  754. container.ResolvConfPath = nc.ResolvConfPath
  755. container.Config.Hostname = nc.Config.Hostname
  756. container.Config.Domainname = nc.Config.Domainname
  757. return nil
  758. }
  759. if container.hostConfig.NetworkMode.IsHost() {
  760. container.Config.Hostname, err = os.Hostname()
  761. if err != nil {
  762. return err
  763. }
  764. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  765. if len(parts) > 1 {
  766. container.Config.Hostname = parts[0]
  767. container.Config.Domainname = parts[1]
  768. }
  769. }
  770. if err := container.AllocateNetwork(); err != nil {
  771. return err
  772. }
  773. return container.buildHostnameFile()
  774. }
  775. func (container *Container) ExportRw() (archive.Archive, error) {
  776. if container.daemon == nil {
  777. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  778. }
  779. archive, err := container.daemon.Diff(container)
  780. if err != nil {
  781. return nil, err
  782. }
  783. return ioutils.NewReadCloserWrapper(archive, func() error {
  784. err := archive.Close()
  785. return err
  786. }),
  787. nil
  788. }
  789. func (container *Container) getIpcContainer() (*Container, error) {
  790. containerID := container.hostConfig.IpcMode.Container()
  791. c, err := container.daemon.Get(containerID)
  792. if err != nil {
  793. return nil, err
  794. }
  795. if !c.IsRunning() {
  796. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  797. }
  798. return c, nil
  799. }
  800. func (container *Container) setupWorkingDirectory() error {
  801. if container.Config.WorkingDir != "" {
  802. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  803. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  804. if err != nil {
  805. return err
  806. }
  807. pthInfo, err := os.Stat(pth)
  808. if err != nil {
  809. if !os.IsNotExist(err) {
  810. return err
  811. }
  812. if err := system.MkdirAll(pth, 0755); err != nil {
  813. return err
  814. }
  815. }
  816. if pthInfo != nil && !pthInfo.IsDir() {
  817. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  818. }
  819. }
  820. return nil
  821. }
  822. func (container *Container) getNetworkedContainer() (*Container, error) {
  823. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  824. switch parts[0] {
  825. case "container":
  826. if len(parts) != 2 {
  827. return nil, fmt.Errorf("no container specified to join network")
  828. }
  829. nc, err := container.daemon.Get(parts[1])
  830. if err != nil {
  831. return nil, err
  832. }
  833. if container == nc {
  834. return nil, fmt.Errorf("cannot join own network")
  835. }
  836. if !nc.IsRunning() {
  837. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  838. }
  839. return nc, nil
  840. default:
  841. return nil, fmt.Errorf("network mode not set to container")
  842. }
  843. }
  844. func (container *Container) ReleaseNetwork() {
  845. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  846. return
  847. }
  848. eid := container.NetworkSettings.EndpointID
  849. nid := container.NetworkSettings.NetworkID
  850. container.NetworkSettings = &network.Settings{}
  851. if nid == "" || eid == "" {
  852. return
  853. }
  854. n, err := container.daemon.netController.NetworkByID(nid)
  855. if err != nil {
  856. logrus.Errorf("error locating network id %s: %v", nid, err)
  857. return
  858. }
  859. ep, err := n.EndpointByID(eid)
  860. if err != nil {
  861. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  862. return
  863. }
  864. switch {
  865. case container.hostConfig.NetworkMode.IsHost():
  866. if err := ep.Leave(container.ID); err != nil {
  867. logrus.Errorf("Error leaving endpoint id %s for container %s: %v", eid, container.ID, err)
  868. return
  869. }
  870. default:
  871. if err := container.daemon.netController.LeaveAll(container.ID); err != nil {
  872. logrus.Errorf("Leave all failed for %s: %v", container.ID, err)
  873. return
  874. }
  875. }
  876. // In addition to leaving all endpoints, delete implicitly created endpoint
  877. if container.Config.PublishService == "" {
  878. if err := ep.Delete(); err != nil {
  879. logrus.Errorf("deleting endpoint failed: %v", err)
  880. }
  881. }
  882. }
  883. func disableAllActiveLinks(container *Container) {
  884. if container.activeLinks != nil {
  885. for _, link := range container.activeLinks {
  886. link.Disable()
  887. }
  888. }
  889. }
  890. func (container *Container) DisableLink(name string) {
  891. if container.activeLinks != nil {
  892. if link, exists := container.activeLinks[name]; exists {
  893. link.Disable()
  894. delete(container.activeLinks, name)
  895. if err := container.UpdateNetwork(); err != nil {
  896. logrus.Debugf("Could not update network to remove link: %v", err)
  897. }
  898. } else {
  899. logrus.Debugf("Could not find active link for %s", name)
  900. }
  901. }
  902. }
  903. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  904. var volumeMounts []mountPoint
  905. for _, mntPoint := range container.MountPoints {
  906. dest, err := container.GetResourcePath(mntPoint.Destination)
  907. if err != nil {
  908. return err
  909. }
  910. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  911. }
  912. for _, mnt := range container.networkMounts() {
  913. dest, err := container.GetResourcePath(mnt.Destination)
  914. if err != nil {
  915. return err
  916. }
  917. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  918. }
  919. for _, volumeMount := range volumeMounts {
  920. if forceSyscall {
  921. syscall.Unmount(volumeMount.Destination, 0)
  922. }
  923. if volumeMount.Volume != nil {
  924. if err := volumeMount.Volume.Unmount(); err != nil {
  925. return err
  926. }
  927. }
  928. }
  929. return nil
  930. }
  931. func (container *Container) PrepareStorage() error {
  932. return nil
  933. }
  934. func (container *Container) CleanupStorage() error {
  935. return nil
  936. }