metadata.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package aliyun
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "github.com/rancher/os/netconf"
  7. "github.com/rancher/os/config/cloudinit/datasource"
  8. "github.com/rancher/os/config/cloudinit/datasource/metadata"
  9. )
  10. const (
  11. DefaultAddress = "http://100.100.100.200/"
  12. apiVersion = "2016-01-01/"
  13. userdataPath = apiVersion + "user-data/"
  14. metadataPath = apiVersion + "meta-data/"
  15. )
  16. type MetadataService struct {
  17. metadata.Service
  18. }
  19. func NewDatasource(root string) *MetadataService {
  20. if root == "" {
  21. root = DefaultAddress
  22. }
  23. return &MetadataService{metadata.NewDatasource(root, apiVersion, userdataPath, metadataPath, nil)}
  24. }
  25. func (ms MetadataService) AvailabilityChanges() bool {
  26. // TODO: if it can't find the network, maybe we can start it?
  27. return false
  28. }
  29. func (ms MetadataService) FetchMetadata() (metadata datasource.Metadata, err error) {
  30. // see https://www.alibabacloud.com/help/faq-detail/49122.htm
  31. metadata.NetworkConfig = netconf.NetworkConfig{}
  32. enablePublicKey := false
  33. rootContents, err := ms.FetchAttributes("")
  34. if err != nil {
  35. return metadata, err
  36. }
  37. for _, c := range rootContents {
  38. if c == "public-keys/" {
  39. enablePublicKey = true
  40. break
  41. }
  42. }
  43. if !enablePublicKey {
  44. return metadata, fmt.Errorf("The public-keys should be enable in %s", ms.Type())
  45. }
  46. keynames, err := ms.FetchAttributes("public-keys/")
  47. if err != nil {
  48. return metadata, err
  49. }
  50. metadata.SSHPublicKeys = map[string]string{}
  51. for _, k := range keynames {
  52. k = strings.TrimRight(k, "/")
  53. sshkey, err := ms.FetchAttribute(fmt.Sprintf("public-keys/%s/openssh-key", k))
  54. if err != nil {
  55. return metadata, err
  56. }
  57. metadata.SSHPublicKeys[k] = sshkey
  58. log.Printf("Found SSH key for %q\n", k)
  59. }
  60. if hostname, err := ms.FetchAttribute("hostname"); err == nil {
  61. metadata.Hostname = hostname
  62. log.Printf("Found hostname %s\n", hostname)
  63. } else {
  64. return metadata, err
  65. }
  66. return metadata, nil
  67. }
  68. func (ms MetadataService) Type() string {
  69. return "aliyun-metadata-service"
  70. }