container_unix.go 35 KB

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