Skip to content

Commit

Permalink
fix linting
Browse files Browse the repository at this point in the history
  • Loading branch information
jj22ee committed Nov 6, 2024
1 parent b81daa4 commit 751437b
Show file tree
Hide file tree
Showing 26 changed files with 176 additions and 198 deletions.
4 changes: 2 additions & 2 deletions processor/awsapplicationsignalsprocessor/common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ const (
AttributeK8SWorkload = "K8s.Workload"
AttributeK8SPod = "K8s.Pod"
AttributeEC2AutoScalingGroup = "EC2.AutoScalingGroup"
AttributeEC2InstanceId = "EC2.InstanceId"
AttributeEC2InstanceID = "EC2.InstanceId"
AttributeHost = "Host"
)

// Platform attribute used as CloudWatch EMF log field.
const (
MetricAttributeECSCluster = "ECS.Cluster"
MetricAttributeECSTaskId = "ECS.TaskId"
MetricAttributeECSTaskID = "ECS.TaskId"
MetricAttributeECSTaskDefinitionFamily = "ECS.TaskDefinitionFamily"
MetricAttributeECSTaskDefinitionRevision = "ECS.TaskDefinitionRevision"
)
Expand Down
9 changes: 4 additions & 5 deletions processor/awsapplicationsignalsprocessor/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ import (
"context"
"errors"

appsignalsconfig "github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/processor"
"go.opentelemetry.io/collector/processor/processorhelper"

appsignalsconfig "github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
)

