container.go 42 KB

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