init.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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/cmd/control/service"
  14. "github.com/rancher/os/config"
  15. "github.com/rancher/os/dfs"
  16. "github.com/rancher/os/log"
  17. "github.com/rancher/os/util"
  18. "github.com/rancher/os/util/network"
  19. )
  20. const (
  21. state string = "/state"
  22. boot2DockerMagic string = "boot2docker, please format-me"
  23. tmpfsMagic int64 = 0x01021994
  24. ramfsMagic int64 = 0x858458f6
  25. )
  26. var (
  27. mountConfig = dfs.Config{
  28. CgroupHierarchy: map[string]string{
  29. "cpu": "cpu",
  30. "cpuacct": "cpu",
  31. "net_cls": "net_cls",
  32. "net_prio": "net_cls",
  33. },
  34. }
  35. )
  36. func loadModules(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  37. mounted := map[string]bool{}
  38. f, err := os.Open("/proc/modules")
  39. if err != nil {
  40. return cfg, err
  41. }
  42. defer f.Close()
  43. reader := bufio.NewScanner(f)
  44. for reader.Scan() {
  45. mounted[strings.SplitN(reader.Text(), " ", 2)[0]] = true
  46. }
  47. for _, module := range cfg.Rancher.Modules {
  48. if mounted[module] {
  49. continue
  50. }
  51. log.Debugf("Loading module %s", module)
  52. cmd := exec.Command("modprobe", module)
  53. cmd.Stdout = os.Stdout
  54. cmd.Stderr = os.Stderr
  55. if err := cmd.Run(); err != nil {
  56. log.Errorf("Could not load module %s, err %v", module, err)
  57. }
  58. }
  59. return cfg, nil
  60. }
  61. func sysInit(c *config.CloudConfig) (*config.CloudConfig, error) {
  62. args := append([]string{config.SysInitBin}, os.Args[1:]...)
  63. cmd := &exec.Cmd{
  64. Path: config.RosBin,
  65. Args: args,
  66. }
  67. cmd.Stdin = os.Stdin
  68. cmd.Stderr = os.Stderr
  69. cmd.Stdout = os.Stdout
  70. if err := cmd.Start(); err != nil {
  71. return c, err
  72. }
  73. return c, os.Stdin.Close()
  74. }
  75. func MainInit() {
  76. log.InitLogger()
  77. // TODO: this breaks and does nothing if the cfg is invalid (or is it due to threading?)
  78. defer func() {
  79. if r := recover(); r != nil {
  80. fmt.Printf("Starting Recovery console: %v\n", r)
  81. recovery(nil)
  82. }
  83. }()
  84. if err := RunInit(); err != nil {
  85. log.Fatal(err)
  86. }
  87. }
  88. func mountConfigured(display, dev, fsType, target string) error {
  89. var err error
  90. if dev == "" {
  91. return nil
  92. }
  93. dev = util.ResolveDevice(dev)
  94. if dev == "" {
  95. return fmt.Errorf("Could not resolve device %q", dev)
  96. }
  97. if fsType == "auto" {
  98. fsType, err = util.GetFsType(dev)
  99. }
  100. if err != nil {
  101. return err
  102. }
  103. log.Debugf("FsType has been set to %s", fsType)
  104. log.Infof("Mounting %s device %s to %s", display, dev, target)
  105. return util.Mount(dev, target, fsType, "")
  106. }
  107. func mountState(cfg *config.CloudConfig) error {
  108. return mountConfigured("state", cfg.Rancher.State.Dev, cfg.Rancher.State.FsType, state)
  109. }
  110. func mountOem(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  111. if cfg == nil {
  112. cfg = config.LoadConfig()
  113. }
  114. if err := mountConfigured("oem", cfg.Rancher.State.OemDev, cfg.Rancher.State.OemFsType, config.OEM); err != nil {
  115. log.Debugf("Not mounting OEM: %v", err)
  116. } else {
  117. log.Infof("Mounted OEM: %s", cfg.Rancher.State.OemDev)
  118. }
  119. return cfg, nil
  120. }
  121. func tryMountState(cfg *config.CloudConfig) error {
  122. if mountState(cfg) == nil {
  123. return nil
  124. }
  125. // If we failed to mount lets run bootstrap and try again
  126. if err := bootstrap(cfg); err != nil {
  127. return err
  128. }
  129. return mountState(cfg)
  130. }
  131. func tryMountAndBootstrap(cfg *config.CloudConfig) (*config.CloudConfig, bool, error) {
  132. if !isInitrd() || cfg.Rancher.State.Dev == "" {
  133. return cfg, false, nil
  134. }
  135. if err := tryMountState(cfg); !cfg.Rancher.State.Required && err != nil {
  136. return cfg, false, nil
  137. } else if err != nil {
  138. return cfg, false, err
  139. }
  140. return cfg, true, nil
  141. }
  142. func getLaunchConfig(cfg *config.CloudConfig, dockerCfg *config.DockerConfig) (*dfs.Config, []string) {
  143. var launchConfig dfs.Config
  144. args := dfs.ParseConfig(&launchConfig, dockerCfg.FullArgs()...)
  145. launchConfig.DNSConfig.Nameservers = cfg.Rancher.Defaults.Network.DNS.Nameservers
  146. launchConfig.DNSConfig.Search = cfg.Rancher.Defaults.Network.DNS.Search
  147. launchConfig.Environment = dockerCfg.Environment
  148. if !cfg.Rancher.Debug {
  149. launchConfig.LogFile = config.SystemDockerLog
  150. }
  151. return &launchConfig, args
  152. }
  153. func isInitrd() bool {
  154. var stat syscall.Statfs_t
  155. syscall.Statfs("/", &stat)
  156. return int64(stat.Type) == tmpfsMagic || int64(stat.Type) == ramfsMagic
  157. }
  158. func setupSharedRoot(c *config.CloudConfig) (*config.CloudConfig, error) {
  159. if c.Rancher.NoSharedRoot {
  160. return c, nil
  161. }
  162. if isInitrd() {
  163. for _, i := range []string{"/mnt", "/media", "/var/lib/system-docker"} {
  164. if err := os.MkdirAll(i, 0755); err != nil {
  165. return c, err
  166. }
  167. if err := mount.Mount("tmpfs", i, "tmpfs", "rw"); err != nil {
  168. return c, err
  169. }
  170. if err := mount.MakeShared(i); err != nil {
  171. return c, err
  172. }
  173. }
  174. return c, nil
  175. }
  176. return c, mount.MakeShared("/")
  177. }
  178. func PrintConfig() {
  179. cfgString, err := config.Export(false, true)
  180. if err != nil {
  181. log.WithFields(log.Fields{"err": err}).Error("Error serializing config")
  182. } else {
  183. log.Debugf("Config: %s", cfgString)
  184. }
  185. }
  186. func RunInit() error {
  187. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  188. if isInitrd() {
  189. log.Debug("Booting off an in-memory filesystem")
  190. // Magic setting to tell Docker to do switch_root and not pivot_root
  191. os.Setenv("DOCKER_RAMDISK", "true")
  192. } else {
  193. log.Debug("Booting off a persistent filesystem")
  194. }
  195. boot2DockerEnvironment := false
  196. var shouldSwitchRoot bool
  197. hypervisor := ""
  198. configFiles := make(map[string][]byte)
  199. initFuncs := []config.CfgFuncData{
  200. config.CfgFuncData{"preparefs", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  201. return c, dfs.PrepareFs(&mountConfig)
  202. }},
  203. config.CfgFuncData{"save init cmdline", func(c *config.CloudConfig) (*config.CloudConfig, error) {
  204. // will this be passed to cloud-init-save?
  205. cmdLineArgs := strings.Join(os.Args, " ")
  206. config.SaveInitCmdline(cmdLineArgs)
  207. cfg := config.LoadConfig()
  208. log.Debugf("Cmdline debug = %s", cfg.Rancher.Debug)
  209. if cfg.Rancher.Debug {
  210. log.SetLevel(log.DebugLevel)
  211. } else {
  212. log.SetLevel(log.InfoLevel)
  213. }
  214. return cfg, nil
  215. }},
  216. config.CfgFuncData{"mount OEM", mountOem},
  217. config.CfgFuncData{"debug save cfg", func(_ *config.CloudConfig) (*config.CloudConfig, error) {
  218. PrintConfig()
  219. cfg := config.LoadConfig()
  220. return cfg, nil
  221. }},
  222. config.CfgFuncData{"load modules", loadModules},
  223. config.CfgFuncData{"recovery console", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  224. if cfg.Rancher.Recovery {
  225. recovery(nil)
  226. }
  227. return cfg, nil
  228. }},
  229. config.CfgFuncData{"b2d env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  230. if dev := util.ResolveDevice("LABEL=B2D_STATE"); dev != "" {
  231. boot2DockerEnvironment = true
  232. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  233. log.Infof("boot2DockerEnvironment %s: %s", cfg.Rancher.State.Dev, dev)
  234. return cfg, nil
  235. }
  236. devices := []string{"/dev/sda", "/dev/vda"}
  237. data := make([]byte, len(boot2DockerMagic))
  238. for _, device := range devices {
  239. f, err := os.Open(device)
  240. if err == nil {
  241. defer f.Close()
  242. _, err = f.Read(data)
  243. if err == nil && string(data) == boot2DockerMagic {
  244. boot2DockerEnvironment = true
  245. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  246. cfg.Rancher.State.Autoformat = []string{device}
  247. log.Infof("boot2DockerEnvironment %s: Autoformat %s", cfg.Rancher.State.Dev, cfg.Rancher.State.Autoformat[0])
  248. break
  249. }
  250. }
  251. }
  252. // save here so the bootstrap service can see it (when booting from iso, its very early)
  253. if boot2DockerEnvironment {
  254. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  255. log.Errorf("Failed to update rancher.state.dev: %v", err)
  256. }
  257. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  258. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  259. }
  260. }
  261. return config.LoadConfig(), nil
  262. }},
  263. config.CfgFuncData{"mount and bootstrap", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  264. var err error
  265. cfg, shouldSwitchRoot, err = tryMountAndBootstrap(cfg)
  266. if err != nil {
  267. return nil, err
  268. }
  269. return cfg, nil
  270. }},
  271. config.CfgFuncData{"cloud-init", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  272. cfg.Rancher.CloudInit.Datasources = config.LoadConfigWithPrefix(state).Rancher.CloudInit.Datasources
  273. hypervisor = util.GetHypervisor()
  274. if hypervisor == "vmware" {
  275. // add vmware to the end - we don't want to over-ride an choices the user has made
  276. cfg.Rancher.CloudInit.Datasources = append(cfg.Rancher.CloudInit.Datasources, hypervisor)
  277. if err := config.Set("rancher.cloud_init.datasources", cfg.Rancher.CloudInit.Datasources); err != nil {
  278. log.Error(err)
  279. }
  280. }
  281. log.Infof("init, runCloudInitServices(%v)", cfg.Rancher.CloudInit.Datasources)
  282. if err := runCloudInitServices(cfg); err != nil {
  283. log.Error(err)
  284. }
  285. return config.LoadConfig(), nil
  286. }},
  287. config.CfgFuncData{"read cfg and log files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  288. filesToCopy := []string{
  289. config.CloudConfigInitFile,
  290. config.CloudConfigBootFile,
  291. config.CloudConfigNetworkFile,
  292. config.MetaDataFile,
  293. }
  294. // And all the files in /var/log/boot/
  295. // TODO: I wonder if we can put this code into the log module, and have things write to the buffer until we FsReady()
  296. bootLog := "/var/log/boot/"
  297. if files, err := ioutil.ReadDir(bootLog); err == nil {
  298. for _, file := range files {
  299. filePath := filepath.Join(bootLog, file.Name())
  300. filesToCopy = append(filesToCopy, filePath)
  301. }
  302. }
  303. for _, name := range filesToCopy {
  304. if _, err := os.Lstat(name); !os.IsNotExist(err) {
  305. content, err := ioutil.ReadFile(name)
  306. if err != nil {
  307. log.Errorf("read cfg file (%s) %s", name, err)
  308. continue
  309. }
  310. log.Debugf("Saved %s to memory", name)
  311. configFiles[name] = content
  312. }
  313. }
  314. return cfg, nil
  315. }},
  316. config.CfgFuncData{"switchroot", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  317. if !shouldSwitchRoot {
  318. return cfg, nil
  319. }
  320. log.Debugf("Switching to new root at %s %s", state, cfg.Rancher.State.Directory)
  321. if err := switchRoot(state, cfg.Rancher.State.Directory, cfg.Rancher.RmUsr); err != nil {
  322. return cfg, err
  323. }
  324. return cfg, nil
  325. }},
  326. config.CfgFuncData{"mount OEM2", mountOem},
  327. config.CfgFuncData{"write cfg and log files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  328. for name, content := range configFiles {
  329. dirMode := os.ModeDir | 0755
  330. fileMode := os.FileMode(0444)
  331. if strings.HasPrefix(name, "/var/lib/rancher/conf/") {
  332. // only make the conf files harder to get to
  333. dirMode = os.ModeDir | 0700
  334. fileMode = os.FileMode(0400)
  335. }
  336. if err := os.MkdirAll(filepath.Dir(name), dirMode); err != nil {
  337. log.Error(err)
  338. }
  339. if err := util.WriteFileAtomic(name, content, fileMode); err != nil {
  340. log.Error(err)
  341. }
  342. log.Infof("Wrote log to %s", name)
  343. }
  344. if err := os.MkdirAll(config.VarRancherDir, os.ModeDir|0755); err != nil {
  345. log.Error(err)
  346. }
  347. if err := os.Chmod(config.VarRancherDir, os.ModeDir|0755); err != nil {
  348. log.Error(err)
  349. }
  350. log.FsReady()
  351. log.Debugf("WARNING: switchroot and mount OEM2 phases not written to log file")
  352. return cfg, nil
  353. }},
  354. config.CfgFuncData{"b2d Env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  355. if boot2DockerEnvironment {
  356. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  357. log.Errorf("Failed to update rancher.state.dev: %v", err)
  358. }
  359. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  360. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  361. }
  362. }
  363. return config.LoadConfig(), nil
  364. }},
  365. config.CfgFuncData{"hypervisor tools", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  366. enableHypervisorService(cfg, hypervisor)
  367. return config.LoadConfig(), nil
  368. }},
  369. config.CfgFuncData{"preparefs2", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  370. return cfg, dfs.PrepareFs(&mountConfig)
  371. }},
  372. config.CfgFuncData{"load modules2", loadModules},
  373. config.CfgFuncData{"set proxy env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  374. network.SetProxyEnvironmentVariables(cfg)
  375. return cfg, nil
  376. }},
  377. config.CfgFuncData{"init SELinux", initializeSelinux},
  378. config.CfgFuncData{"setupSharedRoot", setupSharedRoot},
  379. config.CfgFuncData{"sysinit", sysInit},
  380. }
  381. cfg, err := config.ChainCfgFuncs(nil, initFuncs)
  382. if err != nil {
  383. recovery(err)
  384. }
  385. launchConfig, args := getLaunchConfig(cfg, &cfg.Rancher.SystemDocker)
  386. launchConfig.Fork = !cfg.Rancher.SystemDocker.Exec
  387. //launchConfig.NoLog = true
  388. log.Info("Launching System Docker")
  389. _, err = dfs.LaunchDocker(launchConfig, config.SystemDockerBin, args...)
  390. if err != nil {
  391. log.Errorf("Error Launching System Docker: %s", err)
  392. recovery(err)
  393. return err
  394. }
  395. // Code never gets here - rancher.system_docker.exec=true
  396. return pidOne()
  397. }
  398. func enableHypervisorService(cfg *config.CloudConfig, hypervisorName string) {
  399. if hypervisorName == "" {
  400. return
  401. }
  402. if hypervisorName == "vmware" {
  403. hypervisorName = "open"
  404. }
  405. serviceName := hypervisorName + "-vm-tools"
  406. if !cfg.Rancher.HypervisorService {
  407. log.Infof("Skipping %s as `rancher.hypervisor_service` is set to false", serviceName)
  408. return
  409. }
  410. // check quickly to see if there is a yml file available
  411. if service.ValidService(serviceName, cfg) {
  412. log.Infof("Setting rancher.services_include. %s=true", serviceName)
  413. if err := config.Set("rancher.services_include."+serviceName, "true"); err != nil {
  414. log.Error(err)
  415. }
  416. } else {
  417. log.Infof("Skipping %s, can't get %s.yml file", serviceName, serviceName)
  418. }
  419. }