From db17e15dffe873a5faee5f4656864a24759bdc70 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 14:38:41 -0400 Subject: [PATCH 01/23] Add log before panic and translate some err to e in test case --- cmd/config-downloader/downloader.go | 42 ++++++++++++------- cmd/config-translator/translator.go | 8 +++- cmd/config-translator/translator_test.go | 4 +- .../k8sdecorator/stores/podstore.go | 4 +- .../k8sdecorator/stores/podstore_test.go | 5 ++- .../migration/linux/knownConfigKeys.go | 5 ++- .../migration/linux/linuxMigration.go | 12 +++--- translator/cmdutil/translatorutil.go | 12 ++++-- translator/cmdutil/userutil.go | 10 +++-- translator/config/os.go | 5 ++- translator/config/schema_test.go | 6 +-- translator/context/context.go | 4 +- translator/jsonconfig/mergeJsonConfig.go | 4 +- translator/toenvconfig/toEnvConfig.go | 4 +- translator/toenvconfig/toEnvConfig_test.go | 6 +-- translator/totomlconfig/toTomlConfig.go | 6 +-- translator/translate/agent/ruleLogFile.go | 6 ++- .../logs/logs_collected/logs_collected.go | 4 +- .../windows_events/windows_event_test.go | 6 +-- .../prometheus/ruleConfigPath.go | 12 ++++-- .../append_dimensions_test.go | 8 ++-- .../metrics/metrics_collect/disk/disk_test.go | 18 ++++---- .../metrics_collect/gpu/nvidiaSmi_test.go | 12 +++--- .../metrics/metrics_collect/mem/mem_test.go | 6 +-- .../metrics/metrics_collect/swap/swap_test.go | 9 ++-- .../rollupDimensions_test.go | 16 +++---- .../translate/metrics/util/measurementutil.go | 4 +- translator/translate/translate.go | 8 +++- translator/util/searchutil_test.go | 12 +++--- 29 files changed, 159 insertions(+), 99 deletions(-) diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index 80496f635a..940d6d5288 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -7,7 +7,7 @@ import ( "flag" "io/ioutil" "os" - + "log" "strings" configaws "github.com/aws/amazon-cloudwatch-agent/cfg/aws" @@ -125,13 +125,15 @@ 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) + errorMessage := fmt.Sprintf("E! Failed to open Common Config: %v\n", err) + log.Printf(errorMessage) + panic(errorMessage) } if err := cc.Parse(f); err != nil { - fmt.Printf("E! Failed to parse Common Config: %v\n", err) - panic(err) + errorMessage := fmt.Sprintf("E! Failed to parse Common Config: %v\n", err) + log.Printf(errorMessage) + panic(errorMessage) } } util.SetProxyEnv(cc.ProxyMap()) @@ -140,10 +142,11 @@ func main() { if downloadLocation == "" || outputDir == "" { executable, e := os.Executable() if e == nil { - errorMessage = fmt.Sprintf("usage: " + filepath.Base(executable) + " --output-dir --download-source ssm: ") + 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: ") } + log.Printf(errorMessage) panic(errorMessage) } @@ -154,11 +157,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") } + log.Printf(errorMessage) panic(errorMessage) } @@ -187,7 +191,9 @@ 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)) + errorMessage := fmt.Sprintf("E! downloadLocation %s is malformated.\n", downloadLocation) + log.Printf(errorMessage) + panic(errorMessage) } var config, outputFilePath string @@ -209,25 +215,33 @@ func main() { config, err = readFromFile(locationArray[1]) } default: - panic(fmt.Sprintf("location type %s is not supported.", locationArray[0])) + errorMessage := fmt.Sprintf("E! Location type %s is not supported.", locationArray[0]) + log.Printf(errorMessage) + panic(errorMessage) } if err != nil { - panic(fmt.Sprintf("Fail to fetch/remove json config: %v\n", err)) + errorMessage := fmt.Sprintf("E! Fail to fetch/remove json config: %v\n", err) + log.Printf(errorMessage) + panic(errorMessage) } 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)) + errorMessage := fmt.Sprintf("E! Failed to write the json file %v: %v\n", outputFilePath, err) + log.Printf(errorMessage) + panic(errorMessage) } 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)) + errorMessage := fmt.Sprintf("E! Failed to remove the json file %v: %v", outputFilePath, err) + log.Printf(errorMessage) + panic(errorMessage) } 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 b49a9f12e6..fe8694837c 100644 --- a/cmd/config-translator/translator.go +++ b/cmd/config-translator/translator.go @@ -90,7 +90,9 @@ func main() { mergedJsonConfigMap, err := cmdutil.GenerateMergedJsonConfigMap(ctx) if err != nil { - panic(fmt.Sprintf("E! Failed to generate merged json config: %v", err)) + errorMessage := fmt.Sprintf("E! Failed to generate merged json config: %v", err) + log.Printf(errorMessage) + panic(errorMessage) } if !ctx.RunInContainer() { @@ -99,7 +101,9 @@ func main() { if e == nil && current.Name == "root" { runAsUser, err := cmdutil.DetectRunAsUser(mergedJsonConfigMap) if err != nil { - panic("E! Failed to detectRunAsUser\n") + errorMessage := fmt.Sprintf("E! Failed to detectRunAsUser\n") + log.Printf(errorMessage) + panic(errorMessage) } cmdutil.VerifyCredentials(ctx, runAsUser) } diff --git a/cmd/config-translator/translator_test.go b/cmd/config-translator/translator_test.go index 1048a3cf3a..65ae9a4f2e 100644 --- a/cmd/config-translator/translator_test.go +++ b/cmd/config-translator/translator_test.go @@ -181,7 +181,7 @@ func TestInvalidLogFilterConfig(t *testing.T) { // Validate all sampleConfig files schema func TestSampleConfigSchema(t *testing.T) { - if files, err := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); err == nil { + if files, e := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); err == nil { re := regexp.MustCompile(".json") for _, file := range files { if re.MatchString(file.Name()) { @@ -191,6 +191,6 @@ func TestSampleConfigSchema(t *testing.T) { } } } else { - panic(err) + panic(e) } } diff --git a/plugins/processors/k8sdecorator/stores/podstore.go b/plugins/processors/k8sdecorator/stores/podstore.go index ed6542f21c..23ed46c4db 100644 --- a/plugins/processors/k8sdecorator/stores/podstore.go +++ b/plugins/processors/k8sdecorator/stores/podstore.go @@ -74,7 +74,9 @@ 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)) + errorMessage := fmt.Sprintf("Cannot get pod from kubelet, err: %v", err) + log.Printf(errorMessage) + panic(errorMessage) } return podStore diff --git a/plugins/processors/k8sdecorator/stores/podstore_test.go b/plugins/processors/k8sdecorator/stores/podstore_test.go index 58a126df8e..2070d7849a 100644 --- a/plugins/processors/k8sdecorator/stores/podstore_test.go +++ b/plugins/processors/k8sdecorator/stores/podstore_test.go @@ -8,6 +8,7 @@ import ( "fmt" "testing" "time" + "log" "github.com/aws/amazon-cloudwatch-agent/internal/mapWithExpiry" @@ -180,7 +181,9 @@ func getBaseTestPodInfo() *corev1.Pod { pods := corev1.PodList{} err := json.Unmarshal([]byte(podJson), &pods) if err != nil { - panic(fmt.Sprintf("unmarshal pod err %v", err)) + errorMessage := fmt.Sprintf("unmarshal pod err %v", err) + log.Printf(errorMessage) + panic(errorMessage) } return &pods.Items[0] diff --git a/tool/processors/migration/linux/knownConfigKeys.go b/tool/processors/migration/linux/knownConfigKeys.go index a6204728d5..283ed8a4af 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,9 @@ 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)) + errorMessage := fmt.Sprintf("E! Encoding %s is not supported.", encoding) + log.Printf(errorMessage) + panic(errorMessage) } else { encoding = normalized } diff --git a/tool/processors/migration/linux/linuxMigration.go b/tool/processors/migration/linux/linuxMigration.go index e982c71736..40e40ca39a 100644 --- a/tool/processors/migration/linux/linuxMigration.go +++ b/tool/processors/migration/linux/linuxMigration.go @@ -5,7 +5,7 @@ package linux import ( "fmt" - + "log" "github.com/aws/amazon-cloudwatch-agent/tool/data" "github.com/aws/amazon-cloudwatch-agent/tool/data/config" "github.com/aws/amazon-cloudwatch-agent/tool/processors" @@ -44,14 +44,16 @@ 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) + errorMessage := fmt.Printf("Error in reading old python config from file %s: %v\n", filePath, err) + log.Printf(errorMessage) + panic(errorMessage) } 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) + errorMessage := fmt.Sprintf("E! Error in removing generic section from the config file %s:\n %v\n", filePath, err) + log.Printf(errorMessage) + panic(errorMessage) } } for _, section := range p.Sections() { diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 1bcbf25b81..b7609d163b 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -35,7 +35,9 @@ 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())) + errorMessage := fmt.Sprintf("Failed to create the configuration validation file. Reason: %s \n", err.Error() + log.Printf(errorMessage) + panic(errorMessage) } else { for _, infoMessage := range translator.InfoMessages { fmt.Println(infoMessage) @@ -43,7 +45,9 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf fmt.Println(exitSuccessMessage) } } else { - panic("Failed to generate configuration validation content. ") + errorMessage := fmt.Sprintf("Failed to generate configuration validation content.") + log.Printf(errorMessage) + panic(errorMessage) } } @@ -54,7 +58,9 @@ 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())) + errorMessage := fmt.Sprintf("Failed to create env config. Reason: %s \n", err.Error()) + log.Printf(errorMessage) + panic(errorMessage) } } diff --git a/translator/cmdutil/userutil.go b/translator/cmdutil/userutil.go index 7aeb300d03..b5160441dd 100644 --- a/translator/cmdutil/userutil.go +++ b/translator/cmdutil/userutil.go @@ -35,8 +35,10 @@ 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") + + errorMessage := fmt.Sprintf("E! run_as_user is not string %v \n", user) + log.Printf(errorMessage) + panic(errorMessage) } // agent section exists, but "runasuser" does not exist, then use "root" @@ -116,7 +118,9 @@ 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") + errorMessage := fmt.Sprintf("E! Credentials path is not set while runasuser is not root") + log.Printf(errorMessage) + panic(errorMessage) } } } diff --git a/translator/config/os.go b/translator/config/os.go index 50ddc20790..8a8d30b4dd 100644 --- a/translator/config/os.go +++ b/translator/config/os.go @@ -5,6 +5,7 @@ package config import ( "fmt" + "log" "runtime" "strings" ) @@ -28,5 +29,7 @@ func ToValidOs(os string) string { return formattedOs } } - panic(fmt.Sprintf("%v is not a supported osType type", os)) + errorMessage := fmt.Sprintf("E! %v is not a supported osType type", os) + log.Printf(errorMessage) + panic(errorMessage) } diff --git a/translator/config/schema_test.go b/translator/config/schema_test.go index dc3741d7d9..fc94b0e347 100644 --- a/translator/config/schema_test.go +++ b/translator/config/schema_test.go @@ -12,9 +12,9 @@ import ( ) func TestGetJsonSchema(t *testing.T) { - jsonFile, err := ioutil.ReadFile("./schema.json") - if err != nil { - panic(err) + jsonFile, e := ioutil.ReadFile("./schema.json") + if e != nil { + panic(e) } str := strings.ReplaceAll(string(jsonFile), "\r\n", "\n") assert.Equal(t, str, GetJsonSchema(), "Json schema is inconsistent") diff --git a/translator/context/context.go b/translator/context/context.go index 2eb5079fc8..70e59ae9b5 100644 --- a/translator/context/context.go +++ b/translator/context/context.go @@ -114,7 +114,9 @@ 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)) + errorMessage := fmt.Sprintf("Invalid mode %s. Valid mode values are %s and %s.\n", mode, config.ModeEC2, config.ModeOnPrem) + log.Printf(errorMessage) + panic(errorMessage) } } diff --git a/translator/jsonconfig/mergeJsonConfig.go b/translator/jsonconfig/mergeJsonConfig.go index c32976bc68..6775c08ef5 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -54,7 +54,9 @@ func MergeJsonConfigMaps(jsonConfigMapMap map[string]map[string]interface{}, def } if !translator.IsTranslateSuccess() { - panic("Failed to merge multiple json config files.") + errorMessage := fmt.Sprintf("Failed to merge multiple json config files.") + log.Printf(errorMessage) + panic(errorMessage) } return resultMap, nil diff --git a/translator/toenvconfig/toEnvConfig.go b/translator/toenvconfig/toEnvConfig.go index 16798ca7b4..e4b7306b0c 100644 --- a/translator/toenvconfig/toEnvConfig.go +++ b/translator/toenvconfig/toEnvConfig.go @@ -64,7 +64,9 @@ 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())) + errorMessage := fmt.Sprintf("Failed to create json map for environment variables. Reason: %s \n", err.Error()) + log.Printf(errorMessage) + panic(errorMessage) } return bytes } diff --git a/translator/toenvconfig/toEnvConfig_test.go b/translator/toenvconfig/toEnvConfig_test.go index de7740ccf6..b08f99551c 100644 --- a/translator/toenvconfig/toEnvConfig_test.go +++ b/translator/toenvconfig/toEnvConfig_test.go @@ -23,9 +23,9 @@ import ( ) func ReadFromFile(filename string) string { - data, err := ioutil.ReadFile(filename) - if err != nil { - panic(err) + data, e := ioutil.ReadFile(filename) + if e != nil { + panic(e) } str := string(data) return str diff --git a/translator/totomlconfig/toTomlConfig.go b/translator/totomlconfig/toTomlConfig.go index e675f73764..0430020e60 100755 --- a/translator/totomlconfig/toTomlConfig.go +++ b/translator/totomlconfig/toTomlConfig.go @@ -58,9 +58,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 { + panic(err) } return buf.String() } diff --git a/translator/translate/agent/ruleLogFile.go b/translator/translate/agent/ruleLogFile.go index bff46e2717..f6896b4bfc 100644 --- a/translator/translate/agent/ruleLogFile.go +++ b/translator/translate/agent/ruleLogFile.go @@ -5,7 +5,7 @@ package agent import ( "fmt" - + "log" "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/context" @@ -33,7 +33,9 @@ func getDefaultValue() string { case config.OS_TYPE_WINDOWS: return util.GetWindowsProgramDataPath() + "\\Amazon\\AmazonCloudWatchAgent\\Logs\\amazon-cloudwatch-agent.log" default: - panic(fmt.Sprintf("Unsupported platform %v for logRule", targetPlatform)) + errorMessage := fmt.Sprintf("Unsupported platform %v for logRule", targetPlatform) + log.Printf(errorMessage) + panic(errorMessage) } } diff --git a/translator/translate/logs/logs_collected/logs_collected.go b/translator/translate/logs/logs_collected/logs_collected.go index 5d49ada8bc..c78db8fbda 100644 --- a/translator/translate/logs/logs_collected/logs_collected.go +++ b/translator/translate/logs/logs_collected/logs_collected.go @@ -55,7 +55,9 @@ func (l *LogsCollected) ApplyRule(input interface{}) (returnKey string, returnVa case config.OS_TYPE_WINDOWS: targetRuleMap = windowsMetricCollectRule default: - panic("unknown target platform " + translator.GetTargetPlatform()) + errorMessage := fmt.Sprintf("E! Unknown target platform ", translator.GetTargetPlatform()) + log.Printf(errorMessage) + panic(errorMessage) } if _, ok := im[SectionKey]; !ok { 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 e908903081..6ef19c8b85 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 { + e := json.Unmarshal([]byte(rawJsonString), &input) + if e == nil { context.CurrentContext().SetOs(config.OS_TYPE_WINDOWS) _, actual = w.ApplyRule(input) assert.Equal(t, expected, actual) } else { - panic(error) + panic(e) } } diff --git a/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go b/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go index b624ab8e07..60a0d95237 100644 --- a/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go +++ b/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go @@ -34,7 +34,9 @@ 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)) + errorMessage := fmt.Sprintf("Prometheus config path: %s is malformated.\n", configPath) + log.Printf(errorMessage) + panic(errorMessage) } return locationArray[1] @@ -67,12 +69,16 @@ 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())) + errorMessage := fmt.Sprintf("Failed to download the Prometheus config yaml file. Reason: %s \n", error.Error()) + log.Printf(errorMessage) + panic(errorMessage) } 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)) + errorMessage := fmt.Sprintf("Failed to download the Prometheus config yaml from ENV: %v. Reason: ENV does not exist \n", configEnv) + log.Printf(errorMessage) + panic(errorMessage) } return SectionKeyConfigPath, downloadingPath } diff --git a/translator/translate/metrics/append_dimensions/append_dimensions_test.go b/translator/translate/metrics/append_dimensions/append_dimensions_test.go index da7f10fef1..133b4d92bf 100644 --- a/translator/translate/metrics/append_dimensions/append_dimensions_test.go +++ b/translator/translate/metrics/append_dimensions/append_dimensions_test.go @@ -11,10 +11,10 @@ import ( ) func TestAppendDimensions(t *testing.T) { - e := new(appendDimensions) + a := new(appendDimensions) //Check whether override default config var input interface{} - err := json.Unmarshal([]byte(`{ + e := json.Unmarshal([]byte(`{ "append_dimensions": { "ImageId": "${aws:ImageId}", "InstanceId": "${aws:InstanceId}", @@ -23,7 +23,7 @@ func TestAppendDimensions(t *testing.T) { } }`), &input) if err == nil { - _, actual := e.ApplyRule(input) + _, actual := a.ApplyRule(input) expected := map[string]interface{}{ "ec2tagger": []interface{}{ map[string]interface{}{ @@ -37,6 +37,6 @@ func TestAppendDimensions(t *testing.T) { } assert.Equal(t, expected, actual, "Expect to be equal") } else { - panic(err) + panic(e) } } diff --git a/translator/translate/metrics/metrics_collect/disk/disk_test.go b/translator/translate/metrics/metrics_collect/disk/disk_test.go index ed57682d67..3292fc2ecc 100644 --- a/translator/translate/metrics/metrics_collect/disk/disk_test.go +++ b/translator/translate/metrics/metrics_collect/disk/disk_test.go @@ -24,7 +24,7 @@ func TestDiskSpecificConfig(t *testing.T) { } //Check whether provide specific config var input1 interface{} - err := json.Unmarshal([]byte(`{"disk":{ + e = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -36,7 +36,7 @@ func TestDiskSpecificConfig(t *testing.T) { "total", "used" ]}}`), &input1) - if err == nil { + if e == nil { _, actualVal := d.ApplyRule(input1) expectedVal := []interface{}{map[string]interface{}{ "ignore_fs": []interface{}{"sysfs", "devtmpfs"}, @@ -47,12 +47,12 @@ func TestDiskSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(err) + panic(e) } //check when "drop_device" = true var input2 interface{} - er := json.Unmarshal([]byte(`{"disk":{ + e = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -66,7 +66,7 @@ func TestDiskSpecificConfig(t *testing.T) { ], "drop_device": true }}`), &input2) - if er == nil { + if e == 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(e) } //check when "drop_device" = false var input3 interface{} - err3 := json.Unmarshal([]byte(`{"disk":{ + e = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -96,7 +96,7 @@ func TestDiskSpecificConfig(t *testing.T) { ], "drop_device": false }}`), &input3) - if err3 == nil { + if e == 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(e) } } diff --git a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go index 56c3c52ba6..2221c84c8d 100644 --- a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go +++ b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go @@ -11,11 +11,11 @@ import ( func TestSpecificConfig(t *testing.T) { n := new(NvidiaSmi) var input interface{} - err := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ + e := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ "utilization_gpu", "temperature_gpu" ]}}`), &input) - if err == nil { + if e == nil { _, actualVal := n.ApplyRule(input) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"utilization_gpu", "temperature_gpu"}, @@ -24,7 +24,7 @@ func TestSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(err) + panic(e) } } @@ -43,7 +43,7 @@ func TestNoFieldConfig(t *testing.T) { func TestFullConfig(t *testing.T) { n := new(NvidiaSmi) var input interface{} - err := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ + e := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ "utilization_gpu", "temperature_gpu", "power_draw", @@ -63,7 +63,7 @@ func TestFullConfig(t *testing.T) { "clocks_current_memory", "clocks_current_video" ]}}`), &input) - if err == nil { + if e == nil { _, actualVal := n.ApplyRule(input) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"utilization_gpu", "temperature_gpu", "power_draw", "utilization_memory", @@ -76,7 +76,7 @@ func TestFullConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(err) + panic(e) } } diff --git a/translator/translate/metrics/metrics_collect/mem/mem_test.go b/translator/translate/metrics/metrics_collect/mem/mem_test.go index 6d2d71c77d..a194164fab 100644 --- a/translator/translate/metrics/metrics_collect/mem/mem_test.go +++ b/translator/translate/metrics/metrics_collect/mem/mem_test.go @@ -24,11 +24,11 @@ func TestMemSpecificConfig(t *testing.T) { } var input1 interface{} - err := json.Unmarshal([]byte(`{"mem":{"measurement": [ + e = json.Unmarshal([]byte(`{"mem":{"measurement": [ "free", "total" ]}}`), &input1) - if err == nil { + if e == nil { _, actualVal := m.ApplyRule(input1) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"free", "total"}, @@ -36,6 +36,6 @@ func TestMemSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(err) + panic(e) } } diff --git a/translator/translate/metrics/metrics_collect/swap/swap_test.go b/translator/translate/metrics/metrics_collect/swap/swap_test.go index 47e20adc41..9363862905 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/rollup_dimensions/rollupDimensions_test.go b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go index 831d58d14e..a9082b1820 100644 --- a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go +++ b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go @@ -13,13 +13,13 @@ import ( ) func TestRollupDimensions(t *testing.T) { - e := new(rollupDimensions) + r := new(rollupDimensions) var input interface{} - err := json.Unmarshal([]byte(`{ + e := json.Unmarshal([]byte(`{ "aggregation_dimensions": [["ImageId"], ["InstanceId", "InstanceType"], ["d1"],[]] }`), &input) - if err == nil { - _, actual := e.ApplyRule(input) + if e == nil { + _, actual := r.ApplyRule(input) expected := map[string]interface{}{ "rollup_dimensions": []interface{}{ []interface{}{"ImageId"}, @@ -29,7 +29,7 @@ func TestRollupDimensions(t *testing.T) { } assert.Equal(t, expected, actual, "Expect to be equal") } else { - panic(err) + panic(e) } } @@ -75,7 +75,7 @@ func TestValidRollupList(t *testing.T) { var input interface{} var actualVal interface{} - err := json.Unmarshal([]byte(`{ + e := json.Unmarshal([]byte(`{ "aggregation_dimensions":[["ImageId"], ["InstanceId", "InstanceType"], ["d1"],[]] }`), &input) @@ -85,9 +85,9 @@ func TestValidRollupList(t *testing.T) { t.FailNow() } - if err == nil { + if e == nil { assert.Equal(t, true, isValidRollupList(actualVal), "Expect to be true") } else { - panic(err) + panic(e) } } diff --git a/translator/translate/metrics/util/measurementutil.go b/translator/translate/metrics/util/measurementutil.go index d6b5ce72c1..978e0cd72e 100755 --- a/translator/translate/metrics/util/measurementutil.go +++ b/translator/translate/metrics/util/measurementutil.go @@ -117,7 +117,9 @@ func getValidMetric(targetOs string, pluginName string, metricName string) strin case translatorConfig.OS_TYPE_WINDOWS: return metricName default: - panic("unknown os platform in getValidMetric: " + targetOs) + errorMessage := fmt.Sprintf("unknown os platform in getValidMetric: ", targetOs) + log.Printf(errorMessage) + panic(errorMessage) } if val, ok := registeredMetrics[pluginName]; ok { formatted_metricName := getFormattedMetricName(metricName, pluginName) diff --git a/translator/translate/translate.go b/translator/translate/translate.go index 627d0ce7a2..4bff47f77e 100644 --- a/translator/translate/translate.go +++ b/translator/translate/translate.go @@ -4,8 +4,10 @@ package translate import ( + "fmt" + "log" "sort" - + "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/translate/agent" @@ -56,7 +58,9 @@ func (t *Translator) ApplyRule(input interface{}) (returnKey string, returnVal i case config.OS_TYPE_WINDOWS: targetRuleMap = windowsTranslateRule default: - panic("unknown target platform " + translator.GetTargetPlatform()) + errorMessage := fmt.Sprintf("E! Unknown target platform ", translator.GetTargetPlatform()) + log.Printf(errorMessage) + panic(errorMessage) } //We need to apply agent rule first, since global setting lies there, which will impact the override logic diff --git a/translator/util/searchutil_test.go b/translator/util/searchutil_test.go index 4d5f79a05e..f0269043ef 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 { + e := json.Unmarshal([]byte(rawJsonString), &input) + if e == nil { SetWithSameKeyIfFound(input, target_key_list, actual) assert.Equal(t, expected, actual) } else { - panic(error) + panic(e) } } @@ -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 { + e := json.Unmarshal([]byte(rawJsonString), &input) + if e == nil { SetWithCustomizedKeyIfFound(input, targetKeyMap, actual) assert.Equal(t, expected, actual) } else { - panic(error) + panic(e) } } From 611ad9f951eaa8bfa06f78b4f8e4b937422d3f52 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 14:58:23 -0400 Subject: [PATCH 02/23] Continue to add log before panic --- internal/containerinsightscommon/nodeCapacity.go | 4 +++- internal/ecsservicediscovery/containerinstanceprocessor.go | 4 +++- internal/publisher/blockingfifoqueue.go | 4 +++- internal/publisher/nonblockingfifoqueue.go | 4 +++- internal/publisher/nonblockinglifoqueue.go | 4 +++- plugins/inputs/cadvisor/cadvisor_linux.go | 4 +++- plugins/inputs/logfile/tail/tail.go | 7 +++++-- plugins/inputs/logfile/tail/watch/inotify.go | 4 +++- plugins/inputs/logfile/tail/watch/polling.go | 4 +++- translator/mergeTwoUniqueMaps.go | 6 +++--- 10 files changed, 32 insertions(+), 13 deletions(-) diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 4b6c457687..57bb3734ca 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -18,7 +18,9 @@ type NodeCapacity struct { func NewNodeCapacity() *NodeCapacity { if _, err := os.Lstat("/rootfs/proc"); os.IsNotExist(err) { - panic("/rootfs/proc doesn't exists") + errorMessage := fmt.Sprintf("E! /rootfs/proc doesn't exists\n") + log.Printf(errorMessage) + panic(errorMessage) } 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 d4b2aa0637..4840f94e7e 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -45,7 +45,9 @@ 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.") + errorMessage := fmt.Sprintf("splitMapKeys size cannot be zero.") + log.Printf(errorMessage) + panic(errorMessage) } result := make([][]string, 0) diff --git a/internal/publisher/blockingfifoqueue.go b/internal/publisher/blockingfifoqueue.go index c42c6db7dd..a7baea1c41 100644 --- a/internal/publisher/blockingfifoqueue.go +++ b/internal/publisher/blockingfifoqueue.go @@ -10,7 +10,9 @@ type BlockingFifoQueue struct { func NewBlockingFifoQueue(size int) *BlockingFifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") + log.Printf(errorMessage) + panic(errorMessage) } return &BlockingFifoQueue{queue: make(chan interface{}, size)} diff --git a/internal/publisher/nonblockingfifoqueue.go b/internal/publisher/nonblockingfifoqueue.go index 2bdf495efd..68f0ec1e89 100644 --- a/internal/publisher/nonblockingfifoqueue.go +++ b/internal/publisher/nonblockingfifoqueue.go @@ -18,7 +18,9 @@ type NonBlockingFifoQueue struct { func NewNonBlockingFifoQueue(size int) *NonBlockingFifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") + log.Printf(errorMessage) + panic(errorMessage) } return &NonBlockingFifoQueue{ queue: list.New(), diff --git a/internal/publisher/nonblockinglifoqueue.go b/internal/publisher/nonblockinglifoqueue.go index 2a0fc150ec..68d17ea0bf 100644 --- a/internal/publisher/nonblockinglifoqueue.go +++ b/internal/publisher/nonblockinglifoqueue.go @@ -25,7 +25,9 @@ type node struct { func NewNonBlockingLifoQueue(size int) *NonBlockingLifoQueue { if size <= 0 { - panic("Queue Size should be larger than 0!") + errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") + log.Printf(errorMessage) + panic(errorMessage) } return &NonBlockingLifoQueue{maxSize: size} } diff --git a/plugins/inputs/cadvisor/cadvisor_linux.go b/plugins/inputs/cadvisor/cadvisor_linux.go index 57144d1df3..008abfcd29 100644 --- a/plugins/inputs/cadvisor/cadvisor_linux.go +++ b/plugins/inputs/cadvisor/cadvisor_linux.go @@ -86,7 +86,9 @@ func (c *Cadvisor) Gather(acc telegraf.Accumulator) error { var err error if c.manager == nil && c.initManager() != nil { - panic("Cannot initiate manager") + errorMessage := fmt.Sprintf("E! Cannot initiate manager") + log.Printf(errorMessage) + panic(errorMessage) } req := &cinfo.ContainerInfoRequest{ diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index 3a2d1b1689..479b65871a 100644 --- a/plugins/inputs/logfile/tail/tail.go +++ b/plugins/inputs/logfile/tail/tail.go @@ -465,7 +465,10 @@ func (tail *Tail) waitForChanges() error { case <-tail.Dying(): return ErrStop } - panic("unreachable") + errorMessage := fmt.Sprintf("E! Unreachable to file ",tail.Filename) + tail.Logger.Errorf(errorMessage) + panic(errorMessage) + } func (tail *Tail) openReader() { @@ -593,7 +596,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 3a67813ba6..9d84553f84 100644 --- a/plugins/inputs/logfile/tail/watch/inotify.go +++ b/plugins/inputs/logfile/tail/watch/inotify.go @@ -61,7 +61,9 @@ func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - panic("unreachable") + errorMessage := fmt.Sprintf("E! Unreachable to file with InotifyFileWatcher",fw.Filename) + log.Printf(errorMessage) + panic(errorMessage) } 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 597092c0ea..accf452335 100644 --- a/plugins/inputs/logfile/tail/watch/polling.go +++ b/plugins/inputs/logfile/tail/watch/polling.go @@ -39,7 +39,9 @@ func (fw *PollingFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - panic("unreachable") + errorMessage := fmt.Sprintf("E! Unreachable to file %s with PollingFileWatcher",fw.Filename) + log.Printf(errorMessage) + panic(errorMessage) } func (fw *PollingFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { diff --git a/translator/mergeTwoUniqueMaps.go b/translator/mergeTwoUniqueMaps.go index 0a0fa646a1..9c525dd386 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 } From 9f9147404cdc664d737fb2c88b0d689e1feb9dcc Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 15:58:32 -0400 Subject: [PATCH 03/23] Fix some corresponding error --- cmd/config-translator/translator_test.go | 14 +++++++------- internal/containerinsightscommon/nodeCapacity.go | 3 ++- .../containerinstanceprocessor.go | 1 + internal/publisher/blockingfifoqueue.go | 4 +--- internal/publisher/nonblockingfifoqueue.go | 4 +--- internal/publisher/nonblockinglifoqueue.go | 4 +--- plugins/inputs/logfile/tail/tail.go | 2 +- plugins/inputs/logfile/tail/watch/inotify.go | 2 +- plugins/inputs/logfile/tail/watch/polling.go | 1 + tool/processors/migration/linux/linuxMigration.go | 4 ++-- translator/cmdutil/translatorutil.go | 4 ++-- translator/context/context.go | 2 +- translator/jsonconfig/mergeJsonConfig.go | 2 +- translator/toenvconfig/toEnvConfig.go | 2 +- .../logs/logs_collected/logs_collected.go | 4 +--- .../append_dimensions/append_dimensions_test.go | 2 +- .../translate/metrics/util/measurementutil.go | 2 +- translator/translate/translate.go | 2 +- 18 files changed, 27 insertions(+), 32 deletions(-) diff --git a/cmd/config-translator/translator_test.go b/cmd/config-translator/translator_test.go index 65ae9a4f2e..07ded6d940 100644 --- a/cmd/config-translator/translator_test.go +++ b/cmd/config-translator/translator_test.go @@ -19,14 +19,14 @@ import ( func checkIfSchemaValidateAsExpected(t *testing.T, jsonInputPath string, shouldSuccess bool, expectedErrorMap map[string]int) { actualErrorMap := make(map[string]int) - jsonInputMap, err := util.GetJsonMapFromFile(jsonInputPath) - if err != nil { - t.Fatalf("Failed to get json map from %v with error: %v", jsonInputPath, err) + jsonInputMap, e := util.GetJsonMapFromFile(jsonInputPath) + if e != nil { + t.Fatalf("Failed to get json map from %v with error: %v", jsonInputPath, e) } - result, err := cmdutil.RunSchemaValidation(jsonInputMap) - if err != nil { - t.Fatalf("Failed to run schema validation: %v", err) + result, e := cmdutil.RunSchemaValidation(jsonInputMap) + if e != nil { + t.Fatalf("Failed to run schema validation: %v", e) } if result.Valid() { @@ -181,7 +181,7 @@ func TestInvalidLogFilterConfig(t *testing.T) { // Validate all sampleConfig files schema func TestSampleConfigSchema(t *testing.T) { - if files, e := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); err == nil { + if files, e := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); e == nil { re := regexp.MustCompile(".json") for _, file := range files { if re.MatchString(file.Name()) { diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 57bb3734ca..727e19c5c4 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -4,9 +4,10 @@ package containerinsightscommon import ( + "fmt" "log" "os" - + "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/mem" ) diff --git a/internal/ecsservicediscovery/containerinstanceprocessor.go b/internal/ecsservicediscovery/containerinstanceprocessor.go index 4840f94e7e..6c29902157 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -4,6 +4,7 @@ package ecsservicediscovery import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" diff --git a/internal/publisher/blockingfifoqueue.go b/internal/publisher/blockingfifoqueue.go index a7baea1c41..c42c6db7dd 100644 --- a/internal/publisher/blockingfifoqueue.go +++ b/internal/publisher/blockingfifoqueue.go @@ -10,9 +10,7 @@ type BlockingFifoQueue struct { func NewBlockingFifoQueue(size int) *BlockingFifoQueue { if size <= 0 { - errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") - log.Printf(errorMessage) - panic(errorMessage) + panic("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 68f0ec1e89..2bdf495efd 100644 --- a/internal/publisher/nonblockingfifoqueue.go +++ b/internal/publisher/nonblockingfifoqueue.go @@ -18,9 +18,7 @@ type NonBlockingFifoQueue struct { func NewNonBlockingFifoQueue(size int) *NonBlockingFifoQueue { if size <= 0 { - errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") - log.Printf(errorMessage) - panic(errorMessage) + panic("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 68d17ea0bf..2a0fc150ec 100644 --- a/internal/publisher/nonblockinglifoqueue.go +++ b/internal/publisher/nonblockinglifoqueue.go @@ -25,9 +25,7 @@ type node struct { func NewNonBlockingLifoQueue(size int) *NonBlockingLifoQueue { if size <= 0 { - errorMessage := fmt.Sprintf("E! Queue Size should be larger than 0!") - log.Printf(errorMessage) - panic(errorMessage) + panic("Queue Size should be larger than 0!") } return &NonBlockingLifoQueue{maxSize: size} } diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index 479b65871a..d5445def3e 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 } - errorMessage := fmt.Sprintf("E! Unreachable to file ",tail.Filename) + errorMessage := fmt.Sprintf("E! Unreachable to file %s",tail.Filename) tail.Logger.Errorf(errorMessage) panic(errorMessage) diff --git a/plugins/inputs/logfile/tail/watch/inotify.go b/plugins/inputs/logfile/tail/watch/inotify.go index 9d84553f84..d3c37b1d5f 100644 --- a/plugins/inputs/logfile/tail/watch/inotify.go +++ b/plugins/inputs/logfile/tail/watch/inotify.go @@ -61,7 +61,7 @@ func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - errorMessage := fmt.Sprintf("E! Unreachable to file with InotifyFileWatcher",fw.Filename) + errorMessage := fmt.Sprintf("E! Unreachable to file with InotifyFileWatcher %s",fw.Filename) log.Printf(errorMessage) panic(errorMessage) } diff --git a/plugins/inputs/logfile/tail/watch/polling.go b/plugins/inputs/logfile/tail/watch/polling.go index accf452335..4be7fe6cac 100644 --- a/plugins/inputs/logfile/tail/watch/polling.go +++ b/plugins/inputs/logfile/tail/watch/polling.go @@ -4,6 +4,7 @@ package watch import ( + "fmt" "log" "os" "runtime" diff --git a/tool/processors/migration/linux/linuxMigration.go b/tool/processors/migration/linux/linuxMigration.go index 40e40ca39a..c940796c42 100644 --- a/tool/processors/migration/linux/linuxMigration.go +++ b/tool/processors/migration/linux/linuxMigration.go @@ -44,14 +44,14 @@ 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 { - errorMessage := fmt.Printf("Error in reading old python config from file %s: %v\n", filePath, err) + errorMessage := fmt.Sprintf("Error in reading old python config from file %s: %v", filePath, err) log.Printf(errorMessage) panic(errorMessage) } if p.HasSection(genericSectionName) { err := p.RemoveSection(genericSectionName) if err != nil { - errorMessage := fmt.Sprintf("E! Error in removing generic section from the config file %s:\n %v\n", filePath, err) + errorMessage := fmt.Sprintf("E! Error in removing generic section from the config file %s: %v", filePath, err) log.Printf(errorMessage) panic(errorMessage) } diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index b7609d163b..c5bc9d3dcb 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -35,7 +35,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 { - errorMessage := fmt.Sprintf("Failed to create the configuration validation file. Reason: %s \n", err.Error() + errorMessage := fmt.Sprintf("Failed to create the configuration validation file. Reason: %s", err.Error()) log.Printf(errorMessage) panic(errorMessage) } else { @@ -58,7 +58,7 @@ func TranslateJsonMapToEnvConfigFile(jsonConfigValue map[string]interface{}, env } bytes := toenvconfig.ToEnvConfig(jsonConfigValue) if err := ioutil.WriteFile(envConfigPath, bytes, 0644); err != nil { - errorMessage := fmt.Sprintf("Failed to create env config. Reason: %s \n", err.Error()) + errorMessage := fmt.Sprintf("Failed to create env config. Reason: %s", err.Error()) log.Printf(errorMessage) panic(errorMessage) } diff --git a/translator/context/context.go b/translator/context/context.go index 70e59ae9b5..c0178f684f 100644 --- a/translator/context/context.go +++ b/translator/context/context.go @@ -5,7 +5,7 @@ package context import ( "fmt" - + "log" "os" "github.com/aws/amazon-cloudwatch-agent/translator/config" diff --git a/translator/jsonconfig/mergeJsonConfig.go b/translator/jsonconfig/mergeJsonConfig.go index 6775c08ef5..d0835a0981 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -7,7 +7,7 @@ import ( "fmt" "os" "sort" - + "log" "github.com/aws/amazon-cloudwatch-agent/translator/util/ecsutil" "github.com/aws/amazon-cloudwatch-agent/translator" diff --git a/translator/toenvconfig/toEnvConfig.go b/translator/toenvconfig/toEnvConfig.go index e4b7306b0c..0e86349103 100644 --- a/translator/toenvconfig/toEnvConfig.go +++ b/translator/toenvconfig/toEnvConfig.go @@ -6,7 +6,7 @@ package toenvconfig import ( "encoding/json" "fmt" - + "log" "github.com/aws/amazon-cloudwatch-agent/cfg/commonconfig" "github.com/aws/amazon-cloudwatch-agent/cfg/envconfig" "github.com/aws/amazon-cloudwatch-agent/internal/csm" diff --git a/translator/translate/logs/logs_collected/logs_collected.go b/translator/translate/logs/logs_collected/logs_collected.go index c78db8fbda..9a9b329bf7 100644 --- a/translator/translate/logs/logs_collected/logs_collected.go +++ b/translator/translate/logs/logs_collected/logs_collected.go @@ -55,9 +55,7 @@ func (l *LogsCollected) ApplyRule(input interface{}) (returnKey string, returnVa case config.OS_TYPE_WINDOWS: targetRuleMap = windowsMetricCollectRule default: - errorMessage := fmt.Sprintf("E! Unknown target platform ", translator.GetTargetPlatform()) - log.Printf(errorMessage) - panic(errorMessage) + panic("Unknown target platform " + translator.GetTargetPlatform()) } if _, ok := im[SectionKey]; !ok { diff --git a/translator/translate/metrics/append_dimensions/append_dimensions_test.go b/translator/translate/metrics/append_dimensions/append_dimensions_test.go index 133b4d92bf..f990b4e7e1 100644 --- a/translator/translate/metrics/append_dimensions/append_dimensions_test.go +++ b/translator/translate/metrics/append_dimensions/append_dimensions_test.go @@ -22,7 +22,7 @@ func TestAppendDimensions(t *testing.T) { "AutoScalingGroupName": "${aws:AutoScalingGroupName}" } }`), &input) - if err == nil { + if e == nil { _, actual := a.ApplyRule(input) expected := map[string]interface{}{ "ec2tagger": []interface{}{ diff --git a/translator/translate/metrics/util/measurementutil.go b/translator/translate/metrics/util/measurementutil.go index 978e0cd72e..fb815d6d40 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: - errorMessage := fmt.Sprintf("unknown os platform in getValidMetric: ", targetOs) + errorMessage := fmt.Sprintf("unknown os platform in getValidMetric: %s", targetOs) log.Printf(errorMessage) panic(errorMessage) } diff --git a/translator/translate/translate.go b/translator/translate/translate.go index 4bff47f77e..bd9c81932a 100644 --- a/translator/translate/translate.go +++ b/translator/translate/translate.go @@ -58,7 +58,7 @@ func (t *Translator) ApplyRule(input interface{}) (returnKey string, returnVal i case config.OS_TYPE_WINDOWS: targetRuleMap = windowsTranslateRule default: - errorMessage := fmt.Sprintf("E! Unknown target platform ", translator.GetTargetPlatform()) + errorMessage := fmt.Sprintf("E! Unknown target platform %s", translator.GetTargetPlatform()) log.Printf(errorMessage) panic(errorMessage) } From 114055d33f394e4045a6e3bd06ec0cb2c61d7e04 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 16:19:46 -0400 Subject: [PATCH 04/23] Add package fmt for cadvisor linux --- plugins/inputs/cadvisor/cadvisor_linux.go | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/inputs/cadvisor/cadvisor_linux.go b/plugins/inputs/cadvisor/cadvisor_linux.go index 008abfcd29..e0531d0c5d 100644 --- a/plugins/inputs/cadvisor/cadvisor_linux.go +++ b/plugins/inputs/cadvisor/cadvisor_linux.go @@ -8,6 +8,7 @@ package cadvisor import ( "flag" + "fmt" "log" "net/http" "time" From 166e28e11caafb6c6e76df1f8913d0ce13eb1926 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 16:43:10 -0400 Subject: [PATCH 05/23] Delete some log before panic --- internal/containerinsightscommon/nodeCapacity.go | 4 +--- internal/ecsservicediscovery/containerinstanceprocessor.go | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 727e19c5c4..6e15eb886b 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -19,9 +19,7 @@ type NodeCapacity struct { func NewNodeCapacity() *NodeCapacity { if _, err := os.Lstat("/rootfs/proc"); os.IsNotExist(err) { - errorMessage := fmt.Sprintf("E! /rootfs/proc doesn't exists\n") - log.Printf(errorMessage) - panic(errorMessage) + panic("E! /rootfs/proc doesn't exists") } 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 6c29902157..a46bc9369f 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -46,9 +46,7 @@ func NewContainerInstanceProcessor(ecs *ecs.ECS, ec2 *ec2.EC2, s *ProcessorStats func splitMapKeys(a map[string]*EC2MetaData, size int) [][]string { if size == 0 { - errorMessage := fmt.Sprintf("splitMapKeys size cannot be zero.") - log.Printf(errorMessage) - panic(errorMessage) + panic("splitMapKeys size cannot be zero.") } result := make([][]string, 0) From 2fcd4a5a05d5498698d83b7987e21e30607381a8 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Wed, 30 Mar 2022 16:45:00 -0400 Subject: [PATCH 06/23] Delete log before panic with internal --- internal/containerinsightscommon/nodeCapacity.go | 1 - internal/ecsservicediscovery/containerinstanceprocessor.go | 1 - 2 files changed, 2 deletions(-) diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 6e15eb886b..21a45974ba 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -4,7 +4,6 @@ package containerinsightscommon import ( - "fmt" "log" "os" diff --git a/internal/ecsservicediscovery/containerinstanceprocessor.go b/internal/ecsservicediscovery/containerinstanceprocessor.go index a46bc9369f..d4b2aa0637 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -4,7 +4,6 @@ package ecsservicediscovery import ( - "fmt" "log" "github.com/aws/aws-sdk-go/aws" From 8c9332b5bb4d0179926d090cd36bb4e20a2f4629 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 05:34:32 -0400 Subject: [PATCH 07/23] Change to log.Panicf --- cmd/config-downloader/downloader.go | 33 +++++-------------- cmd/config-translator/translator.go | 9 ++--- plugins/inputs/cadvisor/cadvisor_linux.go | 4 +-- .../k8sdecorator/stores/podstore.go | 5 +-- .../k8sdecorator/stores/podstore_test.go | 5 +-- .../migration/linux/knownConfigKeys.go | 4 +-- .../migration/linux/linuxMigration.go | 9 ++--- translator/cmdutil/translatorutil.go | 12 ++----- translator/cmdutil/userutil.go | 10 ++---- translator/config/os.go | 8 ++--- translator/context/context.go | 5 +-- translator/jsonconfig/mergeJsonConfig.go | 4 +-- translator/toenvconfig/toEnvConfig.go | 5 +-- translator/translate/agent/ruleLogFile.go | 6 ++-- .../prometheus/ruleConfigPath.go | 13 ++------ .../metrics/drop_origin/drop_origin.go | 2 +- .../translate/metrics/util/measurementutil.go | 4 +-- translator/translate/translate.go | 5 +-- 18 files changed, 38 insertions(+), 105 deletions(-) diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index 940d6d5288..0b4d74434c 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -125,15 +125,11 @@ func main() { if inputConfig != "" { f, err := os.Open(inputConfig) if err != nil { - errorMessage := fmt.Sprintf("E! Failed to open Common Config: %v\n", err) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Failed to open Common Config: %v", err) } if err := cc.Parse(f); err != nil { - errorMessage := fmt.Sprintf("E! Failed to parse Common Config: %v\n", err) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Failed to open Common Config: %v", err) } } util.SetProxyEnv(cc.ProxyMap()) @@ -146,8 +142,7 @@ func main() { } else { errorMessage = fmt.Sprintf("E! usage: --output-dir --download-source ssm: ") } - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf(errorMessage) } mode = sdkutil.DetectAgentMode(mode) @@ -162,8 +157,7 @@ func main() { 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") } - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf(errorMessage) } // clean up output dir for tmp files before writing out new tmp file. @@ -192,8 +186,7 @@ func main() { locationArray := strings.SplitN(downloadLocation, locationSeparator, 2) if locationArray == nil || len(locationArray) < 2 && downloadLocation != locationDefault { errorMessage := fmt.Sprintf("E! downloadLocation %s is malformated.\n", downloadLocation) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf(errorMessage) } var config, outputFilePath string @@ -215,33 +208,25 @@ func main() { config, err = readFromFile(locationArray[1]) } default: - errorMessage := fmt.Sprintf("E! Location type %s is not supported.", locationArray[0]) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Location type %s is not supported.", locationArray[0]) } if err != nil { - errorMessage := fmt.Sprintf("E! Fail to fetch/remove json config: %v\n", err) - log.Printf(errorMessage) - panic(errorMessage) + 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 { - errorMessage := fmt.Sprintf("E! Failed to write the json file %v: %v\n", outputFilePath, err) - log.Printf(errorMessage) - panic(errorMessage) + 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 { - errorMessage := fmt.Sprintf("E! Failed to remove the json file %v: %v", outputFilePath, err) - log.Printf(errorMessage) - panic(errorMessage) + 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 fe8694837c..4ae0eddcad 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,9 +89,7 @@ func main() { mergedJsonConfigMap, err := cmdutil.GenerateMergedJsonConfigMap(ctx) if err != nil { - errorMessage := fmt.Sprintf("E! Failed to generate merged json config: %v", err) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Failed to generate merged json config: %v", err) } if !ctx.RunInContainer() { @@ -101,9 +98,7 @@ func main() { if e == nil && current.Name == "root" { runAsUser, err := cmdutil.DetectRunAsUser(mergedJsonConfigMap) if err != nil { - errorMessage := fmt.Sprintf("E! Failed to detectRunAsUser\n") - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Failed to detectRunAsUser") } cmdutil.VerifyCredentials(ctx, runAsUser) } diff --git a/plugins/inputs/cadvisor/cadvisor_linux.go b/plugins/inputs/cadvisor/cadvisor_linux.go index e0531d0c5d..aff4ab1af7 100644 --- a/plugins/inputs/cadvisor/cadvisor_linux.go +++ b/plugins/inputs/cadvisor/cadvisor_linux.go @@ -87,9 +87,7 @@ func (c *Cadvisor) Gather(acc telegraf.Accumulator) error { var err error if c.manager == nil && c.initManager() != nil { - errorMessage := fmt.Sprintf("E! Cannot initiate manager") - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Cannot initiate manager") } req := &cinfo.ContainerInfoRequest{ diff --git a/plugins/processors/k8sdecorator/stores/podstore.go b/plugins/processors/k8sdecorator/stores/podstore.go index 23ed46c4db..8182798a26 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,9 +73,7 @@ func NewPodStore(hostIP string, prefFullPodName bool) *PodStore { // Try to detect kubelet permission issue here if _, err := podStore.kubeClient.ListPods(); err != nil { - errorMessage := fmt.Sprintf("Cannot get pod from kubelet, err: %v", err) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Cannot get pod from kubelet, err: %v", err) } return podStore diff --git a/plugins/processors/k8sdecorator/stores/podstore_test.go b/plugins/processors/k8sdecorator/stores/podstore_test.go index 2070d7849a..58a126df8e 100644 --- a/plugins/processors/k8sdecorator/stores/podstore_test.go +++ b/plugins/processors/k8sdecorator/stores/podstore_test.go @@ -8,7 +8,6 @@ import ( "fmt" "testing" "time" - "log" "github.com/aws/amazon-cloudwatch-agent/internal/mapWithExpiry" @@ -181,9 +180,7 @@ func getBaseTestPodInfo() *corev1.Pod { pods := corev1.PodList{} err := json.Unmarshal([]byte(podJson), &pods) if err != nil { - errorMessage := fmt.Sprintf("unmarshal pod err %v", err) - log.Printf(errorMessage) - panic(errorMessage) + panic(fmt.Sprintf("unmarshal pod err %v", err)) } return &pods.Items[0] diff --git a/tool/processors/migration/linux/knownConfigKeys.go b/tool/processors/migration/linux/knownConfigKeys.go index 283ed8a4af..d923c0c450 100644 --- a/tool/processors/migration/linux/knownConfigKeys.go +++ b/tool/processors/migration/linux/knownConfigKeys.go @@ -65,9 +65,7 @@ func addLogConfig(logsConfig *config.Logs, filePath, section string, p *configpa if encoding != "" { normalized := NormalizeEncoding(encoding) if normalized == "" { - errorMessage := fmt.Sprintf("E! Encoding %s is not supported.", encoding) - log.Printf(errorMessage) - panic(errorMessage) + 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 c940796c42..f51d49d20a 100644 --- a/tool/processors/migration/linux/linuxMigration.go +++ b/tool/processors/migration/linux/linuxMigration.go @@ -4,7 +4,6 @@ package linux import ( - "fmt" "log" "github.com/aws/amazon-cloudwatch-agent/tool/data" "github.com/aws/amazon-cloudwatch-agent/tool/data/config" @@ -44,16 +43,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 { - errorMessage := fmt.Sprintf("Error in reading old python config from file %s: %v", filePath, err) - log.Printf(errorMessage) - panic(errorMessage) + 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 { - errorMessage := fmt.Sprintf("E! Error in removing generic section from the config file %s: %v", filePath, err) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Error in removing generic section from the config file %s: %v", filePath, err) } } for _, section := range p.Sections() { diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index c5bc9d3dcb..0cfe953178 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -35,9 +35,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 { - errorMessage := fmt.Sprintf("Failed to create the configuration validation file. Reason: %s", err.Error()) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Failed to create the configuration validation file. Reason: %s", err.Error()) } else { for _, infoMessage := range translator.InfoMessages { fmt.Println(infoMessage) @@ -45,9 +43,7 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf fmt.Println(exitSuccessMessage) } } else { - errorMessage := fmt.Sprintf("Failed to generate configuration validation content.") - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Failed to generate configuration validation content.") } } @@ -58,9 +54,7 @@ func TranslateJsonMapToEnvConfigFile(jsonConfigValue map[string]interface{}, env } bytes := toenvconfig.ToEnvConfig(jsonConfigValue) if err := ioutil.WriteFile(envConfigPath, bytes, 0644); err != nil { - errorMessage := fmt.Sprintf("Failed to create env config. Reason: %s", err.Error()) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Failed to create env config. Reason: %s", err.Error()) } } diff --git a/translator/cmdutil/userutil.go b/translator/cmdutil/userutil.go index b5160441dd..21ce1f85c1 100644 --- a/translator/cmdutil/userutil.go +++ b/translator/cmdutil/userutil.go @@ -35,10 +35,8 @@ func DetectRunAsUser(mergedJsonConfigMap map[string]interface{}) (runAsUser stri if runasuser, ok := user.(string); ok { return runasuser, nil } - - errorMessage := fmt.Sprintf("E! run_as_user is not string %v \n", user) - log.Printf(errorMessage) - panic(errorMessage) + + log.Panicf("E! run_as_user is not string %v",user) } // agent section exists, but "runasuser" does not exist, then use "root" @@ -118,9 +116,7 @@ func VerifyCredentials(ctx *context.Context, runAsUser string) { if config.ModeOnPrem == ctx.Mode() { if runAsUser != "root" { if _, ok := credentials["shared_credential_file"]; !ok { - errorMessage := fmt.Sprintf("E! Credentials path is not set while runasuser is not root") - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("E! Credentials path is not set while runasuser is not root") } } } diff --git a/translator/config/os.go b/translator/config/os.go index 8a8d30b4dd..957bcf5c34 100644 --- a/translator/config/os.go +++ b/translator/config/os.go @@ -4,7 +4,6 @@ package config import ( - "fmt" "log" "runtime" "strings" @@ -23,13 +22,14 @@ 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 } } - errorMessage := fmt.Sprintf("E! %v is not a supported osType type", os) - log.Printf(errorMessage) - panic(errorMessage) + + log.Panicf("E! %v is not a supported osType type", os) + return "" } diff --git a/translator/context/context.go b/translator/context/context.go index c0178f684f..43eb33e26f 100644 --- a/translator/context/context.go +++ b/translator/context/context.go @@ -4,7 +4,6 @@ package context import ( - "fmt" "log" "os" @@ -114,9 +113,7 @@ func (ctx *Context) SetMode(mode string) { case config.ModeOnPrem: ctx.mode = config.ModeOnPrem default: - errorMessage := fmt.Sprintf("Invalid mode %s. Valid mode values are %s and %s.\n", mode, config.ModeEC2, config.ModeOnPrem) - log.Printf(errorMessage) - panic(errorMessage) + 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 d0835a0981..4154bcea4f 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -54,9 +54,7 @@ func MergeJsonConfigMaps(jsonConfigMapMap map[string]map[string]interface{}, def } if !translator.IsTranslateSuccess() { - errorMessage := fmt.Sprintf("Failed to merge multiple json config files.") - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Failed to merge multiple json config files.") } return resultMap, nil diff --git a/translator/toenvconfig/toEnvConfig.go b/translator/toenvconfig/toEnvConfig.go index 0e86349103..60762a868f 100644 --- a/translator/toenvconfig/toEnvConfig.go +++ b/translator/toenvconfig/toEnvConfig.go @@ -5,7 +5,6 @@ package toenvconfig import ( "encoding/json" - "fmt" "log" "github.com/aws/amazon-cloudwatch-agent/cfg/commonconfig" "github.com/aws/amazon-cloudwatch-agent/cfg/envconfig" @@ -64,9 +63,7 @@ func ToEnvConfig(jsonConfigValue map[string]interface{}) []byte { bytes, err := json.MarshalIndent(envVars, "", "\t") if err != nil { - errorMessage := fmt.Sprintf("Failed to create json map for environment variables. Reason: %s \n", err.Error()) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Failed to create json map for environment variables. Reason: %s", err.Error()) } return bytes } diff --git a/translator/translate/agent/ruleLogFile.go b/translator/translate/agent/ruleLogFile.go index f6896b4bfc..0d13e533da 100644 --- a/translator/translate/agent/ruleLogFile.go +++ b/translator/translate/agent/ruleLogFile.go @@ -4,7 +4,6 @@ package agent import ( - "fmt" "log" "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" @@ -33,9 +32,8 @@ func getDefaultValue() string { case config.OS_TYPE_WINDOWS: return util.GetWindowsProgramDataPath() + "\\Amazon\\AmazonCloudWatchAgent\\Logs\\amazon-cloudwatch-agent.log" default: - errorMessage := fmt.Sprintf("Unsupported platform %v for logRule", targetPlatform) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Unsupported platform %v for logRule", targetPlatform) + return "" } } diff --git a/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go b/translator/translate/logs/metrics_collected/prometheus/ruleConfigPath.go index 60a0d95237..5cf3e66bab 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,9 +33,7 @@ type ConfigPath struct { func splitConfigPath(configPath string) string { locationArray := strings.SplitN(configPath, sourceSeparator, 2) if locationArray == nil || len(locationArray) < 2 { - errorMessage := fmt.Sprintf("Prometheus config path: %s is malformated.\n", configPath) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("Prometheus config path: %s is malformated.", configPath) } return locationArray[1] @@ -69,16 +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 { - errorMessage := fmt.Sprintf("Failed to download the Prometheus config yaml file. Reason: %s \n", error.Error()) - log.Printf(errorMessage) - panic(errorMessage) + 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 { - errorMessage := fmt.Sprintf("Failed to download the Prometheus config yaml from ENV: %v. Reason: ENV does not exist \n", configEnv) - log.Printf(errorMessage) - panic(errorMessage) + 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/metrics/drop_origin/drop_origin.go b/translator/translate/metrics/drop_origin/drop_origin.go index 2c36c16598..13930012b0 100644 --- a/translator/translate/metrics/drop_origin/drop_origin.go +++ b/translator/translate/metrics/drop_origin/drop_origin.go @@ -36,7 +36,7 @@ func (do *dropOrigin) ApplyRule(input interface{}) (returnKey string, returnVal if reflect.TypeOf(value).String() == "string" { droppingDimensions = append(droppingDimensions, value.(string)) } else { - log.Panic("Fail to translate the JSON config, invalid format of dropping dimensions.") + log.Panicf("Fail to translate the JSON config, invalid format of dropping dimensions.") } } diff --git a/translator/translate/metrics/util/measurementutil.go b/translator/translate/metrics/util/measurementutil.go index fb815d6d40..9e4282505f 100755 --- a/translator/translate/metrics/util/measurementutil.go +++ b/translator/translate/metrics/util/measurementutil.go @@ -117,9 +117,7 @@ func getValidMetric(targetOs string, pluginName string, metricName string) strin case translatorConfig.OS_TYPE_WINDOWS: return metricName default: - errorMessage := fmt.Sprintf("unknown os platform in getValidMetric: %s", targetOs) - log.Printf(errorMessage) - panic(errorMessage) + log.Panicf("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 bd9c81932a..7ee1600c8a 100644 --- a/translator/translate/translate.go +++ b/translator/translate/translate.go @@ -4,7 +4,6 @@ package translate import ( - "fmt" "log" "sort" @@ -58,9 +57,7 @@ func (t *Translator) ApplyRule(input interface{}) (returnKey string, returnVal i case config.OS_TYPE_WINDOWS: targetRuleMap = windowsTranslateRule default: - errorMessage := fmt.Sprintf("E! Unknown target platform %s", translator.GetTargetPlatform()) - log.Printf(errorMessage) - panic(errorMessage) + 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 From 65594c923404561783cc9f0913b20f20a9eff83e Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:16:27 -0400 Subject: [PATCH 08/23] Delete panic for cw --- plugins/inputs/logfile/tail/watch/inotify.go | 3 --- plugins/inputs/logfile/tail/watch/polling.go | 4 ---- 2 files changed, 7 deletions(-) diff --git a/plugins/inputs/logfile/tail/watch/inotify.go b/plugins/inputs/logfile/tail/watch/inotify.go index d3c37b1d5f..48617cc176 100644 --- a/plugins/inputs/logfile/tail/watch/inotify.go +++ b/plugins/inputs/logfile/tail/watch/inotify.go @@ -61,9 +61,6 @@ func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - errorMessage := fmt.Sprintf("E! Unreachable to file with InotifyFileWatcher %s",fw.Filename) - log.Printf(errorMessage) - panic(errorMessage) } 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 4be7fe6cac..d66af76938 100644 --- a/plugins/inputs/logfile/tail/watch/polling.go +++ b/plugins/inputs/logfile/tail/watch/polling.go @@ -4,7 +4,6 @@ package watch import ( - "fmt" "log" "os" "runtime" @@ -40,9 +39,6 @@ func (fw *PollingFileWatcher) BlockUntilExists(t *tomb.Tomb) error { return tomb.ErrDying } } - errorMessage := fmt.Sprintf("E! Unreachable to file %s with PollingFileWatcher",fw.Filename) - log.Printf(errorMessage) - panic(errorMessage) } func (fw *PollingFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) { From f22721d05e1964ecce92183ece618d7797233056 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:35:44 -0400 Subject: [PATCH 09/23] Fix some issues --- internal/containerinsightscommon/nodeCapacity.go | 2 +- internal/ecsservicediscovery/containerinstanceprocessor.go | 2 +- internal/publisher/nonblockingfifoqueue.go | 2 +- internal/publisher/nonblockinglifoqueue.go | 2 +- plugins/inputs/cadvisor/cadvisor_linux.go | 1 - plugins/inputs/logfile/tail/tail.go | 2 +- tool/processors/defaultConfig/defaultConfig.go | 2 +- translator/cmdutil/translatorutil.go | 2 +- translator/totomlconfig/toTomlConfig.go | 6 +++--- translator/totomlconfig/toTomlConfig_test.go | 6 +++--- translator/translate/logs/logs_collected/logs_collected.go | 4 +++- .../windows_events/collect_list/collectlist_test.go | 6 +++--- 12 files changed, 19 insertions(+), 18 deletions(-) diff --git a/internal/containerinsightscommon/nodeCapacity.go b/internal/containerinsightscommon/nodeCapacity.go index 21a45974ba..51489a98da 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("E! /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 d4b2aa0637..85f64fb98c 100644 --- a/internal/ecsservicediscovery/containerinstanceprocessor.go +++ b/internal/ecsservicediscovery/containerinstanceprocessor.go @@ -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/publisher/nonblockingfifoqueue.go b/internal/publisher/nonblockingfifoqueue.go index 2bdf495efd..742f081538 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("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 2a0fc150ec..01db6a920a 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 aff4ab1af7..6823e17b36 100644 --- a/plugins/inputs/cadvisor/cadvisor_linux.go +++ b/plugins/inputs/cadvisor/cadvisor_linux.go @@ -8,7 +8,6 @@ package cadvisor import ( "flag" - "fmt" "log" "net/http" "time" diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index d5445def3e..4a994d97c5 100644 --- a/plugins/inputs/logfile/tail/tail.go +++ b/plugins/inputs/logfile/tail/tail.go @@ -596,7 +596,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") + log.Panic("Invalid chunkSize") } length := len(s) chunks := 1 + length/chunkSize diff --git a/tool/processors/defaultConfig/defaultConfig.go b/tool/processors/defaultConfig/defaultConfig.go index d463190fdc..44c9f7e6d5 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/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 0cfe953178..630ffdfa8e 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -110,7 +110,7 @@ func checkSchema(inputJsonMap map[string]interface{}) { for _, errorDetail := range errorDetails { translator.AddErrorMessages(config.GetFormattedPath(errorDetail.Context().String()), errorDetail.Description()) } - panic("Invalid Json input schema.") + log.Panic("Invalid Json input schema.") } } diff --git a/translator/totomlconfig/toTomlConfig.go b/translator/totomlconfig/toTomlConfig.go index 0430020e60..e675f73764 100755 --- a/translator/totomlconfig/toTomlConfig.go +++ b/translator/totomlconfig/toTomlConfig.go @@ -58,9 +58,9 @@ func ToTomlConfig(c interface{}) string { _, val := r.ApplyRule(c) buf := bytes.Buffer{} enc := toml.NewEncoder(&buf) - err := enc.Encode(val) - if err != nil { - panic(err) + e := enc.Encode(val) + if e != nil { + panic(e) } return buf.String() } diff --git a/translator/totomlconfig/toTomlConfig_test.go b/translator/totomlconfig/toTomlConfig_test.go index b56495b518..e93ae0c891 100644 --- a/translator/totomlconfig/toTomlConfig_test.go +++ b/translator/totomlconfig/toTomlConfig_test.go @@ -30,9 +30,9 @@ import ( ) func ReadFromFile(filename string) string { - data, err := ioutil.ReadFile(filename) - if err != nil { - panic(err) + data, e := ioutil.ReadFile(filename) + if e != nil { + panic(e) } str := string(data) return strings.ReplaceAll(str, "\r\n", "\n") diff --git a/translator/translate/logs/logs_collected/logs_collected.go b/translator/translate/logs/logs_collected/logs_collected.go index 9a9b329bf7..fc9ad8da13 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 23ea37f039..1e7ee128a9 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 @@ -59,11 +59,11 @@ func TestApplyRule(t *testing.T) { var actual interface{} - error := json.Unmarshal([]byte(rawJsonString), &input) - if error == nil { + e := json.Unmarshal([]byte(rawJsonString), &input) + if e == nil { _, actual = c.ApplyRule(input) assert.Equal(t, expected, actual) } else { - panic(error) + panic(e) } } From 15380e66909f6bc78e019c1ea70aaf2268ab9e47 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:38:09 -0400 Subject: [PATCH 10/23] Add some log before panic --- internal/publisher/blockingfifoqueue.go | 6 +++++- internal/publisher/nonblockingfifoqueue.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/publisher/blockingfifoqueue.go b/internal/publisher/blockingfifoqueue.go index c42c6db7dd..2d19c2fb7b 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 742f081538..22cb156d9d 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 { - log.Panic("Queue Size should be larger than 0!") + log.Panic("E! Queue Size should be larger than 0!") } return &NonBlockingFifoQueue{ queue: list.New(), From 50d8144e26c26cbc4b96808fd7ff408c3fe6747a Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:40:22 -0400 Subject: [PATCH 11/23] Add log before panic for ecs service discovery --- internal/ecsservicediscovery/containerinstanceprocessor.go | 2 +- internal/ecsservicediscovery/taskdefinitionprocessor.go | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/ecsservicediscovery/containerinstanceprocessor.go b/internal/ecsservicediscovery/containerinstanceprocessor.go index 85f64fb98c..ffc0c84010 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 diff --git a/internal/ecsservicediscovery/taskdefinitionprocessor.go b/internal/ecsservicediscovery/taskdefinitionprocessor.go index bef1e84568..c7947bd470 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 From 7dadcd5cd7b5cf53156c0c5bff68c17c045a3719 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:44:30 -0400 Subject: [PATCH 12/23] Fix some logs for translator --- translator/cmdutil/translatorutil.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 630ffdfa8e..a9e02b52f9 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -35,7 +35,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 { - log.Panicf("Failed to create the configuration validation file. Reason: %s", 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) @@ -43,7 +43,7 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf fmt.Println(exitSuccessMessage) } } else { - log.Panicf("Failed to generate configuration validation content.") + log.Panicf("E! Failed to generate configuration validation content.") } } @@ -54,14 +54,14 @@ func TranslateJsonMapToEnvConfigFile(jsonConfigValue map[string]interface{}, env } bytes := toenvconfig.ToEnvConfig(jsonConfigValue) if err := ioutil.WriteFile(envConfigPath, bytes, 0644); err != nil { - log.Panicf("Failed to create env config. Reason: %s", 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) } @@ -101,7 +101,7 @@ 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.") From 8d98083c9d3eb319bf3c59dc6d07aa747e53c9cb Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 12:45:51 -0400 Subject: [PATCH 13/23] Change back to invalid chunk size --- plugins/inputs/logfile/tail/tail.go | 2 +- translator/cmdutil/translatorutil.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index 4a994d97c5..d5445def3e 100644 --- a/plugins/inputs/logfile/tail/tail.go +++ b/plugins/inputs/logfile/tail/tail.go @@ -596,7 +596,7 @@ func (tail *Tail) exitOnDeletion() { // with the last chunk of variable size. func partitionString(s string, chunkSize int) []string { if chunkSize <= 0 { - log.Panic("Invalid chunkSize") + panic("Invalid chunkSize") } length := len(s) chunks := 1 + length/chunkSize diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index a9e02b52f9..0b649c0b1e 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -104,13 +104,13 @@ func checkSchema(inputJsonMap map[string]interface{}) { 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()) } - log.Panic("Invalid Json input schema.") + log.Panic("E! Invalid Json input schema.") } } From 04f34208de20f65ad7f976dc0df646cf1ed26d66 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 14:07:53 -0400 Subject: [PATCH 14/23] Change e to err for some test --- ...refreshable_shared_credentials_provider.go | 4 +-- cmd/config-downloader/downloader.go | 4 +-- cmd/config-translator/translator.go | 4 +-- cmd/config-translator/translator_test.go | 16 +++++----- .../inputs/logfile/tail/winfile/winfile.go | 10 +++---- .../metrics_receiver_test.go | 18 +++++------ tool/util/util.go | 18 +++++------ translator/config/schema_test.go | 6 ++-- translator/toenvconfig/toEnvConfig_test.go | 12 ++++---- translator/totomlconfig/toTomlConfig.go | 6 ++-- translator/totomlconfig/toTomlConfig_test.go | 6 ++-- translator/translate/agent/agent_test.go | 30 +++++++++---------- .../agent/ruleGlobalCredentials_test.go | 6 ++-- translator/translate/csm/csm_test.go | 6 ++-- .../translate/globaltags/globaltags_test.go | 4 +-- .../windows_events/windows_event_test.go | 6 ++-- translator/translate/logs/logs_test.go | 24 +++++++-------- .../translate/logs/ruleLogCredentials_test.go | 18 +++++------ .../append_dimensions_test.go | 6 ++-- .../append_dimensions/ruleCreds_test.go | 6 ++-- .../metrics/metrics_collect/cpu/cpu_test.go | 18 +++++------ .../cpu/ruleReportActive_test.go | 18 +++++------ .../metrics/metrics_collect/disk/disk_test.go | 24 +++++++-------- .../metrics_collect/gpu/nvidiaSmi_test.go | 12 ++++---- .../metrics/metrics_collect/mem/mem_test.go | 12 ++++---- .../metrics/metrics_collect/net/net_test.go | 18 +++++------ translator/translate/metrics/metrics_test.go | 12 ++++---- .../rollupDimensions_test.go | 18 +++++------ .../metrics/ruleMetricCredentials_test.go | 18 +++++------ .../metrics/util/commonconfigutil_test.go | 12 ++++---- translator/translate/util/credsutil_test.go | 6 ++-- translator/util/sdkutil.go | 6 ++-- translator/util/searchutil_test.go | 12 ++++---- 33 files changed, 198 insertions(+), 198 deletions(-) diff --git a/cfg/aws/refreshable_shared_credentials_provider.go b/cfg/aws/refreshable_shared_credentials_provider.go index cdc742fecd..9fb0c260b2 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 0b4d74434c..a1229900fa 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -136,8 +136,8 @@ func main() { util.SetSSLEnv(cc.SSLMap()) var errorMessage string if downloadLocation == "" || outputDir == "" { - executable, e := os.Executable() - if e == nil { + executable, err := os.Executable() + if err == nil { errorMessage = fmt.Sprintf("E! usage: " + filepath.Base(executable) + " --output-dir --download-source ssm: ") } else { errorMessage = fmt.Sprintf("E! usage: --output-dir --download-source ssm: ") diff --git a/cmd/config-translator/translator.go b/cmd/config-translator/translator.go index 4ae0eddcad..046f02e0c8 100644 --- a/cmd/config-translator/translator.go +++ b/cmd/config-translator/translator.go @@ -94,8 +94,8 @@ func main() { 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 { log.Panicf("E! Failed to detectRunAsUser") diff --git a/cmd/config-translator/translator_test.go b/cmd/config-translator/translator_test.go index 07ded6d940..1048a3cf3a 100644 --- a/cmd/config-translator/translator_test.go +++ b/cmd/config-translator/translator_test.go @@ -19,14 +19,14 @@ import ( func checkIfSchemaValidateAsExpected(t *testing.T, jsonInputPath string, shouldSuccess bool, expectedErrorMap map[string]int) { actualErrorMap := make(map[string]int) - jsonInputMap, e := util.GetJsonMapFromFile(jsonInputPath) - if e != nil { - t.Fatalf("Failed to get json map from %v with error: %v", jsonInputPath, e) + jsonInputMap, err := util.GetJsonMapFromFile(jsonInputPath) + if err != nil { + t.Fatalf("Failed to get json map from %v with error: %v", jsonInputPath, err) } - result, e := cmdutil.RunSchemaValidation(jsonInputMap) - if e != nil { - t.Fatalf("Failed to run schema validation: %v", e) + result, err := cmdutil.RunSchemaValidation(jsonInputMap) + if err != nil { + t.Fatalf("Failed to run schema validation: %v", err) } if result.Valid() { @@ -181,7 +181,7 @@ func TestInvalidLogFilterConfig(t *testing.T) { // Validate all sampleConfig files schema func TestSampleConfigSchema(t *testing.T) { - if files, e := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); e == nil { + if files, err := ioutil.ReadDir("../../translator/totomlconfig/sampleConfig/"); err == nil { re := regexp.MustCompile(".json") for _, file := range files { if re.MatchString(file.Name()) { @@ -191,6 +191,6 @@ func TestSampleConfigSchema(t *testing.T) { } } } else { - panic(e) + panic(err) } } diff --git a/plugins/inputs/logfile/tail/winfile/winfile.go b/plugins/inputs/logfile/tail/winfile/winfile.go index 965794105b..3c21f4f8b2 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 7e21756e0f..a8e48851ee 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/tool/util/util.go b/tool/util/util.go index 75c97e993b..5dea79601f 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/config/schema_test.go b/translator/config/schema_test.go index fc94b0e347..dc3741d7d9 100644 --- a/translator/config/schema_test.go +++ b/translator/config/schema_test.go @@ -12,9 +12,9 @@ import ( ) func TestGetJsonSchema(t *testing.T) { - jsonFile, e := ioutil.ReadFile("./schema.json") - if e != nil { - panic(e) + jsonFile, err := ioutil.ReadFile("./schema.json") + if err != nil { + panic(err) } str := strings.ReplaceAll(string(jsonFile), "\r\n", "\n") assert.Equal(t, str, GetJsonSchema(), "Json schema is inconsistent") diff --git a/translator/toenvconfig/toEnvConfig_test.go b/translator/toenvconfig/toEnvConfig_test.go index b08f99551c..b8329da137 100644 --- a/translator/toenvconfig/toEnvConfig_test.go +++ b/translator/toenvconfig/toEnvConfig_test.go @@ -23,9 +23,9 @@ import ( ) func ReadFromFile(filename string) string { - data, e := ioutil.ReadFile(filename) - if e != nil { - panic(e) + data, err := ioutil.ReadFile(filename) + if err != nil { + panic(err) } str := string(data) return str @@ -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 e675f73764..0430020e60 100755 --- a/translator/totomlconfig/toTomlConfig.go +++ b/translator/totomlconfig/toTomlConfig.go @@ -58,9 +58,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 { + panic(err) } return buf.String() } diff --git a/translator/totomlconfig/toTomlConfig_test.go b/translator/totomlconfig/toTomlConfig_test.go index e93ae0c891..b56495b518 100644 --- a/translator/totomlconfig/toTomlConfig_test.go +++ b/translator/totomlconfig/toTomlConfig_test.go @@ -30,9 +30,9 @@ import ( ) func ReadFromFile(filename string) string { - data, e := ioutil.ReadFile(filename) - if e != nil { - panic(e) + data, err := ioutil.ReadFile(filename) + if err != nil { + panic(err) } str := string(data) return strings.ReplaceAll(str, "\r\n", "\n") diff --git a/translator/translate/agent/agent_test.go b/translator/translate/agent/agent_test.go index 4ef88d509c..c04b02a723 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 7bc9fac7a2..5aabf2f1e5 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 5a0541df72..e6dac6f09c 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 50794abb12..53bda6e9ef 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/windows_events/windows_event_test.go b/translator/translate/logs/logs_collected/windows_events/windows_event_test.go index 6ef19c8b85..f3e320379e 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{} - e := json.Unmarshal([]byte(rawJsonString), &input) - if e == 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(e) + panic(err) } } diff --git a/translator/translate/logs/logs_test.go b/translator/translate/logs/logs_test.go index c855005280..820af5d7dd 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/ruleLogCredentials_test.go b/translator/translate/logs/ruleLogCredentials_test.go index 26b263f364..21e5a3db9a 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/append_dimensions_test.go b/translator/translate/metrics/append_dimensions/append_dimensions_test.go index f990b4e7e1..62375e6f49 100644 --- a/translator/translate/metrics/append_dimensions/append_dimensions_test.go +++ b/translator/translate/metrics/append_dimensions/append_dimensions_test.go @@ -14,7 +14,7 @@ func TestAppendDimensions(t *testing.T) { a := new(appendDimensions) //Check whether override default config var input interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "append_dimensions": { "ImageId": "${aws:ImageId}", "InstanceId": "${aws:InstanceId}", @@ -22,7 +22,7 @@ func TestAppendDimensions(t *testing.T) { "AutoScalingGroupName": "${aws:AutoScalingGroupName}" } }`), &input) - if e == nil { + if err == nil { _, actual := a.ApplyRule(input) expected := map[string]interface{}{ "ec2tagger": []interface{}{ @@ -37,6 +37,6 @@ func TestAppendDimensions(t *testing.T) { } assert.Equal(t, expected, actual, "Expect to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/append_dimensions/ruleCreds_test.go b/translator/translate/metrics/append_dimensions/ruleCreds_test.go index 1361ad36fb..5309e9423e 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 e721f93dee..28eccdaadc 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 7ad1f22a20..638e9cbbbb 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 3292fc2ecc..c2b8c17503 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{} - e = json.Unmarshal([]byte(`{"disk":{ + err = json.Unmarshal([]byte(`{"disk":{ "resources": [ "/", "/dev", "/sys" ], @@ -36,7 +36,7 @@ func TestDiskSpecificConfig(t *testing.T) { "total", "used" ]}}`), &input1) - if e == nil { + if err == nil { _, actualVal := d.ApplyRule(input1) expectedVal := []interface{}{map[string]interface{}{ "ignore_fs": []interface{}{"sysfs", "devtmpfs"}, @@ -47,12 +47,12 @@ func TestDiskSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(e) + panic(err) } //check when "drop_device" = true var input2 interface{} - e = 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 e == 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(e) + panic(err) } //check when "drop_device" = false var input3 interface{} - e = 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 e == 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(e) + 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 2221c84c8d..e0c5fb78ad 100644 --- a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go +++ b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go @@ -11,11 +11,11 @@ import ( func TestSpecificConfig(t *testing.T) { n := new(NvidiaSmi) var input interface{} - e := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ + err := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ "utilization_gpu", "temperature_gpu" ]}}`), &input) - if e == nil { + if err == nil { _, actualVal := n.ApplyRule(input) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"utilization_gpu", "temperature_gpu"}, @@ -24,7 +24,7 @@ func TestSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(e) + panic(err) } } @@ -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 a194164fab..a83ea440d6 100644 --- a/translator/translate/metrics/metrics_collect/mem/mem_test.go +++ b/translator/translate/metrics/metrics_collect/mem/mem_test.go @@ -15,20 +15,20 @@ 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{} - e = json.Unmarshal([]byte(`{"mem":{"measurement": [ + err = json.Unmarshal([]byte(`{"mem":{"measurement": [ "free", "total" ]}}`), &input1) - if e == nil { + if err == nil { _, actualVal := m.ApplyRule(input1) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"free", "total"}, @@ -36,6 +36,6 @@ func TestMemSpecificConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/metrics_collect/net/net_test.go b/translator/translate/metrics/metrics_collect/net/net_test.go index 59a726fbca..316e198d1b 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_test.go b/translator/translate/metrics/metrics_test.go index 4777ebf341..680a4c5172 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 a9082b1820..a63a328b89 100644 --- a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go +++ b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go @@ -15,10 +15,10 @@ import ( func TestRollupDimensions(t *testing.T) { r := new(rollupDimensions) var input interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "aggregation_dimensions": [["ImageId"], ["InstanceId", "InstanceType"], ["d1"],[]] }`), &input) - if e == nil { + if err == nil { _, actual := r.ApplyRule(input) expected := map[string]interface{}{ "rollup_dimensions": []interface{}{ @@ -29,7 +29,7 @@ func TestRollupDimensions(t *testing.T) { } assert.Equal(t, expected, actual, "Expect to be equal") } else { - panic(e) + panic(err) } } @@ -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] @@ -75,7 +75,7 @@ func TestValidRollupList(t *testing.T) { var input interface{} var actualVal interface{} - e := json.Unmarshal([]byte(`{ + err := json.Unmarshal([]byte(`{ "aggregation_dimensions":[["ImageId"], ["InstanceId", "InstanceType"], ["d1"],[]] }`), &input) @@ -85,9 +85,9 @@ func TestValidRollupList(t *testing.T) { t.FailNow() } - if e == nil { + if err == nil { assert.Equal(t, true, isValidRollupList(actualVal), "Expect to be true") } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/ruleMetricCredentials_test.go b/translator/translate/metrics/ruleMetricCredentials_test.go index 4d4666b513..a786a968d4 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 dd4fbebc18..3b879bd513 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/util/credsutil_test.go b/translator/translate/util/credsutil_test.go index d0e7549db8..71dd5c2ded 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/util/sdkutil.go b/translator/util/sdkutil.go index 9175294189..fe1ad1763c 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 f0269043ef..5fd523446c 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{}{} - e := json.Unmarshal([]byte(rawJsonString), &input) - if e == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { SetWithSameKeyIfFound(input, target_key_list, actual) assert.Equal(t, expected, actual) } else { - panic(e) + panic(err) } } @@ -69,11 +69,11 @@ func TestSetWithCustomizedKeyIfFound(t *testing.T) { "tagCMapped": map[string]interface{}{"key1": "value1", "key2": "value2"}, } var actual = map[string]interface{}{} - e := json.Unmarshal([]byte(rawJsonString), &input) - if e == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { SetWithCustomizedKeyIfFound(input, targetKeyMap, actual) assert.Equal(t, expected, actual) } else { - panic(e) + panic(err) } } From 346330cae79e3c09c8579bd14254319648edcbab Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 17:24:03 -0400 Subject: [PATCH 15/23] FOrmat go --- cmd/config-downloader/downloader.go | 2 +- integration/clean/clean_ami.go | 5 +- integration/test/agent_util.go | 2 +- integration/test/ca_bundle/ca_bundle_test.go | 14 +- .../containerinsightscommon/nodeCapacity.go | 2 +- .../taskdefinitionprocessor.go | 2 +- plugins/inputs/logfile/logfile_test.go | 2 +- plugins/inputs/logfile/tail/tail.go | 2 +- .../windows_event_log/wineventlog/utils.go | 26 +- .../wineventlog/utils_test.go | 8 +- .../processors/defaultConfig/defaultConfig.go | 2 +- .../migration/linux/linuxMigration.go | 1 + translator/cmdutil/translatorutil.go | 4 +- translator/cmdutil/userutil.go | 4 +- translator/config/os.go | 4 +- translator/jsonconfig/mergeJsonConfig.go | 3 +- translator/toenvconfig/toEnvConfig.go | 1 + translator/totomlconfig/toTomlConfig_test.go | 15 +- .../tomlConfigTemplate/tomlConfig.go | 374 +++++++++--------- translator/translate/agent/ruleLogFile.go | 1 + .../logs/logs_collected/logs_collected.go | 4 +- translator/translate/translate.go | 2 +- translator/translate/util/placeholderUtil.go | 12 +- .../translate/util/placeholderUtil_test.go | 12 +- translator/util/ec2util/ec2util.go | 11 +- 25 files changed, 259 insertions(+), 256 deletions(-) diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index a1229900fa..9d796491e8 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -6,8 +6,8 @@ package main import ( "flag" "io/ioutil" - "os" "log" + "os" "strings" configaws "github.com/aws/amazon-cloudwatch-agent/cfg/aws" diff --git a/integration/clean/clean_ami.go b/integration/clean/clean_ami.go index 01b79c0544..8dd29d2336 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 6b0f6052bd..45deadad20 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 1076197653..2d7a748d07 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 51489a98da..70ed4cd69e 100644 --- a/internal/containerinsightscommon/nodeCapacity.go +++ b/internal/containerinsightscommon/nodeCapacity.go @@ -6,7 +6,7 @@ package containerinsightscommon import ( "log" "os" - + "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/mem" ) diff --git a/internal/ecsservicediscovery/taskdefinitionprocessor.go b/internal/ecsservicediscovery/taskdefinitionprocessor.go index c7947bd470..72b712a969 100644 --- a/internal/ecsservicediscovery/taskdefinitionprocessor.go +++ b/internal/ecsservicediscovery/taskdefinitionprocessor.go @@ -5,7 +5,7 @@ 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" diff --git a/plugins/inputs/logfile/logfile_test.go b/plugins/inputs/logfile/logfile_test.go index 318a117e27..a30bf292b3 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 d5445def3e..13ce97757f 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 } - errorMessage := fmt.Sprintf("E! Unreachable to file %s",tail.Filename) + errorMessage := fmt.Sprintf("E! Unreachable to file %s", tail.Filename) tail.Logger.Errorf(errorMessage) panic(errorMessage) diff --git a/plugins/inputs/windows_event_log/wineventlog/utils.go b/plugins/inputs/windows_event_log/wineventlog/utils.go index 4ef163305e..ca57856007 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 1c455014a6..7b05d93350 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/tool/processors/defaultConfig/defaultConfig.go b/tool/processors/defaultConfig/defaultConfig.go index 44c9f7e6d5..03cbf3f0f2 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: - log.Panicf("Unknown default config: %s",whichDefaultConfig) + log.Panicf("Unknown default config: %s", whichDefaultConfig) } if config.SatisfiedWithCurrentConfig(ctx) { if ctx.OsParameter == util.OsTypeWindows { diff --git a/tool/processors/migration/linux/linuxMigration.go b/tool/processors/migration/linux/linuxMigration.go index f51d49d20a..c1605e93ef 100644 --- a/tool/processors/migration/linux/linuxMigration.go +++ b/tool/processors/migration/linux/linuxMigration.go @@ -5,6 +5,7 @@ package linux import ( "log" + "github.com/aws/amazon-cloudwatch-agent/tool/data" "github.com/aws/amazon-cloudwatch-agent/tool/data/config" "github.com/aws/amazon-cloudwatch-agent/tool/processors" diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 0b649c0b1e..883cce365d 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -61,7 +61,7 @@ func TranslateJsonMapToEnvConfigFile(jsonConfigValue map[string]interface{}, env func getCurBinaryPath() string { ex, err := os.Executable() if err != nil { - log.Panicf("E! Failed to get executable path because of %v",err) + log.Panicf("E! Failed to get executable path because of %v", err) } return path.Dir(ex) } @@ -101,7 +101,7 @@ func RunSchemaValidation(inputJsonMap map[string]interface{}) (*gojsonschema.Res func checkSchema(inputJsonMap map[string]interface{}) { result, err := RunSchemaValidation(inputJsonMap) if err != nil { - log.Panicf("E! Failed to run schema validation because of %v",err) + log.Panicf("E! Failed to run schema validation because of %v", err) } if result.Valid() { log.Print("I! Valid Json input schema.") diff --git a/translator/cmdutil/userutil.go b/translator/cmdutil/userutil.go index 21ce1f85c1..e9577dcecd 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 } - - log.Panicf("E! run_as_user is not string %v",user) + + log.Panicf("E! run_as_user is not string %v", user) } // agent section exists, but "runasuser" does not exist, then use "root" diff --git a/translator/config/os.go b/translator/config/os.go index 957bcf5c34..d8fe5429b1 100644 --- a/translator/config/os.go +++ b/translator/config/os.go @@ -22,14 +22,14 @@ 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 } } - + log.Panicf("E! %v is not a supported osType type", os) return "" } diff --git a/translator/jsonconfig/mergeJsonConfig.go b/translator/jsonconfig/mergeJsonConfig.go index 4154bcea4f..83db841845 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -5,9 +5,10 @@ package jsonconfig import ( "fmt" + "log" "os" "sort" - "log" + "github.com/aws/amazon-cloudwatch-agent/translator/util/ecsutil" "github.com/aws/amazon-cloudwatch-agent/translator" diff --git a/translator/toenvconfig/toEnvConfig.go b/translator/toenvconfig/toEnvConfig.go index 60762a868f..0db8ac663f 100644 --- a/translator/toenvconfig/toEnvConfig.go +++ b/translator/toenvconfig/toEnvConfig.go @@ -6,6 +6,7 @@ package toenvconfig import ( "encoding/json" "log" + "github.com/aws/amazon-cloudwatch-agent/cfg/commonconfig" "github.com/aws/amazon-cloudwatch-agent/cfg/envconfig" "github.com/aws/amazon-cloudwatch-agent/internal/csm" diff --git a/translator/totomlconfig/toTomlConfig_test.go b/translator/totomlconfig/toTomlConfig_test.go index b56495b518..f04afead2e 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 8314321d4b..ab8bd1a7a2 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/ruleLogFile.go b/translator/translate/agent/ruleLogFile.go index 0d13e533da..fe60c99c82 100644 --- a/translator/translate/agent/ruleLogFile.go +++ b/translator/translate/agent/ruleLogFile.go @@ -5,6 +5,7 @@ package agent import ( "log" + "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/context" diff --git a/translator/translate/logs/logs_collected/logs_collected.go b/translator/translate/logs/logs_collected/logs_collected.go index fc9ad8da13..2f6f9f9c33 100644 --- a/translator/translate/logs/logs_collected/logs_collected.go +++ b/translator/translate/logs/logs_collected/logs_collected.go @@ -5,7 +5,7 @@ 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" @@ -57,7 +57,7 @@ func (l *LogsCollected) ApplyRule(input interface{}) (returnKey string, returnVa case config.OS_TYPE_WINDOWS: targetRuleMap = windowsMetricCollectRule default: - log.Panicf("E! Unknown target platform: %s ",translator.GetTargetPlatform()) + log.Panicf("E! Unknown target platform: %s ", translator.GetTargetPlatform()) } if _, ok := im[SectionKey]; !ok { diff --git a/translator/translate/translate.go b/translator/translate/translate.go index 7ee1600c8a..22cc34f3b4 100644 --- a/translator/translate/translate.go +++ b/translator/translate/translate.go @@ -6,7 +6,7 @@ package translate import ( "log" "sort" - + "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/translate/agent" diff --git a/translator/translate/util/placeholderUtil.go b/translator/translate/util/placeholderUtil.go index bc65e354b3..a9a679ad5f 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 7ee63f59d1..56925ec2a6 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 5fa9929f7e..66eae0eb39 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 From 65ddb9b1c1527290127c2fc2df6cd26c0fa30c96 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Thu, 31 Mar 2022 17:26:39 -0400 Subject: [PATCH 16/23] Delte unreachable --- cmd/config-downloader/downloader.go | 2 +- plugins/inputs/logfile/tail/tail.go | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index 9d796491e8..615f2c7f84 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -185,7 +185,7 @@ func main() { locationArray := strings.SplitN(downloadLocation, locationSeparator, 2) if locationArray == nil || len(locationArray) < 2 && downloadLocation != locationDefault { - errorMessage := fmt.Sprintf("E! downloadLocation %s is malformated.\n", downloadLocation) + errorMessage := fmt.Sprintf("E! downloadLocation %s is malformated.", downloadLocation) log.Panicf(errorMessage) } diff --git a/plugins/inputs/logfile/tail/tail.go b/plugins/inputs/logfile/tail/tail.go index 13ce97757f..b270e197e4 100644 --- a/plugins/inputs/logfile/tail/tail.go +++ b/plugins/inputs/logfile/tail/tail.go @@ -465,9 +465,6 @@ func (tail *Tail) waitForChanges() error { case <-tail.Dying(): return ErrStop } - errorMessage := fmt.Sprintf("E! Unreachable to file %s", tail.Filename) - tail.Logger.Errorf(errorMessage) - panic(errorMessage) } From ed5b8b3e4f315326d49dc1722b22f733aed4f164 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 14:39:48 -0400 Subject: [PATCH 17/23] Change log.Panicf to log.Panic for some logs --- cmd/config-translator/translator.go | 2 +- plugins/inputs/cadvisor/cadvisor_linux.go | 2 +- translator/cmdutil/translatorutil.go | 2 +- translator/cmdutil/userutil.go | 2 +- translator/jsonconfig/mergeJsonConfig.go | 2 +- translator/translate/metrics/drop_origin/drop_origin.go | 2 +- .../translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cmd/config-translator/translator.go b/cmd/config-translator/translator.go index 046f02e0c8..43c2f74f9f 100644 --- a/cmd/config-translator/translator.go +++ b/cmd/config-translator/translator.go @@ -98,7 +98,7 @@ func main() { if err == nil && current.Name == "root" { runAsUser, err := cmdutil.DetectRunAsUser(mergedJsonConfigMap) if err != nil { - log.Panicf("E! Failed to detectRunAsUser") + log.Panic("E! Failed to detectRunAsUser") } cmdutil.VerifyCredentials(ctx, runAsUser) } diff --git a/plugins/inputs/cadvisor/cadvisor_linux.go b/plugins/inputs/cadvisor/cadvisor_linux.go index 6823e17b36..32c0b740a8 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 { - log.Panicf("E! Cannot initiate manager") + log.Panic("E! Cannot initiate manager") } req := &cinfo.ContainerInfoRequest{ diff --git a/translator/cmdutil/translatorutil.go b/translator/cmdutil/translatorutil.go index 883cce365d..d27426afd9 100644 --- a/translator/cmdutil/translatorutil.go +++ b/translator/cmdutil/translatorutil.go @@ -43,7 +43,7 @@ func TranslateJsonMapToTomlFile(jsonConfigValue map[string]interface{}, tomlConf fmt.Println(exitSuccessMessage) } } else { - log.Panicf("E! Failed to generate configuration validation content.") + log.Panic("E! Failed to generate configuration validation content.") } } diff --git a/translator/cmdutil/userutil.go b/translator/cmdutil/userutil.go index e9577dcecd..672b2e3504 100644 --- a/translator/cmdutil/userutil.go +++ b/translator/cmdutil/userutil.go @@ -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 { - log.Panicf("E! Credentials path is not set while runasuser is not root") + log.Panic("E! Credentials path is not set while runasuser is not root") } } } diff --git a/translator/jsonconfig/mergeJsonConfig.go b/translator/jsonconfig/mergeJsonConfig.go index 83db841845..48d9704c03 100644 --- a/translator/jsonconfig/mergeJsonConfig.go +++ b/translator/jsonconfig/mergeJsonConfig.go @@ -55,7 +55,7 @@ func MergeJsonConfigMaps(jsonConfigMapMap map[string]map[string]interface{}, def } if !translator.IsTranslateSuccess() { - log.Panicf("Failed to merge multiple json config files.") + log.Panic("Failed to merge multiple json config files.") } return resultMap, nil diff --git a/translator/translate/metrics/drop_origin/drop_origin.go b/translator/translate/metrics/drop_origin/drop_origin.go index 13930012b0..2c36c16598 100644 --- a/translator/translate/metrics/drop_origin/drop_origin.go +++ b/translator/translate/metrics/drop_origin/drop_origin.go @@ -36,7 +36,7 @@ func (do *dropOrigin) ApplyRule(input interface{}) (returnKey string, returnVal if reflect.TypeOf(value).String() == "string" { droppingDimensions = append(droppingDimensions, value.(string)) } else { - log.Panicf("Fail to translate the JSON config, invalid format of dropping dimensions.") + log.Panic("Fail to translate the JSON config, invalid format of dropping dimensions.") } } diff --git a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go index e0c5fb78ad..0890ace16a 100644 --- a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go +++ b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go @@ -43,7 +43,7 @@ func TestNoFieldConfig(t *testing.T) { func TestFullConfig(t *testing.T) { n := new(NvidiaSmi) var input interface{} - e := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ + err := json.Unmarshal([]byte(`{"nvidia_gpu":{"measurement": [ "utilization_gpu", "temperature_gpu", "power_draw", From 1f11a99e364e9298c0852c4fccc2253782167274 Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 14:42:01 -0400 Subject: [PATCH 18/23] Change to err for some files --- .../windows_events/collect_list/collectlist_test.go | 6 +++--- .../metrics/append_dimensions/append_dimensions_test.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) 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 1e7ee128a9..3f904d4d39 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 @@ -59,11 +59,11 @@ func TestApplyRule(t *testing.T) { var actual interface{} - e := json.Unmarshal([]byte(rawJsonString), &input) - if e == nil { + err := json.Unmarshal([]byte(rawJsonString), &input) + if err == nil { _, actual = c.ApplyRule(input) assert.Equal(t, expected, actual) } else { - panic(e) + panic(err) } } diff --git a/translator/translate/metrics/append_dimensions/append_dimensions_test.go b/translator/translate/metrics/append_dimensions/append_dimensions_test.go index 62375e6f49..89242c321f 100644 --- a/translator/translate/metrics/append_dimensions/append_dimensions_test.go +++ b/translator/translate/metrics/append_dimensions/append_dimensions_test.go @@ -11,7 +11,7 @@ import ( ) func TestAppendDimensions(t *testing.T) { - a := new(appendDimensions) + e := new(appendDimensions) //Check whether override default config var input interface{} err := json.Unmarshal([]byte(`{ From 719134af59235731258bcdb581e2d4573037857c Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 14:48:17 -0400 Subject: [PATCH 19/23] Revert some error changes --- .../metrics/rollup_dimensions/rollupDimensions_test.go | 4 ++-- translator/translate/metrics/util/measurementutil.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go index a63a328b89..007d5e5d69 100644 --- a/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go +++ b/translator/translate/metrics/rollup_dimensions/rollupDimensions_test.go @@ -13,13 +13,13 @@ import ( ) func TestRollupDimensions(t *testing.T) { - r := new(rollupDimensions) + e := new(rollupDimensions) var input interface{} err := json.Unmarshal([]byte(`{ "aggregation_dimensions": [["ImageId"], ["InstanceId", "InstanceType"], ["d1"],[]] }`), &input) if err == nil { - _, actual := r.ApplyRule(input) + _, actual := e.ApplyRule(input) expected := map[string]interface{}{ "rollup_dimensions": []interface{}{ []interface{}{"ImageId"}, diff --git a/translator/translate/metrics/util/measurementutil.go b/translator/translate/metrics/util/measurementutil.go index 9e4282505f..ae9520fb9e 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: - log.Panicf("unknown os platform in getValidMetric: %s", targetOs) + log.Panicf("E! Unknown os platform in getValidMetric: %s", targetOs) } if val, ok := registeredMetrics[pluginName]; ok { formatted_metricName := getFormattedMetricName(metricName, pluginName) From 43028293cdcab6b8bee9b8d87a31195894107f9e Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 15:02:28 -0400 Subject: [PATCH 20/23] Fix some typo --- cmd/config-downloader/downloader.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cmd/config-downloader/downloader.go b/cmd/config-downloader/downloader.go index 615f2c7f84..bc35f791d6 100644 --- a/cmd/config-downloader/downloader.go +++ b/cmd/config-downloader/downloader.go @@ -185,8 +185,7 @@ func main() { locationArray := strings.SplitN(downloadLocation, locationSeparator, 2) if locationArray == nil || len(locationArray) < 2 && downloadLocation != locationDefault { - errorMessage := fmt.Sprintf("E! downloadLocation %s is malformated.", downloadLocation) - log.Panicf(errorMessage) + log.Panicf("E! downloadLocation %s is malformated.", downloadLocation) } var config, outputFilePath string From 881b3eff93994af977dd1c0f2884682772edfe7f Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 15:04:20 -0400 Subject: [PATCH 21/23] Change back for some logs and fix typo --- translator/config/os.go | 5 ++--- translator/translate/agent/ruleLogFile.go | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/translator/config/os.go b/translator/config/os.go index d8fe5429b1..6aca672ea3 100644 --- a/translator/config/os.go +++ b/translator/config/os.go @@ -4,7 +4,7 @@ package config import ( - "log" + "fmt" "runtime" "strings" ) @@ -30,6 +30,5 @@ func ToValidOs(os string) string { } } - log.Panicf("E! %v is not a supported osType type", os) - return "" + panic(fmt.Sprintf("%v is not a supported osType type", os)) } diff --git a/translator/translate/agent/ruleLogFile.go b/translator/translate/agent/ruleLogFile.go index fe60c99c82..2cd58cc8d7 100644 --- a/translator/translate/agent/ruleLogFile.go +++ b/translator/translate/agent/ruleLogFile.go @@ -33,8 +33,7 @@ func getDefaultValue() string { case config.OS_TYPE_WINDOWS: return util.GetWindowsProgramDataPath() + "\\Amazon\\AmazonCloudWatchAgent\\Logs\\amazon-cloudwatch-agent.log" default: - log.Panicf("Unsupported platform %v for logRule", targetPlatform) - return "" + panic(fmt.Sprintf("Unsupported platform %v for logRule", targetPlatform)) } } From 0d05e88ecc5d88982193e39cd4db2451f8c6ac1c Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 15:47:07 -0400 Subject: [PATCH 22/23] Fix package issue --- translator/totomlconfig/toTomlConfig.go | 2 ++ translator/translate/agent/ruleLogFile.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/translator/totomlconfig/toTomlConfig.go b/translator/totomlconfig/toTomlConfig.go index 0430020e60..26b5d6919d 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" @@ -60,6 +61,7 @@ func ToTomlConfig(c interface{}) string { enc := toml.NewEncoder(&buf) err := enc.Encode(val) if err != nil { + log.Panicf("") panic(err) } return buf.String() diff --git a/translator/translate/agent/ruleLogFile.go b/translator/translate/agent/ruleLogFile.go index 2cd58cc8d7..bff46e2717 100644 --- a/translator/translate/agent/ruleLogFile.go +++ b/translator/translate/agent/ruleLogFile.go @@ -4,7 +4,7 @@ package agent import ( - "log" + "fmt" "github.com/aws/amazon-cloudwatch-agent/translator" "github.com/aws/amazon-cloudwatch-agent/translator/config" From 805abd48c0e492ffc6626a498b574522e061023f Mon Sep 17 00:00:00 2001 From: Khanh Nguyen Date: Mon, 4 Apr 2022 15:53:56 -0400 Subject: [PATCH 23/23] Fix some type and add panic --- translator/totomlconfig/toTomlConfig.go | 3 +-- .../metrics/append_dimensions/append_dimensions_test.go | 2 +- .../translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/translator/totomlconfig/toTomlConfig.go b/translator/totomlconfig/toTomlConfig.go index 26b5d6919d..4b1dda232b 100755 --- a/translator/totomlconfig/toTomlConfig.go +++ b/translator/totomlconfig/toTomlConfig.go @@ -61,8 +61,7 @@ func ToTomlConfig(c interface{}) string { enc := toml.NewEncoder(&buf) err := enc.Encode(val) if err != nil { - log.Panicf("") - panic(err) + log.Panicf("Encode to a valid TOML config fails because of %v",err) } return buf.String() } diff --git a/translator/translate/metrics/append_dimensions/append_dimensions_test.go b/translator/translate/metrics/append_dimensions/append_dimensions_test.go index 89242c321f..da7f10fef1 100644 --- a/translator/translate/metrics/append_dimensions/append_dimensions_test.go +++ b/translator/translate/metrics/append_dimensions/append_dimensions_test.go @@ -23,7 +23,7 @@ func TestAppendDimensions(t *testing.T) { } }`), &input) if err == nil { - _, actual := a.ApplyRule(input) + _, actual := e.ApplyRule(input) expected := map[string]interface{}{ "ec2tagger": []interface{}{ map[string]interface{}{ diff --git a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go index 0890ace16a..ef3b958ebd 100644 --- a/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go +++ b/translator/translate/metrics/metrics_collect/gpu/nvidiaSmi_test.go @@ -63,7 +63,7 @@ func TestFullConfig(t *testing.T) { "clocks_current_memory", "clocks_current_video" ]}}`), &input) - if e == nil { + if err == nil { _, actualVal := n.ApplyRule(input) expectedVal := []interface{}{map[string]interface{}{ "fieldpass": []string{"utilization_gpu", "temperature_gpu", "power_draw", "utilization_memory", @@ -76,7 +76,7 @@ func TestFullConfig(t *testing.T) { } assert.Equal(t, expectedVal, actualVal, "Expect to be equal") } else { - panic(e) + panic(err) } }