console_init.go 10 KB

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