disk.go 11 KB

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