container.go 42 KB

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