metadata.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package metadata
  15. import (
  16. "fmt"
  17. "net/http"
  18. "strings"
  19. "github.com/rancher/os/config/cloudinit/pkg"
  20. "github.com/rancher/os/log"
  21. )
  22. type Service struct {
  23. Root string
  24. Client pkg.Getter
  25. APIVersion string
  26. UserdataPath string
  27. MetadataPath string
  28. lastError error
  29. }
  30. func NewDatasource(root, apiVersion, userdataPath, metadataPath string, header http.Header) Service {
  31. if !strings.HasSuffix(root, "/") {
  32. root += "/"
  33. }
  34. return Service{root, pkg.NewHTTPClientHeader(header), apiVersion, userdataPath, metadataPath, nil}
  35. }
  36. func (ms Service) IsAvailable() bool {
  37. _, ms.lastError = ms.Client.Get(ms.Root + ms.APIVersion)
  38. if ms.lastError != nil {
  39. log.Errorf("%s: %s (lastError: %s)", "IsAvailable", ms.Root+":"+ms.UserdataPath, ms.lastError)
  40. }
  41. return (ms.lastError == nil)
  42. }
  43. func (ms *Service) Finish() error {
  44. return nil
  45. }
  46. func (ms *Service) String() string {
  47. return fmt.Sprintf("%s: %s (lastError: %s)", "metadata", ms.Root+ms.UserdataPath, ms.lastError)
  48. }
  49. func (ms Service) AvailabilityChanges() bool {
  50. return true
  51. }
  52. func (ms Service) ConfigRoot() string {
  53. return ms.Root
  54. }
  55. func (ms Service) FetchUserdata() ([]byte, error) {
  56. return ms.FetchData(ms.UserdataURL())
  57. }
  58. func (ms Service) FetchData(url string) ([]byte, error) {
  59. if data, err := ms.Client.GetRetry(url); err == nil {
  60. return data, err
  61. } else if _, ok := err.(pkg.ErrNotFound); ok {
  62. return []byte{}, nil
  63. } else {
  64. return data, err
  65. }
  66. }
  67. func (ms Service) MetadataURL() string {
  68. return (ms.Root + ms.MetadataPath)
  69. }
  70. func (ms Service) UserdataURL() string {
  71. return (ms.Root + ms.UserdataPath)
  72. }