Skip to content

Commit bf32e2d

Browse files
committed
MCreate helper function for making api call
1 parent de05cbc commit bf32e2d

File tree

2 files changed

+62
-63
lines changed

2 files changed

+62
-63
lines changed

test/entity/entity_test.go

Lines changed: 13 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@
44
package entity
55

66
import (
7-
"bytes"
8-
"context"
9-
"crypto/sha256"
10-
"encoding/hex"
117
"encoding/json"
128
"fmt"
139
"log"
@@ -18,8 +14,6 @@ import (
1814
"time"
1915

2016
"github.com/aws/aws-sdk-go-v2/aws"
21-
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
22-
"github.com/aws/aws-sdk-go-v2/config"
2317
"github.com/stretchr/testify/assert"
2418

2519
"github.com/aws/amazon-cloudwatch-agent-test/environment"
@@ -256,56 +250,16 @@ func TestResourceMetrics(t *testing.T) {
256250
time.Sleep(sleepForFlush)
257251
common.StopAgent()
258252

259-
// this section builds, signs, and sends the request
260-
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
261-
assert.NoError(t, err)
262-
signer := v4.NewSigner()
263-
264-
body := []byte(fmt.Sprintf(`{
265-
"Namespace": "CWAgent",
266-
"MetricName": "cpu_usage_idle",
267-
"Dimensions": [
268-
{"Name": "InstanceId", "Value": "%s"},
269-
{"Name": "cpu", "Value": "cpu-total"}
270-
]
271-
}`, instanceId))
272-
273-
h := sha256.New()
274-
h.Write(body)
275-
payloadHash := hex.EncodeToString(h.Sum(nil))
276-
277-
// essentially trying to convert this curl command:
278-
279-
// curl -i -X POST monitoring.us-west-2.amazonaws.com -H 'Content-Type: application/json' \
280-
// -H 'Content-Encoding: amz-1.0' \
281-
// --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
282-
// -H "x-amz-security-token: $AWS_SESSION_TOKEN" \
283-
// --aws-sigv4 "aws:amz:us-west-2:monitoring" \
284-
// -H 'X-Amz-Target: com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.ListEntitiesForMetric' \
285-
// -d '{
286-
// "Namespace": "CWAgent",
287-
// "MetricName": "cpu_usage_idle",
288-
// "Dimensions": [{"Name": "InstanceId", "Value": "i-0123456789012"}, { "Name": "cpu", "Value": "cpu-total"}]
289-
// }'
290-
291-
// build the request
292-
req, err := http.NewRequest("POST", "https://monitoring."+region+".amazonaws.com/", bytes.NewReader(body))
293-
assert.NoError(t, err, "Error creating request")
294-
295-
// set headers
296-
req.Header.Set("Content-Type", "application/json")
297-
req.Header.Set("X-Amz-Target", "com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.ListEntitiesForMetric")
298-
req.Header.Set("Content-Encoding", "amz-1.0")
299-
300-
// set creds
301-
credentials, err := cfg.Credentials.Retrieve(context.TODO())
302-
assert.NoError(t, err, "Error getting credentials")
303-
304-
req.Header.Set("x-amz-security-token", credentials.SessionToken)
305-
306-
// sign the request
307-
err = signer.SignHTTP(context.TODO(), credentials, req, payloadHash, "monitoring", region, time.Now())
308-
assert.NoError(t, err, "Error signing the request")
253+
// build ListEntitiesForMetric request:
254+
requestBody := []byte(fmt.Sprintf(`{
255+
"Namespace": "CWAgent",
256+
"MetricName": "cpu_usage_idle",
257+
"Dimensions": [
258+
{"Name": "InstanceId", "Value": "%s"},
259+
{"Name": "cpu", "Value": "cpu-total"}
260+
]
261+
}`, instanceId))
262+
req = BuildListEntitiesForMetricRequest(requestBody, region)
309263

310264
// send the request
311265
client := &http.Client{}
@@ -328,22 +282,18 @@ func TestResourceMetrics(t *testing.T) {
328282
assert.NoError(t, err, "Error parsing JSON response")
329283

330284
// Verify the KeyAttributes
331-
assert.NotEmpty(t, response.Entities, "No entities found in the response")
332-
entity := response.Entities[0]
333-
// assert.Equal(t, "AWS::Resource", entity.KeyAttributes.Type)
334-
// assert.Equal(t, "AWS::EC2::Instance", entity.KeyAttributes.ResourceType)
335-
// assert.Equal(t, instanceId, entity.KeyAttributes.Identifier)
336-
337285
expectedEntity := expectedEntity{
338286
entityType: "AWS::Resource",
339287
platformType: "AWS::EC2::Instance",
340288
instanceId: instanceId,
341289
}
290+
assert.NotEmpty(t, response.Entities, "No entities found in the response")
291+
292+
entity := response.Entities[0]
342293
validator := NewEntityValidator("EC2", expectedEntity)
343294
validator.ValidateField(entityType, entity.KeyAttributes.Type, t)
344295
validator.ValidateField(entityPlatform, entity.KeyAttributes.ResourceType, t)
345296
validator.ValidateField(entityInstanceId, entity.KeyAttributes.Identifier, t)
346-
347297
}
348298

349299
// ValidateLogEntity performs the entity validation for PutLogEvents.

util/common/metrics.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"bytes"
88
"context"
99
"crypto/rand"
10+
"crypto/sha256"
1011
"encoding/binary"
1112
"encoding/hex"
1213
"errors"
@@ -23,7 +24,10 @@ import (
2324
"collectd.org/exec"
2425
"collectd.org/network"
2526
"github.com/DataDog/datadog-go/statsd"
27+
"github.com/aws/aws-sdk-go-v2/config"
28+
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
2629
"github.com/prozz/aws-embedded-metrics-golang/emf"
30+
"github.com/stretchr/testify/assert"
2731
)
2832

2933
const SleepDuration = 5 * time.Second
@@ -350,3 +354,48 @@ func SendEMFMetrics(metricPerInterval int, metricLogGroup, metricNamespace strin
350354
}
351355

352356
}
357+
358+
// This function builds and signs an ListEntitiesForMetric call, essentially trying to replicate this curl command:
359+
//
360+
// curl -i -X POST monitoring.us-west-2.amazonaws.com -H 'Content-Type: application/json' \
361+
// -H 'Content-Encoding: amz-1.0' \
362+
// --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
363+
// -H "x-amz-security-token: $AWS_SESSION_TOKEN" \
364+
// --aws-sigv4 "aws:amz:us-west-2:monitoring" \
365+
// -H 'X-Amz-Target: com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.ListEntitiesForMetric' \
366+
// -d '{
367+
// // sample request body:
368+
// "Namespace": "CWAgent",
369+
// "MetricName": "cpu_usage_idle",
370+
// "Dimensions": [{"Name": "InstanceId", "Value": "i-0123456789012"}, { "Name": "cpu", "Value": "cpu-total"}]
371+
// }'
372+
func BuildListEntitiesForMetricRequest(body []byte, region string) {
373+
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
374+
assert.NoError(t, err)
375+
signer := v4.NewSigner()
376+
h := sha256.New()
377+
378+
h.Write(body)
379+
payloadHash := hex.EncodeToString(h.Sum(nil))
380+
381+
// build the request
382+
req, err := http.NewRequest("POST", "https://monitoring."+region+".amazonaws.com/", bytes.NewReader(body))
383+
assert.NoError(t, err, "Error creating request")
384+
385+
// set headers
386+
req.Header.Set("Content-Type", "application/json")
387+
req.Header.Set("X-Amz-Target", "com.amazonaws.cloudwatch.v2013_01_16.CloudWatchVersion20130116.ListEntitiesForMetric")
388+
req.Header.Set("Content-Encoding", "amz-1.0")
389+
390+
// set creds
391+
credentials, err := cfg.Credentials.Retrieve(context.TODO())
392+
assert.NoError(t, err, "Error getting credentials")
393+
394+
req.Header.Set("x-amz-security-token", credentials.SessionToken)
395+
396+
// sign the request
397+
err = signer.SignHTTP(context.TODO(), credentials, req, payloadHash, "monitoring", region, time.Now())
398+
assert.NoError(t, err, "Error signing the request")
399+
400+
return req
401+
}

0 commit comments

Comments
 (0)