disk.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. return rawCfg
  81. }
  82. log.SetLevel(log.DebugLevel)
  83. _, rawCfg = getOrSetVal("rancher.docker.debug", rawCfg, true)
  84. _, rawCfg = getOrSetVal("rancher.system_docker.debug", rawCfg, true)
  85. _, rawCfg = getOrSetVal("rancher.bootstrap_docker.debug", rawCfg, true)
  86. _, rawCfg = getOrSetVal("rancher.log", rawCfg, true)
  87. return rawCfg
  88. }
  89. // mergeMetadata merges certain options from md (meta-data from the datasource)
  90. // onto cc (a CloudConfig derived from user-data), if they are not already set
  91. // on cc (i.e. user-data always takes precedence)
  92. func mergeMetadata(rawCfg map[interface{}]interface{}, md datasource.Metadata) map[interface{}]interface{} {
  93. if rawCfg == nil {
  94. return nil
  95. }
  96. out := util.MapCopy(rawCfg)
  97. outHostname, ok := out["hostname"]
  98. if !ok {
  99. outHostname = ""
  100. }
  101. if md.Hostname != "" {
  102. if outHostname != "" {
  103. log.Debugf("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", outHostname, md.Hostname)
  104. } else {
  105. out["hostname"] = md.Hostname
  106. }
  107. }
  108. // Sort SSH keys by key name
  109. keys := []string{}
  110. for k := range md.SSHPublicKeys {
  111. keys = append(keys, k)
  112. }
  113. sort.Sort(sort.StringSlice(keys))
  114. finalKeys, _ := out["ssh_authorized_keys"].([]interface{})
  115. for _, k := range keys {
  116. finalKeys = append(finalKeys, md.SSHPublicKeys[k])
  117. }
  118. out["ssh_authorized_keys"] = finalKeys
  119. return out
  120. }
  121. func readMetadata() datasource.Metadata {
  122. metadata := datasource.Metadata{}
  123. if metaDataBytes, err := ioutil.ReadFile(MetaDataFile); err == nil {
  124. yaml.Unmarshal(metaDataBytes, &metadata)
  125. }
  126. return metadata
  127. }
  128. func readCmdline() map[interface{}]interface{} {
  129. log.Debug("Reading config cmdline")
  130. cmdLine, err := ioutil.ReadFile("/proc/cmdline")
  131. if err != nil {
  132. log.WithFields(log.Fields{"err": err}).Error("Failed to read kernel params")
  133. return nil
  134. }
  135. if len(cmdLine) == 0 {
  136. return nil
  137. }
  138. log.Debugf("Config cmdline %s", cmdLine)
  139. cmdLineObj := parseCmdline(strings.TrimSpace(util.UnescapeKernelParams(string(cmdLine))))
  140. return cmdLineObj
  141. }
  142. func amendNils(c *CloudConfig) *CloudConfig {
  143. t := *c
  144. if t.Rancher.Environment == nil {
  145. t.Rancher.Environment = map[string]string{}
  146. }
  147. if t.Rancher.Autoformat == nil {
  148. t.Rancher.Autoformat = map[string]*composeConfig.ServiceConfigV1{}
  149. }
  150. if t.Rancher.BootstrapContainers == nil {
  151. t.Rancher.BootstrapContainers = map[string]*composeConfig.ServiceConfigV1{}
  152. }
  153. if t.Rancher.Services == nil {
  154. t.Rancher.Services = map[string]*composeConfig.ServiceConfigV1{}
  155. }
  156. if t.Rancher.ServicesInclude == nil {
  157. t.Rancher.ServicesInclude = map[string]bool{}
  158. }
  159. if t.Rancher.RegistryAuths == nil {
  160. t.Rancher.RegistryAuths = map[string]types.AuthConfig{}
  161. }
  162. if t.Rancher.Sysctl == nil {
  163. t.Rancher.Sysctl = map[string]string{}
  164. }
  165. return &t
  166. }
  167. func amendContainerNames(c *CloudConfig) *CloudConfig {
  168. for _, scm := range []map[string]*composeConfig.ServiceConfigV1{
  169. c.Rancher.Autoformat,
  170. c.Rancher.BootstrapContainers,
  171. c.Rancher.Services,
  172. } {
  173. for k, v := range scm {
  174. v.ContainerName = k
  175. }
  176. }
  177. return c
  178. }
  179. func WriteToFile(data interface{}, filename string) error {
  180. content, err := yaml.Marshal(data)
  181. if err != nil {
  182. return err
  183. }
  184. return util.WriteFileAtomic(filename, content, 400)
  185. }
  186. func readConfigs(bytes []byte, substituteMetadataVars, returnErr bool, files ...string) (map[interface{}]interface{}, error) {
  187. // You can't just overlay yaml bytes on to maps, it won't merge, but instead
  188. // just override the keys and not merge the map values.
  189. left := make(map[interface{}]interface{})
  190. metadata := readMetadata()
  191. for _, file := range files {
  192. content, err := readConfigFile(file)
  193. if err != nil {
  194. if returnErr {
  195. return nil, err
  196. }
  197. log.Errorf("Failed to read config file %s: %s", file, err)
  198. continue
  199. }
  200. if len(content) == 0 {
  201. continue
  202. }
  203. if substituteMetadataVars {
  204. content = substituteVars(content, metadata)
  205. }
  206. right := make(map[interface{}]interface{})
  207. err = yaml.Unmarshal(content, &right)
  208. if err != nil {
  209. if returnErr {
  210. return nil, err
  211. }
  212. log.Errorf("Failed to parse config file %s: %s", file, err)
  213. continue
  214. }
  215. // Verify there are no issues converting to CloudConfig
  216. c := &CloudConfig{}
  217. if err := util.Convert(right, c); err != nil {
  218. if returnErr {
  219. return nil, err
  220. }
  221. log.Errorf("Failed to parse config file %s: %s", file, err)
  222. continue
  223. }
  224. left = util.Merge(left, right)
  225. }
  226. if bytes == nil || len(bytes) == 0 {
  227. return left, nil
  228. }
  229. right := make(map[interface{}]interface{})
  230. if substituteMetadataVars {
  231. bytes = substituteVars(bytes, metadata)
  232. }
  233. if err := yaml.Unmarshal(bytes, &right); err != nil {
  234. if returnErr {
  235. return nil, err
  236. }
  237. log.Errorf("Failed to parse bytes: %s", err)
  238. return left, nil
  239. }
  240. c := &CloudConfig{}
  241. if err := util.Convert(right, c); err != nil {
  242. if returnErr {
  243. return nil, err
  244. }
  245. log.Errorf("Failed to parse bytes: %s", err)
  246. return left, nil
  247. }
  248. left = util.Merge(left, right)
  249. return left, nil
  250. }
  251. func readConfigFile(file string) ([]byte, error) {
  252. content, err := ioutil.ReadFile(file)
  253. if err != nil {
  254. if os.IsNotExist(err) {
  255. err = nil
  256. content = []byte{}
  257. } else {
  258. return nil, err
  259. }
  260. }
  261. return content, err
  262. }
  263. func substituteVars(userDataBytes []byte, metadata datasource.Metadata) []byte {
  264. env := initialize.NewEnvironment("", "", "", "", metadata)
  265. userData := env.Apply(string(userDataBytes))
  266. return []byte(userData)
  267. }