scratch.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. package dfs
  2. import (
  3. "bufio"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/docker/libnetwork/resolvconf"
  13. "github.com/rancher/os/log"
  14. "github.com/rancher/os/netconf"
  15. "github.com/rancher/os/selinux"
  16. "github.com/rancher/os/util"
  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", "ro"},
  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: %v", 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. }
  181. return nil, syscall.Exec(expand(docker), append([]string{cmd}, args...), env)
  182. }
  183. func copyDefault(folder, name string) error {
  184. defaultFile := path.Join(defaultPrefix, folder, name)
  185. return CopyFile(defaultFile, folder, name)
  186. }
  187. func copyDefaultFolder(folder string) error {
  188. log.Debugf("Copying folder %s", folder)
  189. defaultFolder := path.Join(defaultPrefix, folder)
  190. files, _ := ioutil.ReadDir(defaultFolder)
  191. for _, file := range files {
  192. var err error
  193. if file.IsDir() {
  194. err = copyDefaultFolder(path.Join(folder, file.Name()))
  195. } else {
  196. err = copyDefault(folder, file.Name())
  197. }
  198. if err != nil {
  199. return err
  200. }
  201. }
  202. return nil
  203. }
  204. func defaultFiles(files ...string) error {
  205. for _, file := range files {
  206. dir := path.Dir(file)
  207. name := path.Base(file)
  208. if err := copyDefault(dir, name); err != nil {
  209. return err
  210. }
  211. }
  212. return nil
  213. }
  214. func defaultFolders(folders ...string) error {
  215. for _, folder := range folders {
  216. if err := copyDefaultFolder(folder); err != nil {
  217. return err
  218. }
  219. }
  220. return nil
  221. }
  222. func CopyFile(src, folder, name string) error {
  223. return CopyFileOverwrite(src, folder, name, false)
  224. }
  225. func CopyFileOverwrite(src, folder, name string, overwrite bool) error {
  226. if _, err := os.Lstat(src); os.IsNotExist(err) {
  227. log.Debugf("Not copying %s, does not exists", src)
  228. return nil
  229. }
  230. dst := path.Join(folder, name)
  231. if !overwrite {
  232. if _, err := os.Lstat(dst); err == nil {
  233. log.Debugf("Not copying %s => %s already exists", src, dst)
  234. return nil
  235. }
  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(cfg *Config) error {
  284. if cfg == 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(cfg.DNSConfig.Nameservers) != 0 {
  299. resolve, err := ioutil.ReadFile("/etc/resolv.conf")
  300. log.Debugf("Resolve.conf == [%s], %v", resolve, err)
  301. if err != nil {
  302. log.Infof("scratch Writing empty resolv.conf (%v) %v", []string{}, []string{})
  303. if _, err := resolvconf.Build("/etc/resolv.conf", []string{}, []string{}, nil); err != nil {
  304. return err
  305. }
  306. }
  307. }
  308. if cfg.BridgeName != "" && cfg.BridgeName != "none" {
  309. log.Debugf("Creating bridge %s (%s)", cfg.BridgeName, cfg.BridgeAddress)
  310. if _, err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  311. Interfaces: map[string]netconf.InterfaceConfig{
  312. cfg.BridgeName: {
  313. Address: cfg.BridgeAddress,
  314. MTU: cfg.BridgeMtu,
  315. Bridge: "true",
  316. },
  317. },
  318. }, false, false); err != nil {
  319. log.Errorf("Error creating bridge: %s", err)
  320. return err
  321. }
  322. }
  323. return nil
  324. }
  325. func GetValue(index int, args []string) string {
  326. val := args[index]
  327. parts := strings.SplitN(val, "=", 2)
  328. if len(parts) == 1 {
  329. if len(args) > index+1 {
  330. return args[index+1]
  331. }
  332. return ""
  333. }
  334. return parts[1]
  335. }
  336. func ParseConfig(config *Config, args ...string) []string {
  337. for i, arg := range args {
  338. if strings.HasPrefix(arg, "--bip") {
  339. config.BridgeAddress = GetValue(i, args)
  340. } else if strings.HasPrefix(arg, "--fixed-cidr") {
  341. config.BridgeAddress = GetValue(i, args)
  342. } else if strings.HasPrefix(arg, "-b") || strings.HasPrefix(arg, "--bridge") {
  343. config.BridgeName = GetValue(i, args)
  344. } else if strings.HasPrefix(arg, "--config-file") {
  345. config.DaemonConfig = GetValue(i, args)
  346. } else if strings.HasPrefix(arg, "--mtu") {
  347. mtu, err := strconv.Atoi(GetValue(i, args))
  348. if err != nil {
  349. config.BridgeMtu = mtu
  350. }
  351. } else if strings.HasPrefix(arg, "-g") || strings.HasPrefix(arg, "--graph") {
  352. config.GraphDirectory = GetValue(i, args)
  353. }
  354. }
  355. if config.BridgeName != "" && config.BridgeAddress != "" {
  356. newArgs := []string{}
  357. skip := false
  358. for _, arg := range args {
  359. if skip {
  360. skip = false
  361. continue
  362. }
  363. if arg == "--bip" {
  364. skip = true
  365. continue
  366. } else if strings.HasPrefix(arg, "--bip=") {
  367. continue
  368. }
  369. newArgs = append(newArgs, arg)
  370. }
  371. args = newArgs
  372. }
  373. return args
  374. }
  375. func PrepareFs(config *Config) error {
  376. if err := createMounts(mounts...); err != nil {
  377. return err
  378. }
  379. createOptionalMounts(optionalMounts...)
  380. if err := mountCgroups(config.CgroupHierarchy); err != nil {
  381. return err
  382. }
  383. if err := createLayout(config); err != nil {
  384. return err
  385. }
  386. return firstPrepare()
  387. }
  388. func touchSocket(path string) error {
  389. if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) {
  390. return err
  391. }
  392. return ioutil.WriteFile(path, []byte{}, 0700)
  393. }
  394. func touchSockets(args ...string) error {
  395. touched := false
  396. for i, arg := range args {
  397. if strings.HasPrefix(arg, "-H") {
  398. val := GetValue(i, args)
  399. if strings.HasPrefix(val, "unix://") {
  400. val = val[len("unix://"):]
  401. log.Debugf("Creating temp file at %s", val)
  402. if err := touchSocket(val); err != nil {
  403. return err
  404. }
  405. touched = true
  406. }
  407. }
  408. }
  409. if !touched {
  410. return touchSocket("/var/run/docker.sock")
  411. }
  412. return nil
  413. }
  414. func createDaemonConfig(config *Config) error {
  415. if config.DaemonConfig == "" {
  416. return nil
  417. }
  418. if _, err := os.Stat(config.DaemonConfig); os.IsNotExist(err) {
  419. if err := os.MkdirAll(path.Dir(config.DaemonConfig), 0755); err != nil {
  420. return err
  421. }
  422. return ioutil.WriteFile(config.DaemonConfig, []byte("{}"), 0600)
  423. }
  424. return nil
  425. }
  426. func cleanupFiles(graphDirectory string) {
  427. zeroFiles := []string{
  428. "/etc/docker/key.json",
  429. "/etc/docker/daemon.json",
  430. "/etc/docker/system-daemon.json",
  431. path.Join(graphDirectory, "image/overlay/repositories.json"),
  432. }
  433. for _, file := range zeroFiles {
  434. if stat, err := os.Stat(file); err == nil {
  435. if stat.Size() < 2 {
  436. log.Warnf("Deleting invalid json file: %s", file)
  437. os.Remove(file)
  438. }
  439. }
  440. }
  441. }
  442. func createLayout(config *Config) error {
  443. if err := createDirs("/tmp", "/root/.ssh", "/var", "/usr/lib"); err != nil {
  444. return err
  445. }
  446. graphDirectory := config.GraphDirectory
  447. if config.GraphDirectory == "" {
  448. graphDirectory = "/var/lib/docker"
  449. }
  450. if err := createDirs(graphDirectory); err != nil {
  451. return err
  452. }
  453. if err := createDaemonConfig(config); err != nil {
  454. return err
  455. }
  456. cleanupFiles(graphDirectory)
  457. selinux.SetFileContext(graphDirectory, "system_u:object_r:var_lib_t:s0")
  458. return CreateSymlinks([][]string{
  459. {"usr/lib", "/lib"},
  460. {"usr/sbin", "/sbin"},
  461. {"../run", "/var/run"},
  462. })
  463. }
  464. func firstPrepare() error {
  465. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  466. if err := defaultFiles(
  467. "/etc/ssl/certs/ca-certificates.crt",
  468. "/etc/passwd",
  469. "/etc/group",
  470. ); err != nil {
  471. return err
  472. }
  473. if err := defaultFolders(
  474. "/etc/docker",
  475. "/etc/selinux",
  476. "/etc/selinux/ros",
  477. "/etc/selinux/ros/policy",
  478. "/etc/selinux/ros/contexts",
  479. ); err != nil {
  480. return err
  481. }
  482. if err := createPasswd(); err != nil {
  483. return err
  484. }
  485. return createGroup()
  486. }
  487. func secondPrepare(config *Config, docker string, args ...string) error {
  488. if err := setupNetworking(config); err != nil {
  489. return err
  490. }
  491. if err := touchSockets(args...); err != nil {
  492. return err
  493. }
  494. if err := setupLogging(config); err != nil {
  495. return err
  496. }
  497. for _, i := range []string{docker, iptables, modprobe} {
  498. if err := setupBin(config, i); err != nil {
  499. return err
  500. }
  501. }
  502. if err := setUlimit(config); err != nil {
  503. return err
  504. }
  505. ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0655)
  506. return nil
  507. }
  508. func expand(bin string) string {
  509. expanded, err := exec.LookPath(bin)
  510. if err == nil {
  511. return expanded
  512. }
  513. return bin
  514. }
  515. func setupBin(config *Config, bin string) error {
  516. expanded, err := exec.LookPath(bin)
  517. if err == nil {
  518. return nil
  519. }
  520. expanded, err = exec.LookPath(bin + distSuffix)
  521. if err != nil {
  522. // Purposely not returning error
  523. return nil
  524. }
  525. return CreateSymlink(expanded, expanded[:len(expanded)-len(distSuffix)])
  526. }
  527. func setupLogging(config *Config) error {
  528. if config.LogFile == "" {
  529. return nil
  530. }
  531. if err := createDirs(path.Dir(config.LogFile)); err != nil {
  532. return err
  533. }
  534. output, err := os.OpenFile(config.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  535. if err != nil {
  536. return err
  537. }
  538. syscall.Dup3(int(output.Fd()), int(os.Stdout.Fd()), 0)
  539. syscall.Dup3(int(output.Fd()), int(os.Stderr.Fd()), 0)
  540. return nil
  541. }
  542. func setUlimit(cfg *Config) error {
  543. var rLimit syscall.Rlimit
  544. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
  545. return err
  546. }
  547. if cfg.NoFiles == 0 {
  548. rLimit.Max = 1000000
  549. } else {
  550. rLimit.Max = cfg.NoFiles
  551. }
  552. rLimit.Cur = rLimit.Max
  553. return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  554. }
  555. func runOrExec(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  556. if err := secondPrepare(config, docker, args...); err != nil {
  557. return nil, err
  558. }
  559. cmd := path.Base(docker)
  560. if config != nil && config.CommandName != "" {
  561. cmd = config.CommandName
  562. }
  563. if cmd == "dockerd" && len(args) > 1 && args[0] == "daemon" {
  564. args = args[1:]
  565. }
  566. return execDocker(config, docker, cmd, args)
  567. }
  568. func LaunchDocker(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  569. if err := PrepareFs(config); err != nil {
  570. return nil, err
  571. }
  572. return runOrExec(config, docker, args...)
  573. }
  574. func Main() {
  575. log.InitLogger()
  576. if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
  577. log.SetLevel(log.DebugLevel)
  578. }
  579. if len(os.Args) < 2 {
  580. log.Fatalf("Usage Example: %s /usr/bin/docker -d -D", os.Args[0])
  581. }
  582. args := []string{}
  583. if len(os.Args) > 1 {
  584. args = os.Args[2:]
  585. }
  586. var config Config
  587. args = ParseConfig(&config, args...)
  588. if os.Getenv("DOCKER_LAUNCH_REAP") == "true" {
  589. config.Fork = true
  590. config.PidOne = true
  591. }
  592. log.Debugf("Launch config %#v", config)
  593. _, err := LaunchDocker(&config, os.Args[1], args...)
  594. if err != nil {
  595. log.Fatal(err)
  596. }
  597. }