init.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // +build linux
  2. package init
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "syscall"
  12. "github.com/docker/docker/pkg/mount"
  13. "github.com/rancher/os/config"
  14. "github.com/rancher/os/dfs"
  15. "github.com/rancher/os/log"
  16. "github.com/rancher/os/util"
  17. "github.com/rancher/os/util/network"
  18. )
  19. const (
  20. state string = "/state"
  21. boot2DockerMagic string = "boot2docker, please format-me"
  22. tmpfsMagic int64 = 0x01021994
  23. ramfsMagic int64 = 0x858458f6
  24. )
  25. var (
  26. mountConfig = dfs.Config{
  27. CgroupHierarchy: map[string]string{
  28. "cpu": "cpu",
  29. "cpuacct": "cpu",
  30. "net_cls": "net_cls",
  31. "net_prio": "net_cls",
  32. },
  33. }
  34. )
  35. func loadModules(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  36. mounted := map[string]bool{}
  37. f, err := os.Open("/proc/modules")
  38. if err != nil {
  39. return cfg, err
  40. }
  41. defer f.Close()
  42. reader := bufio.NewScanner(f)
  43. for reader.Scan() {
  44. mounted[strings.SplitN(reader.Text(), " ", 2)[0]] = true
  45. }
  46. for _, module := range cfg.Rancher.Modules {
  47. if mounted[module] {
  48. continue
  49. }
  50. log.Debugf("Loading module %s", module)
  51. cmd := exec.Command("modprobe", module)
  52. cmd.Stdout = os.Stdout
  53. cmd.Stderr = os.Stderr
  54. if err := cmd.Run(); err != nil {
  55. log.Errorf("Could not load module %s, err %v", module, err)
  56. }
  57. }
  58. return cfg, nil
  59. }
  60. func sysInit(c *config.CloudConfig) (*config.CloudConfig, error) {
  61. args := append([]string{config.SysInitBin}, os.Args[1:]...)
  62. cmd := &exec.Cmd{
  63. Path: config.RosBin,
  64. Args: args,
  65. }
  66. cmd.Stdin = os.Stdin
  67. cmd.Stderr = os.Stderr
  68. cmd.Stdout = os.Stdout
  69. if err := cmd.Start(); err != nil {
  70. return c, err
  71. }
  72. return c, os.Stdin.Close()
  73. }
  74. func MainInit() {
  75. log.InitLogger()
  76. log.Infof("MainInit() start")
  77. if err := RunInit(); err != nil {
  78. log.Fatal(err)
  79. }
  80. }
  81. func mountConfigured(display, dev, fsType, target string) error {
  82. var err error
  83. if dev == "" {
  84. return nil
  85. }
  86. dev = util.ResolveDevice(dev)
  87. if dev == "" {
  88. return fmt.Errorf("Could not resolve device %q", dev)
  89. }
  90. if fsType == "auto" {
  91. fsType, err = util.GetFsType(dev)
  92. }
  93. if err != nil {
  94. return err
  95. }
  96. log.Debugf("FsType has been set to %s", fsType)
  97. log.Infof("Mounting %s device %s to %s", display, dev, target)
  98. return util.Mount(dev, target, fsType, "")
  99. }
  100. func mountState(cfg *config.CloudConfig) error {
  101. return mountConfigured("state", cfg.Rancher.State.Dev, cfg.Rancher.State.FsType, state)
  102. }
  103. func mountOem(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  104. if cfg == nil {
  105. cfg = config.LoadConfig()
  106. }
  107. if err := mountConfigured("oem", cfg.Rancher.State.OemDev, cfg.Rancher.State.OemFsType, config.OEM); err != nil {
  108. log.Debugf("Not mounting OEM: %v", err)
  109. } else {
  110. log.Infof("Mounted OEM: %s", cfg.Rancher.State.OemDev)
  111. }
  112. return cfg, nil
  113. }
  114. func tryMountState(cfg *config.CloudConfig) error {
  115. if mountState(cfg) == nil {
  116. return nil
  117. }
  118. // If we failed to mount lets run bootstrap and try again
  119. if err := bootstrap(cfg); err != nil {
  120. return err
  121. }
  122. return mountState(cfg)
  123. }
  124. func tryMountAndBootstrap(cfg *config.CloudConfig) (*config.CloudConfig, bool, error) {
  125. if !isInitrd() || cfg.Rancher.State.Dev == "" {
  126. return cfg, false, nil
  127. }
  128. if err := tryMountState(cfg); !cfg.Rancher.State.Required && err != nil {
  129. return cfg, false, nil
  130. } else if err != nil {
  131. return cfg, false, err
  132. }
  133. return cfg, true, nil
  134. }
  135. func getLaunchConfig(cfg *config.CloudConfig, dockerCfg *config.DockerConfig) (*dfs.Config, []string) {
  136. var launchConfig dfs.Config
  137. args := dfs.ParseConfig(&launchConfig, dockerCfg.FullArgs()...)
  138. launchConfig.DNSConfig.Nameservers = cfg.Rancher.Defaults.Network.DNS.Nameservers
  139. launchConfig.DNSConfig.Search = cfg.Rancher.Defaults.Network.DNS.Search
  140. launchConfig.Environment = dockerCfg.Environment
  141. if !cfg.Rancher.Debug {
  142. launchConfig.LogFile = config.SystemDockerLog
  143. }
  144. return &launchConfig, args
  145. }
  146. func isInitrd() bool {
  147. var stat syscall.Statfs_t
  148. syscall.Statfs("/", &stat)
  149. return int64(stat.Type) == tmpfsMagic || int64(stat.Type) == ramfsMagic
  150. }
  151. func setupSharedRoot(c *config.CloudConfig) (*config.CloudConfig, error) {
  152. if c.Rancher.NoSharedRoot {
  153. return c, nil
  154. }
  155. if isInitrd() {
  156. for _, i := range []string{"/mnt", "/media", "/var/lib/system-docker"} {
  157. if err := os.MkdirAll(i, 0755); err != nil {
  158. return c, err
  159. }
  160. if err := mount.Mount("tmpfs", i, "tmpfs", "rw"); err != nil {
  161. return c, err
  162. }
  163. if err := mount.MakeShared(i); err != nil {
  164. return c, err
  165. }
  166. }
  167. return c, nil
  168. }
  169. return c, mount.MakeShared("/")
  170. }
  171. func RunInit() error {
  172. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  173. if isInitrd() {
  174. log.Debug("Booting off an in-memory filesystem")
  175. // Magic setting to tell Docker to do switch_root and not pivot_root
  176. os.Setenv("DOCKER_RAMDISK", "true")
  177. } else {
  178. log.Debug("Booting off a persistent filesystem")
  179. }
  180. boot2DockerEnvironment := false
  181. var shouldSwitchRoot bool
  182. configFiles := make(map[string][]byte)
  183. initFuncs := []config.CfgFuncData{
  184. config.CfgFuncData{"preparefs", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  185. return c, dfs.PrepareFs(&mountConfig)
  186. }},
  187. config.CfgFuncData{"save init cmdline", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  188. // will this be passed to cloud-init-save?
  189. cmdLineArgs := strings.Join(os.Args, " ")
  190. config.SaveInitCmdline(cmdLineArgs)
  191. return c, nil
  192. }},
  193. config.CfgFuncData{"mount OEM", mountOem},
  194. config.CfgFuncData{"debug save cfg", func(_ *config.CloudConfig) (*config.CloudConfig, error) {
  195. cfg := config.LoadConfig()
  196. if cfg.Rancher.Debug {
  197. cfgString, err := config.Export(false, true)
  198. if err != nil {
  199. log.WithFields(log.Fields{"err": err}).Error("Error serializing config")
  200. } else {
  201. log.Debugf("Config: %s", cfgString)
  202. }
  203. }
  204. return cfg, nil
  205. }},
  206. config.CfgFuncData{"load modules", loadModules},
  207. config.CfgFuncData{"b2d env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  208. if util.ResolveDevice("LABEL=B2D_STATE") != "" {
  209. boot2DockerEnvironment = true
  210. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  211. return cfg, nil
  212. }
  213. devices := []string{"/dev/sda", "/dev/vda"}
  214. data := make([]byte, len(boot2DockerMagic))
  215. for _, device := range devices {
  216. f, err := os.Open(device)
  217. if err == nil {
  218. defer f.Close()
  219. _, err = f.Read(data)
  220. if err == nil && string(data) == boot2DockerMagic {
  221. boot2DockerEnvironment = true
  222. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  223. cfg.Rancher.State.Autoformat = []string{device}
  224. break
  225. }
  226. }
  227. }
  228. // save here so the bootstrap service can see it (when booting from iso, its very early)
  229. if boot2DockerEnvironment {
  230. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  231. log.Errorf("Failed to update rancher.state.dev: %v", err)
  232. }
  233. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  234. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  235. }
  236. }
  237. return config.LoadConfig(), nil
  238. }},
  239. config.CfgFuncData{"mount and bootstrap", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  240. var err error
  241. cfg, shouldSwitchRoot, err = tryMountAndBootstrap(cfg)
  242. if err != nil {
  243. return nil, err
  244. }
  245. return cfg, nil
  246. }},
  247. config.CfgFuncData{"cloud-init", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  248. cfg.Rancher.CloudInit.Datasources = config.LoadConfigWithPrefix(state).Rancher.CloudInit.Datasources
  249. if err := config.Set("rancher.cloud_init.datasources", cfg.Rancher.CloudInit.Datasources); err != nil {
  250. log.Error(err)
  251. }
  252. log.Debug("init, runCloudInitServices()")
  253. if err := runCloudInitServices(cfg); err != nil {
  254. log.Error(err)
  255. }
  256. // return any newly detected network config.
  257. cfg = config.LoadConfig()
  258. return cfg, nil
  259. }},
  260. config.CfgFuncData{"read cfg files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  261. filesToCopy := []string{
  262. config.CloudConfigInitFile,
  263. config.CloudConfigBootFile,
  264. config.CloudConfigNetworkFile,
  265. config.MetaDataFile,
  266. }
  267. for _, name := range filesToCopy {
  268. if _, err := os.Lstat(name); !os.IsNotExist(err) {
  269. content, err := ioutil.ReadFile(name)
  270. if err != nil {
  271. log.Errorf("read cfg file (%s) %s", name, err)
  272. continue
  273. }
  274. configFiles[name] = content
  275. }
  276. }
  277. return cfg, nil
  278. }},
  279. config.CfgFuncData{"switchroot", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  280. if !shouldSwitchRoot {
  281. return cfg, nil
  282. }
  283. log.Debugf("Switching to new root at %s %s", state, cfg.Rancher.State.Directory)
  284. if err := switchRoot(state, cfg.Rancher.State.Directory, cfg.Rancher.RmUsr); err != nil {
  285. return cfg, err
  286. }
  287. return cfg, nil
  288. }},
  289. config.CfgFuncData{"mount OEM2", mountOem},
  290. config.CfgFuncData{"write cfg files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  291. for name, content := range configFiles {
  292. if err := os.MkdirAll(filepath.Dir(name), os.ModeDir|0700); err != nil {
  293. log.Error(err)
  294. }
  295. if err := util.WriteFileAtomic(name, content, 400); err != nil {
  296. log.Error(err)
  297. }
  298. }
  299. if err := os.MkdirAll(config.VarRancherDir, os.ModeDir|0755); err != nil {
  300. log.Error(err)
  301. }
  302. if err := os.Chmod(config.VarRancherDir, os.ModeDir|0755); err != nil {
  303. log.Error(err)
  304. }
  305. return cfg, nil
  306. }},
  307. config.CfgFuncData{"b2d Env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  308. if boot2DockerEnvironment {
  309. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  310. log.Errorf("Failed to update rancher.state.dev: %v", err)
  311. }
  312. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  313. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  314. }
  315. }
  316. return config.LoadConfig(), nil
  317. }},
  318. config.CfgFuncData{"preparefs2", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  319. return c, dfs.PrepareFs(&mountConfig)
  320. }},
  321. config.CfgFuncData{"load modules2", loadModules},
  322. config.CfgFuncData{"set proxy env", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  323. network.SetProxyEnvironmentVariables(c)
  324. return c, nil
  325. }},
  326. config.CfgFuncData{"init SELinux", initializeSelinux},
  327. config.CfgFuncData{"setupSharedRoot", setupSharedRoot},
  328. config.CfgFuncData{"sysinit", sysInit},
  329. }
  330. cfg, err := config.ChainCfgFuncs(nil, initFuncs)
  331. if err != nil {
  332. return err
  333. }
  334. launchConfig, args := getLaunchConfig(cfg, &cfg.Rancher.SystemDocker)
  335. launchConfig.Fork = !cfg.Rancher.SystemDocker.Exec
  336. log.Info("Launching System Docker")
  337. _, err = dfs.LaunchDocker(launchConfig, config.SystemDockerBin, args...)
  338. if err != nil {
  339. return err
  340. }
  341. return pidOne()
  342. }