container.go 42 KB

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