cloudinitsave.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. "github.com/rancher/os/cmd/control"
  25. "github.com/rancher/os/cmd/network"
  26. rancherConfig "github.com/rancher/os/config"
  27. "github.com/rancher/os/config/cloudinit/config"
  28. "github.com/rancher/os/config/cloudinit/datasource"
  29. "github.com/rancher/os/config/cloudinit/datasource/configdrive"
  30. "github.com/rancher/os/config/cloudinit/datasource/file"
  31. "github.com/rancher/os/config/cloudinit/datasource/metadata/aliyun"
  32. "github.com/rancher/os/config/cloudinit/datasource/metadata/cloudstack"
  33. "github.com/rancher/os/config/cloudinit/datasource/metadata/digitalocean"
  34. "github.com/rancher/os/config/cloudinit/datasource/metadata/ec2"
  35. "github.com/rancher/os/config/cloudinit/datasource/metadata/gce"
  36. "github.com/rancher/os/config/cloudinit/datasource/metadata/packet"
  37. "github.com/rancher/os/config/cloudinit/datasource/proccmdline"
  38. "github.com/rancher/os/config/cloudinit/datasource/url"
  39. "github.com/rancher/os/config/cloudinit/datasource/vmware"
  40. "github.com/rancher/os/config/cloudinit/pkg"
  41. "github.com/rancher/os/pkg/log"
  42. "github.com/rancher/os/pkg/netconf"
  43. "github.com/rancher/os/pkg/util"
  44. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  45. )
  46. const (
  47. datasourceInterval = 100 * time.Millisecond
  48. datasourceMaxInterval = 30 * time.Second
  49. datasourceTimeout = 5 * time.Minute
  50. )
  51. func Main() {
  52. log.InitLogger()
  53. log.Info("Running cloud-init-save")
  54. if err := control.UdevSettle(); err != nil {
  55. log.Errorf("Failed to run udev settle: %v", err)
  56. }
  57. if err := saveCloudConfig(); err != nil {
  58. log.Errorf("Failed to save cloud-config: %v", err)
  59. }
  60. // exit wpa_supplicant
  61. netconf.StopWpaSupplicant()
  62. // exit dhcpcd
  63. netconf.StopDhcpcd()
  64. }
  65. func saveCloudConfig() error {
  66. log.Infof("SaveCloudConfig")
  67. cfg := rancherConfig.LoadConfig()
  68. log.Debugf("init: SaveCloudConfig(pre ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  69. network.ApplyNetworkConfig(cfg)
  70. log.Infof("datasources that will be considered: %#v", cfg.Rancher.CloudInit.Datasources)
  71. dss := getDatasources(cfg.Rancher.CloudInit.Datasources)
  72. if len(dss) == 0 {
  73. log.Errorf("currentDatasource - none found")
  74. return nil
  75. }
  76. foundDs := selectDatasource(dss)
  77. log.Infof("Cloud-init datasource that was used: %s", foundDs)
  78. // Apply any newly detected network config.
  79. cfg = rancherConfig.LoadConfig()
  80. log.Debugf("init: SaveCloudConfig(post ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  81. network.ApplyNetworkConfig(cfg)
  82. return nil
  83. }
  84. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  85. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  86. if len(scriptBytes) > 0 {
  87. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  88. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  89. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  90. return err
  91. }
  92. }
  93. if len(cloudConfigBytes) > 0 {
  94. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  95. return err
  96. }
  97. log.Infof("Wrote to %s", rancherConfig.CloudConfigBootFile)
  98. }
  99. metaDataBytes, err := yaml.Marshal(metadata)
  100. if err != nil {
  101. return err
  102. }
  103. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  104. return err
  105. }
  106. log.Infof("Wrote to %s", rancherConfig.MetaDataFile)
  107. // if we write the empty meta yml, the merge fails.
  108. // 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
  109. emptyMeta, err := yaml.Marshal(datasource.Metadata{})
  110. if err != nil {
  111. return err
  112. }
  113. if bytes.Compare(metaDataBytes, emptyMeta) == 0 {
  114. log.Infof("not writing %s: its all defaults.", rancherConfig.CloudConfigNetworkFile)
  115. return nil
  116. }
  117. type nonRancherCfg struct {
  118. Network netconf.NetworkConfig `yaml:"network,omitempty"`
  119. }
  120. type nonCfg struct {
  121. Rancher nonRancherCfg `yaml:"rancher,omitempty"`
  122. }
  123. // write the network.yml file from metadata
  124. cc := nonCfg{
  125. Rancher: nonRancherCfg{
  126. Network: metadata.NetworkConfig,
  127. },
  128. }
  129. if err := os.MkdirAll(path.Dir(rancherConfig.CloudConfigNetworkFile), 0700); err != nil {
  130. log.Errorf("Failed to create directory for file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  131. }
  132. if err := rancherConfig.WriteToFile(cc, rancherConfig.CloudConfigNetworkFile); err != nil {
  133. log.Errorf("Failed to save config file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  134. }
  135. log.Infof("Wrote to %s", rancherConfig.CloudConfigNetworkFile)
  136. return nil
  137. }
  138. func fetchAndSave(ds datasource.Datasource) error {
  139. var metadata datasource.Metadata
  140. log.Infof("Fetching user-data from datasource %s", ds)
  141. userDataBytes, err := ds.FetchUserdata()
  142. if err != nil {
  143. log.Errorf("Failed fetching user-data from datasource: %v", err)
  144. return err
  145. }
  146. userDataBytes, err = decompressIfGzip(userDataBytes)
  147. if err != nil {
  148. log.Errorf("Failed decompressing user-data from datasource: %v", err)
  149. return err
  150. }
  151. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  152. metadata, err = ds.FetchMetadata()
  153. if err != nil {
  154. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  155. return err
  156. }
  157. userData := string(userDataBytes)
  158. scriptBytes := []byte{}
  159. if config.IsScript(userData) {
  160. scriptBytes = userDataBytes
  161. userDataBytes = []byte{}
  162. } else if isCompose(userData) {
  163. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  164. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  165. return err
  166. }
  167. } else if config.IsCloudConfig(userData) {
  168. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  169. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  170. userDataBytes = []byte{}
  171. }
  172. } else {
  173. log.Errorf("Unrecognized user-data\n(%s)", userData)
  174. userDataBytes = []byte{}
  175. }
  176. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  177. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  178. return errors.New("Failed to parse cloud-config")
  179. }
  180. return saveFiles(userDataBytes, scriptBytes, metadata)
  181. }
  182. // getDatasources creates a slice of possible Datasources for cloudinit based
  183. // on the different source command-line flags.
  184. func getDatasources(datasources []string) []datasource.Datasource {
  185. dss := make([]datasource.Datasource, 0, 5)
  186. for _, ds := range datasources {
  187. parts := strings.SplitN(ds, ":", 2)
  188. root := ""
  189. if len(parts) > 1 {
  190. root = parts[1]
  191. }
  192. switch parts[0] {
  193. case "*":
  194. dss = append(dss, getDatasources([]string{"configdrive", "vmware", "ec2", "digitalocean", "packet", "gce", "cloudstack"})...)
  195. case "cloudstack":
  196. for _, source := range cloudstack.NewDatasource(root) {
  197. dss = append(dss, source)
  198. }
  199. case "ec2":
  200. dss = append(dss, ec2.NewDatasource(root))
  201. case "file":
  202. if root != "" {
  203. dss = append(dss, file.NewDatasource(root))
  204. }
  205. case "url":
  206. if root != "" {
  207. dss = append(dss, url.NewDatasource(root))
  208. }
  209. case "cmdline":
  210. if len(parts) == 1 {
  211. dss = append(dss, proccmdline.NewDatasource())
  212. }
  213. case "configdrive":
  214. if root == "" {
  215. root = "/media/config-2"
  216. }
  217. dss = append(dss, configdrive.NewDatasource(root))
  218. case "digitalocean":
  219. // TODO: should we enableDoLinkLocal() - to avoid the need for the other kernel/oem options?
  220. dss = append(dss, digitalocean.NewDatasource(root))
  221. case "gce":
  222. dss = append(dss, gce.NewDatasource(root))
  223. case "packet":
  224. dss = append(dss, packet.NewDatasource(root))
  225. case "vmware":
  226. // made vmware datasource dependent on detecting vmware independently, as it crashes things otherwise
  227. v := vmware.NewDatasource(root)
  228. if v != nil {
  229. dss = append(dss, v)
  230. }
  231. case "aliyun":
  232. dss = append(dss, aliyun.NewDatasource(root))
  233. }
  234. }
  235. return dss
  236. }
  237. func enableDoLinkLocal() {
  238. cfg := rancherConfig.LoadConfig()
  239. dhcpTimeout := cfg.Rancher.Defaults.Network.DHCPTimeout
  240. if cfg.Rancher.Network.DHCPTimeout > 0 {
  241. dhcpTimeout = cfg.Rancher.Network.DHCPTimeout
  242. }
  243. _, err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  244. Interfaces: map[string]netconf.InterfaceConfig{
  245. "eth0": {
  246. IPV4LL: true,
  247. },
  248. },
  249. DHCPTimeout: dhcpTimeout,
  250. }, false, false)
  251. if err != nil {
  252. log.Errorf("Failed to apply link local on eth0: %v", err)
  253. }
  254. }
  255. // selectDatasource attempts to choose a valid Datasource to use based on its
  256. // current availability. The first Datasource to report to be available is
  257. // returned. Datasources will be retried if possible if they are not
  258. // immediately available. If all Datasources are permanently unavailable or
  259. // datasourceTimeout is reached before one becomes available, nil is returned.
  260. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  261. ds := make(chan datasource.Datasource)
  262. stop := make(chan struct{})
  263. var wg sync.WaitGroup
  264. for _, s := range sources {
  265. wg.Add(1)
  266. go func(s datasource.Datasource) {
  267. defer wg.Done()
  268. duration := datasourceInterval
  269. for {
  270. log.Infof("cloud-init: Checking availability of %q", s.Type())
  271. if s.IsAvailable() {
  272. log.Infof("cloud-init: Datasource available: %s", s)
  273. ds <- s
  274. return
  275. }
  276. if !s.AvailabilityChanges() {
  277. log.Infof("cloud-init: Datasource unavailable, skipping: %s", s)
  278. return
  279. }
  280. log.Errorf("cloud-init: Datasource not ready, will retry: %s", s)
  281. select {
  282. case <-stop:
  283. return
  284. case <-time.After(duration):
  285. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  286. }
  287. }
  288. }(s)
  289. }
  290. done := make(chan struct{})
  291. go func() {
  292. wg.Wait()
  293. close(done)
  294. }()
  295. var s datasource.Datasource
  296. select {
  297. case s = <-ds:
  298. err := fetchAndSave(s)
  299. if err != nil {
  300. log.Errorf("Error fetching cloud-init datasource(%s): %s", s, err)
  301. }
  302. case <-done:
  303. case <-time.After(datasourceTimeout):
  304. }
  305. close(stop)
  306. return s
  307. }
  308. func isCompose(content string) bool {
  309. return strings.HasPrefix(content, "#compose\n")
  310. }
  311. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  312. compose := make(map[interface{}]interface{})
  313. err := yaml.Unmarshal(bytes, &compose)
  314. if err != nil {
  315. return nil, err
  316. }
  317. return yaml.Marshal(map[interface{}]interface{}{
  318. "rancher": map[interface{}]interface{}{
  319. "services": compose,
  320. },
  321. })
  322. }
  323. const gzipMagicBytes = "\x1f\x8b"
  324. func decompressIfGzip(userdataBytes []byte) ([]byte, error) {
  325. if !bytes.HasPrefix(userdataBytes, []byte(gzipMagicBytes)) {
  326. return userdataBytes, nil
  327. }
  328. return config.DecompressGzip(userdataBytes)
  329. }