console.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package console
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "regexp"
  10. "strings"
  11. "syscall"
  12. log "github.com/Sirupsen/logrus"
  13. "github.com/rancher/os/cmd/cloudinitexecute"
  14. "github.com/rancher/os/config"
  15. "github.com/rancher/os/util"
  16. )
  17. const (
  18. consoleDone = "/run/console-done"
  19. dockerHome = "/home/docker"
  20. gettyCmd = "/sbin/agetty"
  21. rancherHome = "/home/rancher"
  22. startScript = "/opt/rancher/bin/start.sh"
  23. )
  24. type symlink struct {
  25. oldname, newname string
  26. }
  27. func Main() {
  28. cfg := config.LoadConfig()
  29. if _, err := os.Stat(rancherHome); os.IsNotExist(err) {
  30. if err := os.MkdirAll(rancherHome, 0755); err != nil {
  31. log.Error(err)
  32. }
  33. if err := os.Chown(rancherHome, 1100, 1100); err != nil {
  34. log.Error(err)
  35. }
  36. }
  37. if _, err := os.Stat(dockerHome); os.IsNotExist(err) {
  38. if err := os.MkdirAll(dockerHome, 0755); err != nil {
  39. log.Error(err)
  40. }
  41. if err := os.Chown(dockerHome, 1101, 1101); err != nil {
  42. log.Error(err)
  43. }
  44. }
  45. password := config.GetCmdline("rancher.password")
  46. if password != "" {
  47. cmd := exec.Command("chpasswd")
  48. cmd.Stdin = strings.NewReader(fmt.Sprint("rancher:", password))
  49. if err := cmd.Run(); err != nil {
  50. log.Error(err)
  51. }
  52. cmd = exec.Command("bash", "-c", `sed -E -i 's/(rancher:.*:).*(:.*:.*:.*:.*:.*:.*)$/\1\2/' /etc/shadow`)
  53. if err := cmd.Run(); err != nil {
  54. log.Error(err)
  55. }
  56. }
  57. if err := setupSSH(cfg); err != nil {
  58. log.Error(err)
  59. }
  60. if err := writeRespawn(); err != nil {
  61. log.Error(err)
  62. }
  63. if err := modifySshdConfig(); err != nil {
  64. log.Error(err)
  65. }
  66. if err := writeOsRelease(); err != nil {
  67. log.Error(err)
  68. }
  69. for _, link := range []symlink{
  70. {"/var/lib/rancher/engine/docker", "/usr/bin/docker"},
  71. {"/var/lib/rancher/engine/docker-containerd", "/usr/bin/docker-containerd"},
  72. {"/var/lib/rancher/engine/docker-containerd-ctr", "/usr/bin/docker-containerd-ctr"},
  73. {"/var/lib/rancher/engine/docker-containerd-shim", "/usr/bin/docker-containerd-shim"},
  74. {"/var/lib/rancher/engine/dockerd", "/usr/bin/dockerd"},
  75. {"/var/lib/rancher/engine/docker-proxy", "/usr/bin/docker-proxy"},
  76. {"/var/lib/rancher/engine/docker-runc", "/usr/bin/docker-runc"},
  77. } {
  78. syscall.Unlink(link.newname)
  79. if err := os.Symlink(link.oldname, link.newname); err != nil {
  80. log.Error(err)
  81. }
  82. }
  83. cmd := exec.Command("bash", "-c", `echo 'RancherOS \n \l' > /etc/issue`)
  84. if err := cmd.Run(); err != nil {
  85. log.Error(err)
  86. }
  87. 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`)
  88. if err := cmd.Run(); err != nil {
  89. log.Error(err)
  90. }
  91. cloudinitexecute.ApplyConsole(cfg)
  92. if err := runScript(config.CloudConfigScriptFile); err != nil {
  93. log.Error(err)
  94. }
  95. if err := runScript(startScript); err != nil {
  96. log.Error(err)
  97. }
  98. if err := ioutil.WriteFile(consoleDone, []byte(cfg.Rancher.Console), 0644); err != nil {
  99. log.Error(err)
  100. }
  101. if err := runScript("/etc/rc.local"); err != nil {
  102. log.Error(err)
  103. }
  104. os.Setenv("TERM", "linux")
  105. respawnBinPath, err := exec.LookPath("respawn")
  106. if err != nil {
  107. log.Fatal(err)
  108. }
  109. log.Fatal(syscall.Exec(respawnBinPath, []string{"respawn", "-f", "/etc/respawn.conf"}, os.Environ()))
  110. }
  111. func generateRespawnConf(cmdline string) string {
  112. var respawnConf bytes.Buffer
  113. for i := 1; i < 7; i++ {
  114. tty := fmt.Sprintf("tty%d", i)
  115. respawnConf.WriteString(gettyCmd)
  116. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  117. respawnConf.WriteString(" --autologin rancher")
  118. }
  119. respawnConf.WriteString(fmt.Sprintf(" 115200 %s\n", tty))
  120. }
  121. for _, tty := range []string{"ttyS0", "ttyS1", "ttyS2", "ttyS3", "ttyAMA0"} {
  122. if !strings.Contains(cmdline, fmt.Sprintf("console=%s", tty)) {
  123. continue
  124. }
  125. respawnConf.WriteString(gettyCmd)
  126. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  127. respawnConf.WriteString(" --autologin rancher")
  128. }
  129. respawnConf.WriteString(fmt.Sprintf(" 115200 %s\n", tty))
  130. }
  131. respawnConf.WriteString("/usr/sbin/sshd -D")
  132. return respawnConf.String()
  133. }
  134. func writeRespawn() error {
  135. cmdline, err := ioutil.ReadFile("/proc/cmdline")
  136. if err != nil {
  137. return err
  138. }
  139. respawn := generateRespawnConf(string(cmdline))
  140. files, err := ioutil.ReadDir("/etc/respawn.conf.d")
  141. if err == nil {
  142. for _, f := range files {
  143. p := path.Join("/etc/respawn.conf.d", f.Name())
  144. content, err := ioutil.ReadFile(p)
  145. if err != nil {
  146. log.Errorf("Failed to read %s: %v", p, err)
  147. continue
  148. }
  149. respawn += fmt.Sprintf("\n%s", string(content))
  150. }
  151. } else if !os.IsNotExist(err) {
  152. log.Error(err)
  153. }
  154. return ioutil.WriteFile("/etc/respawn.conf", []byte(respawn), 0644)
  155. }
  156. func modifySshdConfig() error {
  157. sshdConfig, err := ioutil.ReadFile("/etc/ssh/sshd_config")
  158. if err != nil {
  159. return err
  160. }
  161. sshdConfigString := string(sshdConfig)
  162. for _, item := range []string{
  163. "UseDNS no",
  164. "PermitRootLogin no",
  165. "ServerKeyBits 2048",
  166. "AllowGroups docker",
  167. } {
  168. match, err := regexp.Match("^"+item, sshdConfig)
  169. if err != nil {
  170. return err
  171. }
  172. if !match {
  173. sshdConfigString += fmt.Sprintf("%s\n", item)
  174. }
  175. }
  176. return ioutil.WriteFile("/etc/ssh/sshd_config", []byte(sshdConfigString), 0644)
  177. }
  178. func writeOsRelease() error {
  179. idLike := "busybox"
  180. if osRelease, err := ioutil.ReadFile("/etc/os-release"); err == nil {
  181. for _, line := range strings.Split(string(osRelease), "\n") {
  182. if strings.HasPrefix(line, "ID_LIKE") {
  183. split := strings.Split(line, "ID_LIKE")
  184. if len(split) > 1 {
  185. idLike = split[1]
  186. }
  187. }
  188. }
  189. }
  190. return ioutil.WriteFile("/etc/os-release", []byte(fmt.Sprintf(`
  191. NAME="RancherOS"
  192. VERSION=%s
  193. ID=rancheros
  194. ID_LIKE=%s
  195. VERSION_ID=%s
  196. PRETTY_NAME="RancherOS %s"
  197. HOME_URL=
  198. SUPPORT_URL=
  199. BUG_REPORT_URL=
  200. BUILD_ID=
  201. `, config.VERSION, idLike, config.VERSION, config.VERSION)), 0644)
  202. }
  203. func setupSSH(cfg *config.CloudConfig) error {
  204. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  205. outputFile := fmt.Sprintf("/etc/ssh/ssh_host_%s_key", keyType)
  206. outputFilePub := fmt.Sprintf("/etc/ssh/ssh_host_%s_key.pub", keyType)
  207. if _, err := os.Stat(outputFile); err == nil {
  208. continue
  209. }
  210. saved, savedExists := cfg.Rancher.Ssh.Keys[keyType]
  211. pub, pubExists := cfg.Rancher.Ssh.Keys[keyType+"-pub"]
  212. if savedExists && pubExists {
  213. // TODO check permissions
  214. if err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {
  215. return err
  216. }
  217. if err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {
  218. return err
  219. }
  220. continue
  221. }
  222. cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -f %s -N '' -t %s", outputFile, keyType))
  223. if err := cmd.Run(); err != nil {
  224. return err
  225. }
  226. savedBytes, err := ioutil.ReadFile(outputFile)
  227. if err != nil {
  228. return err
  229. }
  230. pubBytes, err := ioutil.ReadFile(outputFilePub)
  231. if err != nil {
  232. return err
  233. }
  234. config.Set(fmt.Sprintf("rancher.ssh.keys.%s", keyType), string(savedBytes))
  235. config.Set(fmt.Sprintf("rancher.ssh.keys.%s-pub", keyType), string(pubBytes))
  236. }
  237. return os.MkdirAll("/var/run/sshd", 0644)
  238. }
  239. func runScript(path string) error {
  240. if !util.ExistsAndExecutable(path) {
  241. return nil
  242. }
  243. script, err := os.Open(path)
  244. if err != nil {
  245. return err
  246. }
  247. magic := make([]byte, 2)
  248. if _, err = script.Read(magic); err != nil {
  249. return err
  250. }
  251. cmd := exec.Command("/bin/sh", path)
  252. if string(magic) == "#!" {
  253. cmd = exec.Command(path)
  254. }
  255. cmd.Stdout = os.Stdout
  256. cmd.Stderr = os.Stderr
  257. return cmd.Run()
  258. }