pcf.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package utilization
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. )
  8. type pcf struct {
  9. InstanceGUID string `json:"cf_instance_guid,omitempty"`
  10. InstanceIP string `json:"cf_instance_ip,omitempty"`
  11. MemoryLimit string `json:"memory_limit,omitempty"`
  12. }
  13. func gatherPCF(util *Data, _ *http.Client) error {
  14. pcf, err := getPCF(os.Getenv)
  15. if err != nil {
  16. // Only return the error here if it is unexpected to prevent
  17. // warning customers who aren't running PCF about a timeout.
  18. if _, ok := err.(unexpectedPCFErr); ok {
  19. return err
  20. }
  21. return nil
  22. }
  23. util.Vendors.PCF = pcf
  24. return nil
  25. }
  26. type unexpectedPCFErr struct{ e error }
  27. func (e unexpectedPCFErr) Error() string {
  28. return fmt.Sprintf("unexpected PCF error: %v", e.e)
  29. }
  30. var (
  31. errNoPCFVariables = errors.New("no PCF environment variables present")
  32. )
  33. func getPCF(initializer func(key string) string) (*pcf, error) {
  34. p := &pcf{}
  35. p.InstanceGUID = initializer("CF_INSTANCE_GUID")
  36. p.InstanceIP = initializer("CF_INSTANCE_IP")
  37. p.MemoryLimit = initializer("MEMORY_LIMIT")
  38. if "" == p.InstanceGUID && "" == p.InstanceIP && "" == p.MemoryLimit {
  39. return nil, errNoPCFVariables
  40. }
  41. if err := p.validate(); err != nil {
  42. return nil, unexpectedPCFErr{e: err}
  43. }
  44. return p, nil
  45. }
  46. func (pcf *pcf) validate() (err error) {
  47. pcf.InstanceGUID, err = normalizeValue(pcf.InstanceGUID)
  48. if err != nil {
  49. return fmt.Errorf("Invalid instance GUID: %v", err)
  50. }
  51. pcf.InstanceIP, err = normalizeValue(pcf.InstanceIP)
  52. if err != nil {
  53. return fmt.Errorf("Invalid instance IP: %v", err)
  54. }
  55. pcf.MemoryLimit, err = normalizeValue(pcf.MemoryLimit)
  56. if err != nil {
  57. return fmt.Errorf("Invalid memory limit: %v", err)
  58. }
  59. if pcf.InstanceGUID == "" || pcf.InstanceIP == "" || pcf.MemoryLimit == "" {
  60. err = errors.New("One or more environment variables are unavailable")
  61. }
  62. return
  63. }