config.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package control
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "sort"
  10. "strings"
  11. "text/template"
  12. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  13. "github.com/rancher/os/log"
  14. "github.com/codegangsta/cli"
  15. "github.com/pkg/errors"
  16. "github.com/rancher/os/config"
  17. "github.com/rancher/os/util"
  18. )
  19. func configSubcommands() []cli.Command {
  20. return []cli.Command{
  21. {
  22. Name: "get",
  23. Usage: "get value",
  24. Action: configGet,
  25. },
  26. {
  27. Name: "set",
  28. Usage: "set a value",
  29. Action: configSet,
  30. },
  31. {
  32. Name: "images",
  33. Usage: "List Docker images for a configuration from a file",
  34. Action: runImages,
  35. Flags: []cli.Flag{
  36. cli.StringFlag{
  37. Name: "input, i",
  38. Usage: "File from which to read config",
  39. },
  40. },
  41. },
  42. {
  43. Name: "generate",
  44. Usage: "Generate a configuration file from a template",
  45. Action: runGenerate,
  46. HideHelp: true,
  47. },
  48. {
  49. Name: "export",
  50. Usage: "export configuration",
  51. Flags: []cli.Flag{
  52. cli.StringFlag{
  53. Name: "output, o",
  54. Usage: "File to which to save",
  55. },
  56. cli.BoolFlag{
  57. Name: "private, p",
  58. Usage: "Include the generated private keys",
  59. },
  60. cli.BoolFlag{
  61. Name: "full, f",
  62. Usage: "Export full configuration, including internal and default settings",
  63. },
  64. },
  65. Action: export,
  66. },
  67. {
  68. Name: "merge",
  69. Usage: "merge configuration from stdin",
  70. Action: merge,
  71. Flags: []cli.Flag{
  72. cli.StringFlag{
  73. Name: "input, i",
  74. Usage: "File from which to read",
  75. },
  76. },
  77. },
  78. {
  79. Name: "syslinux",
  80. Usage: "edit Syslinux boot global.cfg",
  81. Action: editSyslinux,
  82. },
  83. {
  84. Name: "validate",
  85. Usage: "validate configuration from stdin",
  86. Action: validate,
  87. Flags: []cli.Flag{
  88. cli.StringFlag{
  89. Name: "input, i",
  90. Usage: "File from which to read",
  91. },
  92. },
  93. },
  94. }
  95. }
  96. func imagesFromConfig(cfg *config.CloudConfig) []string {
  97. imagesMap := map[string]int{}
  98. for _, service := range cfg.Rancher.BootstrapContainers {
  99. imagesMap[service.Image] = 1
  100. }
  101. for _, service := range cfg.Rancher.Services {
  102. imagesMap[service.Image] = 1
  103. }
  104. images := make([]string, len(imagesMap))
  105. i := 0
  106. for image := range imagesMap {
  107. images[i] = image
  108. i++
  109. }
  110. sort.Strings(images)
  111. return images
  112. }
  113. func runImages(c *cli.Context) error {
  114. configFile := c.String("input")
  115. cfg, err := config.ReadConfig(nil, false, configFile)
  116. if err != nil {
  117. log.WithFields(log.Fields{"err": err, "file": configFile}).Fatalf("Could not read config from file")
  118. }
  119. images := imagesFromConfig(cfg)
  120. fmt.Println(strings.Join(images, " "))
  121. return nil
  122. }
  123. func runGenerate(c *cli.Context) error {
  124. if err := genTpl(os.Stdin, os.Stdout); err != nil {
  125. log.Fatalf("Failed to generate config, err: '%s'", err)
  126. }
  127. return nil
  128. }
  129. func genTpl(in io.Reader, out io.Writer) error {
  130. bytes, err := ioutil.ReadAll(in)
  131. if err != nil {
  132. log.Fatal("Could not read from stdin")
  133. }
  134. tpl := template.Must(template.New("osconfig").Parse(string(bytes)))
  135. return tpl.Execute(out, env2map(os.Environ()))
  136. }
  137. func env2map(env []string) map[string]string {
  138. m := make(map[string]string, len(env))
  139. for _, s := range env {
  140. d := strings.Split(s, "=")
  141. m[d[0]] = d[1]
  142. }
  143. return m
  144. }
  145. func editSyslinux(c *cli.Context) error {
  146. // check whether is Raspberry Pi or not
  147. bytes, err := ioutil.ReadFile("/proc/device-tree/model")
  148. if err == nil && strings.Contains(strings.ToLower(string(bytes)), "raspberry") {
  149. buf := bufio.NewWriter(os.Stdout)
  150. fmt.Fprintln(buf, "raspberry pi can not use this command")
  151. buf.Flush()
  152. return errors.New("raspberry pi can not use this command")
  153. }
  154. if _, err := os.Stat("/proc/1/root/boot/global.cfg"); os.IsNotExist(err) {
  155. buf := bufio.NewWriter(os.Stdout)
  156. fmt.Fprintln(buf, "global.cfg can not be found")
  157. buf.Flush()
  158. return errors.New("global.cfg can not be found")
  159. }
  160. cmd := exec.Command("system-docker", "run", "--rm", "-it",
  161. "-v", "/:/host",
  162. "-w", "/host",
  163. "--entrypoint=vi",
  164. "rancher/os-console:"+config.Version,
  165. "boot/global.cfg")
  166. cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
  167. return cmd.Run()
  168. }
  169. func configSet(c *cli.Context) error {
  170. if c.NArg() < 2 {
  171. return nil
  172. }
  173. key := c.Args().Get(0)
  174. value := c.Args().Get(1)
  175. if key == "" {
  176. return nil
  177. }
  178. err := config.Set(key, value)
  179. if err != nil {
  180. log.Fatal(err)
  181. }
  182. return nil
  183. }
  184. func configGet(c *cli.Context) error {
  185. arg := c.Args().Get(0)
  186. if arg == "" {
  187. return nil
  188. }
  189. val, err := config.Get(arg)
  190. if err != nil {
  191. log.WithFields(log.Fields{"key": arg, "val": val, "err": err}).Fatal("config get: failed to retrieve value")
  192. }
  193. printYaml := false
  194. switch val.(type) {
  195. case []interface{}:
  196. printYaml = true
  197. case map[interface{}]interface{}:
  198. printYaml = true
  199. }
  200. if printYaml {
  201. bytes, err := yaml.Marshal(val)
  202. if err != nil {
  203. log.Fatal(err)
  204. }
  205. fmt.Println(string(bytes))
  206. } else {
  207. fmt.Println(val)
  208. }
  209. return nil
  210. }
  211. func merge(c *cli.Context) error {
  212. bytes, err := inputBytes(c)
  213. if err != nil {
  214. log.Fatal(err)
  215. }
  216. if err = config.Merge(bytes); err != nil {
  217. log.Error(err)
  218. validationErrors, err := config.ValidateBytes(bytes)
  219. if err != nil {
  220. log.Fatal(err)
  221. }
  222. for _, validationError := range validationErrors.Errors() {
  223. log.Error(validationError)
  224. }
  225. log.Fatal("EXITING: Failed to parse configuration")
  226. }
  227. return nil
  228. }
  229. func export(c *cli.Context) error {
  230. content, err := config.Export(c.Bool("private"), c.Bool("full"))
  231. if err != nil {
  232. log.Fatal(err)
  233. }
  234. output := c.String("output")
  235. if output == "" {
  236. fmt.Println(content)
  237. } else {
  238. err := util.WriteFileAtomic(output, []byte(content), 0400)
  239. if err != nil {
  240. log.Fatal(err)
  241. }
  242. }
  243. return nil
  244. }
  245. func validate(c *cli.Context) error {
  246. bytes, err := inputBytes(c)
  247. if err != nil {
  248. log.Fatal(err)
  249. }
  250. validationErrors, err := config.ValidateBytes(bytes)
  251. if err != nil {
  252. log.Fatal(err)
  253. }
  254. for _, validationError := range validationErrors.Errors() {
  255. log.Error(validationError)
  256. }
  257. return nil
  258. }
  259. func inputBytes(c *cli.Context) ([]byte, error) {
  260. input := os.Stdin
  261. inputFile := c.String("input")
  262. if inputFile != "" {
  263. var err error
  264. input, err = os.Open(inputFile)
  265. if err != nil {
  266. return nil, err
  267. }
  268. defer input.Close()
  269. }
  270. return ioutil.ReadAll(input)
  271. }