console_init.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package control
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "text/template"
  13. "github.com/rancher/os/cmd/cloudinitexecute"
  14. "github.com/rancher/os/config"
  15. "github.com/rancher/os/config/cmdline"
  16. "github.com/rancher/os/pkg/compose"
  17. "github.com/rancher/os/pkg/log"
  18. "github.com/rancher/os/pkg/util"
  19. "github.com/codegangsta/cli"
  20. "golang.org/x/crypto/ssh/terminal"
  21. "golang.org/x/sys/unix"
  22. )
  23. const (
  24. consoleDone = "/run/console-done"
  25. dockerHome = "/home/docker"
  26. gettyCmd = "/sbin/agetty"
  27. rancherHome = "/home/rancher"
  28. startScript = "/opt/rancher/bin/start.sh"
  29. runLockDir = "/run/lock"
  30. )
  31. type symlink struct {
  32. oldname, newname string
  33. }
  34. func ConsoleInitMain() {
  35. if err := consoleInitFunc(); err != nil {
  36. log.Fatal(err)
  37. }
  38. }
  39. func consoleInitAction(c *cli.Context) error {
  40. return consoleInitFunc()
  41. }
  42. func createHomeDir(homedir string, uid, gid int) {
  43. if _, err := os.Stat(homedir); os.IsNotExist(err) {
  44. if err := os.MkdirAll(homedir, 0755); err != nil {
  45. log.Error(err)
  46. }
  47. if err := os.Chown(homedir, uid, gid); err != nil {
  48. log.Error(err)
  49. }
  50. }
  51. }
  52. func consoleInitFunc() error {
  53. cfg := config.LoadConfig()
  54. // Now that we're booted, stop writing debug messages to the console
  55. cmd := exec.Command("sudo", "dmesg", "--console-off")
  56. if err := cmd.Run(); err != nil {
  57. log.Error(err)
  58. }
  59. createHomeDir(rancherHome, 1100, 1100)
  60. createHomeDir(dockerHome, 1101, 1101)
  61. // some software need this dir, like open-iscsi
  62. if _, err := os.Stat(runLockDir); os.IsNotExist(err) {
  63. if err = os.Mkdir(runLockDir, 0755); err != nil {
  64. log.Error(err)
  65. }
  66. }
  67. ignorePassword := false
  68. for _, d := range cfg.Rancher.Disable {
  69. if d == "password" {
  70. ignorePassword = true
  71. break
  72. }
  73. }
  74. password := cmdline.GetCmdline("rancher.password")
  75. if !ignorePassword && password != "" {
  76. cmd := exec.Command("chpasswd")
  77. cmd.Stdin = strings.NewReader(fmt.Sprint("rancher:", password))
  78. if err := cmd.Run(); err != nil {
  79. log.Error(err)
  80. }
  81. cmd = exec.Command("bash", "-c", `sed -E -i 's/(rancher:.*:).*(:.*:.*:.*:.*:.*:.*)$/\1\2/' /etc/shadow`)
  82. if err := cmd.Run(); err != nil {
  83. log.Error(err)
  84. }
  85. }
  86. if err := setupSSH(cfg); err != nil {
  87. log.Error(err)
  88. }
  89. if err := writeRespawn("rancher", cfg.Rancher.SSH.Daemon, false); err != nil {
  90. log.Error(err)
  91. }
  92. if err := modifySshdConfig(cfg); err != nil {
  93. log.Error(err)
  94. }
  95. p, err := compose.GetProject(cfg, false, true)
  96. if err != nil {
  97. log.Error(err)
  98. }
  99. // check the multi engine service & generate the multi engine script
  100. for _, key := range p.ServiceConfigs.Keys() {
  101. serviceConfig, ok := p.ServiceConfigs.Get(key)
  102. if !ok {
  103. log.Errorf("Failed to get service config from the project")
  104. continue
  105. }
  106. if _, ok := serviceConfig.Labels[config.UserDockerLabel]; ok {
  107. err = util.GenerateDindEngineScript(serviceConfig.Labels[config.UserDockerLabel])
  108. if err != nil {
  109. log.Errorf("Failed to generate engine script: %v", err)
  110. continue
  111. }
  112. }
  113. }
  114. baseSymlink := symLinkEngineBinary(cfg.Rancher.Docker.Engine)
  115. if _, err := os.Stat(dockerCompletionFile); err == nil {
  116. baseSymlink = append(baseSymlink, symlink{
  117. dockerCompletionFile, dockerCompletionLinkFile,
  118. })
  119. }
  120. if cfg.Rancher.Console == "default" {
  121. // add iptables symlinks for default console
  122. baseSymlink = append(baseSymlink, []symlink{
  123. {"/usr/sbin/iptables", "/usr/sbin/iptables-save"},
  124. {"/usr/sbin/iptables", "/usr/sbin/iptables-restore"},
  125. {"/usr/sbin/iptables", "/usr/sbin/ip6tables"},
  126. {"/usr/sbin/iptables", "/usr/sbin/ip6tables-save"},
  127. {"/usr/sbin/iptables", "/usr/sbin/ip6tables-restore"},
  128. {"/usr/sbin/iptables", "/usr/bin/iptables-xml"},
  129. }...)
  130. }
  131. for _, link := range baseSymlink {
  132. syscall.Unlink(link.newname)
  133. if err := os.Symlink(link.oldname, link.newname); err != nil {
  134. log.Error(err)
  135. }
  136. }
  137. // mount systemd cgroups
  138. if err := os.MkdirAll("/sys/fs/cgroup/systemd", 0555); err != nil {
  139. log.Error(err)
  140. }
  141. if err := unix.Mount("cgroup", "/sys/fs/cgroup/systemd", "cgroup", 0, "none,name=systemd"); err != nil {
  142. log.Error(err)
  143. }
  144. // font backslashes need to be escaped for when issue is output! (but not the others..)
  145. if err := ioutil.WriteFile("/etc/issue", []byte(config.Banner), 0644); err != nil {
  146. log.Error(err)
  147. }
  148. // write out a profile.d file for the proxy settings.
  149. // maybe write these on the host and bindmount into everywhere?
  150. proxyLines := []string{}
  151. for _, k := range []string{"http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "no_proxy", "NO_PROXY"} {
  152. if v, ok := cfg.Rancher.Environment[k]; ok {
  153. proxyLines = append(proxyLines, fmt.Sprintf("export %s=%s", k, v))
  154. }
  155. }
  156. if len(proxyLines) > 0 {
  157. proxyString := strings.Join(proxyLines, "\n")
  158. proxyString = fmt.Sprintf("#!/bin/sh\n%s\n", proxyString)
  159. if err := ioutil.WriteFile("/etc/profile.d/proxy.sh", []byte(proxyString), 0755); err != nil {
  160. log.Error(err)
  161. }
  162. }
  163. // write out a profile.d file for the PATH settings.
  164. pathLines := []string{}
  165. for _, k := range []string{"PATH", "path"} {
  166. if v, ok := cfg.Rancher.Environment[k]; ok {
  167. for _, p := range strings.Split(v, ",") {
  168. pathLines = append(pathLines, fmt.Sprintf("export PATH=$PATH:%s", strings.TrimSpace(p)))
  169. }
  170. }
  171. }
  172. if len(pathLines) > 0 {
  173. pathString := strings.Join(pathLines, "\n")
  174. pathString = fmt.Sprintf("#!/bin/sh\n%s\n", pathString)
  175. if err := ioutil.WriteFile("/etc/profile.d/path.sh", []byte(pathString), 0755); err != nil {
  176. log.Error(err)
  177. }
  178. }
  179. cmd = exec.Command("bash", "-c", `echo $(/sbin/ifconfig | grep -B1 "inet addr" |awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' |awk -F: '{ print $1 ": " $3}') >> /etc/issue`)
  180. if err := cmd.Run(); err != nil {
  181. log.Error(err)
  182. }
  183. cloudinitexecute.ApplyConsole(cfg)
  184. if err := util.RunScript(config.CloudConfigScriptFile); err != nil {
  185. log.Error(err)
  186. }
  187. if err := util.RunScript(startScript); err != nil {
  188. log.Error(err)
  189. }
  190. if err := ioutil.WriteFile(consoleDone, []byte(CurrentConsole()), 0644); err != nil {
  191. log.Error(err)
  192. }
  193. if err := util.RunScript("/etc/rc.local"); err != nil {
  194. log.Error(err)
  195. }
  196. os.Setenv("TERM", "linux")
  197. respawnBinPath, err := exec.LookPath("respawn")
  198. if err != nil {
  199. return err
  200. }
  201. return syscall.Exec(respawnBinPath, []string{"respawn", "-f", "/etc/respawn.conf"}, os.Environ())
  202. }
  203. func generateRespawnConf(cmdline, user string, sshd, recovery bool) string {
  204. var respawnConf bytes.Buffer
  205. autologinBin := "/usr/bin/autologin"
  206. if recovery {
  207. autologinBin = "/usr/bin/recovery"
  208. }
  209. config := config.LoadConfig()
  210. allowAutoLogin := true
  211. for _, d := range config.Rancher.Disable {
  212. if d == "autologin" {
  213. allowAutoLogin = false
  214. break
  215. }
  216. }
  217. for i := 1; i < 7; i++ {
  218. tty := fmt.Sprintf("tty%d", i)
  219. if !istty(tty) {
  220. continue
  221. }
  222. respawnConf.WriteString(gettyCmd)
  223. if allowAutoLogin && strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  224. respawnConf.WriteString(fmt.Sprintf(" -n -l %s -o %s:tty%d", autologinBin, user, i))
  225. }
  226. respawnConf.WriteString(fmt.Sprintf(" --noclear %s linux\n", tty))
  227. }
  228. for _, tty := range []string{"ttyS0", "ttyS1", "ttyS2", "ttyS3", "ttyAMA0"} {
  229. if !strings.Contains(cmdline, fmt.Sprintf("console=%s", tty)) {
  230. continue
  231. }
  232. if !istty(tty) {
  233. continue
  234. }
  235. respawnConf.WriteString(gettyCmd)
  236. if allowAutoLogin && strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  237. respawnConf.WriteString(fmt.Sprintf(" -n -l %s -o %s:%s", autologinBin, user, tty))
  238. }
  239. respawnConf.WriteString(fmt.Sprintf(" %s\n", tty))
  240. }
  241. if sshd {
  242. respawnConf.WriteString("/usr/sbin/sshd -D")
  243. }
  244. return respawnConf.String()
  245. }
  246. func writeRespawn(user string, sshd, recovery bool) error {
  247. cmdline, err := ioutil.ReadFile("/proc/cmdline")
  248. if err != nil {
  249. return err
  250. }
  251. respawn := generateRespawnConf(string(cmdline), user, sshd, recovery)
  252. files, err := ioutil.ReadDir("/etc/respawn.conf.d")
  253. if err == nil {
  254. for _, f := range files {
  255. p := path.Join("/etc/respawn.conf.d", f.Name())
  256. content, err := ioutil.ReadFile(p)
  257. if err != nil {
  258. log.Errorf("Failed to read %s: %v", p, err)
  259. continue
  260. }
  261. respawn += fmt.Sprintf("\n%s", string(content))
  262. }
  263. } else if !os.IsNotExist(err) {
  264. log.Error(err)
  265. }
  266. return ioutil.WriteFile("/etc/respawn.conf", []byte(respawn), 0644)
  267. }
  268. func modifySshdConfig(cfg *config.CloudConfig) error {
  269. os.Remove("/etc/ssh/sshd_config")
  270. sshdTpl, err := template.ParseFiles("/etc/ssh/sshd_config.tpl")
  271. if err != nil {
  272. return err
  273. }
  274. f, err := os.OpenFile("/etc/ssh/sshd_config", os.O_WRONLY|os.O_CREATE, 0644)
  275. if err != nil {
  276. return err
  277. }
  278. defer f.Close()
  279. config := map[string]string{}
  280. if cfg.Rancher.SSH.Port > 0 && cfg.Rancher.SSH.Port < 65355 {
  281. config["Port"] = strconv.Itoa(cfg.Rancher.SSH.Port)
  282. }
  283. if cfg.Rancher.SSH.ListenAddress != "" {
  284. config["ListenAddress"] = cfg.Rancher.SSH.ListenAddress
  285. }
  286. return sshdTpl.Execute(f, config)
  287. }
  288. func setupSSH(cfg *config.CloudConfig) error {
  289. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  290. outputFile := fmt.Sprintf("/etc/ssh/ssh_host_%s_key", keyType)
  291. outputFilePub := fmt.Sprintf("/etc/ssh/ssh_host_%s_key.pub", keyType)
  292. if _, err := os.Stat(outputFile); err == nil {
  293. continue
  294. }
  295. saved, savedExists := cfg.Rancher.SSH.Keys[keyType]
  296. pub, pubExists := cfg.Rancher.SSH.Keys[keyType+"-pub"]
  297. if savedExists && pubExists {
  298. // TODO check permissions
  299. if err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {
  300. return err
  301. }
  302. if err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {
  303. return err
  304. }
  305. continue
  306. }
  307. cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -f %s -N '' -t %s", outputFile, keyType))
  308. if err := cmd.Run(); err != nil {
  309. return err
  310. }
  311. savedBytes, err := ioutil.ReadFile(outputFile)
  312. if err != nil {
  313. return err
  314. }
  315. pubBytes, err := ioutil.ReadFile(outputFilePub)
  316. if err != nil {
  317. return err
  318. }
  319. config.Set(fmt.Sprintf("rancher.ssh.keys.%s", keyType), string(savedBytes))
  320. config.Set(fmt.Sprintf("rancher.ssh.keys.%s-pub", keyType), string(pubBytes))
  321. }
  322. return os.MkdirAll("/var/run/sshd", 0644)
  323. }
  324. func istty(name string) bool {
  325. if f, err := os.Open(fmt.Sprintf("/dev/%s", name)); err == nil {
  326. return terminal.IsTerminal(int(f.Fd()))
  327. }
  328. return false
  329. }