cloudinitsave.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // Copyright 2015 CoreOS, Inc.
  2. // Copyright 2015 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. "errors"
  18. "flag"
  19. "os"
  20. "strings"
  21. "sync"
  22. "time"
  23. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  24. log "github.com/Sirupsen/logrus"
  25. "github.com/coreos/coreos-cloudinit/config"
  26. "github.com/coreos/coreos-cloudinit/datasource"
  27. "github.com/coreos/coreos-cloudinit/datasource/configdrive"
  28. "github.com/coreos/coreos-cloudinit/datasource/file"
  29. "github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean"
  30. "github.com/coreos/coreos-cloudinit/datasource/metadata/ec2"
  31. "github.com/coreos/coreos-cloudinit/datasource/metadata/packet"
  32. "github.com/coreos/coreos-cloudinit/datasource/proc_cmdline"
  33. "github.com/coreos/coreos-cloudinit/datasource/url"
  34. "github.com/coreos/coreos-cloudinit/pkg"
  35. "github.com/rancher/netconf"
  36. "github.com/rancher/os/cmd/cloudinitsave/gce"
  37. rancherConfig "github.com/rancher/os/config"
  38. "github.com/rancher/os/util"
  39. )
  40. const (
  41. datasourceInterval = 100 * time.Millisecond
  42. datasourceMaxInterval = 30 * time.Second
  43. datasourceTimeout = 5 * time.Minute
  44. )
  45. var (
  46. network bool
  47. flags *flag.FlagSet
  48. )
  49. func init() {
  50. flags = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
  51. flags.BoolVar(&network, "network", true, "use network based datasources")
  52. }
  53. func Main() {
  54. flags.Parse(os.Args[1:])
  55. log.Infof("Running cloud-init-save: network=%v", network)
  56. if err := saveCloudConfig(); err != nil {
  57. log.Errorf("Failed to save cloud-config: %v", err)
  58. }
  59. }
  60. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  61. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  62. if len(scriptBytes) > 0 {
  63. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  64. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  65. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  66. return err
  67. }
  68. }
  69. if len(cloudConfigBytes) > 0 {
  70. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  71. return err
  72. }
  73. log.Infof("Written to %s:\n%s", rancherConfig.CloudConfigBootFile, string(cloudConfigBytes))
  74. }
  75. metaDataBytes, err := yaml.Marshal(metadata)
  76. if err != nil {
  77. return err
  78. }
  79. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  80. return err
  81. }
  82. log.Infof("Written to %s:\n%s", rancherConfig.MetaDataFile, string(metaDataBytes))
  83. return nil
  84. }
  85. func currentDatasource() (datasource.Datasource, error) {
  86. cfg := rancherConfig.LoadConfig()
  87. dss := getDatasources(cfg)
  88. if len(dss) == 0 {
  89. return nil, nil
  90. }
  91. ds := selectDatasource(dss)
  92. return ds, nil
  93. }
  94. func saveCloudConfig() error {
  95. userDataBytes, metadata, err := fetchUserData()
  96. if err != nil {
  97. return err
  98. }
  99. userData := string(userDataBytes)
  100. scriptBytes := []byte{}
  101. if config.IsScript(userData) {
  102. scriptBytes = userDataBytes
  103. userDataBytes = []byte{}
  104. } else if isCompose(userData) {
  105. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  106. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  107. return err
  108. }
  109. } else if config.IsCloudConfig(userData) {
  110. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  111. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  112. userDataBytes = []byte{}
  113. }
  114. } else {
  115. log.Errorf("Unrecognized user-data\n%s", userData)
  116. userDataBytes = []byte{}
  117. }
  118. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  119. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  120. return errors.New("Failed to parse cloud-config")
  121. }
  122. return saveFiles(userDataBytes, scriptBytes, metadata)
  123. }
  124. func fetchUserData() ([]byte, datasource.Metadata, error) {
  125. var metadata datasource.Metadata
  126. ds, err := currentDatasource()
  127. if err != nil || ds == nil {
  128. log.Errorf("Failed to select datasource: %v", err)
  129. return nil, metadata, err
  130. }
  131. log.Infof("Fetching user-data from datasource %v", ds.Type())
  132. userDataBytes, err := ds.FetchUserdata()
  133. if err != nil {
  134. log.Errorf("Failed fetching user-data from datasource: %v", err)
  135. return nil, metadata, err
  136. }
  137. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  138. metadata, err = ds.FetchMetadata()
  139. if err != nil {
  140. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  141. return nil, metadata, err
  142. }
  143. return userDataBytes, metadata, nil
  144. }
  145. // getDatasources creates a slice of possible Datasources for cloudinit based
  146. // on the different source command-line flags.
  147. func getDatasources(cfg *rancherConfig.CloudConfig) []datasource.Datasource {
  148. dss := make([]datasource.Datasource, 0, 5)
  149. for _, ds := range cfg.Rancher.CloudInit.Datasources {
  150. parts := strings.SplitN(ds, ":", 2)
  151. switch parts[0] {
  152. case "ec2":
  153. if network {
  154. if len(parts) == 1 {
  155. dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress))
  156. } else {
  157. dss = append(dss, ec2.NewDatasource(parts[1]))
  158. }
  159. }
  160. case "file":
  161. if len(parts) == 2 {
  162. dss = append(dss, file.NewDatasource(parts[1]))
  163. }
  164. case "url":
  165. if network {
  166. if len(parts) == 2 {
  167. dss = append(dss, url.NewDatasource(parts[1]))
  168. }
  169. }
  170. case "cmdline":
  171. if network {
  172. if len(parts) == 1 {
  173. dss = append(dss, proc_cmdline.NewDatasource())
  174. }
  175. }
  176. case "configdrive":
  177. if len(parts) == 2 {
  178. dss = append(dss, configdrive.NewDatasource(parts[1]))
  179. }
  180. case "digitalocean":
  181. if network {
  182. if len(parts) == 1 {
  183. dss = append(dss, digitalocean.NewDatasource(digitalocean.DefaultAddress))
  184. } else {
  185. dss = append(dss, digitalocean.NewDatasource(parts[1]))
  186. }
  187. } else {
  188. enableDoLinkLocal()
  189. }
  190. case "gce":
  191. if network {
  192. dss = append(dss, gce.NewDatasource("http://metadata.google.internal/"))
  193. }
  194. case "packet":
  195. if !network {
  196. enablePacketNetwork(&cfg.Rancher)
  197. }
  198. dss = append(dss, packet.NewDatasource("https://metadata.packet.net/"))
  199. }
  200. }
  201. return dss
  202. }
  203. func enableDoLinkLocal() {
  204. err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  205. Interfaces: map[string]netconf.InterfaceConfig{
  206. "eth0": {
  207. IPV4LL: true,
  208. },
  209. },
  210. })
  211. if err != nil {
  212. log.Errorf("Failed to apply link local on eth0: %v", err)
  213. }
  214. }
  215. // selectDatasource attempts to choose a valid Datasource to use based on its
  216. // current availability. The first Datasource to report to be available is
  217. // returned. Datasources will be retried if possible if they are not
  218. // immediately available. If all Datasources are permanently unavailable or
  219. // datasourceTimeout is reached before one becomes available, nil is returned.
  220. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  221. ds := make(chan datasource.Datasource)
  222. stop := make(chan struct{})
  223. var wg sync.WaitGroup
  224. for _, s := range sources {
  225. wg.Add(1)
  226. go func(s datasource.Datasource) {
  227. defer wg.Done()
  228. duration := datasourceInterval
  229. for {
  230. log.Infof("Checking availability of %q\n", s.Type())
  231. if s.IsAvailable() {
  232. ds <- s
  233. return
  234. } else if !s.AvailabilityChanges() {
  235. return
  236. }
  237. select {
  238. case <-stop:
  239. return
  240. case <-time.After(duration):
  241. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  242. }
  243. }
  244. }(s)
  245. }
  246. done := make(chan struct{})
  247. go func() {
  248. wg.Wait()
  249. close(done)
  250. }()
  251. var s datasource.Datasource
  252. select {
  253. case s = <-ds:
  254. case <-done:
  255. case <-time.After(datasourceTimeout):
  256. }
  257. close(stop)
  258. return s
  259. }
  260. func isCompose(content string) bool {
  261. return strings.HasPrefix(content, "#compose\n")
  262. }
  263. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  264. compose := make(map[interface{}]interface{})
  265. err := yaml.Unmarshal(bytes, &compose)
  266. if err != nil {
  267. return nil, err
  268. }
  269. return yaml.Marshal(map[interface{}]interface{}{
  270. "rancher": map[interface{}]interface{}{
  271. "services": compose,
  272. },
  273. })
  274. }