container.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  1. package daemon
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "syscall"
  14. "time"
  15. "github.com/docker/libcontainer"
  16. "github.com/docker/libcontainer/configs"
  17. "github.com/docker/libcontainer/devices"
  18. "github.com/docker/libcontainer/label"
  19. "github.com/Sirupsen/logrus"
  20. "github.com/docker/docker/daemon/execdriver"
  21. "github.com/docker/docker/daemon/logger"
  22. "github.com/docker/docker/daemon/logger/jsonfilelog"
  23. "github.com/docker/docker/daemon/logger/syslog"
  24. "github.com/docker/docker/engine"
  25. "github.com/docker/docker/image"
  26. "github.com/docker/docker/links"
  27. "github.com/docker/docker/nat"
  28. "github.com/docker/docker/pkg/archive"
  29. "github.com/docker/docker/pkg/broadcastwriter"
  30. "github.com/docker/docker/pkg/directory"
  31. "github.com/docker/docker/pkg/etchosts"
  32. "github.com/docker/docker/pkg/ioutils"
  33. "github.com/docker/docker/pkg/promise"
  34. "github.com/docker/docker/pkg/resolvconf"
  35. "github.com/docker/docker/pkg/stringid"
  36. "github.com/docker/docker/pkg/symlink"
  37. "github.com/docker/docker/pkg/ulimit"
  38. "github.com/docker/docker/runconfig"
  39. "github.com/docker/docker/utils"
  40. )
  41. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  42. var (
  43. ErrNotATTY = errors.New("The PTY is not a file")
  44. ErrNoTTY = errors.New("No PTY found")
  45. ErrContainerStart = errors.New("The container failed to start. Unknown error")
  46. ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.")
  47. )
  48. type StreamConfig struct {
  49. stdout *broadcastwriter.BroadcastWriter
  50. stderr *broadcastwriter.BroadcastWriter
  51. stdin io.ReadCloser
  52. stdinPipe io.WriteCloser
  53. }
  54. type Container struct {
  55. *State `json:"State"` // Needed for remote api version <= 1.11
  56. root string // Path to the "home" of the container, including metadata.
  57. basefs string // Path to the graphdriver mountpoint
  58. ID string
  59. Created time.Time
  60. Path string
  61. Args []string
  62. Config *runconfig.Config
  63. ImageID string `json:"Image"`
  64. NetworkSettings *NetworkSettings
  65. ResolvConfPath string
  66. HostnamePath string
  67. HostsPath string
  68. LogPath string
  69. Name string
  70. Driver string
  71. ExecDriver string
  72. command *execdriver.Command
  73. StreamConfig
  74. daemon *Daemon
  75. MountLabel, ProcessLabel string
  76. AppArmorProfile string
  77. RestartCount int
  78. UpdateDns bool
  79. // Maps container paths to volume paths. The key in this is the path to which
  80. // the volume is being mounted inside the container. Value is the path of the
  81. // volume on disk
  82. Volumes map[string]string
  83. // Store rw/ro in a separate structure to preserve reverse-compatibility on-disk.
  84. // Easier than migrating older container configs :)
  85. VolumesRW map[string]bool
  86. hostConfig *runconfig.HostConfig
  87. activeLinks map[string]*links.Link
  88. monitor *containerMonitor
  89. execCommands *execStore
  90. // logDriver for closing
  91. logDriver logger.Logger
  92. logCopier *logger.Copier
  93. AppliedVolumesFrom map[string]struct{}
  94. }
  95. func (container *Container) FromDisk() error {
  96. pth, err := container.jsonPath()
  97. if err != nil {
  98. return err
  99. }
  100. jsonSource, err := os.Open(pth)
  101. if err != nil {
  102. return err
  103. }
  104. defer jsonSource.Close()
  105. dec := json.NewDecoder(jsonSource)
  106. // Load container settings
  107. // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it
  108. if err := dec.Decode(container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
  109. return err
  110. }
  111. if err := label.ReserveLabel(container.ProcessLabel); err != nil {
  112. return err
  113. }
  114. return container.readHostConfig()
  115. }
  116. func (container *Container) toDisk() error {
  117. data, err := json.Marshal(container)
  118. if err != nil {
  119. return err
  120. }
  121. pth, err := container.jsonPath()
  122. if err != nil {
  123. return err
  124. }
  125. err = ioutil.WriteFile(pth, data, 0666)
  126. if err != nil {
  127. return err
  128. }
  129. return container.WriteHostConfig()
  130. }
  131. func (container *Container) ToDisk() error {
  132. container.Lock()
  133. err := container.toDisk()
  134. container.Unlock()
  135. return err
  136. }
  137. func (container *Container) readHostConfig() error {
  138. container.hostConfig = &runconfig.HostConfig{}
  139. // If the hostconfig file does not exist, do not read it.
  140. // (We still have to initialize container.hostConfig,
  141. // but that's OK, since we just did that above.)
  142. pth, err := container.hostConfigPath()
  143. if err != nil {
  144. return err
  145. }
  146. _, err = os.Stat(pth)
  147. if os.IsNotExist(err) {
  148. return nil
  149. }
  150. data, err := ioutil.ReadFile(pth)
  151. if err != nil {
  152. return err
  153. }
  154. return json.Unmarshal(data, container.hostConfig)
  155. }
  156. func (container *Container) WriteHostConfig() error {
  157. data, err := json.Marshal(container.hostConfig)
  158. if err != nil {
  159. return err
  160. }
  161. pth, err := container.hostConfigPath()
  162. if err != nil {
  163. return err
  164. }
  165. return ioutil.WriteFile(pth, data, 0666)
  166. }
  167. func (container *Container) LogEvent(action string) {
  168. d := container.daemon
  169. if err := d.eng.Job("log", action, container.ID, d.Repositories().ImageName(container.ImageID)).Run(); err != nil {
  170. logrus.Errorf("Error logging event %s for %s: %s", action, container.ID, err)
  171. }
  172. }
  173. func (container *Container) getResourcePath(path string) (string, error) {
  174. cleanPath := filepath.Join("/", path)
  175. return symlink.FollowSymlinkInScope(filepath.Join(container.basefs, cleanPath), container.basefs)
  176. }
  177. func (container *Container) getRootResourcePath(path string) (string, error) {
  178. cleanPath := filepath.Join("/", path)
  179. return symlink.FollowSymlinkInScope(filepath.Join(container.root, cleanPath), container.root)
  180. }
  181. func populateCommand(c *Container, env []string) error {
  182. en := &execdriver.Network{
  183. Mtu: c.daemon.config.Mtu,
  184. Interface: nil,
  185. }
  186. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  187. switch parts[0] {
  188. case "none":
  189. case "host":
  190. en.HostNetworking = true
  191. case "bridge", "": // empty string to support existing containers
  192. if !c.Config.NetworkDisabled {
  193. network := c.NetworkSettings
  194. en.Interface = &execdriver.NetworkInterface{
  195. Gateway: network.Gateway,
  196. Bridge: network.Bridge,
  197. IPAddress: network.IPAddress,
  198. IPPrefixLen: network.IPPrefixLen,
  199. MacAddress: network.MacAddress,
  200. LinkLocalIPv6Address: network.LinkLocalIPv6Address,
  201. GlobalIPv6Address: network.GlobalIPv6Address,
  202. GlobalIPv6PrefixLen: network.GlobalIPv6PrefixLen,
  203. IPv6Gateway: network.IPv6Gateway,
  204. }
  205. }
  206. case "container":
  207. nc, err := c.getNetworkedContainer()
  208. if err != nil {
  209. return err
  210. }
  211. en.ContainerID = nc.ID
  212. default:
  213. return fmt.Errorf("invalid network mode: %s", c.hostConfig.NetworkMode)
  214. }
  215. ipc := &execdriver.Ipc{}
  216. if c.hostConfig.IpcMode.IsContainer() {
  217. ic, err := c.getIpcContainer()
  218. if err != nil {
  219. return err
  220. }
  221. ipc.ContainerID = ic.ID
  222. } else {
  223. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  224. }
  225. pid := &execdriver.Pid{}
  226. pid.HostPid = c.hostConfig.PidMode.IsHost()
  227. // Build lists of devices allowed and created within the container.
  228. userSpecifiedDevices := make([]*configs.Device, len(c.hostConfig.Devices))
  229. for i, deviceMapping := range c.hostConfig.Devices {
  230. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  231. if err != nil {
  232. return fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  233. }
  234. device.Path = deviceMapping.PathInContainer
  235. userSpecifiedDevices[i] = device
  236. }
  237. allowedDevices := append(configs.DefaultAllowedDevices, userSpecifiedDevices...)
  238. autoCreatedDevices := append(configs.DefaultAutoCreatedDevices, userSpecifiedDevices...)
  239. // TODO: this can be removed after lxc-conf is fully deprecated
  240. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  241. if err != nil {
  242. return err
  243. }
  244. var rlimits []*ulimit.Rlimit
  245. ulimits := c.hostConfig.Ulimits
  246. // Merge ulimits with daemon defaults
  247. ulIdx := make(map[string]*ulimit.Ulimit)
  248. for _, ul := range ulimits {
  249. ulIdx[ul.Name] = ul
  250. }
  251. for name, ul := range c.daemon.config.Ulimits {
  252. if _, exists := ulIdx[name]; !exists {
  253. ulimits = append(ulimits, ul)
  254. }
  255. }
  256. for _, limit := range ulimits {
  257. rl, err := limit.GetRlimit()
  258. if err != nil {
  259. return err
  260. }
  261. rlimits = append(rlimits, rl)
  262. }
  263. resources := &execdriver.Resources{
  264. Memory: c.hostConfig.Memory,
  265. MemorySwap: c.hostConfig.MemorySwap,
  266. CpuShares: c.hostConfig.CpuShares,
  267. CpusetCpus: c.hostConfig.CpusetCpus,
  268. Rlimits: rlimits,
  269. }
  270. processConfig := execdriver.ProcessConfig{
  271. Privileged: c.hostConfig.Privileged,
  272. Entrypoint: c.Path,
  273. Arguments: c.Args,
  274. Tty: c.Config.Tty,
  275. User: c.Config.User,
  276. }
  277. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  278. processConfig.Env = env
  279. c.command = &execdriver.Command{
  280. ID: c.ID,
  281. Rootfs: c.RootfsPath(),
  282. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  283. InitPath: "/.dockerinit",
  284. WorkingDir: c.Config.WorkingDir,
  285. Network: en,
  286. Ipc: ipc,
  287. Pid: pid,
  288. Resources: resources,
  289. AllowedDevices: allowedDevices,
  290. AutoCreatedDevices: autoCreatedDevices,
  291. CapAdd: c.hostConfig.CapAdd,
  292. CapDrop: c.hostConfig.CapDrop,
  293. ProcessConfig: processConfig,
  294. ProcessLabel: c.GetProcessLabel(),
  295. MountLabel: c.GetMountLabel(),
  296. LxcConfig: lxcConfig,
  297. AppArmorProfile: c.AppArmorProfile,
  298. CgroupParent: c.hostConfig.CgroupParent,
  299. }
  300. return nil
  301. }
  302. func (container *Container) Start() (err error) {
  303. container.Lock()
  304. defer container.Unlock()
  305. if container.Running {
  306. return nil
  307. }
  308. // if we encounter an error during start we need to ensure that any other
  309. // setup has been cleaned up properly
  310. defer func() {
  311. if err != nil {
  312. container.setError(err)
  313. // if no one else has set it, make sure we don't leave it at zero
  314. if container.ExitCode == 0 {
  315. container.ExitCode = 128
  316. }
  317. container.toDisk()
  318. container.cleanup()
  319. }
  320. }()
  321. if err := container.setupContainerDns(); err != nil {
  322. return err
  323. }
  324. if err := container.Mount(); err != nil {
  325. return err
  326. }
  327. if err := container.initializeNetworking(); err != nil {
  328. return err
  329. }
  330. if err := container.updateParentsHosts(); err != nil {
  331. return err
  332. }
  333. container.verifyDaemonSettings()
  334. if err := container.prepareVolumes(); err != nil {
  335. return err
  336. }
  337. linkedEnv, err := container.setupLinkedContainers()
  338. if err != nil {
  339. return err
  340. }
  341. if err := container.setupWorkingDirectory(); err != nil {
  342. return err
  343. }
  344. env := container.createDaemonEnvironment(linkedEnv)
  345. if err := populateCommand(container, env); err != nil {
  346. return err
  347. }
  348. if err := container.setupMounts(); err != nil {
  349. return err
  350. }
  351. return container.waitForStart()
  352. }
  353. func (container *Container) Run() error {
  354. if err := container.Start(); err != nil {
  355. return err
  356. }
  357. container.WaitStop(-1 * time.Second)
  358. return nil
  359. }
  360. func (container *Container) Output() (output []byte, err error) {
  361. pipe := container.StdoutPipe()
  362. defer pipe.Close()
  363. if err := container.Start(); err != nil {
  364. return nil, err
  365. }
  366. output, err = ioutil.ReadAll(pipe)
  367. container.WaitStop(-1 * time.Second)
  368. return output, err
  369. }
  370. // StreamConfig.StdinPipe returns a WriteCloser which can be used to feed data
  371. // to the standard input of the container's active process.
  372. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser
  373. // which can be used to retrieve the standard output (and error) generated
  374. // by the container's active process. The output (and error) are actually
  375. // copied and delivered to all StdoutPipe and StderrPipe consumers, using
  376. // a kind of "broadcaster".
  377. func (streamConfig *StreamConfig) StdinPipe() io.WriteCloser {
  378. return streamConfig.stdinPipe
  379. }
  380. func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {
  381. reader, writer := io.Pipe()
  382. streamConfig.stdout.AddWriter(writer, "")
  383. return ioutils.NewBufReader(reader)
  384. }
  385. func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {
  386. reader, writer := io.Pipe()
  387. streamConfig.stderr.AddWriter(writer, "")
  388. return ioutils.NewBufReader(reader)
  389. }
  390. func (streamConfig *StreamConfig) StdoutLogPipe() io.ReadCloser {
  391. reader, writer := io.Pipe()
  392. streamConfig.stdout.AddWriter(writer, "stdout")
  393. return ioutils.NewBufReader(reader)
  394. }
  395. func (streamConfig *StreamConfig) StderrLogPipe() io.ReadCloser {
  396. reader, writer := io.Pipe()
  397. streamConfig.stderr.AddWriter(writer, "stderr")
  398. return ioutils.NewBufReader(reader)
  399. }
  400. func (container *Container) buildHostnameFile() error {
  401. hostnamePath, err := container.getRootResourcePath("hostname")
  402. if err != nil {
  403. return err
  404. }
  405. container.HostnamePath = hostnamePath
  406. if container.Config.Domainname != "" {
  407. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  408. }
  409. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  410. }
  411. func (container *Container) buildHostsFiles(IP string) error {
  412. hostsPath, err := container.getRootResourcePath("hosts")
  413. if err != nil {
  414. return err
  415. }
  416. container.HostsPath = hostsPath
  417. var extraContent []etchosts.Record
  418. children, err := container.daemon.Children(container.Name)
  419. if err != nil {
  420. return err
  421. }
  422. for linkAlias, child := range children {
  423. _, alias := path.Split(linkAlias)
  424. // allow access to the linked container via the alias, real name, and container hostname
  425. aliasList := alias + " " + child.Config.Hostname
  426. // only add the name if alias isn't equal to the name
  427. if alias != child.Name[1:] {
  428. aliasList = aliasList + " " + child.Name[1:]
  429. }
  430. extraContent = append(extraContent, etchosts.Record{Hosts: aliasList, IP: child.NetworkSettings.IPAddress})
  431. }
  432. for _, extraHost := range container.hostConfig.ExtraHosts {
  433. // allow IPv6 addresses in extra hosts; only split on first ":"
  434. parts := strings.SplitN(extraHost, ":", 2)
  435. extraContent = append(extraContent, etchosts.Record{Hosts: parts[0], IP: parts[1]})
  436. }
  437. return etchosts.Build(container.HostsPath, IP, container.Config.Hostname, container.Config.Domainname, extraContent)
  438. }
  439. func (container *Container) buildHostnameAndHostsFiles(IP string) error {
  440. if err := container.buildHostnameFile(); err != nil {
  441. return err
  442. }
  443. return container.buildHostsFiles(IP)
  444. }
  445. func (container *Container) AllocateNetwork() error {
  446. mode := container.hostConfig.NetworkMode
  447. if container.Config.NetworkDisabled || !mode.IsPrivate() {
  448. return nil
  449. }
  450. var (
  451. env *engine.Env
  452. err error
  453. eng = container.daemon.eng
  454. )
  455. job := eng.Job("allocate_interface", container.ID)
  456. job.Setenv("RequestedMac", container.Config.MacAddress)
  457. if env, err = job.Stdout.AddEnv(); err != nil {
  458. return err
  459. }
  460. if err = job.Run(); err != nil {
  461. return err
  462. }
  463. // Error handling: At this point, the interface is allocated so we have to
  464. // make sure that it is always released in case of error, otherwise we
  465. // might leak resources.
  466. if container.Config.PortSpecs != nil {
  467. if err = migratePortMappings(container.Config, container.hostConfig); err != nil {
  468. eng.Job("release_interface", container.ID).Run()
  469. return err
  470. }
  471. container.Config.PortSpecs = nil
  472. if err = container.WriteHostConfig(); err != nil {
  473. eng.Job("release_interface", container.ID).Run()
  474. return err
  475. }
  476. }
  477. var (
  478. portSpecs = make(nat.PortSet)
  479. bindings = make(nat.PortMap)
  480. )
  481. if container.Config.ExposedPorts != nil {
  482. portSpecs = container.Config.ExposedPorts
  483. }
  484. if container.hostConfig.PortBindings != nil {
  485. for p, b := range container.hostConfig.PortBindings {
  486. bindings[p] = []nat.PortBinding{}
  487. for _, bb := range b {
  488. bindings[p] = append(bindings[p], nat.PortBinding{
  489. HostIp: bb.HostIp,
  490. HostPort: bb.HostPort,
  491. })
  492. }
  493. }
  494. }
  495. container.NetworkSettings.PortMapping = nil
  496. for port := range portSpecs {
  497. if err = container.allocatePort(eng, port, bindings); err != nil {
  498. eng.Job("release_interface", container.ID).Run()
  499. return err
  500. }
  501. }
  502. container.WriteHostConfig()
  503. container.NetworkSettings.Ports = bindings
  504. container.NetworkSettings.Bridge = env.Get("Bridge")
  505. container.NetworkSettings.IPAddress = env.Get("IP")
  506. container.NetworkSettings.IPPrefixLen = env.GetInt("IPPrefixLen")
  507. container.NetworkSettings.MacAddress = env.Get("MacAddress")
  508. container.NetworkSettings.Gateway = env.Get("Gateway")
  509. container.NetworkSettings.LinkLocalIPv6Address = env.Get("LinkLocalIPv6")
  510. container.NetworkSettings.LinkLocalIPv6PrefixLen = 64
  511. container.NetworkSettings.GlobalIPv6Address = env.Get("GlobalIPv6")
  512. container.NetworkSettings.GlobalIPv6PrefixLen = env.GetInt("GlobalIPv6PrefixLen")
  513. container.NetworkSettings.IPv6Gateway = env.Get("IPv6Gateway")
  514. return nil
  515. }
  516. func (container *Container) ReleaseNetwork() {
  517. if container.Config.NetworkDisabled || !container.hostConfig.NetworkMode.IsPrivate() {
  518. return
  519. }
  520. eng := container.daemon.eng
  521. job := eng.Job("release_interface", container.ID)
  522. job.SetenvBool("overrideShutdown", true)
  523. job.Run()
  524. container.NetworkSettings = &NetworkSettings{}
  525. }
  526. func (container *Container) isNetworkAllocated() bool {
  527. return container.NetworkSettings.IPAddress != ""
  528. }
  529. func (container *Container) RestoreNetwork() error {
  530. mode := container.hostConfig.NetworkMode
  531. // Don't attempt a restore if we previously didn't allocate networking.
  532. // This might be a legacy container with no network allocated, in which case the
  533. // allocation will happen once and for all at start.
  534. if !container.isNetworkAllocated() || container.Config.NetworkDisabled || !mode.IsPrivate() {
  535. return nil
  536. }
  537. eng := container.daemon.eng
  538. // Re-allocate the interface with the same IP and MAC address.
  539. job := eng.Job("allocate_interface", container.ID)
  540. job.Setenv("RequestedIP", container.NetworkSettings.IPAddress)
  541. job.Setenv("RequestedMac", container.NetworkSettings.MacAddress)
  542. if err := job.Run(); err != nil {
  543. return err
  544. }
  545. // Re-allocate any previously allocated ports.
  546. for port := range container.NetworkSettings.Ports {
  547. if err := container.allocatePort(eng, port, container.NetworkSettings.Ports); err != nil {
  548. return err
  549. }
  550. }
  551. return nil
  552. }
  553. // cleanup releases any network resources allocated to the container along with any rules
  554. // around how containers are linked together. It also unmounts the container's root filesystem.
  555. func (container *Container) cleanup() {
  556. container.ReleaseNetwork()
  557. // Disable all active links
  558. if container.activeLinks != nil {
  559. for _, link := range container.activeLinks {
  560. link.Disable()
  561. }
  562. }
  563. if err := container.Unmount(); err != nil {
  564. logrus.Errorf("%v: Failed to umount filesystem: %v", container.ID, err)
  565. }
  566. for _, eConfig := range container.execCommands.s {
  567. container.daemon.unregisterExecCommand(eConfig)
  568. }
  569. }
  570. func (container *Container) KillSig(sig int) error {
  571. logrus.Debugf("Sending %d to %s", sig, container.ID)
  572. container.Lock()
  573. defer container.Unlock()
  574. // We could unpause the container for them rather than returning this error
  575. if container.Paused {
  576. return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID)
  577. }
  578. if !container.Running {
  579. return nil
  580. }
  581. // signal to the monitor that it should not restart the container
  582. // after we send the kill signal
  583. container.monitor.ExitOnNext()
  584. // if the container is currently restarting we do not need to send the signal
  585. // to the process. Telling the monitor that it should exit on it's next event
  586. // loop is enough
  587. if container.Restarting {
  588. return nil
  589. }
  590. return container.daemon.Kill(container, sig)
  591. }
  592. // Wrapper aroung KillSig() suppressing "no such process" error.
  593. func (container *Container) killPossiblyDeadProcess(sig int) error {
  594. err := container.KillSig(sig)
  595. if err == syscall.ESRCH {
  596. logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPid(), sig)
  597. return nil
  598. }
  599. return err
  600. }
  601. func (container *Container) Pause() error {
  602. if container.IsPaused() {
  603. return fmt.Errorf("Container %s is already paused", container.ID)
  604. }
  605. if !container.IsRunning() {
  606. return fmt.Errorf("Container %s is not running", container.ID)
  607. }
  608. return container.daemon.Pause(container)
  609. }
  610. func (container *Container) Unpause() error {
  611. if !container.IsPaused() {
  612. return fmt.Errorf("Container %s is not paused", container.ID)
  613. }
  614. if !container.IsRunning() {
  615. return fmt.Errorf("Container %s is not running", container.ID)
  616. }
  617. return container.daemon.Unpause(container)
  618. }
  619. func (container *Container) Kill() error {
  620. if !container.IsRunning() {
  621. return nil
  622. }
  623. // 1. Send SIGKILL
  624. if err := container.killPossiblyDeadProcess(9); err != nil {
  625. return err
  626. }
  627. // 2. Wait for the process to die, in last resort, try to kill the process directly
  628. if _, err := container.WaitStop(10 * time.Second); err != nil {
  629. // Ensure that we don't kill ourselves
  630. if pid := container.GetPid(); pid != 0 {
  631. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  632. if err := syscall.Kill(pid, 9); err != nil {
  633. if err != syscall.ESRCH {
  634. return err
  635. }
  636. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  637. }
  638. }
  639. }
  640. container.WaitStop(-1 * time.Second)
  641. return nil
  642. }
  643. func (container *Container) Stop(seconds int) error {
  644. if !container.IsRunning() {
  645. return nil
  646. }
  647. // 1. Send a SIGTERM
  648. if err := container.killPossiblyDeadProcess(15); err != nil {
  649. logrus.Infof("Failed to send SIGTERM to the process, force killing")
  650. if err := container.killPossiblyDeadProcess(9); err != nil {
  651. return err
  652. }
  653. }
  654. // 2. Wait for the process to exit on its own
  655. if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil {
  656. logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
  657. // 3. If it doesn't, then send SIGKILL
  658. if err := container.Kill(); err != nil {
  659. container.WaitStop(-1 * time.Second)
  660. return err
  661. }
  662. }
  663. return nil
  664. }
  665. func (container *Container) Restart(seconds int) error {
  666. // Avoid unnecessarily unmounting and then directly mounting
  667. // the container when the container stops and then starts
  668. // again
  669. if err := container.Mount(); err == nil {
  670. defer container.Unmount()
  671. }
  672. if err := container.Stop(seconds); err != nil {
  673. return err
  674. }
  675. return container.Start()
  676. }
  677. func (container *Container) Resize(h, w int) error {
  678. if !container.IsRunning() {
  679. return fmt.Errorf("Cannot resize container %s, container is not running", container.ID)
  680. }
  681. return container.command.ProcessConfig.Terminal.Resize(h, w)
  682. }
  683. func (container *Container) ExportRw() (archive.Archive, error) {
  684. if err := container.Mount(); err != nil {
  685. return nil, err
  686. }
  687. if container.daemon == nil {
  688. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  689. }
  690. archive, err := container.daemon.Diff(container)
  691. if err != nil {
  692. container.Unmount()
  693. return nil, err
  694. }
  695. return ioutils.NewReadCloserWrapper(archive, func() error {
  696. err := archive.Close()
  697. container.Unmount()
  698. return err
  699. }),
  700. nil
  701. }
  702. func (container *Container) Export() (archive.Archive, error) {
  703. if err := container.Mount(); err != nil {
  704. return nil, err
  705. }
  706. archive, err := archive.Tar(container.basefs, archive.Uncompressed)
  707. if err != nil {
  708. container.Unmount()
  709. return nil, err
  710. }
  711. return ioutils.NewReadCloserWrapper(archive, func() error {
  712. err := archive.Close()
  713. container.Unmount()
  714. return err
  715. }),
  716. nil
  717. }
  718. func (container *Container) Mount() error {
  719. return container.daemon.Mount(container)
  720. }
  721. func (container *Container) changes() ([]archive.Change, error) {
  722. return container.daemon.Changes(container)
  723. }
  724. func (container *Container) Changes() ([]archive.Change, error) {
  725. container.Lock()
  726. defer container.Unlock()
  727. return container.changes()
  728. }
  729. func (container *Container) GetImage() (*image.Image, error) {
  730. if container.daemon == nil {
  731. return nil, fmt.Errorf("Can't get image of unregistered container")
  732. }
  733. return container.daemon.graph.Get(container.ImageID)
  734. }
  735. func (container *Container) Unmount() error {
  736. return container.daemon.Unmount(container)
  737. }
  738. func (container *Container) logPath(name string) (string, error) {
  739. return container.getRootResourcePath(fmt.Sprintf("%s-%s.log", container.ID, name))
  740. }
  741. func (container *Container) ReadLog(name string) (io.Reader, error) {
  742. pth, err := container.logPath(name)
  743. if err != nil {
  744. return nil, err
  745. }
  746. return os.Open(pth)
  747. }
  748. func (container *Container) hostConfigPath() (string, error) {
  749. return container.getRootResourcePath("hostconfig.json")
  750. }
  751. func (container *Container) jsonPath() (string, error) {
  752. return container.getRootResourcePath("config.json")
  753. }
  754. // This method must be exported to be used from the lxc template
  755. // This directory is only usable when the container is running
  756. func (container *Container) RootfsPath() string {
  757. return container.basefs
  758. }
  759. func validateID(id string) error {
  760. if id == "" {
  761. return fmt.Errorf("Invalid empty id")
  762. }
  763. return nil
  764. }
  765. // GetSize, return real size, virtual size
  766. func (container *Container) GetSize() (int64, int64) {
  767. var (
  768. sizeRw, sizeRootfs int64
  769. err error
  770. driver = container.daemon.driver
  771. )
  772. if err := container.Mount(); err != nil {
  773. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  774. return sizeRw, sizeRootfs
  775. }
  776. defer container.Unmount()
  777. initID := fmt.Sprintf("%s-init", container.ID)
  778. sizeRw, err = driver.DiffSize(container.ID, initID)
  779. if err != nil {
  780. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  781. // FIXME: GetSize should return an error. Not changing it now in case
  782. // there is a side-effect.
  783. sizeRw = -1
  784. }
  785. if _, err = os.Stat(container.basefs); err != nil {
  786. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  787. sizeRootfs = -1
  788. }
  789. }
  790. return sizeRw, sizeRootfs
  791. }
  792. func (container *Container) Copy(resource string) (io.ReadCloser, error) {
  793. if err := container.Mount(); err != nil {
  794. return nil, err
  795. }
  796. basePath, err := container.getResourcePath(resource)
  797. if err != nil {
  798. container.Unmount()
  799. return nil, err
  800. }
  801. // Check if this is actually in a volume
  802. for _, mnt := range container.VolumeMounts() {
  803. if len(mnt.MountToPath) > 0 && strings.HasPrefix(resource, mnt.MountToPath[1:]) {
  804. return mnt.Export(resource)
  805. }
  806. }
  807. // Check if this is a special one (resolv.conf, hostname, ..)
  808. if resource == "etc/resolv.conf" {
  809. basePath = container.ResolvConfPath
  810. }
  811. if resource == "etc/hostname" {
  812. basePath = container.HostnamePath
  813. }
  814. if resource == "etc/hosts" {
  815. basePath = container.HostsPath
  816. }
  817. stat, err := os.Stat(basePath)
  818. if err != nil {
  819. container.Unmount()
  820. return nil, err
  821. }
  822. var filter []string
  823. if !stat.IsDir() {
  824. d, f := path.Split(basePath)
  825. basePath = d
  826. filter = []string{f}
  827. } else {
  828. filter = []string{path.Base(basePath)}
  829. basePath = path.Dir(basePath)
  830. }
  831. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  832. Compression: archive.Uncompressed,
  833. IncludeFiles: filter,
  834. })
  835. if err != nil {
  836. container.Unmount()
  837. return nil, err
  838. }
  839. return ioutils.NewReadCloserWrapper(archive, func() error {
  840. err := archive.Close()
  841. container.Unmount()
  842. return err
  843. }),
  844. nil
  845. }
  846. // Returns true if the container exposes a certain port
  847. func (container *Container) Exposes(p nat.Port) bool {
  848. _, exists := container.Config.ExposedPorts[p]
  849. return exists
  850. }
  851. func (container *Container) GetPtyMaster() (libcontainer.Console, error) {
  852. ttyConsole, ok := container.command.ProcessConfig.Terminal.(execdriver.TtyTerminal)
  853. if !ok {
  854. return nil, ErrNoTTY
  855. }
  856. return ttyConsole.Master(), nil
  857. }
  858. func (container *Container) HostConfig() *runconfig.HostConfig {
  859. container.Lock()
  860. res := container.hostConfig
  861. container.Unlock()
  862. return res
  863. }
  864. func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) {
  865. container.Lock()
  866. container.hostConfig = hostConfig
  867. container.Unlock()
  868. }
  869. func (container *Container) DisableLink(name string) {
  870. if container.activeLinks != nil {
  871. if link, exists := container.activeLinks[name]; exists {
  872. link.Disable()
  873. } else {
  874. logrus.Debugf("Could not find active link for %s", name)
  875. }
  876. }
  877. }
  878. func (container *Container) setupContainerDns() error {
  879. if container.ResolvConfPath != "" {
  880. // check if this is an existing container that needs DNS update:
  881. if container.UpdateDns {
  882. // read the host's resolv.conf, get the hash and call updateResolvConf
  883. logrus.Debugf("Check container (%s) for update to resolv.conf - UpdateDns flag was set", container.ID)
  884. latestResolvConf, latestHash := resolvconf.GetLastModified()
  885. // clean container resolv.conf re: localhost nameservers and IPv6 NS (if IPv6 disabled)
  886. updatedResolvConf, modified := resolvconf.FilterResolvDns(latestResolvConf, container.daemon.config.EnableIPv6)
  887. if modified {
  888. // changes have occurred during resolv.conf localhost cleanup: generate an updated hash
  889. newHash, err := utils.HashData(bytes.NewReader(updatedResolvConf))
  890. if err != nil {
  891. return err
  892. }
  893. latestHash = newHash
  894. }
  895. if err := container.updateResolvConf(updatedResolvConf, latestHash); err != nil {
  896. return err
  897. }
  898. // successful update of the restarting container; set the flag off
  899. container.UpdateDns = false
  900. }
  901. return nil
  902. }
  903. var (
  904. config = container.hostConfig
  905. daemon = container.daemon
  906. )
  907. resolvConf, err := resolvconf.Get()
  908. if err != nil {
  909. return err
  910. }
  911. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  912. if err != nil {
  913. return err
  914. }
  915. if config.NetworkMode != "host" {
  916. // check configurations for any container/daemon dns settings
  917. if len(config.Dns) > 0 || len(daemon.config.Dns) > 0 || len(config.DnsSearch) > 0 || len(daemon.config.DnsSearch) > 0 {
  918. var (
  919. dns = resolvconf.GetNameservers(resolvConf)
  920. dnsSearch = resolvconf.GetSearchDomains(resolvConf)
  921. )
  922. if len(config.Dns) > 0 {
  923. dns = config.Dns
  924. } else if len(daemon.config.Dns) > 0 {
  925. dns = daemon.config.Dns
  926. }
  927. if len(config.DnsSearch) > 0 {
  928. dnsSearch = config.DnsSearch
  929. } else if len(daemon.config.DnsSearch) > 0 {
  930. dnsSearch = daemon.config.DnsSearch
  931. }
  932. return resolvconf.Build(container.ResolvConfPath, dns, dnsSearch)
  933. }
  934. // replace any localhost/127.*, and remove IPv6 nameservers if IPv6 disabled in daemon
  935. resolvConf, _ = resolvconf.FilterResolvDns(resolvConf, daemon.config.EnableIPv6)
  936. }
  937. //get a sha256 hash of the resolv conf at this point so we can check
  938. //for changes when the host resolv.conf changes (e.g. network update)
  939. resolvHash, err := utils.HashData(bytes.NewReader(resolvConf))
  940. if err != nil {
  941. return err
  942. }
  943. resolvHashFile := container.ResolvConfPath + ".hash"
  944. if err = ioutil.WriteFile(resolvHashFile, []byte(resolvHash), 0644); err != nil {
  945. return err
  946. }
  947. return ioutil.WriteFile(container.ResolvConfPath, resolvConf, 0644)
  948. }
  949. // called when the host's resolv.conf changes to check whether container's resolv.conf
  950. // is unchanged by the container "user" since container start: if unchanged, the
  951. // container's resolv.conf will be updated to match the host's new resolv.conf
  952. func (container *Container) updateResolvConf(updatedResolvConf []byte, newResolvHash string) error {
  953. if container.ResolvConfPath == "" {
  954. return nil
  955. }
  956. if container.Running {
  957. //set a marker in the hostConfig to update on next start/restart
  958. container.UpdateDns = true
  959. return nil
  960. }
  961. resolvHashFile := container.ResolvConfPath + ".hash"
  962. //read the container's current resolv.conf and compute the hash
  963. resolvBytes, err := ioutil.ReadFile(container.ResolvConfPath)
  964. if err != nil {
  965. return err
  966. }
  967. curHash, err := utils.HashData(bytes.NewReader(resolvBytes))
  968. if err != nil {
  969. return err
  970. }
  971. //read the hash from the last time we wrote resolv.conf in the container
  972. hashBytes, err := ioutil.ReadFile(resolvHashFile)
  973. if err != nil {
  974. if !os.IsNotExist(err) {
  975. return err
  976. }
  977. // backwards compat: if no hash file exists, this container pre-existed from
  978. // a Docker daemon that didn't contain this update feature. Given we can't know
  979. // if the user has modified the resolv.conf since container start time, safer
  980. // to just never update the container's resolv.conf during it's lifetime which
  981. // we can control by setting hashBytes to an empty string
  982. hashBytes = []byte("")
  983. }
  984. //if the user has not modified the resolv.conf of the container since we wrote it last
  985. //we will replace it with the updated resolv.conf from the host
  986. if string(hashBytes) == curHash {
  987. logrus.Debugf("replacing %q with updated host resolv.conf", container.ResolvConfPath)
  988. // for atomic updates to these files, use temporary files with os.Rename:
  989. dir := path.Dir(container.ResolvConfPath)
  990. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  991. if err != nil {
  992. return err
  993. }
  994. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  995. if err != nil {
  996. return err
  997. }
  998. // write the updates to the temp files
  999. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newResolvHash), 0644); err != nil {
  1000. return err
  1001. }
  1002. if err = ioutil.WriteFile(tmpResolvFile.Name(), updatedResolvConf, 0644); err != nil {
  1003. return err
  1004. }
  1005. // rename the temp files for atomic replace
  1006. if err = os.Rename(tmpHashFile.Name(), resolvHashFile); err != nil {
  1007. return err
  1008. }
  1009. return os.Rename(tmpResolvFile.Name(), container.ResolvConfPath)
  1010. }
  1011. return nil
  1012. }
  1013. func (container *Container) updateParentsHosts() error {
  1014. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  1015. for _, ref := range refs {
  1016. if ref.ParentID == "0" {
  1017. continue
  1018. }
  1019. c, err := container.daemon.Get(ref.ParentID)
  1020. if err != nil {
  1021. logrus.Error(err)
  1022. }
  1023. if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() {
  1024. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  1025. if err := etchosts.Update(c.HostsPath, container.NetworkSettings.IPAddress, ref.Name); err != nil {
  1026. logrus.Errorf("Failed to update /etc/hosts in parent container %s for alias %s: %v", c.ID, ref.Name, err)
  1027. }
  1028. }
  1029. }
  1030. return nil
  1031. }
  1032. func (container *Container) initializeNetworking() error {
  1033. var err error
  1034. if container.hostConfig.NetworkMode.IsHost() {
  1035. container.Config.Hostname, err = os.Hostname()
  1036. if err != nil {
  1037. return err
  1038. }
  1039. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  1040. if len(parts) > 1 {
  1041. container.Config.Hostname = parts[0]
  1042. container.Config.Domainname = parts[1]
  1043. }
  1044. content, err := ioutil.ReadFile("/etc/hosts")
  1045. if os.IsNotExist(err) {
  1046. return container.buildHostnameAndHostsFiles("")
  1047. } else if err != nil {
  1048. return err
  1049. }
  1050. if err := container.buildHostnameFile(); err != nil {
  1051. return err
  1052. }
  1053. hostsPath, err := container.getRootResourcePath("hosts")
  1054. if err != nil {
  1055. return err
  1056. }
  1057. container.HostsPath = hostsPath
  1058. return ioutil.WriteFile(container.HostsPath, content, 0644)
  1059. }
  1060. if container.hostConfig.NetworkMode.IsContainer() {
  1061. // we need to get the hosts files from the container to join
  1062. nc, err := container.getNetworkedContainer()
  1063. if err != nil {
  1064. return err
  1065. }
  1066. container.HostnamePath = nc.HostnamePath
  1067. container.HostsPath = nc.HostsPath
  1068. container.ResolvConfPath = nc.ResolvConfPath
  1069. container.Config.Hostname = nc.Config.Hostname
  1070. container.Config.Domainname = nc.Config.Domainname
  1071. return nil
  1072. }
  1073. if container.daemon.config.DisableNetwork {
  1074. container.Config.NetworkDisabled = true
  1075. return container.buildHostnameAndHostsFiles("127.0.1.1")
  1076. }
  1077. if err := container.AllocateNetwork(); err != nil {
  1078. return err
  1079. }
  1080. return container.buildHostnameAndHostsFiles(container.NetworkSettings.IPAddress)
  1081. }
  1082. // Make sure the config is compatible with the current kernel
  1083. func (container *Container) verifyDaemonSettings() {
  1084. if container.Config.Memory > 0 && !container.daemon.sysInfo.MemoryLimit {
  1085. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  1086. container.Config.Memory = 0
  1087. }
  1088. if container.Config.Memory > 0 && !container.daemon.sysInfo.SwapLimit {
  1089. logrus.Warnf("Your kernel does not support swap limit capabilities. Limitation discarded.")
  1090. container.Config.MemorySwap = -1
  1091. }
  1092. if container.daemon.sysInfo.IPv4ForwardingDisabled {
  1093. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  1094. }
  1095. }
  1096. func (container *Container) setupLinkedContainers() ([]string, error) {
  1097. var (
  1098. env []string
  1099. daemon = container.daemon
  1100. )
  1101. children, err := daemon.Children(container.Name)
  1102. if err != nil {
  1103. return nil, err
  1104. }
  1105. if len(children) > 0 {
  1106. container.activeLinks = make(map[string]*links.Link, len(children))
  1107. // If we encounter an error make sure that we rollback any network
  1108. // config and iptables changes
  1109. rollback := func() {
  1110. for _, link := range container.activeLinks {
  1111. link.Disable()
  1112. }
  1113. container.activeLinks = nil
  1114. }
  1115. for linkAlias, child := range children {
  1116. if !child.IsRunning() {
  1117. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  1118. }
  1119. link, err := links.NewLink(
  1120. container.NetworkSettings.IPAddress,
  1121. child.NetworkSettings.IPAddress,
  1122. linkAlias,
  1123. child.Config.Env,
  1124. child.Config.ExposedPorts,
  1125. daemon.eng)
  1126. if err != nil {
  1127. rollback()
  1128. return nil, err
  1129. }
  1130. container.activeLinks[link.Alias()] = link
  1131. if err := link.Enable(); err != nil {
  1132. rollback()
  1133. return nil, err
  1134. }
  1135. for _, envVar := range link.ToEnv() {
  1136. env = append(env, envVar)
  1137. }
  1138. }
  1139. }
  1140. return env, nil
  1141. }
  1142. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  1143. // if a domain name was specified, append it to the hostname (see #7851)
  1144. fullHostname := container.Config.Hostname
  1145. if container.Config.Domainname != "" {
  1146. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  1147. }
  1148. // Setup environment
  1149. env := []string{
  1150. "PATH=" + DefaultPathEnv,
  1151. "HOSTNAME=" + fullHostname,
  1152. // Note: we don't set HOME here because it'll get autoset intelligently
  1153. // based on the value of USER inside dockerinit, but only if it isn't
  1154. // set already (ie, that can be overridden by setting HOME via -e or ENV
  1155. // in a Dockerfile).
  1156. }
  1157. if container.Config.Tty {
  1158. env = append(env, "TERM=xterm")
  1159. }
  1160. env = append(env, linkedEnv...)
  1161. // because the env on the container can override certain default values
  1162. // we need to replace the 'env' keys where they match and append anything
  1163. // else.
  1164. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  1165. return env
  1166. }
  1167. func (container *Container) setupWorkingDirectory() error {
  1168. if container.Config.WorkingDir != "" {
  1169. container.Config.WorkingDir = path.Clean(container.Config.WorkingDir)
  1170. pth, err := container.getResourcePath(container.Config.WorkingDir)
  1171. if err != nil {
  1172. return err
  1173. }
  1174. pthInfo, err := os.Stat(pth)
  1175. if err != nil {
  1176. if !os.IsNotExist(err) {
  1177. return err
  1178. }
  1179. if err := os.MkdirAll(pth, 0755); err != nil {
  1180. return err
  1181. }
  1182. }
  1183. if pthInfo != nil && !pthInfo.IsDir() {
  1184. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  1185. }
  1186. }
  1187. return nil
  1188. }
  1189. func (container *Container) startLogging() error {
  1190. cfg := container.hostConfig.LogConfig
  1191. if cfg.Type == "" {
  1192. cfg = container.daemon.defaultLogConfig
  1193. }
  1194. var l logger.Logger
  1195. switch cfg.Type {
  1196. case "json-file":
  1197. pth, err := container.logPath("json")
  1198. if err != nil {
  1199. return err
  1200. }
  1201. dl, err := jsonfilelog.New(pth)
  1202. if err != nil {
  1203. return err
  1204. }
  1205. l = dl
  1206. case "syslog":
  1207. dl, err := syslog.New(container.ID[:12])
  1208. if err != nil {
  1209. return err
  1210. }
  1211. l = dl
  1212. case "none":
  1213. return nil
  1214. default:
  1215. return fmt.Errorf("Unknown logging driver: %s", cfg.Type)
  1216. }
  1217. copier, err := logger.NewCopier(container.ID, map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
  1218. if err != nil {
  1219. return err
  1220. }
  1221. container.logCopier = copier
  1222. copier.Run()
  1223. container.logDriver = l
  1224. return nil
  1225. }
  1226. func (container *Container) waitForStart() error {
  1227. container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy)
  1228. // block until we either receive an error from the initial start of the container's
  1229. // process or until the process is running in the container
  1230. select {
  1231. case <-container.monitor.startSignal:
  1232. case err := <-promise.Go(container.monitor.Start):
  1233. return err
  1234. }
  1235. return nil
  1236. }
  1237. func (container *Container) allocatePort(eng *engine.Engine, port nat.Port, bindings nat.PortMap) error {
  1238. binding := bindings[port]
  1239. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  1240. binding = append(binding, nat.PortBinding{})
  1241. }
  1242. for i := 0; i < len(binding); i++ {
  1243. b := binding[i]
  1244. job := eng.Job("allocate_port", container.ID)
  1245. job.Setenv("HostIP", b.HostIp)
  1246. job.Setenv("HostPort", b.HostPort)
  1247. job.Setenv("Proto", port.Proto())
  1248. job.Setenv("ContainerPort", port.Port())
  1249. portEnv, err := job.Stdout.AddEnv()
  1250. if err != nil {
  1251. return err
  1252. }
  1253. if err := job.Run(); err != nil {
  1254. return err
  1255. }
  1256. b.HostIp = portEnv.Get("HostIP")
  1257. b.HostPort = portEnv.Get("HostPort")
  1258. binding[i] = b
  1259. }
  1260. bindings[port] = binding
  1261. return nil
  1262. }
  1263. func (container *Container) GetProcessLabel() string {
  1264. // even if we have a process label return "" if we are running
  1265. // in privileged mode
  1266. if container.hostConfig.Privileged {
  1267. return ""
  1268. }
  1269. return container.ProcessLabel
  1270. }
  1271. func (container *Container) GetMountLabel() string {
  1272. if container.hostConfig.Privileged {
  1273. return ""
  1274. }
  1275. return container.MountLabel
  1276. }
  1277. func (container *Container) getIpcContainer() (*Container, error) {
  1278. containerID := container.hostConfig.IpcMode.Container()
  1279. c, err := container.daemon.Get(containerID)
  1280. if err != nil {
  1281. return nil, err
  1282. }
  1283. if !c.IsRunning() {
  1284. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  1285. }
  1286. return c, nil
  1287. }
  1288. func (container *Container) getNetworkedContainer() (*Container, error) {
  1289. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  1290. switch parts[0] {
  1291. case "container":
  1292. if len(parts) != 2 {
  1293. return nil, fmt.Errorf("no container specified to join network")
  1294. }
  1295. nc, err := container.daemon.Get(parts[1])
  1296. if err != nil {
  1297. return nil, err
  1298. }
  1299. if !nc.IsRunning() {
  1300. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  1301. }
  1302. return nc, nil
  1303. default:
  1304. return nil, fmt.Errorf("network mode not set to container")
  1305. }
  1306. }
  1307. func (container *Container) Stats() (*execdriver.ResourceStats, error) {
  1308. return container.daemon.Stats(container)
  1309. }
  1310. func (c *Container) LogDriverType() string {
  1311. c.Lock()
  1312. defer c.Unlock()
  1313. if c.hostConfig.LogConfig.Type == "" {
  1314. return c.daemon.defaultLogConfig.Type
  1315. }
  1316. return c.hostConfig.LogConfig.Type
  1317. }