aws.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package utilization
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. const (
  9. awsHostname = "169.254.169.254"
  10. awsEndpointPath = "/2016-09-02/dynamic/instance-identity/document"
  11. awsEndpoint = "http://" + awsHostname + awsEndpointPath
  12. )
  13. type aws struct {
  14. InstanceID string `json:"instanceId,omitempty"`
  15. InstanceType string `json:"instanceType,omitempty"`
  16. AvailabilityZone string `json:"availabilityZone,omitempty"`
  17. }
  18. func gatherAWS(util *Data, client *http.Client) error {
  19. aws, err := getAWS(client)
  20. if err != nil {
  21. // Only return the error here if it is unexpected to prevent
  22. // warning customers who aren't running AWS about a timeout.
  23. if _, ok := err.(unexpectedAWSErr); ok {
  24. return err
  25. }
  26. return nil
  27. }
  28. util.Vendors.AWS = aws
  29. return nil
  30. }
  31. type unexpectedAWSErr struct{ e error }
  32. func (e unexpectedAWSErr) Error() string {
  33. return fmt.Sprintf("unexpected AWS error: %v", e.e)
  34. }
  35. func getAWS(client *http.Client) (*aws, error) {
  36. response, err := client.Get(awsEndpoint)
  37. if err != nil {
  38. // No unexpectedAWSErr here: A timeout is usually going to
  39. // happen.
  40. return nil, err
  41. }
  42. defer response.Body.Close()
  43. if response.StatusCode != 200 {
  44. return nil, unexpectedAWSErr{e: fmt.Errorf("response code %d", response.StatusCode)}
  45. }
  46. data, err := ioutil.ReadAll(response.Body)
  47. if err != nil {
  48. return nil, unexpectedAWSErr{e: err}
  49. }
  50. a := &aws{}
  51. if err := json.Unmarshal(data, a); err != nil {
  52. return nil, unexpectedAWSErr{e: err}
  53. }
  54. if err := a.validate(); err != nil {
  55. return nil, unexpectedAWSErr{e: err}
  56. }
  57. return a, nil
  58. }
  59. func (a *aws) validate() (err error) {
  60. a.InstanceID, err = normalizeValue(a.InstanceID)
  61. if err != nil {
  62. return fmt.Errorf("invalid instance ID: %v", err)
  63. }
  64. a.InstanceType, err = normalizeValue(a.InstanceType)
  65. if err != nil {
  66. return fmt.Errorf("invalid instance type: %v", err)
  67. }
  68. a.AvailabilityZone, err = normalizeValue(a.AvailabilityZone)
  69. if err != nil {
  70. return fmt.Errorf("invalid availability zone: %v", err)
  71. }
  72. return
  73. }