container_unix.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. mode := "Z"
  938. if container.hostConfig.NetworkMode.IsContainer() {
  939. mode = "z"
  940. }
  941. if container.ResolvConfPath != "" {
  942. label.Relabel(container.ResolvConfPath, container.MountLabel, mode)
  943. writable := !container.hostConfig.ReadonlyRootfs
  944. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  945. writable = m.RW
  946. }
  947. mounts = append(mounts, execdriver.Mount{
  948. Source: container.ResolvConfPath,
  949. Destination: "/etc/resolv.conf",
  950. Writable: writable,
  951. Private: true,
  952. })
  953. }
  954. if container.HostnamePath != "" {
  955. label.Relabel(container.HostnamePath, container.MountLabel, mode)
  956. writable := !container.hostConfig.ReadonlyRootfs
  957. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  958. writable = m.RW
  959. }
  960. mounts = append(mounts, execdriver.Mount{
  961. Source: container.HostnamePath,
  962. Destination: "/etc/hostname",
  963. Writable: writable,
  964. Private: true,
  965. })
  966. }
  967. if container.HostsPath != "" {
  968. label.Relabel(container.HostsPath, container.MountLabel, mode)
  969. writable := !container.hostConfig.ReadonlyRootfs
  970. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  971. writable = m.RW
  972. }
  973. mounts = append(mounts, execdriver.Mount{
  974. Source: container.HostsPath,
  975. Destination: "/etc/hosts",
  976. Writable: writable,
  977. Private: true,
  978. })
  979. }
  980. return mounts
  981. }
  982. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  983. container.MountPoints[destination] = &mountPoint{
  984. Name: name,
  985. Source: source,
  986. Destination: destination,
  987. RW: rw,
  988. }
  989. }
  990. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  991. container.MountPoints[destination] = &mountPoint{
  992. Name: name,
  993. Driver: volume.DefaultDriverName,
  994. Destination: destination,
  995. RW: rw,
  996. }
  997. }
  998. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  999. container.MountPoints[destination] = &mountPoint{
  1000. Name: vol.Name(),
  1001. Driver: vol.DriverName(),
  1002. Destination: destination,
  1003. RW: rw,
  1004. Volume: vol,
  1005. }
  1006. }
  1007. func (container *Container) isDestinationMounted(destination string) bool {
  1008. return container.MountPoints[destination] != nil
  1009. }
  1010. func (container *Container) prepareMountPoints() error {
  1011. for _, config := range container.MountPoints {
  1012. if len(config.Driver) > 0 {
  1013. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1014. if err != nil {
  1015. return err
  1016. }
  1017. config.Volume = v
  1018. }
  1019. }
  1020. return nil
  1021. }
  1022. func (container *Container) removeMountPoints(rm bool) error {
  1023. var rmErrors []string
  1024. for _, m := range container.MountPoints {
  1025. if m.Volume == nil {
  1026. continue
  1027. }
  1028. container.daemon.volumes.Decrement(m.Volume)
  1029. if rm {
  1030. if err := container.daemon.volumes.Remove(m.Volume); err != nil {
  1031. rmErrors = append(rmErrors, fmt.Sprintf("%v\n", err))
  1032. continue
  1033. }
  1034. }
  1035. }
  1036. if len(rmErrors) > 0 {
  1037. return fmt.Errorf("Error removing volumes:\n%v", rmErrors)
  1038. }
  1039. return nil
  1040. }