init.go 14 KB

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