scratch.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. 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. log.Infof("Writing resolv.conf (%v) %v", cfg.DNSConfig.Nameservers, cfg.DNSConfig.Search)
  300. if _, err := resolvconf.Build("/etc/resolv.conf", cfg.DNSConfig.Nameservers, cfg.DNSConfig.Search, nil); err != nil {
  301. return err
  302. }
  303. }
  304. if cfg.BridgeName != "" && cfg.BridgeName != "none" {
  305. log.Debugf("Creating bridge %s (%s)", cfg.BridgeName, cfg.BridgeAddress)
  306. if err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  307. Interfaces: map[string]netconf.InterfaceConfig{
  308. cfg.BridgeName: {
  309. Address: cfg.BridgeAddress,
  310. MTU: cfg.BridgeMtu,
  311. Bridge: "true",
  312. },
  313. },
  314. }, false, false); err != nil {
  315. return err
  316. }
  317. }
  318. return nil
  319. }
  320. func GetValue(index int, args []string) string {
  321. val := args[index]
  322. parts := strings.SplitN(val, "=", 2)
  323. if len(parts) == 1 {
  324. if len(args) > index+1 {
  325. return args[index+1]
  326. }
  327. return ""
  328. }
  329. return parts[1]
  330. }
  331. func ParseConfig(config *Config, args ...string) []string {
  332. for i, arg := range args {
  333. if strings.HasPrefix(arg, "--bip") {
  334. config.BridgeAddress = GetValue(i, args)
  335. } else if strings.HasPrefix(arg, "--fixed-cidr") {
  336. config.BridgeAddress = GetValue(i, args)
  337. } else if strings.HasPrefix(arg, "-b") || strings.HasPrefix(arg, "--bridge") {
  338. config.BridgeName = GetValue(i, args)
  339. } else if strings.HasPrefix(arg, "--config-file") {
  340. config.DaemonConfig = GetValue(i, args)
  341. } else if strings.HasPrefix(arg, "--mtu") {
  342. mtu, err := strconv.Atoi(GetValue(i, args))
  343. if err != nil {
  344. config.BridgeMtu = mtu
  345. }
  346. } else if strings.HasPrefix(arg, "-g") || strings.HasPrefix(arg, "--graph") {
  347. config.GraphDirectory = GetValue(i, args)
  348. }
  349. }
  350. if config.BridgeName != "" && config.BridgeAddress != "" {
  351. newArgs := []string{}
  352. skip := false
  353. for _, arg := range args {
  354. if skip {
  355. skip = false
  356. continue
  357. }
  358. if arg == "--bip" {
  359. skip = true
  360. continue
  361. } else if strings.HasPrefix(arg, "--bip=") {
  362. continue
  363. }
  364. newArgs = append(newArgs, arg)
  365. }
  366. args = newArgs
  367. }
  368. return args
  369. }
  370. func PrepareFs(config *Config) error {
  371. if err := createMounts(mounts...); err != nil {
  372. return err
  373. }
  374. createOptionalMounts(optionalMounts...)
  375. if err := mountCgroups(config.CgroupHierarchy); err != nil {
  376. return err
  377. }
  378. if err := createLayout(config); err != nil {
  379. return err
  380. }
  381. return firstPrepare()
  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. return createGroup()
  482. }
  483. func secondPrepare(config *Config, docker string, args ...string) error {
  484. if err := setupNetworking(config); err != nil {
  485. return err
  486. }
  487. if err := touchSockets(args...); err != nil {
  488. return err
  489. }
  490. if err := setupLogging(config); err != nil {
  491. return err
  492. }
  493. for _, i := range []string{docker, iptables, modprobe} {
  494. if err := setupBin(config, i); err != nil {
  495. return err
  496. }
  497. }
  498. if err := setUlimit(config); err != nil {
  499. return err
  500. }
  501. ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0655)
  502. return nil
  503. }
  504. func expand(bin string) string {
  505. expanded, err := exec.LookPath(bin)
  506. if err == nil {
  507. return expanded
  508. }
  509. return bin
  510. }
  511. func setupBin(config *Config, bin string) error {
  512. expanded, err := exec.LookPath(bin)
  513. if err == nil {
  514. return nil
  515. }
  516. expanded, err = exec.LookPath(bin + distSuffix)
  517. if err != nil {
  518. // Purposely not returning error
  519. return nil
  520. }
  521. return CreateSymlink(expanded, expanded[:len(expanded)-len(distSuffix)])
  522. }
  523. func setupLogging(config *Config) error {
  524. if config.LogFile == "" {
  525. return nil
  526. }
  527. if err := createDirs(path.Dir(config.LogFile)); err != nil {
  528. return err
  529. }
  530. output, err := os.OpenFile(config.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  531. if err != nil {
  532. return err
  533. }
  534. syscall.Dup3(int(output.Fd()), int(os.Stdout.Fd()), 0)
  535. syscall.Dup3(int(output.Fd()), int(os.Stderr.Fd()), 0)
  536. return nil
  537. }
  538. func setUlimit(cfg *Config) error {
  539. var rLimit syscall.Rlimit
  540. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
  541. return err
  542. }
  543. if cfg.NoFiles == 0 {
  544. rLimit.Max = 1000000
  545. } else {
  546. rLimit.Max = cfg.NoFiles
  547. }
  548. rLimit.Cur = rLimit.Max
  549. return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
  550. }
  551. func runOrExec(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  552. if err := secondPrepare(config, docker, args...); err != nil {
  553. return nil, err
  554. }
  555. cmd := path.Base(docker)
  556. if config != nil && config.CommandName != "" {
  557. cmd = config.CommandName
  558. }
  559. if cmd == "dockerd" && len(args) > 1 && args[0] == "daemon" {
  560. args = args[1:]
  561. }
  562. return execDocker(config, docker, cmd, args)
  563. }
  564. func LaunchDocker(config *Config, docker string, args ...string) (*exec.Cmd, error) {
  565. if err := PrepareFs(config); err != nil {
  566. return nil, err
  567. }
  568. return runOrExec(config, docker, args...)
  569. }
  570. func Main() {
  571. log.InitLogger()
  572. if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
  573. log.SetLevel(log.DebugLevel)
  574. }
  575. if len(os.Args) < 2 {
  576. log.Fatalf("Usage Example: %s /usr/bin/docker -d -D", os.Args[0])
  577. }
  578. args := []string{}
  579. if len(os.Args) > 1 {
  580. args = os.Args[2:]
  581. }
  582. var config Config
  583. args = ParseConfig(&config, args...)
  584. if os.Getenv("DOCKER_LAUNCH_REAP") == "true" {
  585. config.Fork = true
  586. config.PidOne = true
  587. }
  588. log.Debugf("Launch config %#v", config)
  589. _, err := LaunchDocker(&config, os.Args[1], args...)
  590. if err != nil {
  591. log.Fatal(err)
  592. }
  593. }