container.go 42 KB

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