disk.go 11 KB

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