container.go 35 KB

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