Skip to content

Commit

Permalink
Get Stats For IMDSV2 Fallback Succeed (#838)
Browse files Browse the repository at this point in the history
  • Loading branch information
sethAmazon authored Sep 6, 2023
1 parent 1bf4849 commit c8a4d15
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 3 deletions.
18 changes: 18 additions & 0 deletions handlers/agentinfo/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ var (
fullVersion = getFullVersion(version)
id = uuid.NewString()
sharedConfigFallback atomic.Bool
imdsFallbackSucceed atomic.Bool
)

var isRunningAsRoot = defaultIsRunningAsRoot
Expand All @@ -75,6 +76,7 @@ type agentStats struct {
PayloadBytes *int `json:"load,omitempty"`
StatusCode *int `json:"code,omitempty"`
SharedConfigFallback *int `json:"scfb,omitempty"`
ImdsFallbackSucceed *int `json:"ifs,omitempty"`
}

func New(groupName string) AgentInfo {
Expand Down Expand Up @@ -123,6 +125,7 @@ func (ai *agentInfo) RecordOpData(latency time.Duration, payloadBytes int, err e
stats.FileDescriptorCount = ai.fileDescriptorCount()
stats.ThreadCount = ai.threadCount()
stats.SharedConfigFallback = getSharedConfigFallback()
stats.ImdsFallbackSucceed = succeedImdsFallback()
ai.nextUpdate = now.Add(updateInterval)
}

Expand Down Expand Up @@ -154,6 +157,15 @@ func (ai *agentInfo) fileDescriptorCount() *int32 {
return nil
}

// we only need to know if value is 1
// thus return nil if not set
func succeedImdsFallback() *int {
if imdsFallbackSucceed.Load() {
return aws.Int(1)
}
return nil
}

func (ai *agentInfo) threadCount() *int32 {
if thCount, err := ai.proc.NumThreads(); err == nil {
return aws.Int32(thCount)
Expand Down Expand Up @@ -286,6 +298,8 @@ func readVersionFile() string {
return strings.Trim(string(byteArray), " \n\r\t")
}

// this returns true for true or invalid
// examples of invalid are not set env var, "", "invalid"
func getUsageDataEnabled() bool {
ok, err := strconv.ParseBool(os.Getenv(envconfig.CWAGENT_USAGE_DATA))
return ok || err != nil
Expand All @@ -312,3 +326,7 @@ func getSharedConfigFallback() *int {
}
return nil
}

func SetImdsFallbackSucceed() {
imdsFallbackSucceed.Store(true)
}
13 changes: 13 additions & 0 deletions handlers/agentinfo/info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,12 @@ func TestGetAgentStats(t *testing.T) {
LatencyMillis: aws.Int64(1234),
PayloadBytes: aws.Int(5678),
StatusCode: aws.Int(200),
ImdsFallbackSucceed: aws.Int(1),
}

assert.Equal(t, "\"cpu\":1.2,\"mem\":123,\"fd\":456,\"th\":789,\"lat\":1234,\"load\":5678,\"code\":200,\"ifs\":1", getAgentStats(stats))

stats.ImdsFallbackSucceed = nil
assert.Equal(t, "\"cpu\":1.2,\"mem\":123,\"fd\":456,\"th\":789,\"lat\":1234,\"load\":5678,\"code\":200", getAgentStats(stats))

stats.CpuPercent = nil
Expand Down Expand Up @@ -246,3 +250,12 @@ func TestSharedConfigFallback(t *testing.T) {
RecordSharedConfigFallback()
assert.Equal(t, 1, *(getSharedConfigFallback()))
}

func TestSetImdsFallbackSucceed(t *testing.T) {
defer imdsFallbackSucceed.Store(false)
assert.False(t, imdsFallbackSucceed.Load())
assert.Nil(t, succeedImdsFallback())
SetImdsFallbackSucceed()
assert.True(t, imdsFallbackSucceed.Load())
assert.Equal(t, aws.Int(1), succeedImdsFallback())
}
19 changes: 16 additions & 3 deletions plugins/processors/ec2tagger/ec2metadataprovider.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/aws/aws-sdk-go/aws/ec2metadata"

configaws "github.com/aws/amazon-cloudwatch-agent/cfg/aws"
"github.com/aws/amazon-cloudwatch-agent/handlers/agentinfo"
"github.com/aws/amazon-cloudwatch-agent/internal/retryer"
)

Expand Down Expand Up @@ -49,7 +50,11 @@ func (c *metadataClient) InstanceID(ctx context.Context) (string, error) {
instanceId, err := c.metadataFallbackDisabled.GetMetadataWithContext(ctx, "instance-id")
if err != nil {
log.Printf("D! could not get instance id without imds v1 fallback enable thus enable fallback")
return c.metadataFallbackEnabled.GetMetadataWithContext(ctx, "instance-id")
instanceInner, errorInner := c.metadataFallbackEnabled.GetMetadataWithContext(ctx, "instance-id")
if errorInner == nil {
agentinfo.SetImdsFallbackSucceed()
}
return instanceInner, errorInner
}
return instanceId, err
}
Expand All @@ -58,7 +63,11 @@ func (c *metadataClient) Hostname(ctx context.Context) (string, error) {
hostname, err := c.metadataFallbackDisabled.GetMetadataWithContext(ctx, "hostname")
if err != nil {
log.Printf("D! could not get hostname without imds v1 fallback enable thus enable fallback")
return c.metadataFallbackEnabled.GetMetadataWithContext(ctx, "hostname")
hostnameInner, errorInner := c.metadataFallbackEnabled.GetMetadataWithContext(ctx, "hostname")
if errorInner == nil {
agentinfo.SetImdsFallbackSucceed()
}
return hostnameInner, errorInner
}
return hostname, err
}
Expand All @@ -67,7 +76,11 @@ func (c *metadataClient) Get(ctx context.Context) (ec2metadata.EC2InstanceIdenti
instanceDocument, err := c.metadataFallbackDisabled.GetInstanceIdentityDocumentWithContext(ctx)
if err != nil {
log.Printf("D! could not get instance document without imds v1 fallback enable thus enable fallback")
return c.metadataFallbackEnabled.GetInstanceIdentityDocumentWithContext(ctx)
instanceDocumentInner, errorInner := c.metadataFallbackEnabled.GetInstanceIdentityDocumentWithContext(ctx)
if errorInner == nil {
agentinfo.SetImdsFallbackSucceed()
}
return instanceDocumentInner, errorInner
}
return instanceDocument, err
}
3 changes: 3 additions & 0 deletions translator/util/ec2util/ec2util.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"

configaws "github.com/aws/amazon-cloudwatch-agent/cfg/aws"
"github.com/aws/amazon-cloudwatch-agent/handlers/agentinfo"
"github.com/aws/amazon-cloudwatch-agent/internal/retryer"
"github.com/aws/amazon-cloudwatch-agent/translator/config"
"github.com/aws/amazon-cloudwatch-agent/translator/context"
Expand Down Expand Up @@ -116,6 +117,7 @@ func (e *ec2Util) deriveEC2MetadataFromIMDS() error {
hostnameInner, errInner := mdEnableFallback.GetMetadata("hostname")
if errInner == nil {
e.Hostname = hostnameInner
agentinfo.SetImdsFallbackSucceed()
} else {
fmt.Println("E! [EC2] Fetch hostname from EC2 metadata fail:", errInner)
}
Expand All @@ -135,6 +137,7 @@ func (e *ec2Util) deriveEC2MetadataFromIMDS() error {
e.AccountID = instanceIdentityDocumentInner.AccountID
e.PrivateIP = instanceIdentityDocumentInner.PrivateIP
e.InstanceID = instanceIdentityDocumentInner.InstanceID
agentinfo.SetImdsFallbackSucceed()
} else {
fmt.Println("E! [EC2] Fetch identity document from EC2 metadata fail:", errInner)
}
Expand Down

0 comments on commit c8a4d15

Please sign in to comment.