scratch.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. package dockerlaunch
  2. import (
  3. "bufio"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. log "github.com/Sirupsen/logrus"
  13. "github.com/docker/libnetwork/resolvconf"
  14. "github.com/rancher/docker-from-scratch/selinux"
  15. "github.com/rancher/docker-from-scratch/util"
  16. "github.com/rancher/netconf"
  17. )
  18. const (
  19. defaultPrefix = "/usr"
  20. iptables = "/sbin/iptables"
  21. modprobe = "/sbin/modprobe"
  22. distSuffix = ".dist"
  23. )
  24. var (
  25. mounts = [][]string{
  26. {"devtmpfs", "/dev", "devtmpfs", ""},
  27. {"none", "/dev/pts", "devpts", ""},
  28. {"shm", "/dev/shm", "tmpfs", "rw,nosuid,nodev,noexec,relatime,size=65536k"},
  29. {"mqueue", "/dev/mqueue", "mqueue", "rw,nosuid,nodev,noexec,relatime"},
  30. {"none", "/proc", "proc", ""},
  31. {"none", "/run", "tmpfs", ""},
  32. {"none", "/sys", "sysfs", ""},
  33. {"none", "/sys/fs/cgroup", "tmpfs", ""},
  34. }
  35. optionalMounts = [][]string{
  36. {"none", "/sys/fs/selinux", "selinuxfs", ""},
  37. }
  38. )
  39. type Config struct {
  40. Fork bool
  41. PidOne bool
  42. CommandName string
  43. DnsConfig netconf.DnsConfig
  44. BridgeName string
  45. BridgeAddress string
  46. BridgeMtu int
  47. CgroupHierarchy map[string]string
  48. LogFile string
  49. NoLog bool
  50. NoFiles uint64
  51. Environment []string
  52. GraphDirectory string
  53. DaemonConfig string
  54. }
  55. func createMounts(mounts ...[]string) error {
  56. for _, mount := range mounts {
  57. log.Debugf("Mounting %s %s %s %s", mount[0], mount[1], mount[2], mount[3])
  58. err := util.Mount(mount[0], mount[1], mount[2], mount[3])
  59. if err != nil {
  60. return err
  61. }
  62. }
  63. return nil
  64. }
  65. func createOptionalMounts(mounts ...[]string) {
  66. for _, mount := range mounts {
  67. log.Debugf("Mounting %s %s %s %s", mount[0], mount[1], mount[2], mount[3])
  68. err := util.Mount(mount[0], mount[1], mount[2], mount[3])
  69. if err != nil {
  70. log.Debugf("Unable to mount %s %s %s %s: %s", mount[0], mount[1], mount[2], mount[3], err)
  71. }
  72. }
  73. }
  74. func createDirs(dirs ...string) error {
  75. for _, dir := range dirs {
  76. if _, err := os.Stat(dir); os.IsNotExist(err) {
  77. log.Debugf("Creating %s", dir)
  78. err = os.MkdirAll(dir, 0755)
  79. if err != nil {
  80. return err
  81. }
  82. }
  83. }
  84. return nil
  85. }
  86. func mountCgroups(hierarchyConfig map[string]string) error {
  87. f, err := os.Open("/proc/cgroups")
  88. if err != nil {
  89. return err
  90. }
  91. defer f.Close()
  92. scanner := bufio.NewScanner(f)
  93. hierarchies := make(map[string][]string)
  94. for scanner.Scan() {
  95. text := scanner.Text()
  96. log.Debugf("/proc/cgroups: %s", text)
  97. fields := strings.Split(text, "\t")
  98. cgroup := fields[0]
  99. if cgroup == "" || cgroup[0] == '#' || (len(fields) > 3 && fields[3] == "0") {
  100. continue
  101. }
  102. hierarchy := hierarchyConfig[cgroup]
  103. if hierarchy == "" {
  104. hierarchy = fields[1]
  105. }
  106. if hierarchy == "0" {
  107. hierarchy = cgroup
  108. }
  109. hierarchies[hierarchy] = append(hierarchies[hierarchy], cgroup)
  110. }
  111. for _, hierarchy := range hierarchies {
  112. if err := mountCgroup(strings.Join(hierarchy, ",")); err != nil {
  113. return err
  114. }
  115. }
  116. if err = scanner.Err(); err != nil {
  117. return err
  118. }
  119. log.Debug("Done mouting cgroupfs")
  120. return nil
  121. }
  122. func CreateSymlinks(pathSets [][]string) error {
  123. for _, paths := range pathSets {
  124. if err := CreateSymlink(paths[0], paths[1]); err != nil {
  125. return err
  126. }
  127. }
  128. return nil
  129. }
  130. func CreateSymlink(src, dest string) error {
  131. if _, err := os.Lstat(dest); os.IsNotExist(err) {
  132. log.Debugf("Symlinking %s => %s", dest, src)
  133. if err = os.Symlink(src, dest); err != nil {
  134. return err
  135. }
  136. }
  137. return nil
  138. }
  139. func mountCgroup(cgroup string) error {
  140. if err := createDirs("/sys/fs/cgroup/" + cgroup); err != nil {
  141. return err
  142. }
  143. if err := createMounts([][]string{{"none", "/sys/fs/cgroup/" + cgroup, "cgroup", cgroup}}...); err != nil {
  144. return err
  145. }
  146. parts := strings.Split(cgroup, ",")
  147. if len(parts) > 1 {
  148. for _, part := range parts {
  149. if err := CreateSymlink("/sys/fs/cgroup/"+cgroup, "/sys/fs/cgroup/"+part); err != nil {
  150. return err
  151. }
  152. }
  153. }
  154. return nil
  155. }
  156. func execDocker(config *Config, docker, cmd string, args []string) (*exec.Cmd, error) {
  157. if len(args) > 0 && args[0] == "docker" {
  158. args = args[1:]
  159. }
  160. log.Debugf("Launching Docker %s %s %v", docker, cmd, args)
  161. env := os.Environ()
  162. if len(config.Environment) != 0 {
  163. env = append(env, config.Environment...)
  164. }
  165. if config.Fork {
  166. cmd := exec.Command(docker, args...)
  167. if !config.NoLog {
  168. cmd.Stdout = os.Stdout
  169. cmd.Stderr = os.Stderr
  170. }
  171. cmd.Env = env
  172. err := cmd.Start()
  173. if err != nil {
  174. return cmd, err
  175. }
  176. if config.PidOne {
  177. PidOne()
  178. }
  179. return cmd, err
  180. } else {
  181. err := syscall.Exec(expand(docker), append([]string{cmd}, args...), env)
  182. return nil, err
  183. }
  184. }
  185. func copyDefault(folder, name string) error {
  186. defaultFile := path.Join(defaultPrefix, folder, name)
  187. if err := CopyFile(defaultFile, folder, name); err != nil {
  188. return err
  189. }
  190. return nil
  191. }
  192. func copyDefaultFolder(folder string) error {
  193. log.Debugf("Copying folder %s", folder)
  194. defaultFolder := path.Join(defaultPrefix, folder)
  195. files, _ := ioutil.ReadDir(defaultFolder)
  196. for _, file := range files {
  197. var err error
  198. if file.IsDir() {
  199. err = copyDefaultFolder(path.Join(folder, file.Name()))
  200. } else {
  201. err = copyDefault(folder, file.Name())
  202. }
  203. if err != nil {
  204. return err
  205. }
  206. }
  207. return nil
  208. }
  209. func defaultFiles(files ...string) error {
  210. for _, file := range files {
  211. dir := path.Dir(file)
  212. name := path.Base(file)
  213. if err := copyDefault(dir, name); err != nil {
  214. return err
  215. }
  216. }
  217. return nil
  218. }
  219. func defaultFolders(folders ...string) error {
  220. for _, folder := range folders {
  221. if err := copyDefaultFolder(folder); err != nil {
  222. return err
  223. }
  224. }
  225. return nil
  226. }
  227. func CopyFile(src, folder, name string) error {
  228. if _, err := os.Lstat(src); os.IsNotExist(err) {
  229. log.Debugf("Not copying %s, does not exists", src)
  230. return nil
  231. }
  232. dst := path.Join(folder, name)
  233. if _, err := os.Lstat(dst); err == nil {
  234. log.Debugf("Not copying %s => %s already exists", src, dst)
  235. return nil
  236. }
  237. if err := createDirs(folder); err != nil {
  238. return err
  239. }
  240. stat, err := os.Lstat(src)
  241. if err != nil {
  242. return err
  243. }
  244. if stat.Mode()&os.ModeSymlink != 0 {
  245. symDst, err := os.Readlink(src)
  246. if err != nil {
  247. log.Errorf("Failed to readlink: %v", err)
  248. return err
  249. }
  250. // file is a symlink
  251. log.Debugf("Symlinking %s => %s", dst, symDst)
  252. return os.Symlink(symDst, dst)
  253. }
  254. srcFile, err := os.Open(src)
  255. if err != nil {
  256. return err
  257. }
  258. defer srcFile.Close()
  259. dstFile, err := os.Create(dst)
  260. if err != nil {
  261. return err
  262. }
  263. defer dstFile.Close()
  264. log.Debugf("Copying %s => %s", src, dst)
  265. _, err = io.Copy(dstFile, srcFile)
  266. return err
  267. }
  268. func tryCreateFile(name, content string) error {
  269. if _, err := os.Stat(name); err == nil {
  270. return nil
  271. }
  272. if err := createDirs(path.Dir(name)); err != nil {
  273. return err
  274. }
  275. return ioutil.WriteFile(name, []byte(content), 0644)
  276. }
  277. func createPasswd() error {
  278. return tryCreateFile("/etc/passwd", "root:x:0:0:root:/root:/bin/sh\n")
  279. }
  280. func createGroup() error {
  281. return tryCreateFile("/etc/group", "root:x:0:\n")
  282. }
  283. func setupNetworking(config *Config) error {
  284. if config == nil {
  285. return nil
  286. }
  287. hostname, err := os.Hostname()
  288. if err != nil {
  289. return err
  290. }
  291. tryCreateFile("/etc/hosts", `127.0.0.1 localhost
  292. ::1 localhost ip6-localhost ip6-loopback
  293. fe00::0 ip6-localnet
  294. ff00::0 ip6-mcastprefix
  295. ff02::1 ip6-allnodes
  296. ff02::2 ip6-allrouters
  297. 127.0.1.1 `+hostname)
  298. if len(config.DnsConfig.Nameservers) != 0 {
  299. if _, err := resolvconf.Build("/etc/resolv.conf", config.DnsConfig.Nameservers, config.DnsConfig.Search, nil); err != nil {
  300. return err
  301. }
  302. }
  303. if config.BridgeName != "" && config.BridgeName != "none" {
  304. log.Debugf("Creating bridge %s (%s)", config.BridgeName, config.BridgeAddress)
  305. if err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  306. Interfaces: map[string]netconf.InterfaceConfig{
  307. config.BridgeName: {
  308. Address: config.BridgeAddress,
  309. MTU: config.BridgeMtu,
  310. Bridge: "true",
  311. },
  312. },
  313. }); err != nil {
  314. return err
  315. }
  316. }
  317. return nil
  318. }
  319. func ParseConfig(config *Config, args ...string) []string {
  320. for i, arg := range args {
  321. if strings.HasPrefix(arg, "--bip") {
  322. config.BridgeAddress = util.GetValue(i, args)
  323. } else if strings.HasPrefix(arg, "--fixed-cidr") {
  324. config.BridgeAddress = util.GetValue(i, args)
  325. } else if strings.HasPrefix(arg, "-b") || strings.HasPrefix(arg, "--bridge") {
  326. config.BridgeName = util.GetValue(i, args)
  327. } else if strings.HasPrefix(arg, "--config-file") {
  328. config.DaemonConfig = util.GetValue(i, args)
  329. } else if strings.HasPrefix(arg, "--mtu") {
  330. mtu, err := strconv.Atoi(util.GetValue(i, args))
  331. if err != nil {
  332. config.BridgeMtu = mtu
  333. }
  334. } else if strings.HasPrefix(arg, "-g") || strings.HasPrefix(arg, "--graph") {
  335. config.GraphDirectory = util.GetValue(i, args)
  336. }
  337. }
  338. if config.BridgeName != "" && config.BridgeAddress != "" {
  339. newArgs := []string{}
  340. skip := false
  341. for _, arg := range args {
  342. if skip {
  343. skip = false
  344. continue
  345. }
  346. if arg == "--bip" {
  347. skip = true
  348. continue
  349. } else if strings.HasPrefix(arg, "--bip=") {
  350. continue
  351. }
  352. newArgs = append(newArgs, arg)
  353. }
  354. args = newArgs
  355. }
  356. return args
  357. }
  358. func PrepareFs(config *Config) error {
  359. if err := createMounts(mounts...); err != nil {
  360. return err
  361. }
  362. createOptionalMounts(optionalMounts...)
  363. if err := mountCgroups(config.CgroupHierarchy); err != nil {
  364. return err
  365. }
  366. if err := createLayout(config); err != nil {
  367. return err
  368. }
  369. if err := firstPrepare(); err != nil {
  370. return err
  371. }
  372. return nil
  373. }
  374. func touchSocket(path string) error {
  375. if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) {
  376. return err
  377. }
  378. return ioutil.WriteFile(path, []byte{}, 0700)
  379. }
  380. func touchSockets(args ...string) error {
  381. touched := false
  382. for i, arg := range args {
  383. if strings.HasPrefix(arg, "-H") {
  384. val := util.GetValue(i, args)
  385. if strings.HasPrefix(val, "unix://") {
  386. val = val[len("unix://"):]
  387. log.Debugf("Creating temp file at %s", val)
  388. if err := touchSocket(val); err != nil {
  389. return err
  390. }
  391. touched = true
  392. }
  393. }
  394. }
  395. if !touched {
  396. return touchSocket("/var/run/docker.sock")
  397. }
  398. return nil
  399. }
  400. func createDaemonConfig(config *Config) error {
  401. if config.DaemonConfig == "" {
  402. return nil
  403. }
  404. if _, err := os.Stat(config.DaemonConfig); os.IsNotExist(err) {
  405. if err := os.MkdirAll(path.Dir(config.DaemonConfig), 0755); err != nil {
  406. return err
  407. }
  408. return ioutil.WriteFile(config.DaemonConfig, []byte("{}"), 0600)
  409. }
  410. return nil
  411. }
  412. func cleanupFiles(graphDirectory string) {
  413. zeroFiles := []string{
  414. "/etc/docker/key.json",
  415. "/etc/docker/daemon.json",
  416. "/etc/docker/system-daemon.json",
  417. path.Join(graphDirectory, "image/overlay/repositories.json"),
  418. }
  419. for _, file := range zeroFiles {
  420. if stat, err := os.Stat(file); err == nil {
  421. if stat.Size() < 2 {
  422. log.Warnf("Deleting invalid json file: %s", file)
  423. os.Remove(file)
  424. }
  425. }
  426. }
  427. }
  428. func createLayout(config *Config) error {
  429. if err := createDirs("/tmp", "/root/.ssh", "/var", "/usr/lib"); err != nil {
  430. return err
  431. }
  432. graphDirectory := config.GraphDirectory
  433. if config.GraphDirectory == "" {
  434. graphDirectory = "/var/lib/docker"
  435. }
  436. if err := createDirs(graphDirectory); err != nil {
  437. return err
  438. }
  439. if err := createDaemonConfig(config); err != nil {
  440. return err
  441. }
  442. cleanupFiles(graphDirectory)
  443. selinux.SetFileContext(graphDirectory, "system_u:object_r:var_lib_t:s0")
  444. return CreateSymlinks([][]string{
  445. {"usr/lib", "/lib"},
  446. {"usr/sbin", "/sbin"},
  447. {"../run", "/var/run"},
  448. })
  449. }
  450. func firstPrepare() error {
  451. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  452. if err := defaultFiles(
  453. "/etc/ssl/certs/ca-certificates.crt",
  454. "/etc/passwd",
  455. "/etc/group",
  456. ); err != nil {
  457. return err
  458. }
  459. if err := defaultFolders(
  460. "/etc/docker",
  461. "/etc/selinux",
  462. "/etc/selinux/ros",
  463. "/etc/selinux/ros/policy",
  464. "/etc/selinux/ros/contexts",
  465. "/var/lib/cni",
  466. ); err != nil {
  467. return err
  468. }
  469. if err := createPasswd(); err != nil {
  470. return err
  471. }
  472. if err := createGroup(); err != nil {
  473. return err
  474. }
  475. return nil
  476. }
  477. func secondPrepare(config *Config, docker string, args ...string) error {
  478. if err := setupNetworking(config); err != nil {
  479. return err
  480. }
  481. if err := touchSockets(args...); err != nil {
  482. return err
  483. }
  484. if err := setupLogging(config); err != nil {
  485. return err
  486. }
  487. for _, i := range []string{docker, iptables, modprobe} {
  488. if err := setupBin(config, i); err != nil {
  489. return err
  490. }
  491. }
  492. if err := setUlimit(config); err != nil {
  493. return err
  494. }
  495. ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0655)
  496. return nil
  497. }
  498. func expand(bin string) string {
  499. expanded, err := exec.LookPath(bin)
  500. if err == nil {
  501. return expanded
  502. }
  503. return bin
  504. }
  505. func setupBin(config *Config, bin string) error {
  506. expanded, err := exec.LookPath(bin)
  507. if err == nil {
  508. return nil
  509. }
  510. expanded, err = exec.LookPath(bin + distSuffix)
  511. if err != nil {
  512. // Purposely not returning error
  513. return nil
  514. }
  515. return CreateSymlink(expanded, expanded[:len(expanded)-len(distSuffix)])
  516. }
  517. func setupLogging(config *Config) error {
  518. if config.LogFile == "" {
  519. return nil
  520. }
  521. if err := createDirs(path.Dir(config.LogFile)); err != nil {
  522. return err
  523. }
  524. output, err := os.OpenFile(config.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  525. if err != nil {
  526. return err
  527. }
  528. syscall.Dup3(int(output.Fd()), int(os.Stdout.Fd()), 0)
  529. syscall.Dup3(int(output.Fd()), int(os.Stderr.Fd()), 0)
  530. return nil
  531. }
  532. func setUlimit(cfg *Config) error {
  533. var rLimit syscall.Rlimit
  534. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
  535. return err
  536. }
  537. if cfg.NoFiles == 0 {
  538. rLimit.Max = 1000000
  539. } else {
  540. rLimit.Max = cfg.NoFiles
  541. }
  542. rLimit.Cur = rLimit.Max
  543. return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  544. }
  545. func runOrExec(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  546. if err := secondPrepare(config, docker, args...); err != nil {
  547. return nil, err
  548. }
  549. cmd := path.Base(docker)
  550. if config != nil && config.CommandName != "" {
  551. cmd = config.CommandName
  552. }
  553. if cmd == "dockerd" && len(args) > 1 && args[0] == "daemon" {
  554. args = args[1:]
  555. }
  556. return execDocker(config, docker, cmd, args)
  557. }
  558. func LaunchDocker(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  559. if err := PrepareFs(config); err != nil {
  560. return nil, err
  561. }
  562. return runOrExec(config, docker, args...)
  563. }
  564. func Main() {
  565. if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
  566. log.SetLevel(log.DebugLevel)
  567. }
  568. if len(os.Args) < 2 {
  569. log.Fatalf("Usage Example: %s /usr/bin/docker -d -D", os.Args[0])
  570. }
  571. args := []string{}
  572. if len(os.Args) > 1 {
  573. args = os.Args[2:]
  574. }
  575. var config Config
  576. args = ParseConfig(&config, args...)
  577. if os.Getenv("DOCKER_LAUNCH_REAP") == "true" {
  578. config.Fork = true
  579. config.PidOne = true
  580. }
  581. log.Debugf("Launch config %#v", config)
  582. _, err := LaunchDocker(&config, os.Args[1], args...)
  583. if err != nil {
  584. log.Fatal(err)
  585. }
  586. }