disk.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package config
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path"
  6. "sort"
  7. "strings"
  8. log "github.com/Sirupsen/logrus"
  9. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  10. "github.com/coreos/coreos-cloudinit/datasource"
  11. "github.com/coreos/coreos-cloudinit/initialize"
  12. "github.com/docker/engine-api/types"
  13. composeConfig "github.com/docker/libcompose/config"
  14. "github.com/rancher/os/util"
  15. )
  16. func ReadConfig(bytes []byte, substituteMetadataVars bool, files ...string) (*CloudConfig, error) {
  17. data, err := readConfigs(bytes, substituteMetadataVars, true, files...)
  18. if err != nil {
  19. return nil, err
  20. }
  21. c := &CloudConfig{}
  22. if err := util.Convert(data, c); err != nil {
  23. return nil, err
  24. }
  25. c = amendNils(c)
  26. c = amendContainerNames(c)
  27. return c, nil
  28. }
  29. func loadRawDiskConfig(full bool) map[interface{}]interface{} {
  30. var rawCfg map[interface{}]interface{}
  31. if full {
  32. rawCfg, _ = readConfigs(nil, true, false, OsConfigFile, OemConfigFile)
  33. }
  34. files := append(CloudConfigDirFiles(), CloudConfigFile)
  35. additionalCfgs, _ := readConfigs(nil, true, false, files...)
  36. return util.Merge(rawCfg, additionalCfgs)
  37. }
  38. func loadRawConfig() map[interface{}]interface{} {
  39. rawCfg := loadRawDiskConfig(true)
  40. rawCfg = util.Merge(rawCfg, readCmdline())
  41. rawCfg = applyDebugFlags(rawCfg)
  42. return mergeMetadata(rawCfg, readMetadata())
  43. }
  44. func LoadConfig() *CloudConfig {
  45. rawCfg := loadRawConfig()
  46. cfg := &CloudConfig{}
  47. if err := util.Convert(rawCfg, cfg); err != nil {
  48. log.Errorf("Failed to parse configuration: %s", err)
  49. return &CloudConfig{}
  50. }
  51. cfg = amendNils(cfg)
  52. cfg = amendContainerNames(cfg)
  53. return cfg
  54. }
  55. func CloudConfigDirFiles() []string {
  56. files, err := ioutil.ReadDir(CloudConfigDir)
  57. if err != nil {
  58. if os.IsNotExist(err) {
  59. // do nothing
  60. log.Debugf("%s does not exist", CloudConfigDir)
  61. } else {
  62. log.Errorf("Failed to read %s: %v", CloudConfigDir, err)
  63. }
  64. return []string{}
  65. }
  66. var finalFiles []string
  67. for _, file := range files {
  68. if !file.IsDir() && !strings.HasPrefix(file.Name(), ".") {
  69. finalFiles = append(finalFiles, path.Join(CloudConfigDir, file.Name()))
  70. }
  71. }
  72. return finalFiles
  73. }
  74. func applyDebugFlags(rawCfg map[interface{}]interface{}) map[interface{}]interface{} {
  75. cfg := &CloudConfig{}
  76. if err := util.Convert(rawCfg, cfg); err != nil {
  77. return rawCfg
  78. }
  79. if cfg.Rancher.Debug {
  80. log.SetLevel(log.DebugLevel)
  81. if !util.Contains(cfg.Rancher.Docker.Args, "-D") {
  82. cfg.Rancher.Docker.Args = append(cfg.Rancher.Docker.Args, "-D")
  83. }
  84. if !util.Contains(cfg.Rancher.SystemDocker.Args, "-D") {
  85. cfg.Rancher.SystemDocker.Args = append(cfg.Rancher.SystemDocker.Args, "-D")
  86. }
  87. }
  88. _, rawCfg = getOrSetVal("rancher.docker.args", rawCfg, cfg.Rancher.Docker.Args)
  89. _, rawCfg = getOrSetVal("rancher.system_docker.args", rawCfg, cfg.Rancher.SystemDocker.Args)
  90. return rawCfg
  91. }
  92. // mergeMetadata merges certain options from md (meta-data from the datasource)
  93. // onto cc (a CloudConfig derived from user-data), if they are not already set
  94. // on cc (i.e. user-data always takes precedence)
  95. func mergeMetadata(rawCfg map[interface{}]interface{}, md datasource.Metadata) map[interface{}]interface{} {
  96. if rawCfg == nil {
  97. return nil
  98. }
  99. out := util.MapCopy(rawCfg)
  100. outHostname, ok := out["hostname"]
  101. if !ok {
  102. outHostname = ""
  103. }
  104. if md.Hostname != "" {
  105. if outHostname != "" {
  106. log.Debugf("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", outHostname, md.Hostname)
  107. } else {
  108. out["hostname"] = md.Hostname
  109. }
  110. }
  111. // Sort SSH keys by key name
  112. keys := []string{}
  113. for k := range md.SSHPublicKeys {
  114. keys = append(keys, k)
  115. }
  116. sort.Sort(sort.StringSlice(keys))
  117. currentKeys, ok := out["ssh_authorized_keys"]
  118. if !ok {
  119. return out
  120. }
  121. finalKeys := currentKeys.([]interface{})
  122. for _, k := range keys {
  123. finalKeys = append(finalKeys, md.SSHPublicKeys[k])
  124. }
  125. out["ssh_authorized_keys"] = finalKeys
  126. return out
  127. }
  128. func readMetadata() datasource.Metadata {
  129. metadata := datasource.Metadata{}
  130. if metaDataBytes, err := ioutil.ReadFile(MetaDataFile); err == nil {
  131. yaml.Unmarshal(metaDataBytes, &metadata)
  132. }
  133. return metadata
  134. }
  135. func readCmdline() map[interface{}]interface{} {
  136. log.Debug("Reading config cmdline")
  137. cmdLine, err := ioutil.ReadFile("/proc/cmdline")
  138. if err != nil {
  139. log.WithFields(log.Fields{"err": err}).Error("Failed to read kernel params")
  140. return nil
  141. }
  142. if len(cmdLine) == 0 {
  143. return nil
  144. }
  145. log.Debugf("Config cmdline %s", cmdLine)
  146. cmdLineObj := parseCmdline(strings.TrimSpace(string(cmdLine)))
  147. return cmdLineObj
  148. }
  149. func amendNils(c *CloudConfig) *CloudConfig {
  150. t := *c
  151. if t.Rancher.Environment == nil {
  152. t.Rancher.Environment = map[string]string{}
  153. }
  154. if t.Rancher.Autoformat == nil {
  155. t.Rancher.Autoformat = map[string]*composeConfig.ServiceConfigV1{}
  156. }
  157. if t.Rancher.BootstrapContainers == nil {
  158. t.Rancher.BootstrapContainers = map[string]*composeConfig.ServiceConfigV1{}
  159. }
  160. if t.Rancher.Services == nil {
  161. t.Rancher.Services = map[string]*composeConfig.ServiceConfigV1{}
  162. }
  163. if t.Rancher.ServicesInclude == nil {
  164. t.Rancher.ServicesInclude = map[string]bool{}
  165. }
  166. if t.Rancher.RegistryAuths == nil {
  167. t.Rancher.RegistryAuths = map[string]types.AuthConfig{}
  168. }
  169. return &t
  170. }
  171. func amendContainerNames(c *CloudConfig) *CloudConfig {
  172. for _, scm := range []map[string]*composeConfig.ServiceConfigV1{
  173. c.Rancher.Autoformat,
  174. c.Rancher.BootstrapContainers,
  175. c.Rancher.Services,
  176. } {
  177. for k, v := range scm {
  178. v.ContainerName = k
  179. }
  180. }
  181. return c
  182. }
  183. func WriteToFile(data interface{}, filename string) error {
  184. content, err := yaml.Marshal(data)
  185. if err != nil {
  186. return err
  187. }
  188. return util.WriteFileAtomic(filename, content, 400)
  189. }
  190. func readConfigs(bytes []byte, substituteMetadataVars, returnErr bool, files ...string) (map[interface{}]interface{}, error) {
  191. // You can't just overlay yaml bytes on to maps, it won't merge, but instead
  192. // just override the keys and not merge the map values.
  193. left := make(map[interface{}]interface{})
  194. metadata := readMetadata()
  195. for _, file := range files {
  196. content, err := readConfigFile(file)
  197. if err != nil {
  198. if returnErr {
  199. return nil, err
  200. }
  201. log.Errorf("Failed to read config file %s: %s", file, err)
  202. continue
  203. }
  204. if len(content) == 0 {
  205. continue
  206. }
  207. if substituteMetadataVars {
  208. content = substituteVars(content, metadata)
  209. }
  210. right := make(map[interface{}]interface{})
  211. err = yaml.Unmarshal(content, &right)
  212. if err != nil {
  213. if returnErr {
  214. return nil, err
  215. }
  216. log.Errorf("Failed to parse config file %s: %s", file, err)
  217. continue
  218. }
  219. // Verify there are no issues converting to CloudConfig
  220. c := &CloudConfig{}
  221. if err := util.Convert(right, c); err != nil {
  222. if returnErr {
  223. return nil, err
  224. }
  225. log.Errorf("Failed to parse config file %s: %s", file, err)
  226. continue
  227. }
  228. left = util.Merge(left, right)
  229. }
  230. if bytes == nil || len(bytes) == 0 {
  231. return left, nil
  232. }
  233. right := make(map[interface{}]interface{})
  234. if substituteMetadataVars {
  235. bytes = substituteVars(bytes, metadata)
  236. }
  237. if err := yaml.Unmarshal(bytes, &right); err != nil {
  238. if returnErr {
  239. return nil, err
  240. }
  241. log.Errorf("Failed to parse bytes: %s", err)
  242. return left, nil
  243. }
  244. c := &CloudConfig{}
  245. if err := util.Convert(right, c); err != nil {
  246. if returnErr {
  247. return nil, err
  248. }
  249. log.Errorf("Failed to parse bytes: %s", err)
  250. return left, nil
  251. }
  252. left = util.Merge(left, right)
  253. return left, nil
  254. }
  255. func readConfigFile(file string) ([]byte, error) {
  256. content, err := ioutil.ReadFile(file)
  257. if err != nil {
  258. if os.IsNotExist(err) {
  259. err = nil
  260. content = []byte{}
  261. } else {
  262. return nil, err
  263. }
  264. }
  265. return content, err
  266. }
  267. func substituteVars(userDataBytes []byte, metadata datasource.Metadata) []byte {
  268. env := initialize.NewEnvironment("", "", "", "", metadata)
  269. userData := env.Apply(string(userDataBytes))
  270. return []byte(userData)
  271. }