const (
Expand Down Expand Up @@ -44,7 +43,7 @@ func createDefaultConfig() component.Config {

func createTracesProcessor(
ctx context.Context,
set processor.CreateSettings,
set processor.CreateSettings, //nolint: staticcheck
cfg component.Config,
next consumer.Traces,
) (processor.Traces, error) {
Expand All @@ -66,7 +65,7 @@ func createTracesProcessor(

func createMetricsProcessor(
ctx context.Context,
set processor.CreateSettings,
set processor.CreateSettings, //nolint: staticcheck
cfg component.Config,
nextMetricsConsumer consumer.Metrics,
) (processor.Metrics, error) {
Expand All @@ -87,7 +86,7 @@ func createMetricsProcessor(
}

func createProcessor(
params processor.CreateSettings,
params processor.CreateSettings, //nolint: staticcheck
cfg component.Config,
) (*awsapplicationsignalsprocessor, error) {
pCfg, ok := cfg.(*appsignalsconfig.Config)
Expand Down
5 changes: 2 additions & 3 deletions processor/awsapplicationsignalsprocessor/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import (
"path/filepath"
"testing"

"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/rules"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/confmap/confmaptest"

"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/rules"
)

var expectedRules = []rules.Rule{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const (
AWSECSTaskID = "aws.ecs.task.id"

// resource detection processor attributes
ResourceDetectionHostId = "host.id"
ResourceDetectionHostID = "host.id"
ResourceDetectionHostName = "host.name"
ResourceDetectionASG = "ec2.tag.aws:autoscaling:groupName"
)
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func TestWriteMultipleEntries(t *testing.T) {
if metricDataArray[i] == nil {
metricDataArray[i] = &md
} else {
metricDataArray[i].frequency = metricDataArray[i].frequency + freq
metricDataArray[i].frequency += freq
}

}
Expand All @@ -62,7 +62,7 @@ func TestWriteMultipleEntries(t *testing.T) {
for _, data := range metricDataArray {
val := cms.Get(data)
if data.frequency != val {
err += 1
err++
}
}
collisionRate := err * 100 / len(metricDataArray)
Expand All @@ -80,13 +80,13 @@ func TestAdjustUnsupportedDepth(t *testing.T) {
cms := NewCountMinSketch(5, 10)
assert.Equal(t, 3, cms.depth)
for i := 0; i < 2; i++ {
cms.RegisterHashFunc(func(hashKey string) int64 {
cms.RegisterHashFunc(func(_ string) int64 {
return int64(0)
})
}
assert.Equal(t, 5, cms.depth)
for i := 0; i < 2; i++ {
cms.RegisterHashFunc(func(hashKey string) int64 {
cms.RegisterHashFunc(func(_ string) int64 {
return int64(0)
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ import (
"sync"
"time"

"go.opentelemetry.io/collector/pdata/pcommon"
"go.uber.org/zap"

"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/common"
"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.uber.org/zap"
)

const (
Expand Down Expand Up @@ -104,7 +103,7 @@ func (m *MetricsLimiter) Admit(metricName string, attributes, resourceAttributes
m.mapLock.Lock()
svc = m.services[serviceName]
if svc == nil {
svc = newService(serviceName, m.DropThreshold, m.RotationInterval, m.ctx, m.logger)
svc = newService(m.ctx, serviceName, m.DropThreshold, m.RotationInterval, m.logger)
m.services[serviceName] = svc
}
m.mapLock.Unlock()
Expand Down Expand Up @@ -140,7 +139,7 @@ func (m *MetricsLimiter) Admit(metricName string, attributes, resourceAttributes
return admitted, nil
}

func (m *MetricsLimiter) filterAWSDeclaredAttributes(attributes, resourceAttributes pcommon.Map) (map[string]string, string, bool) {
func (m *MetricsLimiter) filterAWSDeclaredAttributes(attributes, _ pcommon.Map) (map[string]string, string, bool) {
svcNameAttr, exists := attributes.Get(common.CWMetricAttributeLocalService)
if !exists {
return nil, "", false
Expand Down Expand Up @@ -174,7 +173,6 @@ func (m *MetricsLimiter) removeStaleServices() {
}
}


for _, name := range svcToRemove {
m.logger.Info("remove stale service " + name + ".")
delete(m.services, name)
Expand Down Expand Up @@ -262,7 +260,6 @@ func sortAndConcatLabels(labels map[string]string) string {
for _, key := range keys {
concatenatedLabels += labels[key]
}
keys = nil
return concatenatedLabels
}

Expand Down Expand Up @@ -348,7 +345,7 @@ func (s *service) rollupMetricData(attributes pcommon.Map) {
if (indexAttr == common.CWMetricAttributeEnvironment) || (indexAttr == common.CWMetricAttributeLocalService) || (indexAttr == common.CWMetricAttributeRemoteService) {
continue
}
if indexAttr == common.CWMetricAttributeLocalOperation {
if indexAttr == common.CWMetricAttributeLocalOperation { //nolint: gocritic
attributes.PutStr(indexAttr, UnprocessedServiceOperationValue)
} else if indexAttr == common.CWMetricAttributeRemoteOperation {
attributes.PutStr(indexAttr, UnprocessedRemoteServiceOperationValue)
Expand All @@ -359,7 +356,7 @@ func (s *service) rollupMetricData(attributes pcommon.Map) {
}

// As a starting point, you can use rules of thumb, such as setting the depth to be around 4-6 times the logarithm of the expected number of distinct items and the width based on your memory constraints. However, these are rough guidelines, and the optimal size will depend on your unique application and requirements.
func newService(name string, limit int, rotationInterval time.Duration, parentCtx context.Context, logger *zap.Logger) *service {
func newService(parentCtx context.Context, name string, limit int, rotationInterval time.Duration, logger *zap.Logger) *service {
depth := defaultCMSDepth
width := defaultCMSWidth

Expand All @@ -375,7 +372,7 @@ func newService(name string, limit int, rotationInterval time.Duration, parentCt

// Create a ticker to create a new countMinSketch every 1 hour
rotationTicker := time.NewTicker(rotationInterval)
//defer rotationTicker.Stop()
// defer rotationTicker.Stop()

// Create a goroutine to handle rotationTicker.C
go func() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ import (
"testing"
"time"

"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/common"
awsapplicationsignalsconfig "github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.uber.org/zap"

"github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/common"
awsapplicationsignalsconfig "github.com/amazon-contributing/opentelemetry-collector-contrib/processor/awsapplicationsignalsprocessor/config"
)

var emptyResourceAttributes = pcommon.NewMap()
Expand Down Expand Up @@ -47,7 +46,7 @@ func TestAdmitAndRollup(t *testing.T) {
continue
}
attrValue, _ := attr.Get(indexedAttrKey)
if indexedAttrKey == common.CWMetricAttributeLocalOperation {
if indexedAttrKey == common.CWMetricAttributeLocalOperation { //nolint: gocritic
assert.Equal(t, UnprocessedServiceOperationValue, attrValue.AsString())
} else if indexedAttrKey == common.CWMetricAttributeRemoteOperation {
assert.Equal(t, UnprocessedRemoteServiceOperationValue, attrValue.AsString())
Expand All @@ -74,13 +73,13 @@ func TestAdmitByTopK(t *testing.T) {
// fulfill topk with high cardinality attributes
for i := 0; i < 110; i++ {
attr := newHighCardinalityAttributes()
limiter.Admit("latency", attr, emptyResourceAttributes)
_, _ = limiter.Admit("latency", attr, emptyResourceAttributes)
}

// sending low cardinality attributes
for i := 0; i < 100; i++ {
attr := newFixedAttributes(i % 20)
limiter.Admit("latency", attr, emptyResourceAttributes)
_, _ = limiter.Admit("latency", attr, emptyResourceAttributes)
}

for i := 0; i < 20; i++ {
Expand All @@ -104,7 +103,7 @@ func TestAdmitLowCardinalityAttributes(t *testing.T) {
rejectCount := 0
for i := 0; i < 100; i++ {
if ok, _ := limiter.Admit("latency", newLowCardinalityAttributes(10), emptyResourceAttributes); !ok {
rejectCount += 1
rejectCount++
}
}
assert.Equal(t, 0, rejectCount)
Expand All @@ -124,7 +123,7 @@ func TestAdmitReservedMetrics(t *testing.T) {
// fulfill topk with high cardinality attributes
for i := 0; i < 20; i++ {
attr := newHighCardinalityAttributes()
limiter.Admit("latency", attr, emptyResourceAttributes)
_, _ = limiter.Admit("latency", attr, emptyResourceAttributes)
}

for i := 0; i < 20; i++ {
Expand Down Expand Up @@ -157,7 +156,7 @@ func TestClearStaleService(t *testing.T) {
appName := "app" + strconv.Itoa(i)
attr := pcommon.NewMap()
attr.PutStr("Service", appName)
limiter.Admit(appName, attr, emptyResourceAttributes)
_, _ = limiter.Admit(appName, attr, emptyResourceAttributes)
}

time.Sleep(10 * time.Second)
Expand Down Expand Up @@ -219,7 +218,7 @@ func TestInheritanceAfterRotation(t *testing.T) {
}

func TestRotationInterval(t *testing.T) {
svc := newService("test", 1, 5*time.Second, context.Background(), logger)
svc := newService(context.Background(), "test", 1, 5*time.Second, logger)
// wait for secondary to be created
time.Sleep(7 * time.Second)
for i := 0; i < 5; i++ {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,26 @@ type ecsMetadataResponse struct {
TaskARN string
}

type ecsUtil struct {
type EcsUtil struct {
Cluster string
Region string
TaskARN string
httpClient *httpclient.HttpClient
httpClient *httpclient.HTTPClient
}

var ecsUtilInstance *ecsUtil
var ecsUtilInstance *EcsUtil

var ecsUtilOnce sync.Once

func GetECSUtilSingleton() *ecsUtil {
func GetECSUtilSingleton() *EcsUtil {
ecsUtilOnce.Do(func() {
ecsUtilInstance = initECSUtilSingleton()
})
return ecsUtilInstance
}

func initECSUtilSingleton() (newInstance *ecsUtil) {
newInstance = &ecsUtil{httpClient: httpclient.New()}
func initECSUtilSingleton() (newInstance *EcsUtil) {
newInstance = &EcsUtil{httpClient: httpclient.New()}
if os.Getenv(RunInContainer) != TrueValue {
return
}
Expand All @@ -69,11 +69,11 @@ func initECSUtilSingleton() (newInstance *ecsUtil) {

}

func (e *ecsUtil) IsECS() bool {
func (e *EcsUtil) IsECS() bool {
return e.Region != ""
}

func (e *ecsUtil) getECSMetadata() (em *ecsMetadataResponse, err error) {
func (e *EcsUtil) getECSMetadata() (em *ecsMetadataResponse, err error) {
// Based on endpoint to get ECS metadata, for more information on the respond, https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-metadata-endpoint.html
if v4MetadataEndpoint, ok := os.LookupEnv(v4MetadataEndpointEnv); ok {
em, err = e.getMetadataResponse(v4MetadataEndpoint + "/task")
Expand All @@ -85,7 +85,7 @@ func (e *ecsUtil) getECSMetadata() (em *ecsMetadataResponse, err error) {
return
}

func (e *ecsUtil) getMetadataResponse(endpoint string) (em *ecsMetadataResponse, err error) {
func (e *EcsUtil) getMetadataResponse(endpoint string) (em *ecsMetadataResponse, err error) {
em = &ecsMetadataResponse{}
resp, err := e.httpClient.Request(endpoint)

Expand All @@ -105,7 +105,7 @@ func (e *ecsUtil) getMetadataResponse(endpoint string) (em *ecsMetadataResponse,
// arn:aws:ecs:region:aws_account_id:task/task-id
// arn:aws:ecs:region:aws_account_id:task/cluster-name/task-id
// This function will return region extracted from Task ARN
func (e *ecsUtil) parseRegion(em *ecsMetadataResponse) {
func (e *EcsUtil) parseRegion(em *ecsMetadataResponse) {
splitedContent := strings.Split(em.TaskARN, ":")
// When splitting the ARN with ":", the 4th segment is the region
if len(splitedContent) < 4 {
Expand All @@ -116,7 +116,7 @@ func (e *ecsUtil) parseRegion(em *ecsMetadataResponse) {

// There is only one format for ClusterArn (https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Cluster.html)
// arn:aws:ecs:region:aws_account_id:cluster/cluster-name
func (e *ecsUtil) parseClusterName(em *ecsMetadataResponse) {
func (e *EcsUtil) parseClusterName(em *ecsMetadataResponse) {
splitedContent := strings.Split(em.Cluster, "/")
// When splitting the ClusterName with /, the last is always the cluster name
if len(splitedContent) == 0 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ const (
defaultBackoffRetryBaseInMills = 200
)

type HttpClient struct {
type HTTPClient struct {
maxRetries int
backoffRetryBaseInMills int
client *http.Client
}

func New() *HttpClient {
return &HttpClient{
func New() *HTTPClient {
return &HTTPClient{
maxRetries: defaultMaxRetries,
backoffRetryBaseInMills: defaultBackoffRetryBaseInMills,
client: &http.Client{Timeout: defaultTimeout},
}
}

func (h *HttpClient) backoffSleep(currentRetryCount int) {
func (h *HTTPClient) backoffSleep(currentRetryCount int) {
backoffInMillis := int64(float64(h.backoffRetryBaseInMills) * math.Pow(2, float64(currentRetryCount)))
sleepDuration := time.Millisecond * time.Duration(backoffInMillis)
if sleepDuration > 60*1000 {
Expand All @@ -41,7 +41,7 @@ func (h *HttpClient) backoffSleep(currentRetryCount int) {
time.Sleep(sleepDuration)
}

func (h *HttpClient) Request(endpoint string) (body []byte, err error) {
func (h *HTTPClient) Request(endpoint string) (body []byte, err error) {
for i := 0; i < h.maxRetries; i++ {
body, err = h.request(endpoint)
if err != nil {
Expand All @@ -52,10 +52,10 @@ func (h *HttpClient) Request(endpoint string) (body []byte, err error) {
return
}

func (h *HttpClient) request(endpoint string) ([]byte, error) {
func (h *HTTPClient) request(endpoint string) ([]byte, error) {
resp, err := h.client.Get(endpoint)
if err != nil {
return nil, fmt.Errorf("unable to get response from %s, error: %v", endpoint, err)
return nil, fmt.Errorf("unable to get response from %s, error: %w", endpoint, err)
}

if resp.StatusCode != http.StatusOK {
Expand All @@ -65,7 +65,7 @@ func (h *HttpClient) request(endpoint string) ([]byte, error) {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read response body from %s, error: %v", endpoint, err)
return nil, fmt.Errorf("unable to read response body from %s, error: %w", endpoint, err)
}

return body, nil
Expand Down
Loading

0 comments on commit 751437b

Please sign in to comment.