cloudinitsave.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // Copyright 2015 CoreOS, Inc.
  2. // Copyright 2015-2017 Rancher Labs, Inc.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package cloudinitsave
  16. import (
  17. "bytes"
  18. "errors"
  19. "os"
  20. "path"
  21. "strings"
  22. "sync"
  23. "time"
  24. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  25. "github.com/rancher/os/cmd/control"
  26. "github.com/rancher/os/cmd/network"
  27. rancherConfig "github.com/rancher/os/config"
  28. "github.com/rancher/os/config/cloudinit/config"
  29. "github.com/rancher/os/config/cloudinit/datasource"
  30. "github.com/rancher/os/config/cloudinit/datasource/configdrive"
  31. "github.com/rancher/os/config/cloudinit/datasource/file"
  32. "github.com/rancher/os/config/cloudinit/datasource/metadata/digitalocean"
  33. "github.com/rancher/os/config/cloudinit/datasource/metadata/ec2"
  34. "github.com/rancher/os/config/cloudinit/datasource/metadata/gce"
  35. "github.com/rancher/os/config/cloudinit/datasource/metadata/packet"
  36. "github.com/rancher/os/config/cloudinit/datasource/proccmdline"
  37. "github.com/rancher/os/config/cloudinit/datasource/url"
  38. "github.com/rancher/os/config/cloudinit/pkg"
  39. "github.com/rancher/os/log"
  40. "github.com/rancher/os/netconf"
  41. "github.com/rancher/os/util"
  42. )
  43. const (
  44. datasourceInterval = 100 * time.Millisecond
  45. datasourceMaxInterval = 30 * time.Second
  46. datasourceTimeout = 5 * time.Minute
  47. )
  48. func Main() {
  49. log.InitLogger()
  50. log.Info("Running cloud-init-save")
  51. if err := control.UdevSettle(); err != nil {
  52. log.Errorf("Failed to run udev settle: %v", err)
  53. }
  54. if err := saveCloudConfig(); err != nil {
  55. log.Errorf("Failed to save cloud-config: %v", err)
  56. }
  57. }
  58. func saveCloudConfig() error {
  59. log.Debugf("SaveCloudConfig")
  60. cfg := rancherConfig.LoadConfig()
  61. log.Debugf("init: SaveCloudConfig(pre ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  62. network.ApplyNetworkConfig(cfg)
  63. log.Debugf("datasources that will be consided: %#v", cfg.Rancher.CloudInit.Datasources)
  64. dss := getDatasources(cfg.Rancher.CloudInit.Datasources)
  65. if len(dss) == 0 {
  66. log.Errorf("currentDatasource - none found")
  67. return nil
  68. }
  69. selectDatasource(dss)
  70. // Apply any newly detected network config.
  71. cfg = rancherConfig.LoadConfig()
  72. log.Debugf("init: SaveCloudConfig(post ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  73. network.ApplyNetworkConfig(cfg)
  74. return nil
  75. }
  76. func RequiresNetwork(datasource string) bool {
  77. // TODO: move into the datasources (and metadatasources)
  78. // and then we can enable that platforms defaults..
  79. parts := strings.SplitN(datasource, ":", 2)
  80. requiresNetwork, ok := map[string]bool{
  81. "ec2": true,
  82. "file": false,
  83. "url": true,
  84. "cmdline": true,
  85. "configdrive": false,
  86. "digitalocean": true,
  87. "gce": true,
  88. "packet": true,
  89. }[parts[0]]
  90. return ok && requiresNetwork
  91. }
  92. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  93. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  94. if len(scriptBytes) > 0 {
  95. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  96. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  97. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  98. return err
  99. }
  100. }
  101. if len(cloudConfigBytes) > 0 {
  102. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  103. return err
  104. }
  105. log.Infof("Wrote to %s", rancherConfig.CloudConfigBootFile)
  106. }
  107. metaDataBytes, err := yaml.Marshal(metadata)
  108. if err != nil {
  109. return err
  110. }
  111. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  112. return err
  113. }
  114. log.Infof("Wrote to %s", rancherConfig.MetaDataFile)
  115. // if we write the empty meta yml, the merge fails.
  116. // TODO: the problem is that a partially filled one will still have merge issues, so that needs fixing - presumably by making merge more clever, and making more fields optional
  117. emptyMeta, err := yaml.Marshal(datasource.Metadata{})
  118. if err != nil {
  119. return err
  120. }
  121. if bytes.Compare(metaDataBytes, emptyMeta) == 0 {
  122. log.Infof("not writing %s: its all defaults.", rancherConfig.CloudConfigNetworkFile)
  123. return nil
  124. }
  125. type nonRancherCfg struct {
  126. Network netconf.NetworkConfig `yaml:"network,omitempty"`
  127. }
  128. type nonCfg struct {
  129. Rancher nonRancherCfg `yaml:"rancher,omitempty"`
  130. }
  131. // write the network.yml file from metadata
  132. cc := nonCfg{
  133. Rancher: nonRancherCfg{
  134. Network: metadata.NetworkConfig,
  135. },
  136. }
  137. if err := os.MkdirAll(path.Dir(rancherConfig.CloudConfigNetworkFile), 0700); err != nil {
  138. log.Errorf("Failed to create directory for file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  139. }
  140. if err := rancherConfig.WriteToFile(cc, rancherConfig.CloudConfigNetworkFile); err != nil {
  141. log.Errorf("Failed to save config file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  142. }
  143. log.Infof("Wrote to %s", rancherConfig.CloudConfigNetworkFile)
  144. return nil
  145. }
  146. func fetchAndSave(ds datasource.Datasource) error {
  147. var metadata datasource.Metadata
  148. log.Infof("Fetching user-data from datasource %s", ds)
  149. userDataBytes, err := ds.FetchUserdata()
  150. if err != nil {
  151. log.Errorf("Failed fetching user-data from datasource: %v", err)
  152. return err
  153. }
  154. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  155. metadata, err = ds.FetchMetadata()
  156. if err != nil {
  157. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  158. return err
  159. }
  160. userData := string(userDataBytes)
  161. scriptBytes := []byte{}
  162. if config.IsScript(userData) {
  163. scriptBytes = userDataBytes
  164. userDataBytes = []byte{}
  165. } else if isCompose(userData) {
  166. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  167. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  168. return err
  169. }
  170. } else if config.IsCloudConfig(userData) {
  171. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  172. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  173. userDataBytes = []byte{}
  174. }
  175. } else {
  176. log.Errorf("Unrecognized user-data\n(%s)", userData)
  177. userDataBytes = []byte{}
  178. }
  179. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  180. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  181. return errors.New("Failed to parse cloud-config")
  182. }
  183. return saveFiles(userDataBytes, scriptBytes, metadata)
  184. }
  185. // getDatasources creates a slice of possible Datasources for cloudinit based
  186. // on the different source command-line flags.
  187. func getDatasources(datasources []string) []datasource.Datasource {
  188. dss := make([]datasource.Datasource, 0, 5)
  189. for _, ds := range datasources {
  190. parts := strings.SplitN(ds, ":", 2)
  191. root := ""
  192. if len(parts) > 1 {
  193. root = parts[1]
  194. }
  195. switch parts[0] {
  196. case "*":
  197. dss = append(dss, getDatasources([]string{"configdrive", "ec2", "digitalocean", "packet", "gce"})...)
  198. case "ec2":
  199. dss = append(dss, ec2.NewDatasource(root))
  200. case "file":
  201. if root != "" {
  202. dss = append(dss, file.NewDatasource(root))
  203. }
  204. case "url":
  205. if root != "" {
  206. dss = append(dss, url.NewDatasource(root))
  207. }
  208. case "cmdline":
  209. if len(parts) == 1 {
  210. dss = append(dss, proccmdline.NewDatasource())
  211. }
  212. case "configdrive":
  213. if root == "" {
  214. root = "/media/config-2"
  215. }
  216. dss = append(dss, configdrive.NewDatasource(root))
  217. case "digitalocean":
  218. // TODO: should we enableDoLinkLocal() - to avoid the need for the other kernel/oem options?
  219. dss = append(dss, digitalocean.NewDatasource(root))
  220. case "gce":
  221. dss = append(dss, gce.NewDatasource(root))
  222. case "packet":
  223. dss = append(dss, packet.NewDatasource(root))
  224. }
  225. }
  226. return dss
  227. }
  228. func enableDoLinkLocal() {
  229. err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  230. Interfaces: map[string]netconf.InterfaceConfig{
  231. "eth0": {
  232. IPV4LL: true,
  233. },
  234. },
  235. })
  236. if err != nil {
  237. log.Errorf("Failed to apply link local on eth0: %v", err)
  238. }
  239. }
  240. // selectDatasource attempts to choose a valid Datasource to use based on its
  241. // current availability. The first Datasource to report to be available is
  242. // returned. Datasources will be retried if possible if they are not
  243. // immediately available. If all Datasources are permanently unavailable or
  244. // datasourceTimeout is reached before one becomes available, nil is returned.
  245. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  246. ds := make(chan datasource.Datasource)
  247. stop := make(chan struct{})
  248. var wg sync.WaitGroup
  249. for _, s := range sources {
  250. wg.Add(1)
  251. go func(s datasource.Datasource) {
  252. defer wg.Done()
  253. duration := datasourceInterval
  254. for {
  255. log.Infof("cloud-init: Checking availability of %q\n", s.Type())
  256. if s.IsAvailable() {
  257. log.Infof("cloud-init: Datasource available: %s", s)
  258. ds <- s
  259. return
  260. }
  261. if !s.AvailabilityChanges() {
  262. log.Infof("cloud-init: Datasource unavailable, skipping: %s", s)
  263. return
  264. }
  265. log.Errorf("cloud-init: Datasource not ready, will retry: %s", s)
  266. select {
  267. case <-stop:
  268. return
  269. case <-time.After(duration):
  270. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  271. }
  272. }
  273. }(s)
  274. }
  275. done := make(chan struct{})
  276. go func() {
  277. wg.Wait()
  278. close(done)
  279. }()
  280. var s datasource.Datasource
  281. select {
  282. case s = <-ds:
  283. err := fetchAndSave(s)
  284. if err != nil {
  285. log.Errorf("Error fetching cloud-init datasource(%s): %s", s, err)
  286. }
  287. case <-done:
  288. case <-time.After(datasourceTimeout):
  289. }
  290. close(stop)
  291. return s
  292. }
  293. func isCompose(content string) bool {
  294. return strings.HasPrefix(content, "#compose\n")
  295. }
  296. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  297. compose := make(map[interface{}]interface{})
  298. err := yaml.Unmarshal(bytes, &compose)
  299. if err != nil {
  300. return nil, err
  301. }
  302. return yaml.Marshal(map[interface{}]interface{}{
  303. "rancher": map[interface{}]interface{}{
  304. "services": compose,
  305. },
  306. })
  307. }