container.go 43 KB

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