disk.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package config
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "reflect"
  8. "sort"
  9. "strings"
  10. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  11. "github.com/docker/engine-api/types"
  12. composeConfig "github.com/docker/libcompose/config"
  13. "github.com/rancher/os/config/cloudinit/datasource"
  14. "github.com/rancher/os/config/cloudinit/initialize"
  15. "github.com/rancher/os/log"
  16. "github.com/rancher/os/util"
  17. )
  18. func ReadConfig(bytes []byte, substituteMetadataVars bool, files ...string) (*CloudConfig, error) {
  19. data, err := readConfigs(bytes, substituteMetadataVars, true, files...)
  20. if err != nil {
  21. return nil, err
  22. }
  23. c := &CloudConfig{}
  24. if err := util.Convert(data, c); err != nil {
  25. return nil, err
  26. }
  27. c = amendNils(c)
  28. c = amendContainerNames(c)
  29. return c, nil
  30. }
  31. func loadRawDiskConfig(dirPrefix string, full bool) map[interface{}]interface{} {
  32. var rawCfg map[interface{}]interface{}
  33. if full {
  34. rawCfg, _ = readConfigs(nil, true, false, OsConfigFile, OemConfigFile)
  35. }
  36. files := CloudConfigDirFiles(dirPrefix)
  37. files = append(files, path.Join(dirPrefix, CloudConfigFile))
  38. additionalCfgs, _ := readConfigs(nil, true, false, files...)
  39. return util.Merge(rawCfg, additionalCfgs)
  40. }
  41. func loadRawConfig(dirPrefix string, full bool) map[interface{}]interface{} {
  42. rawCfg := loadRawDiskConfig(dirPrefix, full)
  43. rawCfg = util.Merge(rawCfg, readCmdline())
  44. rawCfg = util.Merge(rawCfg, readElidedCmdline(rawCfg))
  45. rawCfg = applyDebugFlags(rawCfg)
  46. return mergeMetadata(rawCfg, readMetadata())
  47. }
  48. func LoadConfig() *CloudConfig {
  49. cfg := LoadConfigWithPrefix("")
  50. if cfg.Rancher.Debug {
  51. log.SetDefaultLevel(log.DebugLevel)
  52. } else {
  53. log.SetDefaultLevel(log.InfoLevel)
  54. }
  55. return cfg
  56. }
  57. func LoadConfigWithPrefix(dirPrefix string) *CloudConfig {
  58. rawCfg := loadRawConfig(dirPrefix, true)
  59. cfg := &CloudConfig{}
  60. if err := util.Convert(rawCfg, cfg); err != nil {
  61. log.Errorf("EXITING: Failed to parse configuration: %s", err)
  62. log.Debugf("Bad cfg:\n%v\n", rawCfg)
  63. // no point returning {}, it'll just sit there broken
  64. // TODO: print some context around what failed..
  65. validationErrors, err := ValidateRawCfg(rawCfg)
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. for _, validationError := range validationErrors.Errors() {
  70. log.Error(validationError)
  71. }
  72. // TODO: I'd love to panic & recover(), for issues on boot, but it doesn't work yet
  73. os.Exit(-1)
  74. return &CloudConfig{}
  75. }
  76. cfg = amendNils(cfg)
  77. cfg = amendContainerNames(cfg)
  78. return cfg
  79. }
  80. func Insert(m interface{}, args ...interface{}) interface{} {
  81. // TODO: move to util.go
  82. if len(args)%2 != 0 {
  83. panic("must have pairs of keys and values")
  84. }
  85. mv := reflect.ValueOf(m)
  86. if mv.IsNil() {
  87. mv = reflect.MakeMap(mv.Type())
  88. }
  89. for i := 0; i < len(args); i += 2 {
  90. mv.SetMapIndex(reflect.ValueOf(args[i]), reflect.ValueOf(args[i+1]))
  91. }
  92. return mv.Interface()
  93. }
  94. func SaveInitCmdline(cmdLineArgs string) {
  95. elidedCfg := parseCmdline(cmdLineArgs)
  96. env := Insert(make(map[interface{}]interface{}), interface{}("EXTRA_CMDLINE"), interface{}(cmdLineArgs))
  97. rancher := Insert(make(map[interface{}]interface{}), interface{}("environment"), env)
  98. newCfg := Insert(elidedCfg, interface{}("rancher"), rancher)
  99. // make it easy for readElidedCmdline(rawCfg)
  100. newCfg = Insert(newCfg, interface{}("EXTRA_CMDLINE"), interface{}(cmdLineArgs))
  101. if err := WriteToFile(newCfg, CloudConfigInitFile); err != nil {
  102. log.Errorf("Failed to write init-cmdline config: %s", err)
  103. }
  104. }
  105. func CloudConfigDirFiles(dirPrefix string) []string {
  106. cloudConfigDir := path.Join(dirPrefix, CloudConfigDir)
  107. files, err := ioutil.ReadDir(cloudConfigDir)
  108. if err != nil {
  109. if os.IsNotExist(err) {
  110. // do nothing
  111. log.Debugf("%s does not exist", CloudConfigDir)
  112. } else {
  113. log.Errorf("Failed to read %s: %v", CloudConfigDir, err)
  114. }
  115. return []string{}
  116. }
  117. var finalFiles []string
  118. for _, file := range files {
  119. if !file.IsDir() && !strings.HasPrefix(file.Name(), ".") {
  120. finalFiles = append(finalFiles, path.Join(cloudConfigDir, file.Name()))
  121. }
  122. }
  123. return finalFiles
  124. }
  125. func applyDebugFlags(rawCfg map[interface{}]interface{}) map[interface{}]interface{} {
  126. cfg := &CloudConfig{}
  127. if err := util.Convert(rawCfg, cfg); err != nil {
  128. return rawCfg
  129. }
  130. if !cfg.Rancher.Debug {
  131. return rawCfg
  132. }
  133. log.SetLevel(log.DebugLevel)
  134. _, rawCfg = getOrSetVal("rancher.docker.debug", rawCfg, true)
  135. _, rawCfg = getOrSetVal("rancher.system_docker.debug", rawCfg, true)
  136. _, rawCfg = getOrSetVal("rancher.bootstrap_docker.debug", rawCfg, true)
  137. _, rawCfg = getOrSetVal("rancher.log", rawCfg, true)
  138. return rawCfg
  139. }
  140. // mergeMetadata merges certain options from md (meta-data from the datasource)
  141. // onto cc (a CloudConfig derived from user-data), if they are not already set
  142. // on cc (i.e. user-data always takes precedence)
  143. func mergeMetadata(rawCfg map[interface{}]interface{}, md datasource.Metadata) map[interface{}]interface{} {
  144. if rawCfg == nil {
  145. return nil
  146. }
  147. out := util.MapCopy(rawCfg)
  148. outHostname, ok := out["hostname"]
  149. if !ok {
  150. outHostname = ""
  151. }
  152. if md.Hostname != "" {
  153. if outHostname != "" {
  154. log.Debugf("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", outHostname, md.Hostname)
  155. } else {
  156. out["hostname"] = md.Hostname
  157. }
  158. }
  159. // Sort SSH keys by key name
  160. keys := []string{}
  161. for k := range md.SSHPublicKeys {
  162. keys = append(keys, k)
  163. }
  164. sort.Sort(sort.StringSlice(keys))
  165. finalKeys, _ := out["ssh_authorized_keys"].([]interface{})
  166. for _, k := range keys {
  167. finalKeys = append(finalKeys, md.SSHPublicKeys[k])
  168. }
  169. out["ssh_authorized_keys"] = finalKeys
  170. return out
  171. }
  172. func readMetadata() datasource.Metadata {
  173. metadata := datasource.Metadata{}
  174. if metaDataBytes, err := ioutil.ReadFile(MetaDataFile); err == nil {
  175. yaml.Unmarshal(metaDataBytes, &metadata)
  176. }
  177. return metadata
  178. }
  179. func readElidedCmdline(rawCfg map[interface{}]interface{}) map[interface{}]interface{} {
  180. for k, v := range rawCfg {
  181. if key, _ := k.(string); key == "EXTRA_CMDLINE" {
  182. if val, ok := v.(string); ok {
  183. cmdLineObj := parseCmdline(strings.TrimSpace(util.UnescapeKernelParams(string(val))))
  184. return cmdLineObj
  185. }
  186. }
  187. }
  188. return nil
  189. }
  190. func readCmdline() map[interface{}]interface{} {
  191. cmdLine, err := ioutil.ReadFile("/proc/cmdline")
  192. if err != nil {
  193. log.WithFields(log.Fields{"err": err}).Error("Failed to read kernel params")
  194. return nil
  195. }
  196. if len(cmdLine) == 0 {
  197. return nil
  198. }
  199. cmdLineObj := parseCmdline(strings.TrimSpace(util.UnescapeKernelParams(string(cmdLine))))
  200. return cmdLineObj
  201. }
  202. func amendNils(c *CloudConfig) *CloudConfig {
  203. t := *c
  204. if t.Rancher.Environment == nil {
  205. t.Rancher.Environment = map[string]string{}
  206. }
  207. if t.Rancher.BootstrapContainers == nil {
  208. t.Rancher.BootstrapContainers = map[string]*composeConfig.ServiceConfigV1{}
  209. }
  210. if t.Rancher.Services == nil {
  211. t.Rancher.Services = map[string]*composeConfig.ServiceConfigV1{}
  212. }
  213. if t.Rancher.ServicesInclude == nil {
  214. t.Rancher.ServicesInclude = map[string]bool{}
  215. }
  216. if t.Rancher.RegistryAuths == nil {
  217. t.Rancher.RegistryAuths = map[string]types.AuthConfig{}
  218. }
  219. if t.Rancher.Sysctl == nil {
  220. t.Rancher.Sysctl = map[string]string{}
  221. }
  222. return &t
  223. }
  224. func amendContainerNames(c *CloudConfig) *CloudConfig {
  225. for _, scm := range []map[string]*composeConfig.ServiceConfigV1{
  226. c.Rancher.BootstrapContainers,
  227. c.Rancher.Services,
  228. } {
  229. for k, v := range scm {
  230. v.ContainerName = k
  231. }
  232. }
  233. return c
  234. }
  235. func WriteToFile(data interface{}, filename string) error {
  236. content, err := yaml.Marshal(data)
  237. if err != nil {
  238. return err
  239. }
  240. if err := os.MkdirAll(filepath.Dir(filename), os.ModeDir|0700); err != nil {
  241. return err
  242. }
  243. return util.WriteFileAtomic(filename, content, 400)
  244. }
  245. func readConfigs(bytes []byte, substituteMetadataVars, returnErr bool, files ...string) (map[interface{}]interface{}, error) {
  246. // You can't just overlay yaml bytes on to maps, it won't merge, but instead
  247. // just override the keys and not merge the map values.
  248. left := make(map[interface{}]interface{})
  249. metadata := readMetadata()
  250. for _, file := range files {
  251. //os.Stderr.WriteString(fmt.Sprintf("READCONFIGS(%s)", file))
  252. content, err := readConfigFile(file)
  253. if err != nil {
  254. if returnErr {
  255. return nil, err
  256. }
  257. log.Errorf("Failed to read config file %s: %s", file, err)
  258. continue
  259. }
  260. if len(content) == 0 {
  261. continue
  262. }
  263. if substituteMetadataVars {
  264. content = substituteVars(content, metadata)
  265. }
  266. right := make(map[interface{}]interface{})
  267. err = yaml.Unmarshal(content, &right)
  268. if err != nil {
  269. if returnErr {
  270. return nil, err
  271. }
  272. log.Errorf("Failed to parse config file %s: %s", file, err)
  273. continue
  274. }
  275. // Verify there are no issues converting to CloudConfig
  276. c := &CloudConfig{}
  277. if err := util.Convert(right, c); err != nil {
  278. if returnErr {
  279. return nil, err
  280. }
  281. log.Errorf("Failed to parse config file %s: %s", file, err)
  282. continue
  283. }
  284. left = util.Merge(left, right)
  285. }
  286. if bytes == nil || len(bytes) == 0 {
  287. return left, nil
  288. }
  289. right := make(map[interface{}]interface{})
  290. if substituteMetadataVars {
  291. bytes = substituteVars(bytes, metadata)
  292. }
  293. if err := yaml.Unmarshal(bytes, &right); err != nil {
  294. if returnErr {
  295. return nil, err
  296. }
  297. log.Errorf("Failed to parse bytes: %s", err)
  298. return left, nil
  299. }
  300. c := &CloudConfig{}
  301. if err := util.Convert(right, c); err != nil {
  302. if returnErr {
  303. return nil, err
  304. }
  305. log.Errorf("Failed to parse bytes: %s", err)
  306. return left, nil
  307. }
  308. left = util.Merge(left, right)
  309. return left, nil
  310. }
  311. func readConfigFile(file string) ([]byte, error) {
  312. content, err := ioutil.ReadFile(file)
  313. if err != nil {
  314. if os.IsNotExist(err) {
  315. err = nil
  316. content = []byte{}
  317. } else {
  318. return nil, err
  319. }
  320. }
  321. return content, err
  322. }
  323. func substituteVars(userDataBytes []byte, metadata datasource.Metadata) []byte {
  324. // TODO: I think this currently does nothing - its hardcoded for COREOS env..
  325. env := initialize.NewEnvironment("", "", "", "", metadata)
  326. userData := env.Apply(string(userDataBytes))
  327. return []byte(userData)
  328. }