container_unix.go 31 KB

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