disk.go 9.8 KB

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