github.com/newrelic/go-agent@v3.26.0+incompatible/internal/utilization/pcf.go (about)

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