init.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // +build linux
  2. package init
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "strings"
  10. "syscall"
  11. "github.com/docker/docker/pkg/mount"
  12. "github.com/rancher/os/cmd/cloudinitsave"
  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. // TODO: log.InitLogger()
  76. if err := RunInit(); err != nil {
  77. log.Fatal(err)
  78. }
  79. }
  80. func mountConfigured(display, dev, fsType, target string) error {
  81. var err error
  82. if dev == "" {
  83. return nil
  84. }
  85. dev = util.ResolveDevice(dev)
  86. if dev == "" {
  87. return fmt.Errorf("Could not resolve device %q", dev)
  88. }
  89. if fsType == "auto" {
  90. fsType, err = util.GetFsType(dev)
  91. }
  92. if err != nil {
  93. return err
  94. }
  95. log.Debugf("FsType has been set to %s", fsType)
  96. log.Infof("Mounting %s device %s to %s", display, dev, target)
  97. return util.Mount(dev, target, fsType, "")
  98. }
  99. func mountState(cfg *config.CloudConfig) error {
  100. return mountConfigured("state", cfg.Rancher.State.Dev, cfg.Rancher.State.FsType, state)
  101. }
  102. func mountOem(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  103. if cfg == nil {
  104. cfg = config.LoadConfig()
  105. }
  106. if err := mountConfigured("oem", cfg.Rancher.State.OemDev, cfg.Rancher.State.OemFsType, config.OEM); err != nil {
  107. log.Debugf("Not mounting OEM: %v", err)
  108. } else {
  109. log.Infof("Mounted OEM: %s", cfg.Rancher.State.OemDev)
  110. }
  111. return cfg, nil
  112. }
  113. func tryMountState(cfg *config.CloudConfig) error {
  114. if mountState(cfg) == nil {
  115. return nil
  116. }
  117. // If we failed to mount lets run bootstrap and try again
  118. if err := bootstrap(cfg); err != nil {
  119. return err
  120. }
  121. return mountState(cfg)
  122. }
  123. func tryMountAndBootstrap(cfg *config.CloudConfig) (*config.CloudConfig, bool, error) {
  124. if !isInitrd() || cfg.Rancher.State.Dev == "" {
  125. return cfg, false, nil
  126. }
  127. if err := tryMountState(cfg); !cfg.Rancher.State.Required && err != nil {
  128. return cfg, false, nil
  129. } else if err != nil {
  130. return cfg, false, err
  131. }
  132. return cfg, true, nil
  133. }
  134. func getLaunchConfig(cfg *config.CloudConfig, dockerCfg *config.DockerConfig) (*dfs.Config, []string) {
  135. var launchConfig dfs.Config
  136. args := dfs.ParseConfig(&launchConfig, dockerCfg.FullArgs()...)
  137. launchConfig.DNSConfig.Nameservers = cfg.Rancher.Defaults.Network.DNS.Nameservers
  138. launchConfig.DNSConfig.Search = cfg.Rancher.Defaults.Network.DNS.Search
  139. launchConfig.Environment = dockerCfg.Environment
  140. if !cfg.Rancher.Debug {
  141. launchConfig.LogFile = config.SystemDockerLog
  142. }
  143. return &launchConfig, args
  144. }
  145. func isInitrd() bool {
  146. var stat syscall.Statfs_t
  147. syscall.Statfs("/", &stat)
  148. return int64(stat.Type) == tmpfsMagic || int64(stat.Type) == ramfsMagic
  149. }
  150. func setupSharedRoot(c *config.CloudConfig) (*config.CloudConfig, error) {
  151. if c.Rancher.NoSharedRoot {
  152. return c, nil
  153. }
  154. if isInitrd() {
  155. for _, i := range []string{"/mnt", "/media", "/var/lib/system-docker"} {
  156. if err := os.MkdirAll(i, 0755); err != nil {
  157. return c, err
  158. }
  159. if err := mount.Mount("tmpfs", i, "tmpfs", "rw"); err != nil {
  160. return c, err
  161. }
  162. if err := mount.MakeShared(i); err != nil {
  163. return c, err
  164. }
  165. }
  166. return c, nil
  167. }
  168. return c, mount.MakeShared("/")
  169. }
  170. func RunInit() error {
  171. os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")
  172. if isInitrd() {
  173. log.Debug("Booting off an in-memory filesystem")
  174. // Magic setting to tell Docker to do switch_root and not pivot_root
  175. os.Setenv("DOCKER_RAMDISK", "true")
  176. } else {
  177. log.Debug("Booting off a persistent filesystem")
  178. }
  179. boot2DockerEnvironment := false
  180. var shouldSwitchRoot bool
  181. var cloudConfigBootFile []byte
  182. var metadataFile []byte
  183. initFuncs := []config.CfgFunc{
  184. func(c *config.CloudConfig) (*config.CloudConfig, error) {
  185. return c, dfs.PrepareFs(&mountConfig)
  186. },
  187. mountOem,
  188. func(_ *config.CloudConfig) (*config.CloudConfig, error) {
  189. cfg := config.LoadConfig()
  190. if cfg.Rancher.Debug {
  191. cfgString, err := config.Export(false, true)
  192. if err != nil {
  193. log.WithFields(log.Fields{"err": err}).Error("Error serializing config")
  194. } else {
  195. log.Debugf("Config: %s", cfgString)
  196. }
  197. }
  198. return cfg, nil
  199. },
  200. loadModules,
  201. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  202. if util.ResolveDevice("LABEL=B2D_STATE") != "" {
  203. boot2DockerEnvironment = true
  204. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  205. return cfg, nil
  206. }
  207. devices := []string{"/dev/sda", "/dev/vda"}
  208. data := make([]byte, len(boot2DockerMagic))
  209. for _, device := range devices {
  210. f, err := os.Open(device)
  211. if err == nil {
  212. defer f.Close()
  213. _, err = f.Read(data)
  214. if err == nil && string(data) == boot2DockerMagic {
  215. boot2DockerEnvironment = true
  216. cfg.Rancher.State.Dev = "LABEL=B2D_STATE"
  217. cfg.Rancher.State.Autoformat = []string{device}
  218. break
  219. }
  220. }
  221. }
  222. // save here so the bootstrap service can see it (when booting from iso, its very early)
  223. if boot2DockerEnvironment {
  224. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  225. log.Errorf("Failed to update rancher.state.dev: %v", err)
  226. }
  227. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  228. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  229. }
  230. }
  231. return config.LoadConfig(), nil
  232. },
  233. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  234. var err error
  235. cfg, shouldSwitchRoot, err = tryMountAndBootstrap(cfg)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return cfg, nil
  240. },
  241. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  242. cfg.Rancher.CloudInit.Datasources = config.LoadConfigWithPrefix(state).Rancher.CloudInit.Datasources
  243. if err := config.Set("rancher.cloud_init.datasources", cfg.Rancher.CloudInit.Datasources); err != nil {
  244. log.Error(err)
  245. }
  246. network := false
  247. for _, datasource := range cfg.Rancher.CloudInit.Datasources {
  248. if cloudinitsave.RequiresNetwork(datasource) {
  249. network = true
  250. break
  251. }
  252. }
  253. if network {
  254. if err := runCloudInitServices(cfg); err != nil {
  255. log.Error(err)
  256. }
  257. } else {
  258. if err := cloudinitsave.MountConfigDrive(); err != nil {
  259. log.Error(err)
  260. }
  261. if err := cloudinitsave.SaveCloudConfig(false); err != nil {
  262. log.Error(err)
  263. }
  264. if err := cloudinitsave.UnmountConfigDrive(); err != nil {
  265. log.Error(err)
  266. }
  267. }
  268. return cfg, nil
  269. },
  270. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  271. var err error
  272. cloudConfigBootFile, err = ioutil.ReadFile(config.CloudConfigBootFile)
  273. if err != nil {
  274. log.Error(err)
  275. }
  276. metadataFile, err = ioutil.ReadFile(config.MetaDataFile)
  277. if err != nil {
  278. log.Error(err)
  279. }
  280. return cfg, nil
  281. },
  282. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  283. if !shouldSwitchRoot {
  284. return cfg, nil
  285. }
  286. log.Debugf("Switching to new root at %s %s", state, cfg.Rancher.State.Directory)
  287. if err := switchRoot(state, cfg.Rancher.State.Directory, cfg.Rancher.RmUsr); err != nil {
  288. return cfg, err
  289. }
  290. return cfg, nil
  291. },
  292. mountOem,
  293. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  294. if err := os.MkdirAll(config.CloudConfigDir, os.ModeDir|0755); err != nil {
  295. log.Error(err)
  296. }
  297. if err := util.WriteFileAtomic(config.CloudConfigBootFile, cloudConfigBootFile, 400); err != nil {
  298. log.Error(err)
  299. }
  300. if err := util.WriteFileAtomic(config.MetaDataFile, metadataFile, 400); err != nil {
  301. log.Error(err)
  302. }
  303. return cfg, nil
  304. },
  305. func(cfg *config.CloudConfig) (*config.CloudConfig, error) {
  306. if boot2DockerEnvironment {
  307. if err := config.Set("rancher.state.dev", cfg.Rancher.State.Dev); err != nil {
  308. log.Errorf("Failed to update rancher.state.dev: %v", err)
  309. }
  310. if err := config.Set("rancher.state.autoformat", cfg.Rancher.State.Autoformat); err != nil {
  311. log.Errorf("Failed to update rancher.state.autoformat: %v", err)
  312. }
  313. }
  314. return config.LoadConfig(), nil
  315. },
  316. func(c *config.CloudConfig) (*config.CloudConfig, error) {
  317. return c, dfs.PrepareFs(&mountConfig)
  318. },
  319. loadModules,
  320. func(c *config.CloudConfig) (*config.CloudConfig, error) {
  321. network.SetProxyEnvironmentVariables(c)
  322. return c, nil
  323. },
  324. initializeSelinux,
  325. setupSharedRoot,
  326. sysInit,
  327. }
  328. cfg, err := config.ChainCfgFuncs(nil, initFuncs...)
  329. if err != nil {
  330. return err
  331. }
  332. launchConfig, args := getLaunchConfig(cfg, &cfg.Rancher.SystemDocker)
  333. launchConfig.Fork = !cfg.Rancher.SystemDocker.Exec
  334. log.Info("Launching System Docker")
  335. _, err = dfs.LaunchDocker(launchConfig, config.SystemDockerBin, args...)
  336. if err != nil {
  337. return err
  338. }
  339. return pidOne()
  340. }