diff --git a/cfg/aws/refreshable_shared_credentials_provider.go b/cfg/aws/refreshable_shared_credentials_provider.go index cdc742fecdb..9fb0c260b2d 100644 --- a/cfg/aws/refreshable_shared_credentials_provider.go +++ b/cfg/aws/refreshable_shared_credentials_provider.go @@ -22,7 +22,7 @@ type Refreshable_shared_credentials_provider struct { func (p *Refreshable_shared_credentials_provider) Retrieve() (credentials.Value, error) { p.SetExpiration(time.Now().Add(p.ExpiryWindow), 0) - creds, e := p.sharedCredentialsProvider.Retrieve() + creds, err := p.sharedCredentialsProvider.Retrieve() - return creds, e + return creds, err } diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index dc5c2204425..3e4c5c2460f 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -6,8 +6,8 @@ package main import ( "flag" "io/ioutil" + "log" "os" - "strings" configaws "github.com/aws/amazon-cloudwatch-agent/cfg/aws" @@ -125,26 +125,24 @@ func main() { if inputConfig != "" { f, err := os.Open(inputConfig) if err != nil { - fmt.Printf("E! Failed to open Common Config: %v\n", err) - panic(err) + log.Panicf("E! Failed to open Common Config: %v", err) } if err := cc.Parse(f); err != nil { - fmt.Printf("E! Failed to parse Common Config: %v\n", err) - panic(err) + log.Panicf("E! Failed to open Common Config: %v", err) } } util.SetProxyEnv(cc.ProxyMap()) util.SetSSLEnv(cc.SSLMap()) var errorMessage string if downloadLocation == "" || outputDir == "" { - executable, e := os.Executable() - if e == nil { - errorMessage = fmt.Sprintf("usage: " + filepath.Base(executable) + " --output-dir --download-source ssm: ") + executable, err := os.Executable() + if err == nil { + errorMessage = fmt.Sprintf("E! usage: " + filepath.Base(executable) + " --output-dir --download-source ssm: ") } else { - errorMessage = fmt.Sprintf("usage: --output-dir --download-source ssm: ") + errorMessage = fmt.Sprintf("E! usage: --output-dir --download-source ssm: ") } - panic(errorMessage) + log.Panicf(errorMessage) } mode = sdkutil.DetectAgentMode(mode) @@ -154,12 +152,12 @@ func main() { if region == "" && downloadLocation != locationDefault { fmt.Println("Unable to determine aws-region.") if mode == config.ModeEC2 { - errorMessage = fmt.Sprintf("Please check if you can access the metadata service. For exampe, on linux, run 'wget -q -O - http://169.254.169.254/latest/meta-data/instance-id && echo' ") + errorMessage = fmt.Sprintf("E! Please check if you can access the metadata service. For example, on linux, run 'wget -q -O - http://169.254.169.254/latest/meta-data/instance-id && echo' ") } else { - errorMessage = fmt.Sprintf("Please make sure the credentials and region set correctly on your hosts.\n" + + errorMessage = fmt.Sprintf("E! Please make sure the credentials and region set correctly on your hosts.\n" + "Refer to http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html") } - panic(errorMessage) + log.Panicf(errorMessage) } // clean up output dir for tmp files before writing out new tmp file. @@ -187,7 +185,7 @@ func main() { locationArray := strings.SplitN(downloadLocation, locationSeparator, 2) if locationArray == nil || len(locationArray) < 2 && downloadLocation != locationDefault { - panic(fmt.Sprintf("downloadLocation %s is malformated.\n", downloadLocation)) + log.Panicf("E! downloadLocation %s is malformated.", downloadLocation) } var config, outputFilePath string @@ -209,25 +207,25 @@ func main() { config, err = readFromFile(locationArray[1]) } default: - panic(fmt.Sprintf("location type %s is not supported.", locationArray[0])) + log.Panicf("E! Location type %s is not supported.", locationArray[0]) } if err != nil { - panic(fmt.Sprintf("Fail to fetch/remove json config: %v\n", err)) + log.Panicf("E! Fail to fetch/remove json config: %v", err) } if multiConfig != "remove" { outputFilePath = filepath.Join(outputDir, outputFilePath+context.TmpFileSuffix) err = ioutil.WriteFile(outputFilePath, []byte(config), 0644) if err != nil { - panic(fmt.Sprintf("Failed to write the json file %v: %v\n", outputFilePath, err)) + log.Panicf("E! Failed to write the json file %v: %v", outputFilePath, err) } else { fmt.Printf("Successfully fetched the config and saved in %s\n", outputFilePath) } } else { outputFilePath = filepath.Join(outputDir, outputFilePath) if err := os.Remove(outputFilePath); err != nil { - panic(fmt.Sprintf("Failed to remove the json file %v: %v", outputFilePath, err)) + log.Panicf("E! Failed to remove the json file %v: %v", outputFilePath, err) } else { fmt.Printf("Successfully removed the config file %s\n", outputFilePath) } diff --git a/cmd/config-translator/translator.go b/cmd/config-translator/translator.go index abf5bc8cf4b..4d2a929b9f7 100644 --- a/cmd/config-translator/translator.go +++ b/cmd/config-translator/translator.go @@ -5,7 +5,6 @@ package main import ( "flag" - "fmt" "log" "os" "os/user" @@ -90,16 +89,16 @@ func main() { mergedJsonConfigMap, err := cmdutil.GenerateMergedJsonConfigMap(ctx) if err != nil { - panic(fmt.Sprintf("E! Failed to generate merged json config: %v", err)) + log.Panicf("E! Failed to generate merged json config: %v", err) } if !ctx.RunInContainer() { // run as user only applies to non container situation. - current, e := user.Current() - if e == nil && current.Name == "root" { + current, err := user.Current() + if err == nil && current.Name == "root" { runAsUser, err := cmdutil.DetectRunAsUser(mergedJsonConfigMap) if err != nil { - panic("E! Failed to detectRunAsUser\n") + log.Panic("E! Failed to detectRunAsUser") } cmdutil.VerifyCredentials(ctx, runAsUser) } diff --git a/integration/clean/clean_ami.go b/integration/clean/clean_ami.go index 01b79c05440..8dd29d2336d 100644 --- a/integration/clean/clean_ami.go +++ b/integration/clean/clean_ami.go @@ -8,13 +8,14 @@ package main import ( "context" + "log" + "time" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" smithyTime "github.com/aws/smithy-go/time" - "log" - "time" ) func main() { diff --git a/integration/test/agent_util.go b/integration/test/agent_util.go index 6b0f6052bdb..45deadad20e 100644 --- a/integration/test/agent_util.go +++ b/integration/test/agent_util.go @@ -83,7 +83,7 @@ func RunShellScript(path string) { } func ReplaceLocalStackHostName(pathIn string) { - out, err := exec.Command("bash", "-c", "sed -i 's/localhost.localstack.cloud/'\"$LOCAL_STACK_HOST_NAME\"'/g' " + pathIn).Output() + out, err := exec.Command("bash", "-c", "sed -i 's/localhost.localstack.cloud/'\"$LOCAL_STACK_HOST_NAME\"'/g' "+pathIn).Output() if err != nil { log.Fatal(fmt.Sprint(err) + string(out)) diff --git a/integration/test/ca_bundle/ca_bundle_test.go b/integration/test/ca_bundle/ca_bundle_test.go index 10761976532..2d7a748d079 100644 --- a/integration/test/ca_bundle/ca_bundle_test.go +++ b/integration/test/ca_bundle/ca_bundle_test.go @@ -50,13 +50,13 @@ func TestBundle(t *testing.T) { log.Printf("resource file location %s find target %t", parameter.dataInput, parameter.findTarget) t.Run(fmt.Sprintf("resource file location %s find target %t", parameter.dataInput, parameter.findTarget), func(t *testing.T) { test.ReplaceLocalStackHostName(parameter.dataInput + configJSON) - test.CopyFile(parameter.dataInput + configJSON, configOutputPath) - test.CopyFile(parameter.dataInput + commonConfigTOML, commonConfigOutputPath) - test.StartAgent(configOutputPath); - time.Sleep(agentRuntime); - log.Printf("Agent has been running for : %s", agentRuntime.String()); - test.StopAgent(); - output := test.ReadAgentOutput(agentRuntime); + test.CopyFile(parameter.dataInput+configJSON, configOutputPath) + test.CopyFile(parameter.dataInput+commonConfigTOML, commonConfigOutputPath) + test.StartAgent(configOutputPath) + time.Sleep(agentRuntime) + log.Printf("Agent has been running for : %s", agentRuntime.String()) + test.StopAgent() + output := test.ReadAgentOutput(agentRuntime) containsTarget := outputLogContainsTarget(output) if (parameter.findTarget && !containsTarget) || (!parameter.findTarget && containsTarget) { t.Errorf("Find target is %t contains target is %t", parameter.findTarget, containsTarget) diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 4b6c457687e..70ed4cd69e9 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -18,7 +18,7 @@ type NodeCapacity struct { func NewNodeCapacity() *NodeCapacity { if _, err := os.Lstat("/rootfs/proc"); os.IsNotExist(err) { - panic("/rootfs/proc doesn't exists") + log.Panic("E! /rootfs/proc does not exist") } if err := os.Setenv(GoPSUtilProcDirEnv, "/rootfs/proc"); err != nil { log.Printf("E! NodeCapacity cannot set goPSUtilProcDirEnv to /rootfs/proc %v", err) diff --git a/internal/ecsservicediscovery/containerinstanceprocessor.go b/internal/ecsservicediscovery/containerinstanceprocessor.go index d4b2aa06379..ffc0c840104 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -37,7 +37,7 @@ func NewContainerInstanceProcessor(ecs *ecs.ECS, ec2 *ec2.EC2, s *ProcessorStats // initiate the container instance metadata LRU caching lru, err := simplelru.NewLRU(ec2metadataCacheSize, nil) if err != nil { - panic(err) + log.Panicf("E! Initial container instance with caching failed because of %v", err) } p.ec2MetaDataCache = lru return p @@ -45,7 +45,7 @@ func NewContainerInstanceProcessor(ecs *ecs.ECS, ec2 *ec2.EC2, s *ProcessorStats func splitMapKeys(a map[string]*EC2MetaData, size int) [][]string { if size == 0 { - panic("splitMapKeys size cannot be zero.") + log.Panic("splitMapKeys size cannot be zero.") } result := make([][]string, 0) diff --git a/internal/ecsservicediscovery/taskdefinitionprocessor.go b/internal/ecsservicediscovery/taskdefinitionprocessor.go index bef1e84568f..72b712a969c 100644 --- a/internal/ecsservicediscovery/taskdefinitionprocessor.go +++ b/internal/ecsservicediscovery/taskdefinitionprocessor.go @@ -4,6 +4,8 @@ package ecsservicediscovery import ( + "log" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" "github.com/hashicorp/golang-lru/simplelru" @@ -31,7 +33,7 @@ func NewTaskDefinitionProcessor(ecs *ecs.ECS, s *ProcessorStats) *TaskDefinition // initiate the caching lru, err := simplelru.NewLRU(taskDefCacheSize, nil) if err != nil { - panic(err) + log.Panicf("E! Initial task definition with caching failed because of %v", err) } p.taskDefCache = lru return p diff --git a/internal/publisher/blockingfifoqueue.go b/internal/publisher/blockingfifoqueue.go index c42c6db7dd1..2d19c2fb7b9 100644 --- a/internal/publisher/blockingfifoqueue.go +++ b/internal/publisher/blockingfifoqueue.go @@ -3,6 +3,10 @@ package publisher +import ( + "log" +) + // It is a FIFO queue with the functionality that block the caller if the queue size reaches to the maxSize type BlockingFifoQueue struct { queue chan interface{} @@ -10,7 +14,7 @@ type BlockingFifoQueue struct { func NewBlockingFifoQueue(size int) *BlockingFifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + log.Panic("E! Queue Size should be larger than 0!") } return &BlockingFifoQueue{queue: make(chan interface{}, size)} diff --git a/internal/publisher/nonblockingfifoqueue.go b/internal/publisher/nonblockingfifoqueue.go index 2bdf495efdd..22cb156d9d1 100644 --- a/internal/publisher/nonblockingfifoqueue.go +++ b/internal/publisher/nonblockingfifoqueue.go @@ -18,7 +18,7 @@ type NonBlockingFifoQueue struct { func NewNonBlockingFifoQueue(size int) *NonBlockingFifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + log.Panic("E! Queue Size should be larger than 0!") } return &NonBlockingFifoQueue{ queue: list.New(), diff --git a/internal/publisher/nonblockinglifoqueue.go b/internal/publisher/nonblockinglifoqueue.go index 2a0fc150ec7..01db6a920a6 100644 --- a/internal/publisher/nonblockinglifoqueue.go +++ b/internal/publisher/nonblockinglifoqueue.go @@ -25,7 +25,7 @@ type node struct { func NewNonBlockingLifoQueue(size int) *NonBlockingLifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + log.Panic("E! Queue Size should be larger than 0!") } return &NonBlockingLifoQueue{maxSize: size} } diff --git a/plugins/inputs/cadvisor/cadvisor_linux.go b/plugins/inputs/cadvisor/cadvisor_linux.go index 57144d1df3d..32c0b740a82 100644 --- a/plugins/inputs/cadvisor/cadvisor_linux.go +++ b/plugins/inputs/cadvisor/cadvisor_linux.go @@ -86,7 +86,7 @@ func (c *Cadvisor) Gather(acc telegraf.Accumulator) error { var err error if c.manager == nil && c.initManager() != nil { - panic("Cannot initiate manager") + log.Panic("E! Cannot initiate manager") } req := &cinfo.ContainerInfoRequest{ diff --git a/plugins/inputs/logfile/logfile_test.go b/plugins/inputs/logfile/logfile_test.go index a621133c5be..ebea61c5d42 100644 --- a/plugins/inputs/logfile/logfile_test.go +++ b/plugins/inputs/logfile/logfile_test.go @@ -404,7 +404,7 @@ func TestLogsFileAutoRemoval(t *testing.T) { }() wg.Add(1) - + go func() { defer wg.Done() diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index 3a2d1b16890..b270e197e43 100644 --- a/plugins/inputs/logfile/tail/tail.go +++ b/plugins/inputs/logfile/tail/tail.go @@ -465,7 +465,7 @@ func (tail *Tail) waitForChanges() error { case <-tail.Dying(): return ErrStop } - panic("unreachable") + } func (tail *Tail) openReader() { @@ -593,7 +593,7 @@ func (tail *Tail) exitOnDeletion() { // with the last chunk of variable size. func partitionString(s string, chunkSize int) []string { if chunkSize <= 0 { - panic("invalid chunkSize") + panic("Invalid chunkSize") } length := len(s) chunks := 1 + length/chunkSize diff --git a/plugins/inputs/logfile/tail/watch/inotify.go b/plugins/inputs/logfile/tail/watch/inotify.go index 3a67813ba61..48617cc176b 100644 --- a/plugins/inputs/logfile/tail/watch/inotify.go +++ b/plugins/inputs/logfile/tail/watch/inotify.go @@ -61,7 +61,6 @@ func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - panic("unreachable") } func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { diff --git a/plugins/inputs/logfile/tail/watch/polling.go b/plugins/inputs/logfile/tail/watch/polling.go index 597092c0eaa..d66af769383 100644 --- a/plugins/inputs/logfile/tail/watch/polling.go +++ b/plugins/inputs/logfile/tail/watch/polling.go @@ -39,7 +39,6 @@ func (fw *PollingFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - panic("unreachable") } func (fw *PollingFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { diff --git a/plugins/inputs/logfile/tail/winfile/winfile.go b/plugins/inputs/logfile/tail/winfile/winfile.go index 965794105be..3c21f4f8b2b 100644 --- a/plugins/inputs/logfile/tail/winfile/winfile.go +++ b/plugins/inputs/logfile/tail/winfile/winfile.go @@ -55,8 +55,8 @@ func Open(path string, mode int, perm uint32) (fd syscall.Handle, err error) { default: createmode = syscall.OPEN_EXISTING } - h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0) - return h, e + h, err := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0) + return h, err } // https://github.com/jnwhiteh/golang/blob/master/src/pkg/syscall/syscall_windows.go#L211 @@ -69,9 +69,9 @@ func makeInheritSa() *syscall.SecurityAttributes { // https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_windows.go#L133 func OpenFile(name string, flag int, perm os.FileMode) (file *os.File, err error) { - r, e := Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm)) - if e != nil { - return nil, e + r, err := Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm)) + if err != nil { + return nil, err } return os.NewFile(uintptr(r), name), nil } diff --git a/plugins/inputs/prometheus_scraper/metrics_receiver_test.go b/plugins/inputs/prometheus_scraper/metrics_receiver_test.go index 7e21756e0fe..a8e48851ee9 100644 --- a/plugins/inputs/prometheus_scraper/metrics_receiver_test.go +++ b/plugins/inputs/prometheus_scraper/metrics_receiver_test.go @@ -20,9 +20,9 @@ func Test_metricAppender_Add_BadMetricName(t *testing.T) { {Name: "name_b", Value: "value_b"}, } - r, e := ma.Add(ls, ts, v) + r, err := ma.Add(ls, ts, v) assert.Equal(t, uint64(0), r) - assert.Equal(t, "metricName of the times-series is missing", e.Error()) + assert.Equal(t, "metricName of the times-series is missing", err.Error()) } func Test_metricAppender_Add(t *testing.T) { @@ -35,9 +35,9 @@ func Test_metricAppender_Add(t *testing.T) { {Name: "tag_a", Value: "a"}, } - ref, e := ma.Add(ls, ts, v) + ref, err := ma.Add(ls, ts, v) assert.Equal(t, ref, uint64(0)) - assert.Nil(t, e) + assert.Nil(t, err) mac, _ := ma.(*metricAppender) assert.Equal(t, 1, len(mac.batch)) @@ -68,9 +68,9 @@ func Test_metricAppender_Rollback(t *testing.T) { {Name: "tag_a", Value: "a"}, } - ref, e := ma.Add(ls, ts, v) + ref, err := ma.Add(ls, ts, v) assert.Equal(t, ref, uint64(0)) - assert.Nil(t, e) + assert.Nil(t, err) mac, _ := ma.(*metricAppender) assert.Equal(t, 1, len(mac.batch)) @@ -89,12 +89,12 @@ func Test_metricAppender_Commit(t *testing.T) { {Name: "tag_a", Value: "a"}, } - ref, e := ma.Add(ls, ts, v) + ref, err := ma.Add(ls, ts, v) assert.Equal(t, ref, uint64(0)) - assert.Nil(t, e) + assert.Nil(t, err) mac, _ := ma.(*metricAppender) assert.Equal(t, 1, len(mac.batch)) - err := ma.Commit() + err = ma.Commit() assert.Equal(t, nil, err) pmb := <-mbCh diff --git a/plugins/inputs/windows_event_log/wineventlog/utils.go b/plugins/inputs/windows_event_log/wineventlog/utils.go index 4ef163305e3..ca57856007f 100644 --- a/plugins/inputs/windows_event_log/wineventlog/utils.go +++ b/plugins/inputs/windows_event_log/wineventlog/utils.go @@ -19,19 +19,19 @@ import ( ) const ( - bookmarkTemplate = `` - eventLogQueryTemplate = `` - eventLogLevelFilter = "Level='%s'" - eventIgnoreOldFilter = "TimeCreated[timediff(@SystemTime) <= %d]" - emptySpaceScanLength = 100 + bookmarkTemplate = `` + eventLogQueryTemplate = `` + eventLogLevelFilter = "Level='%s'" + eventIgnoreOldFilter = "TimeCreated[timediff(@SystemTime) <= %d]" + emptySpaceScanLength = 100 UnknownBytesPerCharacter = 0 - CRITICAL = "CRITICAL" - ERROR = "ERROR" - WARNING = "WARNING" - INFORMATION = "INFORMATION" - VERBOSE = "VERBOSE" - UNKNOWN = "UNKNOWN" + CRITICAL = "CRITICAL" + ERROR = "ERROR" + WARNING = "WARNING" + INFORMATION = "INFORMATION" + VERBOSE = "VERBOSE" + UNKNOWN = "UNKNOWN" ) var NumberOfBytesPerCharacter = UnknownBytesPerCharacter @@ -139,10 +139,10 @@ func isTheEndOfContent(in []byte, length uint32) bool { } max := len(in) if i+emptySpaceScanLength < max { - max = i+emptySpaceScanLength + max = i + emptySpaceScanLength } - for ; i < max - 2; i += 2 { + for ; i < max-2; i += 2 { v1 := uint16(in[i+2]) | uint16(in[i+1])<<8 // Stop at non-null char. if v1 != 0 { diff --git a/plugins/inputs/windows_event_log/wineventlog/utils_test.go b/plugins/inputs/windows_event_log/wineventlog/utils_test.go index 1c455014a6a..7b05d933508 100644 --- a/plugins/inputs/windows_event_log/wineventlog/utils_test.go +++ b/plugins/inputs/windows_event_log/wineventlog/utils_test.go @@ -46,7 +46,7 @@ func TestDecodingWithDifferentBufferUsedReturned(t *testing.T) { resetState() originalHexStr := "3c004500760065006e007400200078006d006c006e0073003d00270068007400740070003a002f002f0073006300680065006d00610073002e006d006900630072006f0073006f00660074002e0063006f006d002f00770069006e002f0032003000300034002f00300038002f006500760065006e00740073002f006500760065006e00740027003e003c00530079007300740065006d003e003c00500072006f007600690064006500720020004e0061006d0065003d0027004d006900630072006f0073006f00660074002d00570069006e0064006f00770073002d00530065006300750072006900740079002d004100750064006900740069006e0067002700200047007500690064003d0027007b00350034003800340039003600320035002d0035003400370038002d0034003900390034002d0041003500420041002d003300450033004200300033003200380043003300300044007d0027002f003e003c004500760065006e007400490044003e0034003600320035003c002f004500760065006e007400490044003e003c00560065007200730069006f006e003e0030003c002f00560065007200730069006f006e003e003c004c006500760065006c003e0030003c002f004c006500760065006c003e003c005400610073006b003e00310032003500340034003c002f005400610073006b003e003c004f00700063006f00640065003e0030003c002f004f00700063006f00640065003e003c004b006500790077006f007200640073003e003000780038003000310030003000300030003000300030003000300030003000300030003c002f004b006500790077006f007200640073003e003c00540069006d00650043007200650061007400650064002000530079007300740065006d00540069006d0065003d00270032003000310039002d00300035002d00300035005400320033003a00310032003a00330037002e003300340039003400370036003100300030005a0027002f003e003c004500760065006e0074005200650063006f0072006400490044003e003600390034003600370034003c002f004500760065006e0074005200650063006f0072006400490044003e003c0043006f007200720065006c006100740069006f006e00200041006300740069007600690074007900490044003d0027007b00320035003200320035004600410031002d0044004100420039002d0030003000300031002d0041003600350046002d003200320032003500420039004400410044003400300031007d0027002f003e003c0045007800650063007500740069006f006e002000500072006f006300650073007300490044003d00270038003000340027002000540068007200650061006400490044003d002700310030003800300027002f003e003c004300680061006e006e0065006c003e00530065006300750072006900740079003c002f004300680061006e006e0065006c003e003c0043006f006d00700075007400650072003e0045004300320041004d0041005a002d0035004a00360049004600530046003c002f0043006f006d00700075007400650072003e003c00530065006300750072006900740079002f003e003c002f00530079007300740065006d003e003c004500760065006e00740044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a00650063007400550073006500720053006900640027003e0053002d0031002d0030002d0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a0065006300740055007300650072004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a0065006300740044006f006d00610069006e004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a006500630074004c006f0067006f006e004900640027003e003000780030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700540061007200670065007400550073006500720053006900640027003e0053002d0031002d0030002d0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270054006100720067006500740055007300650072004e0061006d00650027003e00410044004d0049004e004900530054005200410054004f0052003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270054006100720067006500740044006f006d00610069006e004e0061006d00650027003e003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270053007400610074007500730027003e0030007800630030003000300030003000360064003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004600610069006c0075007200650052006500610073006f006e0027003e002500250032003300310033003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270053007500620053007400610074007500730027003e0030007800630030003000300030003000360061003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006f0067006f006e00540079007000650027003e0033003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006f0067006f006e00500072006f0063006500730073004e0061006d00650027003e004e0074004c006d0053007300700020003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700410075007400680065006e007400690063006100740069006f006e005000610063006b006100670065004e0061006d00650027003e004e0054004c004d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270057006f0072006b00730074006100740069006f006e004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005400720061006e0073006d00690074007400650064005300650072007600690063006500730027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006d005000610063006b006100670065004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004b00650079004c0065006e0067007400680027003e0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700500072006f0063006500730073004900640027003e003000780030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700500072006f0063006500730073004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270049007000410064006400720065007300730027003e003100340036002e00350036002e0036002e003100360036003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004900700050006f007200740027003e0030003c002f0044006100740061003e003c002f004500760065006e00740044006100740061003e003c002f004500760065006e0074003e000000" data, _ := hex.DecodeString(originalHexStr) - bufferUsed := len(data)/2 + bufferUsed := len(data) / 2 bytes, _ := UTF16ToUTF8BytesForWindowsEventBuffer(data, uint32(bufferUsed)) str := string(bytes[:]) assert.Equal(t, "4625001254400x8010000000000000694674SecurityEC2AMAZ-5J6IFSFS-1-0-0--0x0S-1-0-0ADMINISTRATOR0xc000006d%%23130xc000006a3NtLmSsp NTLM---00x0-146.56.6.1660", str) @@ -54,7 +54,7 @@ func TestDecodingWithDifferentBufferUsedReturned(t *testing.T) { // odd bytes test originalHexStr = "3c004500760065006e007400200078006d006c006e0073003d00270068007400740070003a002f002f0073006300680065006d00610073002e006d006900630072006f0073006f00660074002e0063006f006d002f00770069006e002f0032003000300034002f00300038002f006500760065006e00740073002f006500760065006e00740027003e003c00530079007300740065006d003e003c00500072006f007600690064006500720020004e0061006d0065003d0027004d006900630072006f0073006f00660074002d00570069006e0064006f00770073002d00530065006300750072006900740079002d004100750064006900740069006e0067002700200047007500690064003d0027007b00350034003800340039003600320035002d0035003400370038002d0034003900390034002d0041003500420041002d003300450033004200300033003200380043003300300044007d0027002f003e003c004500760065006e007400490044003e0034003600320035003c002f004500760065006e007400490044003e003c00560065007200730069006f006e003e0030003c002f00560065007200730069006f006e003e003c004c006500760065006c003e0030003c002f004c006500760065006c003e003c005400610073006b003e00310032003500340034003c002f005400610073006b003e003c004f00700063006f00640065003e0030003c002f004f00700063006f00640065003e003c004b006500790077006f007200640073003e003000780038003000310030003000300030003000300030003000300030003000300030003c002f004b006500790077006f007200640073003e003c00540069006d00650043007200650061007400650064002000530079007300740065006d00540069006d0065003d00270032003000310039002d00300035002d00300035005400320033003a00310032003a00330037002e003300340039003400370036003100300030005a0027002f003e003c004500760065006e0074005200650063006f0072006400490044003e003600390034003600370034003c002f004500760065006e0074005200650063006f0072006400490044003e003c0043006f007200720065006c006100740069006f006e00200041006300740069007600690074007900490044003d0027007b00320035003200320035004600410031002d0044004100420039002d0030003000300031002d0041003600350046002d003200320032003500420039004400410044003400300031007d0027002f003e003c0045007800650063007500740069006f006e002000500072006f006300650073007300490044003d00270038003000340027002000540068007200650061006400490044003d002700310030003800300027002f003e003c004300680061006e006e0065006c003e00530065006300750072006900740079003c002f004300680061006e006e0065006c003e003c0043006f006d00700075007400650072003e0045004300320041004d0041005a002d0035004a00360049004600530046003c002f0043006f006d00700075007400650072003e003c00530065006300750072006900740079002f003e003c002f00530079007300740065006d003e003c004500760065006e00740044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a00650063007400550073006500720053006900640027003e0053002d0031002d0030002d0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a0065006300740055007300650072004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a0065006300740044006f006d00610069006e004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005300750062006a006500630074004c006f0067006f006e004900640027003e003000780030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700540061007200670065007400550073006500720053006900640027003e0053002d0031002d0030002d0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270054006100720067006500740055007300650072004e0061006d00650027003e00410044004d0049004e004900530054005200410054004f0052003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270054006100720067006500740044006f006d00610069006e004e0061006d00650027003e003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270053007400610074007500730027003e0030007800630030003000300030003000360064003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004600610069006c0075007200650052006500610073006f006e0027003e002500250032003300310033003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270053007500620053007400610074007500730027003e0030007800630030003000300030003000360061003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006f0067006f006e00540079007000650027003e0033003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006f0067006f006e00500072006f0063006500730073004e0061006d00650027003e004e0074004c006d0053007300700020003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700410075007400680065006e007400690063006100740069006f006e005000610063006b006100670065004e0061006d00650027003e004e0054004c004d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270057006f0072006b00730074006100740069006f006e004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027005400720061006e0073006d00690074007400650064005300650072007600690063006500730027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004c006d005000610063006b006100670065004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004b00650079004c0065006e0067007400680027003e0030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700500072006f0063006500730073004900640027003e003000780030003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d002700500072006f0063006500730073004e0061006d00650027003e002d003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d00270049007000410064006400720065007300730027003e003100340036002e00350036002e0036002e003100360036003c002f0044006100740061003e003c00440061007400610020004e0061006d0065003d0027004900700050006f007200740027003e0030003c002f0044006100740061003e003c002f004500760065006e00740044006100740061003e003c002f004500760065006e0074003e00000000" data, _ = hex.DecodeString(originalHexStr) - bufferUsed = len(data)/2 + bufferUsed = len(data) / 2 bytes, _ = UTF16ToUTF8BytesForWindowsEventBuffer(data, uint32(bufferUsed)) str = string(bytes[:]) assert.Equal(t, "4625001254400x8010000000000000694674SecurityEC2AMAZ-5J6IFSFS-1-0-0--0x0S-1-0-0ADMINISTRATOR0xc000006d%%23130xc000006a3NtLmSsp NTLM---00x0-146.56.6.1660", str) @@ -69,7 +69,7 @@ func TestFullBufferUsedWithHalfUsedSizeReturned(t *testing.T) { for i := 2; i < cap; i *= 2 { copy(data[i:], data[:i]) } - bufferUsed := cap/2 + bufferUsed := cap / 2 bytes, _ := UTF16ToUTF8BytesForWindowsEventBuffer(data, uint32(bufferUsed)) str := string(bytes[:]) @@ -79,4 +79,4 @@ func TestFullBufferUsedWithHalfUsedSizeReturned(t *testing.T) { func resetState() { NumberOfBytesPerCharacter = 0 -} \ No newline at end of file +} diff --git a/plugins/processors/k8sdecorator/stores/podstore.go b/plugins/processors/k8sdecorator/stores/podstore.go index ed6542f21c3..8182798a264 100644 --- a/plugins/processors/k8sdecorator/stores/podstore.go +++ b/plugins/processors/k8sdecorator/stores/podstore.go @@ -4,7 +4,6 @@ package stores import ( - "fmt" "log" "regexp" "strings" @@ -74,7 +73,7 @@ func NewPodStore(hostIP string, prefFullPodName bool) *PodStore { // Try to detect kubelet permission issue here if _, err := podStore.kubeClient.ListPods(); err != nil { - panic(fmt.Sprintf("Cannot get pod from kubelet, err: %v", err)) + log.Panicf("Cannot get pod from kubelet, err: %v", err) } return podStore diff --git a/tool/processors/defaultConfig/defaultConfig.go b/tool/processors/defaultConfig/defaultConfig.go index d463190fdc6..03cbf3f0f2b 100644 --- a/tool/processors/defaultConfig/defaultConfig.go +++ b/tool/processors/defaultConfig/defaultConfig.go @@ -64,7 +64,7 @@ func (p *processor) NextProcessor(ctx *runtime.Context, config *data.Config) int case "None": return question.Processor default: - panic(whichDefaultConfig) + log.Panicf("Unknown default config: %s", whichDefaultConfig) } if config.SatisfiedWithCurrentConfig(ctx) { if ctx.OsParameter == util.OsTypeWindows { diff --git a/tool/processors/migration/linux/knownConfigKeys.go b/tool/processors/migration/linux/knownConfigKeys.go index a6204728d53..d923c0c4505 100644 --- a/tool/processors/migration/linux/knownConfigKeys.go +++ b/tool/processors/migration/linux/knownConfigKeys.go @@ -5,6 +5,7 @@ package linux import ( "fmt" + "log" "strconv" "github.com/aws/amazon-cloudwatch-agent/tool/data/config" @@ -64,7 +65,7 @@ func addLogConfig(logsConfig *config.Logs, filePath, section string, p *configpa if encoding != "" { normalized := NormalizeEncoding(encoding) if normalized == "" { - panic(fmt.Sprintf("Encoding %s is not supported.", encoding)) + log.Panicf("E! Encoding %s is not supported.", encoding) } else { encoding = normalized } diff --git a/tool/processors/migration/linux/linuxMigration.go b/tool/processors/migration/linux/linuxMigration.go index e982c717367..c1605e93ef2 100644 --- a/tool/processors/migration/linux/linuxMigration.go +++ b/tool/processors/migration/linux/linuxMigration.go @@ -4,7 +4,7 @@ package linux import ( - "fmt" + "log" "github.com/aws/amazon-cloudwatch-agent/tool/data" "github.com/aws/amazon-cloudwatch-agent/tool/data/config" @@ -44,14 +44,12 @@ func (p *processor) NextProcessor(ctx *runtime.Context, config *data.Config) int func processConfigFromPythonConfigParserFile(filePath string, logsConfig *config.Logs) { p, err := configparser.NewConfigParserFromFile(filePath) if err != nil { - fmt.Printf("Error in reading old python config from file %s: %v\n", filePath, err) - panic(err) + log.Panicf("E! Error in reading old python config from file %s: %v", filePath, err) } if p.HasSection(genericSectionName) { err := p.RemoveSection(genericSectionName) if err != nil { - fmt.Printf("Error in removing generic section from the config file %s:\n %v\n", filePath, err) - panic(err) + log.Panicf("E! Error in removing generic section from the config file %s: %v", filePath, err) } } for _, section := range p.Sections() { diff --git a/tool/util/util.go b/tool/util/util.go index 75c97e993b6..5dea79601f9 100644 --- a/tool/util/util.go +++ b/tool/util/util.go @@ -95,9 +95,9 @@ func SaveResultByteArrayToJsonFile(resultByteArray []byte) string { } func SDKRegion() (region string) { - ses, e := session.NewSession() + ses, err := session.NewSession() - if e != nil { + if err != nil { return } if ses.Config != nil && ses.Config.Region != nil { @@ -107,9 +107,9 @@ func SDKRegion() (region string) { } func SDKRegionWithProfile(profile string) (region string) { - ses, e := session.NewSessionWithOptions(session.Options{Profile: profile, SharedConfigState: session.SharedConfigEnable}) + ses, err := session.NewSessionWithOptions(session.Options{Profile: profile, SharedConfigState: session.SharedConfigEnable}) - if e != nil { + if err != nil { return } if ses.Config != nil && ses.Config.Region != nil { @@ -119,8 +119,8 @@ func SDKRegionWithProfile(profile string) (region string) { } func SDKCredentials() (accessKey, secretKey string, creds *credentials.Credentials) { - ses, e := session.NewSession() - if e != nil { + ses, err := session.NewSession() + if err != nil { return } if ses.Config != nil && ses.Config.Credentials != nil { @@ -135,20 +135,20 @@ func SDKCredentials() (accessKey, secretKey string, creds *credentials.Credentia func DefaultEC2Region() (region string) { fmt.Println("Trying to fetch the default region based on ec2 metadata...") - ses, e := session.NewSession(&aws.Config{ + ses, err := session.NewSession(&aws.Config{ HTTPClient: &http.Client{Timeout: 1 * time.Second}, MaxRetries: aws.Int(0), LogLevel: configaws.SDKLogLevel(), Logger: configaws.SDKLogger{}, }) - if e != nil { + if err != nil { return } md := ec2metadata.New(ses) if !md.Available() { return } - if info, e := md.Region(); e == nil { + if info, err := md.Region(); err == nil { region = info } return diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 9f37932a6ea..9d79742135a 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -36,7 +36,7 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf res := totomlconfig.ToTomlConfig(jsonConfigValue) if translator.IsTranslateSuccess() { if err := ioutil.WriteFile(tomlConfigFilePath, []byte(res), tomlFileMode); err != nil { - panic(fmt.Sprintf("Failed to create the configuration validation file. Reason: %s \n", err.Error())) + log.Panicf("E! Failed to create the configuration validation file. Reason: %s", err.Error()) } else { for _, infoMessage := range translator.InfoMessages { fmt.Println(infoMessage) @@ -44,7 +44,7 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf fmt.Println(exitSuccessMessage) } } else { - panic("Failed to generate configuration validation content. ") + log.Panic("E! Failed to generate configuration validation content.") } } @@ -55,14 +55,14 @@ func TranslateJsonMapToEnvConfigFile(jsonConfigValue map[string]interface{}, env } bytes := toenvconfig.ToEnvConfig(jsonConfigValue) if err := ioutil.WriteFile(envConfigPath, bytes, 0644); err != nil { - panic(fmt.Sprintf("Failed to create env config. Reason: %s \n", err.Error())) + log.Panicf("E! Failed to create env config. Reason: %s", err.Error()) } } func getCurBinaryPath() string { ex, err := os.Executable() if err != nil { - panic(err) + log.Panicf("E! Failed to get executable path because of %v", err) } return path.Dir(ex) } @@ -104,16 +104,16 @@ func RunSchemaValidation(inputJsonMap map[string]interface{}) (*gojsonschema.Res func checkSchema(inputJsonMap map[string]interface{}) { result, err := RunSchemaValidation(inputJsonMap) if err != nil { - panic(err.Error()) + log.Panicf("E! Failed to run schema validation because of %v", err) } if result.Valid() { - fmt.Println("Valid Json input schema.") + log.Print("I! Valid Json input schema.") } else { errorDetails := result.Errors() for _, errorDetail := range errorDetails { translator.AddErrorMessages(config.GetFormattedPath(errorDetail.Context().String()), errorDetail.Description()) } - panic("Invalid Json input schema.") + log.Panic("E! Invalid Json input schema.") } } diff --git a/translator/cmdutil/userutil.go b/translator/cmdutil/userutil.go index 7aeb300d034..672b2e3504b 100644 --- a/translator/cmdutil/userutil.go +++ b/translator/cmdutil/userutil.go @@ -35,8 +35,8 @@ func DetectRunAsUser(mergedJsonConfigMap map[string]interface{}) (runAsUser stri if runasuser, ok := user.(string); ok { return runasuser, nil } - fmt.Printf("E! run_as_user is not string %v \n", user) - panic("E! run_as_user is not string \n") + + log.Panicf("E! run_as_user is not string %v", user) } // agent section exists, but "runasuser" does not exist, then use "root" @@ -116,7 +116,7 @@ func VerifyCredentials(ctx *context.Context, runAsUser string) { if config.ModeOnPrem == ctx.Mode() { if runAsUser != "root" { if _, ok := credentials["shared_credential_file"]; !ok { - panic("E! Credentials path is not set while runasuser is not root \n") + log.Panic("E! Credentials path is not set while runasuser is not root") } } } diff --git a/translator/config/os.go b/translator/config/os.go index 50ddc20790f..6aca672ea31 100644 --- a/translator/config/os.go +++ b/translator/config/os.go @@ -22,11 +22,13 @@ func ToValidOs(os string) string { // Give it a last try, using current osType type os = runtime.GOOS } + formattedOs := strings.ToLower(os) for _, val := range supportedOs { if formattedOs == val { return formattedOs } } + panic(fmt.Sprintf("%v is not a supported osType type", os)) } diff --git a/translator/context/context.go b/translator/context/context.go index 85d3e878b20..43eb33e26fd 100644 --- a/translator/context/context.go +++ b/translator/context/context.go @@ -4,8 +4,7 @@ package context import ( - "fmt" - + "log" "os" "github.com/aws/amazon-cloudwatch-agent/translator/config" @@ -114,7 +113,7 @@ func (ctx *Context) SetMode(mode string) { case config.ModeOnPrem: ctx.mode = config.ModeOnPrem default: - panic(fmt.Sprintf("Invalid mode %s. Valid mode values are %s, and %s.\n", mode, config.ModeEC2, config.ModeOnPrem)) + log.Panicf("Invalid mode %s. Valid mode values are %s and %s.", mode, config.ModeEC2, config.ModeOnPrem) } } diff --git a/translator/jsonconfig/mergeJsonConfig.go b/translator/jsonconfig/mergeJsonConfig.go index c32976bc684..48d9704c036 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -5,6 +5,7 @@ package jsonconfig import ( "fmt" + "log" "os" "sort" @@ -54,7 +55,7 @@ func MergeJsonConfigMaps(jsonConfigMapMap map[string]map[string]interface{}, def } if !translator.IsTranslateSuccess() { - panic("Failed to merge multiple json config files.") + log.Panic("Failed to merge multiple json config files.") } return resultMap, nil diff --git a/translator/mergeTwoUniqueMaps.go b/translator/mergeTwoUniqueMaps.go index 0a0fa646a1f..9c525dd3865 100644 --- a/translator/mergeTwoUniqueMaps.go +++ b/translator/mergeTwoUniqueMaps.go @@ -7,11 +7,11 @@ package translator // This method is mainly to merge maps which don't have same key, it's a shallow merge. Fail this method if not serving this purpose. func MergeTwoUniqueMaps(map1 map[string]interface{}, map2 map[string]interface{}) map[string]interface{} { mergeResult := make(map[string]interface{}) - errorMessages := "Fail to merge two map, since both of them use same key" + errorMessage := "Fail to merge two map, since both of them use same key" for k, v := range map1 { if _, ok := mergeResult[k]; ok { - panic(errorMessages) + panic(errorMessage) } else { mergeResult[k] = v } @@ -19,7 +19,7 @@ func MergeTwoUniqueMaps(map1 map[string]interface{}, map2 map[string]interface{} for k, v := range map2 { if _, ok := mergeResult[k]; ok { - panic(errorMessages) + panic(errorMessage) } else { mergeResult[k] = v } diff --git a/translator/toenvconfig/toEnvConfig.go b/translator/toenvconfig/toEnvConfig.go index 16798ca7b4c..0db8ac663fd 100644 --- a/translator/toenvconfig/toEnvConfig.go +++ b/translator/toenvconfig/toEnvConfig.go @@ -5,7 +5,7 @@ package toenvconfig import ( "encoding/json" - "fmt" + "log" "github.com/aws/amazon-cloudwatch-agent/cfg/commonconfig" "github.com/aws/amazon-cloudwatch-agent/cfg/envconfig" @@ -64,7 +64,7 @@ func ToEnvConfig(jsonConfigValue map[string]interface{}) []byte { bytes, err := json.MarshalIndent(envVars, "", "\t") if err != nil { - panic(fmt.Sprintf("Failed to create json map for environment variables. Reason: %s \n", err.Error())) + log.Panicf("Failed to create json map for environment variables. Reason: %s", err.Error()) } return bytes } diff --git a/translator/toenvconfig/toEnvConfig_test.go b/translator/toenvconfig/toEnvConfig_test.go index de7740ccf63..b8329da1370 100644 --- a/translator/toenvconfig/toEnvConfig_test.go +++ b/translator/toenvconfig/toEnvConfig_test.go @@ -34,8 +34,8 @@ func ReadFromFile(filename string) string { func checkIfTranslateSucceed(t *testing.T, jsonStr string, targetOs string, expectedEnvVars map[string]string) { var input map[string]interface{} translator.SetTargetPlatform(targetOs) - e := json.Unmarshal([]byte(jsonStr), &input) - if e == nil { + err := json.Unmarshal([]byte(jsonStr), &input) + if err == nil { envVarsBytes := ToEnvConfig(input) fmt.Println(string(envVarsBytes)) var actualEnvVars = make(map[string]string) @@ -43,7 +43,7 @@ func checkIfTranslateSucceed(t *testing.T, jsonStr string, targetOs string, expe assert.NoError(t, err) assert.Equal(t, expectedEnvVars, actualEnvVars, "Expect to be equal") } else { - fmt.Printf("Got error %v", e) + fmt.Printf("Got error %v", err) t.Fail() } } diff --git a/translator/totomlconfig/toTomlConfig.go b/translator/totomlconfig/toTomlConfig.go index e675f737647..4b1dda232bb 100755 --- a/translator/totomlconfig/toTomlConfig.go +++ b/translator/totomlconfig/toTomlConfig.go @@ -4,6 +4,7 @@ package totomlconfig import ( + "log" "bytes" "github.com/aws/amazon-cloudwatch-agent/translator/translate" @@ -58,9 +59,9 @@ func ToTomlConfig(c interface{}) string { _, val := r.ApplyRule(c) buf := bytes.Buffer{} enc := toml.NewEncoder(&buf) - e := enc.Encode(val) - if e != nil { - panic(e) + err := enc.Encode(val) + if err != nil { + log.Panicf("Encode to a valid TOML config fails because of %v",err) } return buf.String() } diff --git a/translator/totomlconfig/toTomlConfig_test.go b/translator/totomlconfig/toTomlConfig_test.go index b56495b518f..f04afead2e8 100644 --- a/translator/totomlconfig/toTomlConfig_test.go +++ b/translator/totomlconfig/toTomlConfig_test.go @@ -6,15 +6,16 @@ package totomlconfig import ( "bytes" "encoding/json" + "io/ioutil" + "log" + "strings" + "testing" + "github.com/BurntSushi/toml" "github.com/aws/amazon-cloudwatch-agent/translator/totomlconfig/tomlConfigTemplate" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/kr/pretty" - "io/ioutil" - "log" - "strings" - "testing" "github.com/aws/amazon-cloudwatch-agent/translator" @@ -43,8 +44,8 @@ func TestLogMetricOnly(t *testing.T) { context.CurrentContext().SetRunInContainer(true) os.Setenv(config.HOST_NAME, "host_name_from_env") os.Setenv(config.HOST_IP, "127.0.0.1") - checkTomlTranslation(t, "./sampleConfig/log_metric_only.json","./sampleConfig/log_metric_only.conf", "linux") - checkTomlTranslation(t, "./sampleConfig/log_metric_only.json","./sampleConfig/log_metric_only.conf", "darwin") + checkTomlTranslation(t, "./sampleConfig/log_metric_only.json", "./sampleConfig/log_metric_only.conf", "linux") + checkTomlTranslation(t, "./sampleConfig/log_metric_only.json", "./sampleConfig/log_metric_only.conf", "darwin") os.Unsetenv(config.HOST_NAME) os.Unsetenv(config.HOST_IP) } @@ -234,6 +235,6 @@ func checkIfIdenticalToml(t *testing.T, desiredTomlPath string, tomlStr string) return pretty.Sprint(x) < pretty.Sprint(y) }) diff := cmp.Diff(expect, actual) - log.Printf("D! Toml diff: %s", diff ) + log.Printf("D! Toml diff: %s", diff) assert.True(t, cmp.Equal(expect, actual, opt)) } diff --git a/translator/totomlconfig/tomlConfigTemplate/tomlConfig.go b/translator/totomlconfig/tomlConfigTemplate/tomlConfig.go index 8314321d4b0..ab8bd1a7a2b 100644 --- a/translator/totomlconfig/tomlConfigTemplate/tomlConfig.go +++ b/translator/totomlconfig/tomlConfigTemplate/tomlConfig.go @@ -2,63 +2,63 @@ package tomlConfigTemplate type ( TomlConfig struct { - Agent agentConfig - Inputs inputConfig - Outputs outputConfig + Agent agentConfig + Inputs inputConfig + Outputs outputConfig Processors processorsConfig } agentConfig struct { // Not all names need the explict toml mapping as they are case insensitive, it is only needed when // underscore is replaced - CollectionJitter string `toml:"collection_jitter"` - Debug bool - FlushInterval string `toml:"flush_interval"` - FlushJitter string `toml:"flush_jitter"` - Hostname string - Interval string - Logfile string - LogTarget string - MetricBatchSize int `toml:"metric_batch_size"` - MetricBufferLimit int `toml:"metric_buffer_limit"` - OmitHostname bool `toml:"omit_hostname"` - Precision string - Quiet bool - RoundInterval bool `toml:"round_interval"` + CollectionJitter string `toml:"collection_jitter"` + Debug bool + FlushInterval string `toml:"flush_interval"` + FlushJitter string `toml:"flush_jitter"` + Hostname string + Interval string + Logfile string + LogTarget string + MetricBatchSize int `toml:"metric_batch_size"` + MetricBufferLimit int `toml:"metric_buffer_limit"` + OmitHostname bool `toml:"omit_hostname"` + Precision string + Quiet bool + RoundInterval bool `toml:"round_interval"` } inputConfig struct { - AwsCsmListener []awsCsmListenerConfig `toml:"awscsm_listener"` - Cadvisor []cadvisorConfig - Cpu []cpuConfig - Disk []diskConfig - DiskIo []diskioConfig - Eththool []ethtoolConfig - K8sapiserver []k8sApiServerConfig - Logfile []logFileConfig - Mem []memConfig - Net []netConfig - NetStat []netStatConfig - NvidiaSmi []nvidiaSmi `toml:"nvidia_smi"` - Processes []processesConfig + AwsCsmListener []awsCsmListenerConfig `toml:"awscsm_listener"` + Cadvisor []cadvisorConfig + Cpu []cpuConfig + Disk []diskConfig + DiskIo []diskioConfig + Eththool []ethtoolConfig + K8sapiserver []k8sApiServerConfig + Logfile []logFileConfig + Mem []memConfig + Net []netConfig + NetStat []netStatConfig + NvidiaSmi []nvidiaSmi `toml:"nvidia_smi"` + Processes []processesConfig PrometheusScraper []prometheusScraperConfig `toml:"prometheus_scraper"` - ProcStat []procStatConfig - SocketListener []socketListenerConfig `toml:"socket_listener"` - Statsd []statsdConfig - Swap []swapConfig - WindowsEventLog []windowsEventLogConfig `toml:"windows_event_log"` + ProcStat []procStatConfig + SocketListener []socketListenerConfig `toml:"socket_listener"` + Statsd []statsdConfig + Swap []swapConfig + WindowsEventLog []windowsEventLogConfig `toml:"windows_event_log"` } outputConfig struct { - AwsCsm []awsCsmConfig `toml:"aws_csm"` - CloudWatch []cloudWatchOutputConfig + AwsCsm []awsCsmConfig `toml:"aws_csm"` + CloudWatch []cloudWatchOutputConfig CloudWatchLogs []cloudWatchLogsConfig } processorsConfig struct { - Delta []processorDelta + Delta []processorDelta EcsDecorator []ecsDecoratorConfig - Ec2tagger []ec2TaggerConfig + Ec2tagger []ec2TaggerConfig EmfProcessor []emfProcessorConfig K8sDecorator []k8sDecoratorConfig } @@ -66,273 +66,269 @@ type ( // Input Plugins awsCsmListenerConfig struct { - DataFormat string `toml:"data_format"` - ServiceAddress []string `toml:"service_address"` + DataFormat string `toml:"data_format"` + ServiceAddress []string `toml:"service_address"` } cadvisorConfig struct { ContainerOrchestrator string `toml:"container_orchestrator"` - Interval string - Mode string - Tags map[string]string + Interval string + Mode string + Tags map[string]string } cpuConfig struct { - CollectCpuTime bool `toml:"collect_cpu_time"` - FieldPass []string - Interval string - PerCpu bool - ReportActive bool `toml:"report_active"` - TotalCpu bool - Tags map[string]string + CollectCpuTime bool `toml:"collect_cpu_time"` + FieldPass []string + Interval string + PerCpu bool + ReportActive bool `toml:"report_active"` + TotalCpu bool + Tags map[string]string } diskConfig struct { - FieldPass []string - IgnoreFs []string `toml:"ignore_fs"` - Interval string - MountPoints []string `toml:"mount_points"` - TagExclude []string - Tags map[string]string + FieldPass []string + IgnoreFs []string `toml:"ignore_fs"` + Interval string + MountPoints []string `toml:"mount_points"` + TagExclude []string + Tags map[string]string } diskioConfig struct { FieldPass []string - Interval string + Interval string } ethtoolConfig struct { - FieldPass []string + FieldPass []string InterfaceInclude []string `toml:"interface_include"` - Tags map[string]string + Tags map[string]string } eventConfig struct { - BatchReadSize int `toml:"batch_read_size"` - EventLevels []string `toml:"event_levels"` - EventName string `toml:"event_name"` - LogGroupName string `toml:"log_group_name"` - LogStreamName string `toml:"log_stream_name"` - RetentionInDays int `toml:"retention_in_days"` + BatchReadSize int `toml:"batch_read_size"` + EventLevels []string `toml:"event_levels"` + EventName string `toml:"event_name"` + LogGroupName string `toml:"log_group_name"` + LogStreamName string `toml:"log_stream_name"` + RetentionInDays int `toml:"retention_in_days"` } logFileConfig struct { - Destination string - FileStateFolder string `toml:"file_state_folder"` - FileConfig []fileConfig `toml:"file_config"` + Destination string + FileStateFolder string `toml:"file_state_folder"` + FileConfig []fileConfig `toml:"file_config"` } fileConfig struct { - AutoRemoval bool `toml:"auto_removal"` - FilePath string `toml:"file_path"` - FromBeginning bool `toml:"from_beginning"` - LogGroupName string `toml:"log_group_name"` - LogStreamName string `toml:"log_stream_name"` - Pipe bool - RetentionInDays int `toml:"retention_in_days"` - Timezone string - Tags map[string]string - Filters []fileConfigFilter + AutoRemoval bool `toml:"auto_removal"` + FilePath string `toml:"file_path"` + FromBeginning bool `toml:"from_beginning"` + LogGroupName string `toml:"log_group_name"` + LogStreamName string `toml:"log_stream_name"` + Pipe bool + RetentionInDays int `toml:"retention_in_days"` + Timezone string + Tags map[string]string + Filters []fileConfigFilter } k8sApiServerConfig struct { Interval string - NodeName string `toml:"node_name"` - Tags map[string]string + NodeName string `toml:"node_name"` + Tags map[string]string } memConfig struct { FieldPass []string - Interval string - Tags map[string]string + Interval string + Tags map[string]string } netConfig struct { - FieldPass []string + FieldPass []string Interfaces []string - Tags map[string]string + Tags map[string]string } netStatConfig struct { FieldPass []string - Interval string - Tags map[string]string + Interval string + Tags map[string]string } nvidiaSmi struct { - FieldPass []string - Interval string + FieldPass []string + Interval string TagExclude []string - Tags map[string]string + Tags map[string]string } processesConfig struct { FieldPass []string - Tags map[string]string + Tags map[string]string } prometheusScraperConfig struct { - ClusterName string `toml:"cluster_name"` - PrometheusConfigPath string `toml:"prometheus_config_path"` - EcsServiceDiscovery prometheusEcsServiceDiscoveryConfig `toml:"ecs_service_discovery"` - Tags map[string]string + ClusterName string `toml:"cluster_name"` + PrometheusConfigPath string `toml:"prometheus_config_path"` + EcsServiceDiscovery prometheusEcsServiceDiscoveryConfig `toml:"ecs_service_discovery"` + Tags map[string]string } prometheusEcsServiceDiscoveryConfig struct { - SdClusterRegion string `toml:"sd_cluster_region"` - SdFrequency string `toml:"sd_frequency"` - SdResultFile string `toml:"sd_result_file"` - SdTargetCluster string `toml:"sd_target_cluster"` - DockerLabel map[string]string `toml:"docker_label"` - ServiceNameListForTasks []serviceNameListForTasks `toml:"service_name_list_for_tasks"` - TaskDefinitionList []taskDefinitionList `toml:"task_definition_list"` + SdClusterRegion string `toml:"sd_cluster_region"` + SdFrequency string `toml:"sd_frequency"` + SdResultFile string `toml:"sd_result_file"` + SdTargetCluster string `toml:"sd_target_cluster"` + DockerLabel map[string]string `toml:"docker_label"` + ServiceNameListForTasks []serviceNameListForTasks `toml:"service_name_list_for_tasks"` + TaskDefinitionList []taskDefinitionList `toml:"task_definition_list"` } procStatConfig struct { - FieldPass []string - PidFile string `toml:"pid_file"` - PidFinder string `toml:"pid_finder"` + FieldPass []string + PidFile string `toml:"pid_file"` + PidFinder string `toml:"pid_finder"` TagExclude []string - Tags map[string]string + Tags map[string]string } serviceNameListForTasks struct { - SdContainerNamePattern string `toml:"sd_container_name_pattern"` - SdJobName string `toml:"sd_job_name"` - SdMetricsPath string `toml:"sd_metrics_path"` - SdMetricsPorts string `toml:"sd_metrics_ports"` - SdServiceNamePattern string `toml:"sd_service_name_pattern"` + SdContainerNamePattern string `toml:"sd_container_name_pattern"` + SdJobName string `toml:"sd_job_name"` + SdMetricsPath string `toml:"sd_metrics_path"` + SdMetricsPorts string `toml:"sd_metrics_ports"` + SdServiceNamePattern string `toml:"sd_service_name_pattern"` } - - socketListenerConfig struct { - CollectdAuthFile string `toml:"collectd_auth_file"` - CollectdSecurityLevel string `toml:"collectd_security_level"` - CollectdTypesDb []string `toml:"collectd_typesdb"` - DataFormat string `toml:"data_format"` - NamePrefix string `toml:"name_prefix"` - NameOverride string `toml:"name_override"` - ServiceAddress string `toml:"service_address"` - Tags map[string]string + CollectdAuthFile string `toml:"collectd_auth_file"` + CollectdSecurityLevel string `toml:"collectd_security_level"` + CollectdTypesDb []string `toml:"collectd_typesdb"` + DataFormat string `toml:"data_format"` + NamePrefix string `toml:"name_prefix"` + NameOverride string `toml:"name_override"` + ServiceAddress string `toml:"service_address"` + Tags map[string]string } statsdConfig struct { - AllowedPendingMessages int `toml:"allowed_pending_messages"` - Interval string - MetricSeparator string `toml:"metric_separator"` - ParseDataDogTags bool `toml:"parse_data_dog_tags"` - ServiceAddress string `toml:"service_address"` - Tags map[string]string + AllowedPendingMessages int `toml:"allowed_pending_messages"` + Interval string + MetricSeparator string `toml:"metric_separator"` + ParseDataDogTags bool `toml:"parse_data_dog_tags"` + ServiceAddress string `toml:"service_address"` + Tags map[string]string } swapConfig struct { FieldPass []string - Tags map[string]string + Tags map[string]string } taskDefinitionList struct { - SdJobName string `toml:"sd_job_name"` - SdMetricsPath string `toml:"sd_metrics_path"` - SdMetricsPorts string `toml:"sd_metrics_ports"` - SdTaskDefinitionArnPattern string `toml:"sd_task_definition_arn_pattern"` - + SdJobName string `toml:"sd_job_name"` + SdMetricsPath string `toml:"sd_metrics_path"` + SdMetricsPorts string `toml:"sd_metrics_ports"` + SdTaskDefinitionArnPattern string `toml:"sd_task_definition_arn_pattern"` } windowsEventLogConfig struct { - Destination string - FileStateFolder string `toml:"file_state_folder"` - EventConfig []eventConfig `toml:"event_config"` - Tags map[string]string + Destination string + FileStateFolder string `toml:"file_state_folder"` + EventConfig []eventConfig `toml:"event_config"` + Tags map[string]string } // Output plugins awsCsmConfig struct { - LogLevel int `toml:"log_level"` - MemoryLimitInMb int `toml:"memory_limit_in_mb"` - Region string + LogLevel int `toml:"log_level"` + MemoryLimitInMb int `toml:"memory_limit_in_mb"` + Region string } cloudWatchOutputConfig struct { - EndpointOverride string `toml:"endpoint_override"` - ForceFlushInterval string `toml:"force_flush_interval"` - MaxDatumsPerCall int `toml:"max_datums_per_call"` - MaxValuesPerDatum int `toml:"max_values_per_datum"` - Namespace string - Region string - RoleArn string `toml:"role_arn"` - RollupDimensions [][]string `toml:"rollup_dimensions"` - TagExclude []string - DropOriginalMetrics map[string][]string `toml:"drop_original_metrics"` - MetricDecorations []metricDecorationConfig `toml:"metric_decoration"` - TagPass map[string][]string + EndpointOverride string `toml:"endpoint_override"` + ForceFlushInterval string `toml:"force_flush_interval"` + MaxDatumsPerCall int `toml:"max_datums_per_call"` + MaxValuesPerDatum int `toml:"max_values_per_datum"` + Namespace string + Region string + RoleArn string `toml:"role_arn"` + RollupDimensions [][]string `toml:"rollup_dimensions"` + TagExclude []string + DropOriginalMetrics map[string][]string `toml:"drop_original_metrics"` + MetricDecorations []metricDecorationConfig `toml:"metric_decoration"` + TagPass map[string][]string } metricDecorationConfig struct { Category string - Name string - Rename string - Unit string + Name string + Rename string + Unit string } cloudWatchLogsConfig struct { - EndpointOverride string `toml:"endpoint_override"` - ForceFlushInterval string `toml:"force_flush_interval"` - LogStreamName string `toml:"log_stream_name"` - Region string - RoleArn string `toml:"role_arn"` - TagExclude []string - TagPass map[string][]string + EndpointOverride string `toml:"endpoint_override"` + ForceFlushInterval string `toml:"force_flush_interval"` + LogStreamName string `toml:"log_stream_name"` + Region string + RoleArn string `toml:"role_arn"` + TagExclude []string + TagPass map[string][]string } fileConfigFilter struct { Expression string - Type string + Type string } // Processors processorDelta struct { - } ecsDecoratorConfig struct { - HostIp string `toml:"host_ip"` - Order int + HostIp string `toml:"host_ip"` + Order int TagPass map[string][]string } ec2TaggerConfig struct { - Ec2InstanceTagKeys []string `toml:"ec2_instance_tag_keys"` - Ec2MetadataTags []string `toml:"ec2_metadata_tags"` - RefreshIntervalSeconds string `toml:"refresh_interval_seconds"` - TagPass map[string][]string + Ec2InstanceTagKeys []string `toml:"ec2_instance_tag_keys"` + Ec2MetadataTags []string `toml:"ec2_metadata_tags"` + RefreshIntervalSeconds string `toml:"refresh_interval_seconds"` + TagPass map[string][]string } emfProcessorConfig struct { - MetricDeclarationDedup bool `toml:"metric_declaration_dedup"` - MetricNamespace string `toml:"metric_namespace"` - Order int - MetricDeclaration []emfProcessorMetricDeclaration `toml:"metric_declaration"` - MetricUnit map[string]string `toml:"metric_unit"` - TagPass map[string][]string + MetricDeclarationDedup bool `toml:"metric_declaration_dedup"` + MetricNamespace string `toml:"metric_namespace"` + Order int + MetricDeclaration []emfProcessorMetricDeclaration `toml:"metric_declaration"` + MetricUnit map[string]string `toml:"metric_unit"` + TagPass map[string][]string } emfProcessorMetricDeclaration struct { - Dimensions [][]string - LabelMatcher string `toml:"label_matcher"` - LabelSeparator string `toml:"label_separator"` + Dimensions [][]string + LabelMatcher string `toml:"label_matcher"` + LabelSeparator string `toml:"label_separator"` MetricSelector []string `toml:"metric_selectors"` - SourceLabels []string `toml:"source_labels"` + SourceLabels []string `toml:"source_labels"` } k8sDecoratorConfig struct { - ClusterName string `toml:"cluster_name"` - HostIp string `toml:"host_ip"` - NodeName string `toml:"host_name_from_env"` - Order int - PreferFullPodName bool `toml:"prefer_full_pod_name"` - TagService bool `toml:"tag_service"` - TagPass map[string][]string - } -) \ No newline at end of file + ClusterName string `toml:"cluster_name"` + HostIp string `toml:"host_ip"` + NodeName string `toml:"host_name_from_env"` + Order int + PreferFullPodName bool `toml:"prefer_full_pod_name"` + TagService bool `toml:"tag_service"` + TagPass map[string][]string + } +) diff --git a/translator/translate/agent/agent_test.go b/translator/translate/agent/agent_test.go index 4ef88d509c4..c04b02a7230 100644 --- a/translator/translate/agent/agent_test.go +++ b/translator/translate/agent/agent_test.go @@ -31,9 +31,9 @@ func agentDefaultConfig(t *testing.T, osType string) { a := new(Agent) translator.SetTargetPlatform(osType) var input interface{} - e := json.Unmarshal([]byte(`{"agent":{"metrics_collection_interval":59, "region": "us-west-2"}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"agent":{"metrics_collection_interval":59, "region": "us-west-2"}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, val := a.ApplyRule(input) agent := map[string]interface{}{ @@ -64,9 +64,9 @@ func agentSpecificConfig(t *testing.T, osType string) { translator.SetTargetPlatform(osType) a := new(Agent) var input interface{} - e := json.Unmarshal([]byte(`{"agent":{"debug":true, "region": "us-west-2"}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"agent":{"debug":true, "region": "us-west-2"}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, val := a.ApplyRule(input) agent := map[string]interface{}{ @@ -97,9 +97,9 @@ func noAgentConfig(t *testing.T, osType string) { translator.SetTargetPlatform(osType) a := new(Agent) var input interface{} - e := json.Unmarshal([]byte(`{"agent":{"region": "us-west-2"}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"agent":{"region": "us-west-2"}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, val := a.ApplyRule(input) @@ -131,9 +131,9 @@ func internal(t *testing.T, osType string) { a := new(Agent) translator.SetTargetPlatform(osType) var input interface{} - e := json.Unmarshal([]byte(`{"agent":{"internal": true}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"agent":{"internal": true}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } agent := map[string]interface{}{ @@ -157,9 +157,9 @@ func internal(t *testing.T, osType string) { assert.Equal(t, agent, val, "Expect to be equal") assert.True(t, Global_Config.Internal) - e = json.Unmarshal([]byte(`{"agent":{"internal": false}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err = json.Unmarshal([]byte(`{"agent":{"internal": false}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, val = a.ApplyRule(input) assert.Equal(t, agent, val, "Expect to be equal") diff --git a/translator/translate/agent/ruleGlobalCredentials_test.go b/translator/translate/agent/ruleGlobalCredentials_test.go index 7bc9fac7a2b..5aabf2f1e57 100644 --- a/translator/translate/agent/ruleGlobalCredentials_test.go +++ b/translator/translate/agent/ruleGlobalCredentials_test.go @@ -17,12 +17,12 @@ func TestWithAgentConfig(t *testing.T) { ctx.SetCredentials(map[string]string{}) c := new(GlobalCreds) var input interface{} - e := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) + if err == nil { c.ApplyRule(input) assert.Equal(t, "role_value", Global_Config.Role_arn, "Expected to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/csm/csm_test.go b/translator/translate/csm/csm_test.go index 5a0541df729..e6dac6f09c8 100644 --- a/translator/translate/csm/csm_test.go +++ b/translator/translate/csm/csm_test.go @@ -24,9 +24,9 @@ func TestCsm_Defaults(t *testing.T) { agent.Global_Config.Region = "us-east-1" var input interface{} - e := json.Unmarshal([]byte(`{"csm":{}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"csm":{}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, actual := c.ApplyRule(input) diff --git a/translator/translate/globaltags/globaltags_test.go b/translator/translate/globaltags/globaltags_test.go index 50794abb12d..53bda6e9efa 100644 --- a/translator/translate/globaltags/globaltags_test.go +++ b/translator/translate/globaltags/globaltags_test.go @@ -13,8 +13,8 @@ import ( func TestGlobalTags(t *testing.T) { g := new(GlobalTags) var input interface{} - e := json.Unmarshal([]byte(`{"global_tags":{"dc":"us-east-3"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{"global_tags":{"dc":"us-east-3"}}`), &input) + if err == nil { _, res := g.ApplyRule(input) globaltags := map[string]interface{}{ "dc": "us-east-3", diff --git a/translator/translate/logs/logs_collected/logs_collected.go b/translator/translate/logs/logs_collected/logs_collected.go index 5d49ada8bc6..2f6f9f9c337 100644 --- a/translator/translate/logs/logs_collected/logs_collected.go +++ b/translator/translate/logs/logs_collected/logs_collected.go @@ -4,6 +4,8 @@ package logs_collected import ( + "log" + "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/jsonconfig/mergeJsonRule" @@ -55,7 +57,7 @@ func (l *LogsCollected) ApplyRule(input interface{}) (returnKey string, returnVa case config.OS_TYPE_WINDOWS: targetRuleMap = windowsMetricCollectRule default: - panic("unknown target platform " + translator.GetTargetPlatform()) + log.Panicf("E! Unknown target platform: %s ", translator.GetTargetPlatform()) } if _, ok := im[SectionKey]; !ok { diff --git a/translator/translate/logs/logs_collected/windows_events/collect_list/collectlist_test.go b/translator/translate/logs/logs_collected/windows_events/collect_list/collectlist_test.go index cec4bb3a007..efbf8f4874a 100644 --- a/translator/translate/logs/logs_collected/windows_events/collect_list/collectlist_test.go +++ b/translator/translate/logs/logs_collected/windows_events/collect_list/collectlist_test.go @@ -60,12 +60,12 @@ func TestApplyRule(t *testing.T) { var actual interface{} - error := json.Unmarshal([]byte(rawJsonString), &input) - if error == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { _, actual = c.ApplyRule(input) assert.Equal(t, expected, actual) } else { - panic(error) + panic(err) } } diff --git a/translator/translate/logs/logs_collected/windows_events/windows_event_test.go b/translator/translate/logs/logs_collected/windows_events/windows_event_test.go index e9089030817..f3e320379ec 100644 --- a/translator/translate/logs/logs_collected/windows_events/windows_event_test.go +++ b/translator/translate/logs/logs_collected/windows_events/windows_event_test.go @@ -45,12 +45,12 @@ func TestApplyRule(t *testing.T) { var actual interface{} - error := json.Unmarshal([]byte(rawJsonString), &input) - if error == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { context.CurrentContext().SetOs(config.OS_TYPE_WINDOWS) _, actual = w.ApplyRule(input) assert.Equal(t, expected, actual) } else { - panic(error) + panic(err) } } diff --git a/translator/translate/logs/logs_test.go b/translator/translate/logs/logs_test.go index c855005280c..820af5d7dda 100644 --- a/translator/translate/logs/logs_test.go +++ b/translator/translate/logs/logs_test.go @@ -22,9 +22,9 @@ func TestLogs(t *testing.T) { agent.Global_Config.Region = "us-east-1" var input interface{} - e := json.Unmarshal([]byte(`{"logs":{"log_stream_name":"LOG_STREAM_NAME"}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"logs":{"log_stream_name":"LOG_STREAM_NAME"}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } _, actual := l.ApplyRule(input) @@ -49,9 +49,9 @@ func TestLogs_LogStreamName(t *testing.T) { agent.Global_Config.Region = "us-east-1" var input interface{} - e := json.Unmarshal([]byte(`{"logs":{}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"logs":{}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } ctx := context.CurrentContext() @@ -134,9 +134,9 @@ func TestLogs_ForceFlushInterval(t *testing.T) { agent.Global_Config.Region = "us-east-1" var input interface{} - e := json.Unmarshal([]byte(`{"logs":{"force_flush_interval":10}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"logs":{"force_flush_interval":10}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } ctx := context.CurrentContext() @@ -168,9 +168,9 @@ func TestLogs_EndpointOverride(t *testing.T) { agent.Global_Config.Region = "us-east-1" var input interface{} - e := json.Unmarshal([]byte(`{"logs":{"endpoint_override":"https://logs-fips.us-east-1.amazonaws.com"}}`), &input) - if e != nil { - assert.Fail(t, e.Error()) + err := json.Unmarshal([]byte(`{"logs":{"endpoint_override":"https://logs-fips.us-east-1.amazonaws.com"}}`), &input) + if err != nil { + assert.Fail(t, err.Error()) } ctx := context.CurrentContext() diff --git a/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go b/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go index b624ab8e079..5cf3e66babe 100644 --- a/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go +++ b/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go @@ -4,7 +4,6 @@ package emfprocessor import ( - "fmt" "io/ioutil" "log" "os" @@ -34,7 +33,7 @@ type ConfigPath struct { func splitConfigPath(configPath string) string { locationArray := strings.SplitN(configPath, sourceSeparator, 2) if locationArray == nil || len(locationArray) < 2 { - panic(fmt.Sprintf("Prometheus config path: %s is malformated.\n", configPath)) + log.Panicf("Prometheus config path: %s is malformated.", configPath) } return locationArray[1] @@ -67,12 +66,12 @@ func (obj *ConfigPath) ApplyRule(input interface{}) (string, interface{}) { configEnv := splitConfigPath(configPath) if cc, ok := os.LookupEnv(configEnv); ok { if error := ioutil.WriteFile(downloadingPath, []byte(cc), yamlFileMode); error != nil { - panic(fmt.Sprintf("Failed to download the Prometheus config yaml file. Reason: %s \n", error.Error())) + log.Panicf("Failed to download the Prometheus config yaml file. Reason: %s", error.Error()) } else { log.Printf("Downloaded the prometheus config from ENV: %v.", configEnv) } } else { - panic(fmt.Sprintf("Failed to download the Prometheus config yaml from ENV: %v. Reason: ENV does not exist \n", configEnv)) + log.Panicf("Failed to download the Prometheus config yaml from ENV: %v. Reason: ENV does not exist", configEnv) } return SectionKeyConfigPath, downloadingPath } diff --git a/translator/translate/logs/ruleLogCredentials_test.go b/translator/translate/logs/ruleLogCredentials_test.go index 26b263f3648..21e5a3db9a9 100644 --- a/translator/translate/logs/ruleLogCredentials_test.go +++ b/translator/translate/logs/ruleLogCredentials_test.go @@ -18,30 +18,30 @@ func TestWithAgentConfig(t *testing.T) { ctx.SetCredentials(map[string]string{}) c := new(LogCreds) var input interface{} - e := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "role_value", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } agent.Global_Config.Role_arn = "global_role_arn_test" - e = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) - if e == nil { + err = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "role_value", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } agent.Global_Config.Role_arn = "global_role_arn_test" - e = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) - if e == nil { + err = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "global_role_arn_test", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } agent.Global_Config.Role_arn = "" diff --git a/translator/translate/metrics/append_dimensions/ruleCreds_test.go b/translator/translate/metrics/append_dimensions/ruleCreds_test.go index 1361ad36fbc..5309e9423e0 100644 --- a/translator/translate/metrics/append_dimensions/ruleCreds_test.go +++ b/translator/translate/metrics/append_dimensions/ruleCreds_test.go @@ -14,7 +14,7 @@ import ( func TestNoAgentConfi1g(t *testing.T) { c := new(Creds) var input interface{} - e := json.Unmarshal([]byte(`{ "cloudwatch_creds" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) + err := json.Unmarshal([]byte(`{ "cloudwatch_creds" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) agent.Global_Config.Credentials = map[string]interface{}{ "access_key": "global_ak", "secret_key": "global_sk", @@ -22,7 +22,7 @@ func TestNoAgentConfi1g(t *testing.T) { "profile": "global_profile", "role_arn": "role_arn", } - if e == nil { + if err == nil { _, actual := c.ApplyRule(input) expected := map[string]interface{}{ "access_key": "global_ak", @@ -32,6 +32,6 @@ func TestNoAgentConfi1g(t *testing.T) { } assert.Equal(t, expected, actual, "Expected to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/cpu/cpu_test.go b/translator/translate/metrics/metrics_collect/cpu/cpu_test.go index e721f93dee3..28eccdaadc9 100644 --- a/translator/translate/metrics/metrics_collect/cpu/cpu_test.go +++ b/translator/translate/metrics/metrics_collect/cpu/cpu_test.go @@ -15,35 +15,35 @@ func TestCpuSpecificConfig(t *testing.T) { c := new(Cpu) //Check whether override default config var input interface{} - e := json.Unmarshal([]byte(`{"cpu":{"metrics_collection_interval":"11s"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{"cpu":{"metrics_collection_interval":"11s"}}`), &input) + if err == nil { actualReturnKey, _ := c.ApplyRule(input) assert.Equal(t, "", actualReturnKey, "Expect to be equal") } else { - panic(e) + panic(err) } } func TestNonCpuConfig(t *testing.T) { c := new(Cpu) var input interface{} - e := json.Unmarshal([]byte(`{"NotCpu":{"foo":"bar"}}`), &input) + err := json.Unmarshal([]byte(`{"NotCpu":{"foo":"bar"}}`), &input) - if e == nil { + if err == nil { actualKey, actualVal := c.ApplyRule(input) expectedKey := "" expectedVal := "" assert.Equal(t, expectedKey, actualKey, "ReturnKey should be empty") assert.Equal(t, expectedVal, actualVal, "ReturnVal should be empty") } else { - panic(e) + panic(err) } } func TestInvalidMetrics(t *testing.T) { c := new(Cpu) var input interface{} - e := json.Unmarshal([]byte(`{"cpu": { + err := json.Unmarshal([]byte(`{"cpu": { "resources": [ "*" ], @@ -55,10 +55,10 @@ func TestInvalidMetrics(t *testing.T) { "totalcpu": true, "metrics_collection_interval": "1s" }}`), &input) - if e == nil { + if err == nil { actualKey, _ := c.ApplyRule(input) assert.Equal(t, "", actualKey, "return key should be empty") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/cpu/ruleReportActive_test.go b/translator/translate/metrics/metrics_collect/cpu/ruleReportActive_test.go index 7ad1f22a201..638e9cbbbb5 100644 --- a/translator/translate/metrics/metrics_collect/cpu/ruleReportActive_test.go +++ b/translator/translate/metrics/metrics_collect/cpu/ruleReportActive_test.go @@ -13,51 +13,51 @@ import ( func TestReportActive_NoActive(t *testing.T) { r := new(ReportActive) var input interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "measurement":[ "cpu_usage_idle" ] }`), &input) - if e == nil { + if err == nil { actualReturnKey, _ := r.ApplyRule(input) assert.Equal(t, "", actualReturnKey) } else { - panic(e) + panic(err) } } func TestReportActive_TimeActive(t *testing.T) { r := new(ReportActive) var input interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "measurement": [ "cpu_usage_idle", "cpu_time_active" ] }`), &input) - if e == nil { + if err == nil { actualReturnKey, actualReturnValue := r.ApplyRule(input) assert.Equal(t, "report_active", actualReturnKey) assert.True(t, actualReturnValue.(bool)) } else { - panic(e) + panic(err) } } func TestReportActive_UsageActive(t *testing.T) { r := new(ReportActive) var input interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "measurement": [ "cpu_usage_idle", "usage_active" ] }`), &input) - if e == nil { + if err == nil { actualReturnKey, actualReturnValue := r.ApplyRule(input) assert.Equal(t, "report_active", actualReturnKey) assert.True(t, actualReturnValue.(bool)) } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/disk/disk_test.go b/translator/translate/metrics/metrics_collect/disk/disk_test.go index ed57682d67f..c2b8c175035 100644 --- a/translator/translate/metrics/metrics_collect/disk/disk_test.go +++ b/translator/translate/metrics/metrics_collect/disk/disk_test.go @@ -15,16 +15,16 @@ func TestDiskSpecificConfig(t *testing.T) { d := new(Disk) //Check whether override default config var input interface{} - e := json.Unmarshal([]byte(`{"disk":{"metrics_collection_interval":"60"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{"disk":{"metrics_collection_interval":"60"}}`), &input) + if err == nil { actualReturnKey, _ := d.ApplyRule(input) assert.Equal(t, "", actualReturnKey, "Expect to be equal") } else { - panic(e) + panic(err) } //Check whether provide specific config var input1 interface{} - err := json.Unmarshal([]byte(`{"disk":{ + err = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -52,7 +52,7 @@ func TestDiskSpecificConfig(t *testing.T) { //check when "drop_device" = true var input2 interface{} - er := json.Unmarshal([]byte(`{"disk":{ + err = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -66,7 +66,7 @@ func TestDiskSpecificConfig(t *testing.T) { ], "drop_device": true }}`), &input2) - if er == nil { + if err == nil { _, actualValue := d.ApplyRule(input2) expectedValue := []interface{}{map[string]interface{}{ "ignore_fs": []interface{}{"sysfs", "devtmpfs"}, @@ -77,12 +77,12 @@ func TestDiskSpecificConfig(t *testing.T) { } assert.Equal(t, expectedValue, actualValue, "Expect to be equal") } else { - panic(er) + panic(err) } //check when "drop_device" = false var input3 interface{} - err3 := json.Unmarshal([]byte(`{"disk":{ + err = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -96,7 +96,7 @@ func TestDiskSpecificConfig(t *testing.T) { ], "drop_device": false }}`), &input3) - if err3 == nil { + if err == nil { _, actualValue := d.ApplyRule(input3) expectedValue := []interface{}{map[string]interface{}{ "ignore_fs": []interface{}{"sysfs", "devtmpfs"}, @@ -107,7 +107,7 @@ func TestDiskSpecificConfig(t *testing.T) { } assert.Equal(t, expectedValue, actualValue, "Expect to be equal") } else { - panic(err3) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go index 56c3c52ba65..ef3b958ebdb 100644 --- a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go +++ b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go @@ -102,15 +102,15 @@ func TestInvalidMetrics(t *testing.T) { func TestNonGpuConfig(t *testing.T) { c := new(NvidiaSmi) var input interface{} - e := json.Unmarshal([]byte(`{"nvidia_smi":{"foo":"bar"}}`), &input) + err := json.Unmarshal([]byte(`{"nvidia_smi":{"foo":"bar"}}`), &input) - if e == nil { + if err == nil { actualKey, actualVal := c.ApplyRule(input) expectedKey := "" expectedVal := "" assert.Equal(t, expectedKey, actualKey, "ReturnKey should be empty") assert.Equal(t, expectedVal, actualVal, "ReturnVal should be empty") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/mem/mem_test.go b/translator/translate/metrics/metrics_collect/mem/mem_test.go index 6d2d71c77d8..a83ea440d69 100644 --- a/translator/translate/metrics/metrics_collect/mem/mem_test.go +++ b/translator/translate/metrics/metrics_collect/mem/mem_test.go @@ -15,16 +15,16 @@ func TestMemSpecificConfig(t *testing.T) { m := new(Mem) //Check whether provide specific config var input interface{} - e := json.Unmarshal([]byte(`{"mem":{"metrics_collection_interval":"60s"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{"mem":{"metrics_collection_interval":"60s"}}`), &input) + if err == nil { actualReturnKey, _ := m.ApplyRule(input) assert.Equal(t, "", actualReturnKey, "return key should be empty") } else { - panic(e) + panic(err) } var input1 interface{} - err := json.Unmarshal([]byte(`{"mem":{"measurement": [ + err = json.Unmarshal([]byte(`{"mem":{"measurement": [ "free", "total" ]}}`), &input1) diff --git a/translator/translate/metrics/metrics_collect/net/net_test.go b/translator/translate/metrics/metrics_collect/net/net_test.go index 59a726fbca6..316e198d1bd 100644 --- a/translator/translate/metrics/metrics_collect/net/net_test.go +++ b/translator/translate/metrics/metrics_collect/net/net_test.go @@ -13,11 +13,11 @@ import ( func TestNet(t *testing.T) { n := new(Net) var input interface{} - e := json.Unmarshal([]byte(`{"net":{"measurement": [ + err := json.Unmarshal([]byte(`{"net":{"measurement": [ "bytes_sent", "bytes_recv", "dummy_drop_in"]}}`), &input) - if e == nil { + if err == nil { _, actual := n.ApplyRule(input) expected := []interface{}{map[string]interface{}{ "fieldpass": []string{"bytes_sent", "bytes_recv"}, @@ -25,18 +25,18 @@ func TestNet(t *testing.T) { }} assert.Equal(t, expected, actual, "Expected to be equal") } else { - panic(e) + panic(err) } } func TestNetWithReportDeltaTrue(t *testing.T) { n := new(Net) var input interface{} - e := json.Unmarshal([]byte(`{"net":{"measurement": [ + err := json.Unmarshal([]byte(`{"net":{"measurement": [ "bytes_sent", "bytes_recv", "dummy_drop_in"],"report_deltas":true}}`), &input) - if e == nil { + if err == nil { _, actual := n.ApplyRule(input) expected := []interface{}{map[string]interface{}{ "fieldpass": []string{"bytes_sent", "bytes_recv"}, @@ -44,24 +44,24 @@ func TestNetWithReportDeltaTrue(t *testing.T) { }} assert.Equal(t, expected, actual, "Expected to be equal") } else { - panic(e) + panic(err) } } func TestNetWithReportDeltaFalse(t *testing.T) { n := new(Net) var input interface{} - e := json.Unmarshal([]byte(`{"net":{"measurement": [ + err := json.Unmarshal([]byte(`{"net":{"measurement": [ "bytes_sent", "bytes_recv", "dummy_drop_in"],"report_deltas":false}}`), &input) - if e == nil { + if err == nil { _, actual := n.ApplyRule(input) expected := []interface{}{map[string]interface{}{ "fieldpass": []string{"bytes_sent", "bytes_recv"}, }} assert.Equal(t, expected, actual, "Expected to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/swap/swap_test.go b/translator/translate/metrics/metrics_collect/swap/swap_test.go index 47e20adc412..93638629051 100644 --- a/translator/translate/metrics/metrics_collect/swap/swap_test.go +++ b/translator/translate/metrics/metrics_collect/swap/swap_test.go @@ -21,11 +21,8 @@ func TestSwapSpecificConfig(t *testing.T) { } var input1 interface{} - err := json.Unmarshal([]byte(`{"swap":{"measurement": [ - "used", - "free" - ]}}`), &input1) - if err == nil { + e = json.Unmarshal([]byte(`{"swap":{"measurement": ["used","free"]}}`), &input1) + if e == nil { _, actualVal := s.ApplyRule(input1) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"used", "free"}, @@ -33,6 +30,6 @@ func TestSwapSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(err) + panic(e) } } diff --git a/translator/translate/metrics/metrics_test.go b/translator/translate/metrics/metrics_test.go index 4777ebf341a..680a4c51727 100644 --- a/translator/translate/metrics/metrics_test.go +++ b/translator/translate/metrics/metrics_test.go @@ -15,8 +15,8 @@ func TestMetrics(t *testing.T) { m := new(Metrics) var input interface{} agent.Global_Config.Region = "auto" - e := json.Unmarshal([]byte(`{"metrics":{}}`), &input) - assert.NoError(t, e) + err := json.Unmarshal([]byte(`{"metrics":{}}`), &input) + assert.NoError(t, err) _, actual := m.ApplyRule(input) expected := map[string]interface{}( map[string]interface{}{ @@ -42,8 +42,8 @@ func TestMetrics_Internal(t *testing.T) { var input interface{} agent.Global_Config.Region = "auto" agent.Global_Config.Internal = true - e := json.Unmarshal([]byte(`{"metrics":{}}`), &input) - assert.NoError(t, e) + err := json.Unmarshal([]byte(`{"metrics":{}}`), &input) + assert.NoError(t, err) _, actual := m.ApplyRule(input) expected := map[string]interface{}( map[string]interface{}{ @@ -70,8 +70,8 @@ func TestMetrics_EndpointOverride(t *testing.T) { m := new(Metrics) var input interface{} agent.Global_Config.Region = "auto" - e := json.Unmarshal([]byte(`{"metrics":{"endpoint_override":"https://monitoring-fips.us-east-1.amazonaws.com"}}`), &input) - assert.NoError(t, e) + err := json.Unmarshal([]byte(`{"metrics":{"endpoint_override":"https://monitoring-fips.us-east-1.amazonaws.com"}}`), &input) + assert.NoError(t, err) _, actual := m.ApplyRule(input) expected := map[string]interface{}( map[string]interface{}{ diff --git a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go index 831d58d14e2..007d5e5d699 100644 --- a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go +++ b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go @@ -57,9 +57,9 @@ func TestInvalidRollupList(t *testing.T) { }`), } for _, testInput := range testInputs { - e := json.Unmarshal(testInput, &tmp) - if e != nil { - panic(e) + err := json.Unmarshal(testInput, &tmp) + if err != nil { + panic(err) } if im, ok := tmp.(map[string]interface{}); ok { actualVal = im[SectionKey] diff --git a/translator/translate/metrics/ruleMetricCredentials_test.go b/translator/translate/metrics/ruleMetricCredentials_test.go index 4d4666b513a..a786a968d42 100644 --- a/translator/translate/metrics/ruleMetricCredentials_test.go +++ b/translator/translate/metrics/ruleMetricCredentials_test.go @@ -18,29 +18,29 @@ func TestWithAgentConfig(t *testing.T) { ctx.SetCredentials(map[string]string{}) c := new(MetricsCreds) var input interface{} - e := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) - if e == nil { + err := json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "role_value", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } agent.Global_Config.Role_arn = "global_role_arn_test" - e = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) - if e == nil { + err = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile", "role_arn": "role_value"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "role_value", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } agent.Global_Config.Role_arn = "global_role_arn_test" - e = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) - if e == nil { + err = json.Unmarshal([]byte(`{ "credentials" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) + if err == nil { _, returnVal := c.ApplyRule(input) assert.Equal(t, "global_role_arn_test", returnVal.(map[string]interface{})["role_arn"], "Expected to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/util/commonconfigutil_test.go b/translator/translate/metrics/util/commonconfigutil_test.go index dd4fbebc18a..3b879bd5134 100644 --- a/translator/translate/metrics/util/commonconfigutil_test.go +++ b/translator/translate/metrics/util/commonconfigutil_test.go @@ -13,7 +13,7 @@ import ( func TestProcessLinuxCommonConfigNoValidMetrics(t *testing.T) { var input interface{} result := map[string]interface{}{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "resources": [ "*" ], @@ -25,18 +25,18 @@ func TestProcessLinuxCommonConfigNoValidMetrics(t *testing.T) { "totalcpu": true, "metrics_collection_interval": 1 }`), &input) - if e == nil { + if err == nil { hasValidMetrics := ProcessLinuxCommonConfig(input, "cpu", "", result) assert.False(t, hasValidMetrics, "Shouldn't return any valid metrics") } else { - panic(e) + panic(err) } } func TestProcessLinuxCommonConfigHappy(t *testing.T) { var input interface{} actualResult := map[string]interface{}{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "resources": [ "*" ], @@ -48,7 +48,7 @@ func TestProcessLinuxCommonConfigHappy(t *testing.T) { "totalcpu": true, "metrics_collection_interval": 1 }`), &input) - if e == nil { + if err == nil { hasValidMetrics := ProcessLinuxCommonConfig(input, "cpu", "", actualResult) expectedResult := map[string]interface{}{ "fieldpass": []string{"usage_idle", "usage_nice"}, @@ -58,6 +58,6 @@ func TestProcessLinuxCommonConfigHappy(t *testing.T) { assert.True(t, hasValidMetrics, "Should return valid metrics") assert.Equal(t, expectedResult, actualResult, "should be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/util/measurementutil.go b/translator/translate/metrics/util/measurementutil.go index d6b5ce72c15..ae9520fb9ea 100755 --- a/translator/translate/metrics/util/measurementutil.go +++ b/translator/translate/metrics/util/measurementutil.go @@ -117,7 +117,7 @@ func getValidMetric(targetOs string, pluginName string, metricName string) strin case translatorConfig.OS_TYPE_WINDOWS: return metricName default: - panic("unknown os platform in getValidMetric: " + targetOs) + log.Panicf("E! Unknown os platform in getValidMetric: %s", targetOs) } if val, ok := registeredMetrics[pluginName]; ok { formatted_metricName := getFormattedMetricName(metricName, pluginName) diff --git a/translator/translate/translate.go b/translator/translate/translate.go index 627d0ce7a2c..22cc34f3b4c 100644 --- a/translator/translate/translate.go +++ b/translator/translate/translate.go @@ -4,6 +4,7 @@ package translate import ( + "log" "sort" "github.com/aws/amazon-cloudwatch-agent/translator" @@ -56,7 +57,7 @@ func (t *Translator) ApplyRule(input interface{}) (returnKey string, returnVal i case config.OS_TYPE_WINDOWS: targetRuleMap = windowsTranslateRule default: - panic("unknown target platform " + translator.GetTargetPlatform()) + log.Panicf("E! Unknown target platform %s", translator.GetTargetPlatform()) } //We need to apply agent rule first, since global setting lies there, which will impact the override logic diff --git a/translator/translate/util/credsutil_test.go b/translator/translate/util/credsutil_test.go index d0e7549db8e..71dd5c2ded1 100644 --- a/translator/translate/util/credsutil_test.go +++ b/translator/translate/util/credsutil_test.go @@ -14,14 +14,14 @@ import ( func TestCreds(t *testing.T) { c := GetCredsRule("cloudwatch_creds") var input interface{} - e := json.Unmarshal([]byte(`{ "cloudwatch_creds" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) + err := json.Unmarshal([]byte(`{ "cloudwatch_creds" : {"access_key":"metric_ak", "secret_key":"metric_sk", "token": "dummy_token", "profile": "dummy_profile"}}`), &input) agent.Global_Config.Credentials = map[string]interface{}{ "access_key": "global_ak", "secret_key": "global_sk", "token": "global_token", "profile": "global_profile", } - if e == nil { + if err == nil { _, actual := c.ApplyRule(input) expected := map[string]interface{}{ "access_key": "global_ak", @@ -31,6 +31,6 @@ func TestCreds(t *testing.T) { } assert.Equal(t, expected, actual, "Expected to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/util/placeholderUtil.go b/translator/translate/util/placeholderUtil.go index bc65e354b3c..a9a679ad5f7 100644 --- a/translator/translate/util/placeholderUtil.go +++ b/translator/translate/util/placeholderUtil.go @@ -16,9 +16,9 @@ import ( type Metadata struct { InstanceID string - Hostname string - PrivateIP string - AccountID string + Hostname string + PrivateIP string + AccountID string } type MetadataInfoProvider func() *Metadata @@ -27,9 +27,9 @@ var Ec2MetadataInfoProvider = func() *Metadata { ec2 := ec2util.GetEC2UtilSingleton() return &Metadata{ InstanceID: ec2.InstanceID, - Hostname: ec2.Hostname, - PrivateIP: ec2.PrivateIP, - AccountID: ec2.AccountID, + Hostname: ec2.Hostname, + PrivateIP: ec2.PrivateIP, + AccountID: ec2.AccountID, } } diff --git a/translator/translate/util/placeholderUtil_test.go b/translator/translate/util/placeholderUtil_test.go index 7ee63f59d16..56925ec2a65 100644 --- a/translator/translate/util/placeholderUtil_test.go +++ b/translator/translate/util/placeholderUtil_test.go @@ -11,9 +11,9 @@ import ( const ( dummyInstanceId = "some_instance_id" - dummyHostName = "some_hostname" - dummyPrivateIp = "some_private_ip" - dummyAccountId = "some_account_id" + dummyHostName = "some_hostname" + dummyPrivateIp = "some_private_ip" + dummyAccountId = "some_account_id" ) func TestHostName(t *testing.T) { @@ -56,9 +56,9 @@ func mockMetadataProvider(instanceId, hostname, privateIp, accountId string) fun return func() *Metadata { return &Metadata{ InstanceID: instanceId, - Hostname: hostname, - PrivateIP: privateIp, - AccountID: accountId, + Hostname: hostname, + PrivateIP: privateIp, + AccountID: accountId, } } } diff --git a/translator/util/ec2util/ec2util.go b/translator/util/ec2util/ec2util.go index 5fa9929f7e4..66eae0eb396 100644 --- a/translator/util/ec2util/ec2util.go +++ b/translator/util/ec2util/ec2util.go @@ -4,14 +4,15 @@ package ec2util import ( - "github.com/aws/amazon-cloudwatch-agent/translator/config" - "github.com/aws/amazon-cloudwatch-agent/translator/context" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/session" "log" "net" "sync" "time" + + "github.com/aws/amazon-cloudwatch-agent/translator/config" + "github.com/aws/amazon-cloudwatch-agent/translator/context" + "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/aws/session" ) // this is a singleton struct @@ -20,7 +21,7 @@ type ec2Util struct { PrivateIP string InstanceID string Hostname string - AccountID string + AccountID string } const allowedRetries = 5 diff --git a/translator/util/sdkutil.go b/translator/util/sdkutil.go index ea9308f463f..44af64803e5 100644 --- a/translator/util/sdkutil.go +++ b/translator/util/sdkutil.go @@ -69,8 +69,8 @@ func SDKRegionWithCredsMap(mode string, credsConfig map[string]string) (region s } CheckAndSetHomeDir() opts.SharedConfigState = session.SharedConfigEnable - ses, e := session.NewSessionWithOptions(opts) - if e != nil { + ses, err := session.NewSessionWithOptions(opts) + if err != nil { return "" } if ses.Config != nil && ses.Config.Region != nil { @@ -128,7 +128,7 @@ func detectHomeDirectory() string { systemDrivePath := GetWindowsSystemDrivePath() // C: homeDir = systemDrivePath + "\\Users\\Administrator" } else { - if usr, e := user.Current(); e == nil { + if usr, err := user.Current(); err == nil { homeDir = usr.HomeDir } if homeDir == "" { diff --git a/translator/util/searchutil_test.go b/translator/util/searchutil_test.go index 4d5f79a05e9..5fd523446c2 100644 --- a/translator/util/searchutil_test.go +++ b/translator/util/searchutil_test.go @@ -35,12 +35,12 @@ func TestSetWithSameKeyIfFound(t *testing.T) { "tagC": map[string]interface{}{"key1": "value1", "key2": "value2"}, } var actual = map[string]interface{}{} - error := json.Unmarshal([]byte(rawJsonString), &input) - if error == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { SetWithSameKeyIfFound(input, target_key_list, actual) assert.Equal(t, expected, actual) } else { - panic(error) + panic(err) } } @@ -69,11 +69,11 @@ func TestSetWithCustomizedKeyIfFound(t *testing.T) { "tagCMapped": map[string]interface{}{"key1": "value1", "key2": "value2"}, } var actual = map[string]interface{}{} - error := json.Unmarshal([]byte(rawJsonString), &input) - if error == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { SetWithCustomizedKeyIfFound(input, targetKeyMap, actual) assert.Equal(t, expected, actual) } else { - panic(error) + panic(err) } }