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: %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. }
  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. if err := CopyFile(defaultFile, folder, name); err != nil {
  186. return err
  187. }
  188. return nil
  189. }
  190. func copyDefaultFolder(folder string) error {
  191. log.Debugf("Copying folder %s", folder)
  192. defaultFolder := path.Join(defaultPrefix, folder)
  193. files, _ := ioutil.ReadDir(defaultFolder)
  194. for _, file := range files {
  195. var err error
  196. if file.IsDir() {
  197. err = copyDefaultFolder(path.Join(folder, file.Name()))
  198. } else {
  199. err = copyDefault(folder, file.Name())
  200. }
  201. if err != nil {
  202. return err
  203. }
  204. }
  205. return nil
  206. }
  207. func defaultFiles(files ...string) error {
  208. for _, file := range files {
  209. dir := path.Dir(file)
  210. name := path.Base(file)
  211. if err := copyDefault(dir, name); err != nil {
  212. return err
  213. }
  214. }
  215. return nil
  216. }
  217. func defaultFolders(folders ...string) error {
  218. for _, folder := range folders {
  219. if err := copyDefaultFolder(folder); err != nil {
  220. return err
  221. }
  222. }
  223. return nil
  224. }
  225. func CopyFile(src, folder, name string) 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 _, err := os.Lstat(dst); err == nil {
  232. log.Debugf("Not copying %s => %s already exists", src, dst)
  233. return nil
  234. }
  235. if err := createDirs(folder); err != nil {
  236. return err
  237. }
  238. stat, err := os.Lstat(src)
  239. if err != nil {
  240. return err
  241. }
  242. if stat.Mode()&os.ModeSymlink != 0 {
  243. symDst, err := os.Readlink(src)
  244. if err != nil {
  245. log.Errorf("Failed to readlink: %v", err)
  246. return err
  247. }
  248. // file is a symlink
  249. log.Debugf("Symlinking %s => %s", dst, symDst)
  250. return os.Symlink(symDst, dst)
  251. }
  252. srcFile, err := os.Open(src)
  253. if err != nil {
  254. return err
  255. }
  256. defer srcFile.Close()
  257. dstFile, err := os.Create(dst)
  258. if err != nil {
  259. return err
  260. }
  261. defer dstFile.Close()
  262. log.Debugf("Copying %s => %s", src, dst)
  263. _, err = io.Copy(dstFile, srcFile)
  264. return err
  265. }
  266. func tryCreateFile(name, content string) error {
  267. if _, err := os.Stat(name); err == nil {
  268. return nil
  269. }
  270. if err := createDirs(path.Dir(name)); err != nil {
  271. return err
  272. }
  273. return ioutil.WriteFile(name, []byte(content), 0644)
  274. }
  275. func createPasswd() error {
  276. return tryCreateFile("/etc/passwd", "root:x:0:0:root:/root:/bin/sh\n")
  277. }
  278. func createGroup() error {
  279. return tryCreateFile("/etc/group", "root:x:0:\n")
  280. }
  281. func setupNetworking(cfg *Config) error {
  282. if cfg == nil {
  283. return nil
  284. }
  285. hostname, err := os.Hostname()
  286. if err != nil {
  287. return err
  288. }
  289. tryCreateFile("/etc/hosts", `127.0.0.1 localhost
  290. ::1 localhost ip6-localhost ip6-loopback
  291. fe00::0 ip6-localnet
  292. ff00::0 ip6-mcastprefix
  293. ff02::1 ip6-allnodes
  294. ff02::2 ip6-allrouters
  295. 127.0.1.1 `+hostname)
  296. if len(cfg.DNSConfig.Nameservers) != 0 {
  297. if _, err := resolvconf.Build("/etc/resolv.conf", cfg.DNSConfig.Nameservers, cfg.DNSConfig.Search, nil); err != nil {
  298. return err
  299. }
  300. }
  301. if cfg.BridgeName != "" && cfg.BridgeName != "none" {
  302. log.Debugf("Creating bridge %s (%s)", cfg.BridgeName, cfg.BridgeAddress)
  303. if err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  304. Interfaces: map[string]netconf.InterfaceConfig{
  305. cfg.BridgeName: {
  306. Address: cfg.BridgeAddress,
  307. MTU: cfg.BridgeMtu,
  308. Bridge: "true",
  309. },
  310. },
  311. }); err != nil {
  312. return err
  313. }
  314. }
  315. return nil
  316. }
  317. func GetValue(index int, args []string) string {
  318. val := args[index]
  319. parts := strings.SplitN(val, "=", 2)
  320. if len(parts) == 1 {
  321. if len(args) > index+1 {
  322. return args[index+1]
  323. }
  324. return ""
  325. }
  326. return parts[1]
  327. }
  328. func ParseConfig(config *Config, args ...string) []string {
  329. for i, arg := range args {
  330. if strings.HasPrefix(arg, "--bip") {
  331. config.BridgeAddress = GetValue(i, args)
  332. } else if strings.HasPrefix(arg, "--fixed-cidr") {
  333. config.BridgeAddress = GetValue(i, args)
  334. } else if strings.HasPrefix(arg, "-b") || strings.HasPrefix(arg, "--bridge") {
  335. config.BridgeName = GetValue(i, args)
  336. } else if strings.HasPrefix(arg, "--config-file") {
  337. config.DaemonConfig = GetValue(i, args)
  338. } else if strings.HasPrefix(arg, "--mtu") {
  339. mtu, err := strconv.Atoi(GetValue(i, args))
  340. if err != nil {
  341. config.BridgeMtu = mtu
  342. }
  343. } else if strings.HasPrefix(arg, "-g") || strings.HasPrefix(arg, "--graph") {
  344. config.GraphDirectory = GetValue(i, args)
  345. }
  346. }
  347. if config.BridgeName != "" && config.BridgeAddress != "" {
  348. newArgs := []string{}
  349. skip := false
  350. for _, arg := range args {
  351. if skip {
  352. skip = false
  353. continue
  354. }
  355. if arg == "--bip" {
  356. skip = true
  357. continue
  358. } else if strings.HasPrefix(arg, "--bip=") {
  359. continue
  360. }
  361. newArgs = append(newArgs, arg)
  362. }
  363. args = newArgs
  364. }
  365. return args
  366. }
  367. func PrepareFs(config *Config) error {
  368. if err := createMounts(mounts...); err != nil {
  369. return err
  370. }
  371. createOptionalMounts(optionalMounts...)
  372. if err := mountCgroups(config.CgroupHierarchy); err != nil {
  373. return err
  374. }
  375. if err := createLayout(config); err != nil {
  376. return err
  377. }
  378. if err := firstPrepare(); err != nil {
  379. return err
  380. }
  381. return nil
  382. }
  383. func touchSocket(path string) error {
  384. if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) {
  385. return err
  386. }
  387. return ioutil.WriteFile(path, []byte{}, 0700)
  388. }
  389. func touchSockets(args ...string) error {
  390. touched := false
  391. for i, arg := range args {
  392. if strings.HasPrefix(arg, "-H") {
  393. val := GetValue(i, args)
  394. if strings.HasPrefix(val, "unix://") {
  395. val = val[len("unix://"):]
  396. log.Debugf("Creating temp file at %s", val)
  397. if err := touchSocket(val); err != nil {
  398. return err
  399. }
  400. touched = true
  401. }
  402. }
  403. }
  404. if !touched {
  405. return touchSocket("/var/run/docker.sock")
  406. }
  407. return nil
  408. }
  409. func createDaemonConfig(config *Config) error {
  410. if config.DaemonConfig == "" {
  411. return nil
  412. }
  413. if _, err := os.Stat(config.DaemonConfig); os.IsNotExist(err) {
  414. if err := os.MkdirAll(path.Dir(config.DaemonConfig), 0755); err != nil {
  415. return err
  416. }
  417. return ioutil.WriteFile(config.DaemonConfig, []byte("{}"), 0600)
  418. }
  419. return nil
  420. }
  421. func cleanupFiles(graphDirectory string) {
  422. zeroFiles := []string{
  423. "/etc/docker/key.json",
  424. "/etc/docker/daemon.json",
  425. "/etc/docker/system-daemon.json",
  426. path.Join(graphDirectory, "image/overlay/repositories.json"),
  427. }
  428. for _, file := range zeroFiles {
  429. if stat, err := os.Stat(file); err == nil {
  430. if stat.Size() < 2 {
  431. log.Warnf("Deleting invalid json file: %s", file)
  432. os.Remove(file)
  433. }
  434. }
  435. }
  436. }
  437. func createLayout(config *Config) error {
  438. if err := createDirs("/tmp", "/root/.ssh", "/var", "/usr/lib"); err != nil {
  439. return err
  440. }
  441. graphDirectory := config.GraphDirectory
  442. if config.GraphDirectory == "" {
  443. graphDirectory = "/var/lib/docker"
  444. }
  445. if err := createDirs(graphDirectory); err != nil {
  446. return err
  447. }
  448. if err := createDaemonConfig(config); err != nil {
  449. return err
  450. }
  451. cleanupFiles(graphDirectory)
  452. selinux.SetFileContext(graphDirectory, "system_u:object_r:var_lib_t:s0")
  453. return CreateSymlinks([][]string{
  454. {"usr/lib", "/lib"},
  455. {"usr/sbin", "/sbin"},
  456. {"../run", "/var/run"},
  457. })
  458. }
  459. func firstPrepare() error {
  460. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  461. if err := defaultFiles(
  462. "/etc/ssl/certs/ca-certificates.crt",
  463. "/etc/passwd",
  464. "/etc/group",
  465. ); err != nil {
  466. return err
  467. }
  468. if err := defaultFolders(
  469. "/etc/docker",
  470. "/etc/selinux",
  471. "/etc/selinux/ros",
  472. "/etc/selinux/ros/policy",
  473. "/etc/selinux/ros/contexts",
  474. "/var/lib/cni",
  475. ); err != nil {
  476. return err
  477. }
  478. if err := createPasswd(); err != nil {
  479. return err
  480. }
  481. if err := createGroup(); err != nil {
  482. return err
  483. }
  484. return nil
  485. }
  486. func secondPrepare(config *Config, docker string, args ...string) error {
  487. if err := setupNetworking(config); err != nil {
  488. return err
  489. }
  490. if err := touchSockets(args...); err != nil {
  491. return err
  492. }
  493. if err := setupLogging(config); err != nil {
  494. return err
  495. }
  496. for _, i := range []string{docker, iptables, modprobe} {
  497. if err := setupBin(config, i); err != nil {
  498. return err
  499. }
  500. }
  501. if err := setUlimit(config); err != nil {
  502. return err
  503. }
  504. ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0655)
  505. return nil
  506. }
  507. func expand(bin string) string {
  508. expanded, err := exec.LookPath(bin)
  509. if err == nil {
  510. return expanded
  511. }
  512. return bin
  513. }
  514. func setupBin(config *Config, bin string) error {
  515. expanded, err := exec.LookPath(bin)
  516. if err == nil {
  517. return nil
  518. }
  519. expanded, err = exec.LookPath(bin + distSuffix)
  520. if err != nil {
  521. // Purposely not returning error
  522. return nil
  523. }
  524. return CreateSymlink(expanded, expanded[:len(expanded)-len(distSuffix)])
  525. }
  526. func setupLogging(config *Config) error {
  527. if config.LogFile == "" {
  528. return nil
  529. }
  530. if err := createDirs(path.Dir(config.LogFile)); err != nil {
  531. return err
  532. }
  533. output, err := os.OpenFile(config.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  534. if err != nil {
  535. return err
  536. }
  537. syscall.Dup3(int(output.Fd()), int(os.Stdout.Fd()), 0)
  538. syscall.Dup3(int(output.Fd()), int(os.Stderr.Fd()), 0)
  539. return nil
  540. }
  541. func setUlimit(cfg *Config) error {
  542. var rLimit syscall.Rlimit
  543. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
  544. return err
  545. }
  546. if cfg.NoFiles == 0 {
  547. rLimit.Max = 1000000
  548. } else {
  549. rLimit.Max = cfg.NoFiles
  550. }
  551. rLimit.Cur = rLimit.Max
  552. return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  553. }
  554. func runOrExec(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  555. if err := secondPrepare(config, docker, args...); err != nil {
  556. return nil, err
  557. }
  558. cmd := path.Base(docker)
  559. if config != nil && config.CommandName != "" {
  560. cmd = config.CommandName
  561. }
  562. if cmd == "dockerd" && len(args) > 1 && args[0] == "daemon" {
  563. args = args[1:]
  564. }
  565. return execDocker(config, docker, cmd, args)
  566. }
  567. func LaunchDocker(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  568. if err := PrepareFs(config); err != nil {
  569. return nil, err
  570. }
  571. return runOrExec(config, docker, args...)
  572. }
  573. func Main() {
  574. log.InitLogger()
  575. if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
  576. log.SetLevel(log.DebugLevel)
  577. }
  578. if len(os.Args) < 2 {
  579. log.Fatalf("Usage Example: %s /usr/bin/docker -d -D", os.Args[0])
  580. }
  581. args := []string{}
  582. if len(os.Args) > 1 {
  583. args = os.Args[2:]
  584. }
  585. var config Config
  586. args = ParseConfig(&config, args...)
  587. if os.Getenv("DOCKER_LAUNCH_REAP") == "true" {
  588. config.Fork = true
  589. config.PidOne = true
  590. }
  591. log.Debugf("Launch config %#v", config)
  592. _, err := LaunchDocker(&config, os.Args[1], args...)
  593. if err != nil {
  594. log.Fatal(err)
  595. }
  596. }