File: pcf.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (83 lines) | stat: -rw-r--r-- 1,942 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package utilization

import (
	"errors"
	"fmt"
	"net/http"
	"os"
)

type pcf struct {
	InstanceGUID string `json:"cf_instance_guid,omitempty"`
	InstanceIP   string `json:"cf_instance_ip,omitempty"`
	MemoryLimit  string `json:"memory_limit,omitempty"`
}

func gatherPCF(util *Data, _ *http.Client) error {
	pcf, err := getPCF(os.Getenv)
	if err != nil {
		// Only return the error here if it is unexpected to prevent
		// warning customers who aren't running PCF about a timeout.
		if _, ok := err.(unexpectedPCFErr); ok {
			return err
		}
		return nil
	}
	util.Vendors.PCF = pcf

	return nil
}

type unexpectedPCFErr struct{ e error }

func (e unexpectedPCFErr) Error() string {
	return fmt.Sprintf("unexpected PCF error: %v", e.e)
}

var (
	errNoPCFVariables = errors.New("no PCF environment variables present")
)

func getPCF(initializer func(key string) string) (*pcf, error) {
	p := &pcf{}

	p.InstanceGUID = initializer("CF_INSTANCE_GUID")
	p.InstanceIP = initializer("CF_INSTANCE_IP")
	p.MemoryLimit = initializer("MEMORY_LIMIT")

	if "" == p.InstanceGUID && "" == p.InstanceIP && "" == p.MemoryLimit {
		return nil, errNoPCFVariables
	}

	if err := p.validate(); err != nil {
		return nil, unexpectedPCFErr{e: err}
	}

	return p, nil
}

func (pcf *pcf) validate() (err error) {
	pcf.InstanceGUID, err = normalizeValue(pcf.InstanceGUID)
	if err != nil {
		return fmt.Errorf("Invalid instance GUID: %v", err)
	}

	pcf.InstanceIP, err = normalizeValue(pcf.InstanceIP)
	if err != nil {
		return fmt.Errorf("Invalid instance IP: %v", err)
	}

	pcf.MemoryLimit, err = normalizeValue(pcf.MemoryLimit)
	if err != nil {
		return fmt.Errorf("Invalid memory limit: %v", err)
	}

	if pcf.InstanceGUID == "" || pcf.InstanceIP == "" || pcf.MemoryLimit == "" {
		err = errors.New("One or more environment variables are unavailable")
	}

	return
}