container_unix.go 35 KB

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