container.go 40 KB

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