container_unix.go 34 KB

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