disk.go 7.8 KB

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