container_unix.go 34 KB

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