init.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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/config/cmdline"
  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. // the Kernel Patch added for RancherOS passes `--` (only) elided kernel boot params to the init process
  205. cmdLineArgs := strings.Join(os.Args, " ")
  206. config.SaveInitCmdline(cmdLineArgs)
  207. cfg := config.LoadConfig()
  208. log.Debugf("Cmdline debug = %t", 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 == "" {
  275. log.Infof("ros init: No Detected Hypervisor")
  276. } else {
  277. log.Infof("ros init: Detected Hypervisor: %s", hypervisor)
  278. }
  279. if hypervisor == "vmware" {
  280. // add vmware to the end - we don't want to over-ride an choices the user has made
  281. cfg.Rancher.CloudInit.Datasources = append(cfg.Rancher.CloudInit.Datasources, hypervisor)
  282. }
  283. if err := config.Set("rancher.cloud_init.datasources", cfg.Rancher.CloudInit.Datasources); err != nil {
  284. log.Error(err)
  285. }
  286. log.Infof("init, runCloudInitServices(%v)", cfg.Rancher.CloudInit.Datasources)
  287. if err := runCloudInitServices(cfg); err != nil {
  288. log.Error(err)
  289. }
  290. // It'd be nice to push to rsyslog before this, but we don't have network
  291. log.AddRSyslogHook()
  292. return config.LoadConfig(), nil
  293. }},
  294. config.CfgFuncData{"read cfg and log files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  295. filesToCopy := []string{
  296. config.CloudConfigInitFile,
  297. config.CloudConfigBootFile,
  298. config.CloudConfigNetworkFile,
  299. config.MetaDataFile,
  300. config.EtcResolvConfFile,
  301. }
  302. // And all the files in /var/log/boot/
  303. // TODO: I wonder if we can put this code into the log module, and have things write to the buffer until we FsReady()
  304. bootLog := "/var/log/"
  305. if files, err := ioutil.ReadDir(bootLog); err == nil {
  306. for _, file := range files {
  307. if !file.IsDir() {
  308. filePath := filepath.Join(bootLog, file.Name())
  309. filesToCopy = append(filesToCopy, filePath)
  310. log.Debugf("Swizzle: Found %s to save", filePath)
  311. }
  312. }
  313. }
  314. bootLog = "/var/log/boot/"
  315. if files, err := ioutil.ReadDir(bootLog); err == nil {
  316. for _, file := range files {
  317. filePath := filepath.Join(bootLog, file.Name())
  318. filesToCopy = append(filesToCopy, filePath)
  319. log.Debugf("Swizzle: Found %s to save", filePath)
  320. }
  321. }
  322. for _, name := range filesToCopy {
  323. if _, err := os.Lstat(name); !os.IsNotExist(err) {
  324. content, err := ioutil.ReadFile(name)
  325. if err != nil {
  326. log.Errorf("read cfg file (%s) %s", name, err)
  327. continue
  328. }
  329. log.Debugf("Swizzle: Saved %s to memory", name)
  330. configFiles[name] = content
  331. }
  332. }
  333. return cfg, nil
  334. }},
  335. config.CfgFuncData{"switchroot", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  336. if !shouldSwitchRoot {
  337. return cfg, nil
  338. }
  339. log.Debugf("Switching to new root at %s %s", state, cfg.Rancher.State.Directory)
  340. if err := switchRoot(state, cfg.Rancher.State.Directory, cfg.Rancher.RmUsr); err != nil {
  341. return cfg, err
  342. }
  343. return cfg, nil
  344. }},
  345. config.CfgFuncData{"mount OEM2", mountOem},
  346. config.CfgFuncData{"write cfg and log files", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  347. for name, content := range configFiles {
  348. dirMode := os.ModeDir | 0755
  349. fileMode := os.FileMode(0444)
  350. if strings.HasPrefix(name, "/var/lib/rancher/conf/") {
  351. // only make the conf files harder to get to
  352. dirMode = os.ModeDir | 0700
  353. fileMode = os.FileMode(0400)
  354. }
  355. if err := os.MkdirAll(filepath.Dir(name), dirMode); err != nil {
  356. log.Error(err)
  357. }
  358. if err := util.WriteFileAtomic(name, content, fileMode); err != nil {
  359. log.Error(err)
  360. }
  361. log.Infof("Swizzle: Wrote file to %s", name)
  362. }
  363. if err := os.MkdirAll(config.VarRancherDir, os.ModeDir|0755); err != nil {
  364. log.Error(err)
  365. }
  366. if err := os.Chmod(config.VarRancherDir, os.ModeDir|0755); err != nil {
  367. log.Error(err)
  368. }
  369. log.FsReady()
  370. log.Debugf("WARNING: switchroot and mount OEM2 phases not written to log file")
  371. // update docker-sys bridge setting
  372. if dockerSysSubnet := cmdline.GetCmdline(config.RKPDockerSysBridgeSubnet); dockerSysSubnet != "" {
  373. val := dockerSysSubnet.(string)
  374. config.SaveCNISubnet(val, config.CNIBridgeConfigFile)
  375. }
  376. return cfg, nil
  377. }},
  378. config.CfgFuncData{"b2d Env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  379. log.Debugf("memory Resolve.conf == [%s]", configFiles["/etc/resolv.conf"])
  380. if boot2DockerEnvironment {
  381. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  382. log.Errorf("Failed to update rancher.state.dev: %v", err)
  383. }
  384. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  385. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  386. }
  387. }
  388. return config.LoadConfig(), nil
  389. }},
  390. config.CfgFuncData{"hypervisor tools", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  391. enableHypervisorService(cfg, hypervisor)
  392. return config.LoadConfig(), nil
  393. }},
  394. config.CfgFuncData{"preparefs2", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  395. return cfg, dfs.PrepareFs(&mountConfig)
  396. }},
  397. config.CfgFuncData{"load modules2", loadModules},
  398. config.CfgFuncData{"set proxy env", func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  399. network.SetProxyEnvironmentVariables()
  400. return cfg, nil
  401. }},
  402. config.CfgFuncData{"init SELinux", initializeSelinux},
  403. config.CfgFuncData{"setupSharedRoot", setupSharedRoot},
  404. config.CfgFuncData{"sysinit", sysInit},
  405. }
  406. cfg, err := config.ChainCfgFuncs(nil, initFuncs)
  407. if err != nil {
  408. recovery(err)
  409. }
  410. launchConfig, args := getLaunchConfig(cfg, &cfg.Rancher.SystemDocker)
  411. launchConfig.Fork = !cfg.Rancher.SystemDocker.Exec
  412. //launchConfig.NoLog = true
  413. log.Info("Launching System Docker")
  414. _, err = dfs.LaunchDocker(launchConfig, config.SystemDockerBin, args...)
  415. if err != nil {
  416. log.Errorf("Error Launching System Docker: %s", err)
  417. recovery(err)
  418. return err
  419. }
  420. // Code never gets here - rancher.system_docker.exec=true
  421. return pidOne()
  422. }
  423. func enableHypervisorService(cfg *config.CloudConfig, hypervisorName string) {
  424. if hypervisorName == "" {
  425. return
  426. }
  427. // only enable open-vm-tools for vmware
  428. // these services(xenhvm-vm-tools, kvm-vm-tools, hyperv-vm-tools and bhyve-vm-tools) don't exist yet
  429. if hypervisorName == "vmware" {
  430. hypervisorName = "open"
  431. serviceName := hypervisorName + "-vm-tools"
  432. if !cfg.Rancher.HypervisorService {
  433. log.Infof("Skipping %s as `rancher.hypervisor_service` is set to false", serviceName)
  434. return
  435. }
  436. // Check removed - there's an x509 cert failure on first boot of an installed system
  437. // check quickly to see if there is a yml file available
  438. // if service.ValidService(serviceName, cfg) {
  439. log.Infof("Setting rancher.services_include. %s=true", serviceName)
  440. if err := config.Set("rancher.services_include."+serviceName, "true"); err != nil {
  441. log.Error(err)
  442. }
  443. // } else {
  444. // log.Infof("Skipping %s, can't get %s.yml file", serviceName, serviceName)
  445. // }
  446. }
  447. }