container_unix.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. // Attempt to set the network mounts given a provided destination and
  314. // the path to use for it; return true if the given destination was a
  315. // network mount file
  316. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  317. if destination == "/etc/resolv.conf" {
  318. container.ResolvConfPath = path
  319. return true
  320. }
  321. if destination == "/etc/hostname" {
  322. container.HostnamePath = path
  323. return true
  324. }
  325. if destination == "/etc/hosts" {
  326. container.HostsPath = path
  327. return true
  328. }
  329. return false
  330. }
  331. func (container *Container) buildHostnameFile() error {
  332. hostnamePath, err := container.GetRootResourcePath("hostname")
  333. if err != nil {
  334. return err
  335. }
  336. container.HostnamePath = hostnamePath
  337. if container.Config.Domainname != "" {
  338. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  339. }
  340. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  341. }
  342. func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  343. var (
  344. joinOptions []libnetwork.EndpointOption
  345. err error
  346. dns []string
  347. dnsSearch []string
  348. )
  349. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  350. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  351. if container.hostConfig.NetworkMode.IsHost() {
  352. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  353. }
  354. container.HostsPath, err = container.GetRootResourcePath("hosts")
  355. if err != nil {
  356. return nil, err
  357. }
  358. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  359. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  360. if err != nil {
  361. return nil, err
  362. }
  363. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  364. if len(container.hostConfig.Dns) > 0 {
  365. dns = container.hostConfig.Dns
  366. } else if len(container.daemon.config.Dns) > 0 {
  367. dns = container.daemon.config.Dns
  368. }
  369. for _, d := range dns {
  370. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  371. }
  372. if len(container.hostConfig.DnsSearch) > 0 {
  373. dnsSearch = container.hostConfig.DnsSearch
  374. } else if len(container.daemon.config.DnsSearch) > 0 {
  375. dnsSearch = container.daemon.config.DnsSearch
  376. }
  377. for _, ds := range dnsSearch {
  378. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  379. }
  380. if container.NetworkSettings.SecondaryIPAddresses != nil {
  381. name := container.Config.Hostname
  382. if container.Config.Domainname != "" {
  383. name = name + "." + container.Config.Domainname
  384. }
  385. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  386. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  387. }
  388. }
  389. var childEndpoints, parentEndpoints []string
  390. children, err := container.daemon.Children(container.Name)
  391. if err != nil {
  392. return nil, err
  393. }
  394. for linkAlias, child := range children {
  395. _, alias := path.Split(linkAlias)
  396. // allow access to the linked container via the alias, real name, and container hostname
  397. aliasList := alias + " " + child.Config.Hostname
  398. // only add the name if alias isn't equal to the name
  399. if alias != child.Name[1:] {
  400. aliasList = aliasList + " " + child.Name[1:]
  401. }
  402. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  403. if child.NetworkSettings.EndpointID != "" {
  404. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  405. }
  406. }
  407. for _, extraHost := range container.hostConfig.ExtraHosts {
  408. // allow IPv6 addresses in extra hosts; only split on first ":"
  409. parts := strings.SplitN(extraHost, ":", 2)
  410. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  411. }
  412. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  413. for _, ref := range refs {
  414. if ref.ParentID == "0" {
  415. continue
  416. }
  417. c, err := container.daemon.Get(ref.ParentID)
  418. if err != nil {
  419. logrus.Error(err)
  420. }
  421. if c != nil && !container.daemon.config.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  422. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  423. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  424. if c.NetworkSettings.EndpointID != "" {
  425. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  426. }
  427. }
  428. }
  429. linkOptions := options.Generic{
  430. netlabel.GenericData: options.Generic{
  431. "ParentEndpoints": parentEndpoints,
  432. "ChildEndpoints": childEndpoints,
  433. },
  434. }
  435. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  436. return joinOptions, nil
  437. }
  438. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  439. if ep == nil {
  440. return nil, fmt.Errorf("invalid endpoint while building port map info")
  441. }
  442. if networkSettings == nil {
  443. return nil, fmt.Errorf("invalid networksettings while building port map info")
  444. }
  445. driverInfo, err := ep.DriverInfo()
  446. if err != nil {
  447. return nil, err
  448. }
  449. if driverInfo == nil {
  450. // It is not an error for epInfo to be nil
  451. return networkSettings, nil
  452. }
  453. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  454. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  455. }
  456. networkSettings.Ports = nat.PortMap{}
  457. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  458. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  459. for _, tp := range exposedPorts {
  460. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  461. if err != nil {
  462. return nil, fmt.Errorf("Error parsing Port value(%s):%v", tp.Port, err)
  463. }
  464. networkSettings.Ports[natPort] = nil
  465. }
  466. }
  467. }
  468. mapData, ok := driverInfo[netlabel.PortMap]
  469. if !ok {
  470. return networkSettings, nil
  471. }
  472. if portMapping, ok := mapData.([]types.PortBinding); ok {
  473. for _, pp := range portMapping {
  474. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  475. if err != nil {
  476. return nil, err
  477. }
  478. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  479. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  480. }
  481. }
  482. return networkSettings, nil
  483. }
  484. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  485. if ep == nil {
  486. return nil, fmt.Errorf("invalid endpoint while building port map info")
  487. }
  488. if networkSettings == nil {
  489. return nil, fmt.Errorf("invalid networksettings while building port map info")
  490. }
  491. epInfo := ep.Info()
  492. if epInfo == nil {
  493. // It is not an error to get an empty endpoint info
  494. return networkSettings, nil
  495. }
  496. ifaceList := epInfo.InterfaceList()
  497. if len(ifaceList) == 0 {
  498. return networkSettings, nil
  499. }
  500. iface := ifaceList[0]
  501. ones, _ := iface.Address().Mask.Size()
  502. networkSettings.IPAddress = iface.Address().IP.String()
  503. networkSettings.IPPrefixLen = ones
  504. if iface.AddressIPv6().IP.To16() != nil {
  505. onesv6, _ := iface.AddressIPv6().Mask.Size()
  506. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  507. networkSettings.GlobalIPv6PrefixLen = onesv6
  508. }
  509. if len(ifaceList) == 1 {
  510. return networkSettings, nil
  511. }
  512. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  513. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  514. for _, iface := range ifaceList[1:] {
  515. ones, _ := iface.Address().Mask.Size()
  516. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  517. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  518. if iface.AddressIPv6().IP.To16() != nil {
  519. onesv6, _ := iface.AddressIPv6().Mask.Size()
  520. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  521. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  522. }
  523. }
  524. return networkSettings, nil
  525. }
  526. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  527. epInfo := ep.Info()
  528. if epInfo == nil {
  529. // It is not an error to get an empty endpoint info
  530. return nil
  531. }
  532. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  533. if epInfo.GatewayIPv6().To16() != nil {
  534. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  535. }
  536. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  537. return nil
  538. }
  539. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  540. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  541. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  542. if err != nil {
  543. return err
  544. }
  545. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  546. if err != nil {
  547. return err
  548. }
  549. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  550. networkSettings.Bridge = container.daemon.config.Bridge.Iface
  551. }
  552. container.NetworkSettings = networkSettings
  553. return nil
  554. }
  555. func (container *Container) UpdateNetwork() error {
  556. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  557. if err != nil {
  558. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  559. }
  560. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  561. if err != nil {
  562. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  563. }
  564. if err := ep.Leave(container.ID); err != nil {
  565. return fmt.Errorf("endpoint leave failed: %v", err)
  566. }
  567. joinOptions, err := container.buildJoinOptions()
  568. if err != nil {
  569. return fmt.Errorf("Update network failed: %v", err)
  570. }
  571. if err := ep.Join(container.ID, joinOptions...); err != nil {
  572. return fmt.Errorf("endpoint join failed: %v", err)
  573. }
  574. if err := container.updateJoinInfo(ep); err != nil {
  575. return fmt.Errorf("Updating join info failed: %v", err)
  576. }
  577. return nil
  578. }
  579. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  580. var (
  581. portSpecs = make(nat.PortSet)
  582. bindings = make(nat.PortMap)
  583. pbList []types.PortBinding
  584. exposeList []types.TransportPort
  585. createOptions []libnetwork.EndpointOption
  586. )
  587. if container.Config.ExposedPorts != nil {
  588. portSpecs = container.Config.ExposedPorts
  589. }
  590. if container.hostConfig.PortBindings != nil {
  591. for p, b := range container.hostConfig.PortBindings {
  592. bindings[p] = []nat.PortBinding{}
  593. for _, bb := range b {
  594. bindings[p] = append(bindings[p], nat.PortBinding{
  595. HostIP: bb.HostIP,
  596. HostPort: bb.HostPort,
  597. })
  598. }
  599. }
  600. }
  601. container.NetworkSettings.PortMapping = nil
  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. if err != nil {
  620. return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err)
  621. }
  622. pbCopy.HostPort = uint16(newP.Int())
  623. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  624. pbList = append(pbList, pbCopy)
  625. }
  626. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  627. pbList = append(pbList, pb)
  628. }
  629. }
  630. createOptions = append(createOptions,
  631. libnetwork.CreateOptionPortMapping(pbList),
  632. libnetwork.CreateOptionExposedPorts(exposeList))
  633. if container.Config.MacAddress != "" {
  634. mac, err := net.ParseMAC(container.Config.MacAddress)
  635. if err != nil {
  636. return nil, err
  637. }
  638. genericOption := options.Generic{
  639. netlabel.MacAddress: mac,
  640. }
  641. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  642. }
  643. return createOptions, nil
  644. }
  645. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  646. dn := controller.Config().Daemon.DefaultNetwork
  647. dd := controller.Config().Daemon.DefaultDriver
  648. snd := strings.Split(service, ".")
  649. if len(snd) > 2 {
  650. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  651. }
  652. if len(snd) > 1 {
  653. return snd[0], snd[1], dd
  654. }
  655. return snd[0], dn, dd
  656. }
  657. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  658. createOptions := []libnetwork.NetworkOption{}
  659. genericOption := options.Generic{}
  660. // Bridge driver is special due to legacy reasons
  661. if runconfig.NetworkMode(driver).IsBridge() {
  662. genericOption[netlabel.GenericData] = map[string]interface{}{
  663. "BridgeName": dnet,
  664. "AllowNonDefaultBridge": "true",
  665. }
  666. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  667. createOptions = append(createOptions, networkOption)
  668. }
  669. return controller.NewNetwork(driver, dnet, createOptions...)
  670. }
  671. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  672. switch primaryNetworkType {
  673. case "bridge", "none", "host", "container":
  674. return false
  675. }
  676. if container.daemon.config.DisableBridge {
  677. return false
  678. }
  679. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  680. return true
  681. }
  682. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  683. return true
  684. }
  685. return false
  686. }
  687. func (container *Container) AllocateNetwork() error {
  688. mode := container.hostConfig.NetworkMode
  689. controller := container.daemon.netController
  690. if container.Config.NetworkDisabled || mode.IsContainer() {
  691. return nil
  692. }
  693. networkDriver := string(mode)
  694. service := container.Config.PublishService
  695. networkName := mode.NetworkName()
  696. if mode.IsDefault() {
  697. if service != "" {
  698. service, networkName, networkDriver = parseService(controller, service)
  699. } else {
  700. networkName = controller.Config().Daemon.DefaultNetwork
  701. networkDriver = controller.Config().Daemon.DefaultDriver
  702. }
  703. } else if service != "" {
  704. return fmt.Errorf("conflicting options: publishing a service and network mode")
  705. }
  706. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.config.DisableBridge {
  707. container.Config.NetworkDisabled = true
  708. return nil
  709. }
  710. if service == "" {
  711. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  712. // For backward compatiblity, replacing "." with "-", instead of failing
  713. service = strings.Replace(container.Name, ".", "-", -1)
  714. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  715. service = strings.Replace(service, "/", "", -1)
  716. }
  717. if container.secondaryNetworkRequired(networkDriver) {
  718. // Configure Bridge as secondary network for port binding purposes
  719. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  720. return err
  721. }
  722. }
  723. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  724. return err
  725. }
  726. return container.WriteHostConfig()
  727. }
  728. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  729. controller := container.daemon.netController
  730. n, err := controller.NetworkByName(networkName)
  731. if err != nil {
  732. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  733. return err
  734. }
  735. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  736. return err
  737. }
  738. }
  739. ep, err := n.EndpointByName(service)
  740. if err != nil {
  741. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  742. return err
  743. }
  744. createOptions, err := container.buildCreateEndpointOptions()
  745. if err != nil {
  746. return err
  747. }
  748. ep, err = n.CreateEndpoint(service, createOptions...)
  749. if err != nil {
  750. return err
  751. }
  752. }
  753. if err := container.updateNetworkSettings(n, ep); err != nil {
  754. return err
  755. }
  756. joinOptions, err := container.buildJoinOptions()
  757. if err != nil {
  758. return err
  759. }
  760. if err := ep.Join(container.ID, joinOptions...); err != nil {
  761. return err
  762. }
  763. if err := container.updateJoinInfo(ep); err != nil {
  764. return fmt.Errorf("Updating join info failed: %v", err)
  765. }
  766. return nil
  767. }
  768. func (container *Container) initializeNetworking() error {
  769. var err error
  770. // Make sure NetworkMode has an acceptable value before
  771. // initializing networking.
  772. if container.hostConfig.NetworkMode == runconfig.NetworkMode("") {
  773. container.hostConfig.NetworkMode = runconfig.NetworkMode("default")
  774. }
  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 disableAllActiveLinks(container *Container) {
  913. if container.activeLinks != nil {
  914. for _, link := range container.activeLinks {
  915. link.Disable()
  916. }
  917. }
  918. }
  919. func (container *Container) DisableLink(name string) {
  920. if container.activeLinks != nil {
  921. if link, exists := container.activeLinks[name]; exists {
  922. link.Disable()
  923. delete(container.activeLinks, name)
  924. if err := container.UpdateNetwork(); err != nil {
  925. logrus.Debugf("Could not update network to remove link: %v", err)
  926. }
  927. } else {
  928. logrus.Debugf("Could not find active link for %s", name)
  929. }
  930. }
  931. }
  932. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  933. var volumeMounts []mountPoint
  934. for _, mntPoint := range container.MountPoints {
  935. dest, err := container.GetResourcePath(mntPoint.Destination)
  936. if err != nil {
  937. return err
  938. }
  939. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  940. }
  941. for _, mnt := range container.networkMounts() {
  942. dest, err := container.GetResourcePath(mnt.Destination)
  943. if err != nil {
  944. return err
  945. }
  946. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  947. }
  948. for _, volumeMount := range volumeMounts {
  949. if forceSyscall {
  950. syscall.Unmount(volumeMount.Destination, 0)
  951. }
  952. if volumeMount.Volume != nil {
  953. if err := volumeMount.Volume.Unmount(); err != nil {
  954. return err
  955. }
  956. }
  957. }
  958. return nil
  959. }
  960. func (container *Container) PrepareStorage() error {
  961. return nil
  962. }
  963. func (container *Container) CleanupStorage() error {
  964. return nil
  965. }