From 8ed7549e2a15535ededdef618c4fbbf9eef87297 Mon Sep 17 00:00:00 2001 From: Jason Harper Date: Wed, 6 Nov 2024 08:27:01 -0800 Subject: [PATCH] address issues raised by golangci-lint (#88) --- .gitignore | 1 + Makefile | 8 ++- cmd/config/config.go | 20 +++++-- cmd/metrics/metrics.go | 68 +++++++++++++--------- cmd/metrics/print.go | 103 +++++++++++++++++++-------------- cmd/report/report.go | 2 +- cmd/root.go | 5 +- cmd/telemetry/telemetry.go | 2 +- internal/common/common.go | 17 ++++-- internal/report/report.go | 68 +++++++++++----------- internal/script/script.go | 14 ++++- internal/script/script_test.go | 7 ++- internal/target/target.go | 5 +- 13 files changed, 197 insertions(+), 123 deletions(-) diff --git a/.gitignore b/.gitignore index dad0ed4..9e98870 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ /tools/bin /dist /internal/script/resources/x86_64 +/test \ No newline at end of file diff --git a/Makefile b/Makefile index a7a05ea..60edc10 100644 --- a/Makefile +++ b/Makefile @@ -96,8 +96,14 @@ check_license: if ! grep -E 'Copyright \(C\) [0-9]{4}-[0-9]{4} Intel Corporation' "$$f" >/dev/null; then echo "Error: license not found: $$f"; fail=1; fi; \ done; if [ -n "$$fail" ]; then exit 1; fi +.PHONY: check_lint +check_lint: + @echo "Running golangci-lint..." + go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + golangci-lint run + .PHONY: check -check: check_format check_vet check_static check_license +check: check_format check_vet check_static check_license check_lint .PHONY: clean clean: diff --git a/cmd/config/config.go b/cmd/config/config.go index fb9bf7b..48eb5c0 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -232,7 +232,13 @@ func runCmd(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true return err } - defer myTarget.RemoveDirectory(targetTempDir) + defer func() { + err = myTarget.RemoveDirectory(targetTempDir) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to remove target directory: %+v\n", err) + slog.Error(err.Error()) + } + }() } // print config prior to changes if err := printConfig(myTargets, localTempDir); err != nil { @@ -310,18 +316,22 @@ func printConfig(myTargets []target.Target, localTempDir string) (err error) { } for _, myTarget := range myTargets { multiSpinner := progress.NewMultiSpinner() - multiSpinner.AddSpinner(myTarget.GetName()) + err = multiSpinner.AddSpinner(myTarget.GetName()) + if err != nil { + err = fmt.Errorf("failed to add spinner: %v", err) + return + } multiSpinner.Start() - multiSpinner.Status(myTarget.GetName(), "collecting data") + _ = multiSpinner.Status(myTarget.GetName(), "collecting data") // run the scripts var scriptOutputs map[string]script.ScriptOutput if scriptOutputs, err = script.RunScripts(myTarget, scriptsToRun, true, localTempDir); err != nil { err = fmt.Errorf("failed to run collection scripts: %v", err) - multiSpinner.Status(myTarget.GetName(), "error collecting data") + _ = multiSpinner.Status(myTarget.GetName(), "error collecting data") multiSpinner.Finish() return } - multiSpinner.Status(myTarget.GetName(), "collection complete") + _ = multiSpinner.Status(myTarget.GetName(), "collection complete") multiSpinner.Finish() // process the tables, i.e., get field values from raw script output tableNames := []string{report.ConfigurationTableName} diff --git a/cmd/metrics/metrics.go b/cmd/metrics/metrics.go index 2d564ea..939df72 100644 --- a/cmd/metrics/metrics.go +++ b/cmd/metrics/metrics.go @@ -671,7 +671,7 @@ func runCmd(cmd *cobra.Command, args []string) error { } else { finalMessage += fmt.Sprintf(" for %d seconds", flagDuration) } - multiSpinner.Status(targetContexts[i].target.GetName(), finalMessage) + _ = multiSpinner.Status(targetContexts[i].target.GetName(), finalMessage) } go collectOnTarget(&targetContexts[i], localTempDir, localOutputDir, channelTargetError, multiSpinner.Status) } @@ -687,7 +687,7 @@ func runCmd(cmd *cobra.Command, args []string) error { // finalize and stop the spinner for _, targetContext := range targetContexts { if targetContext.err == nil { - multiSpinner.Status(targetContext.target.GetName(), "collection complete") + _ = multiSpinner.Status(targetContext.target.GetName(), "collection complete") } } // summarize outputs @@ -750,11 +750,11 @@ func runCmd(cmd *cobra.Command, args []string) error { func prepareTarget(targetContext *targetContext, targetTempRoot string, localTempDir string, localPerfPath string, channelError chan targetError, statusUpdate progress.MultiSpinnerUpdateFunc) { myTarget := targetContext.target - // create a temporary directory on the target - statusUpdate(myTarget.GetName(), "configuring target") var err error + // create a temporary directory on the target + _ = statusUpdate(myTarget.GetName(), "configuring target") if targetContext.tempDir, err = myTarget.CreateTempDirectory(targetTempRoot); err != nil { - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %v", err)) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %v", err)) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -764,7 +764,7 @@ func prepareTarget(targetContext *targetContext, targetTempRoot string, localTem var nmiWatchdogEnabled bool if nmiWatchdogEnabled, err = NMIWatchdogEnabled(myTarget); err != nil { err = fmt.Errorf("failed to retrieve NMI watchdog status: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -772,7 +772,7 @@ func prepareTarget(targetContext *targetContext, targetTempRoot string, localTem if nmiWatchdogEnabled { if err = DisableNMIWatchdog(myTarget, localTempDir); err != nil { err = fmt.Errorf("failed to disable NMI watchdog: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -784,14 +784,14 @@ func prepareTarget(targetContext *targetContext, targetTempRoot string, localTem if !flagNoRoot { if targetContext.perfMuxIntervals, err = GetMuxIntervals(myTarget, localTempDir); err != nil { err = fmt.Errorf("failed to get perf mux intervals: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return } if err = SetAllMuxIntervals(myTarget, flagPerfMuxInterval, localTempDir); err != nil { err = fmt.Errorf("failed to set all perf mux intervals: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -800,7 +800,7 @@ func prepareTarget(targetContext *targetContext, targetTempRoot string, localTem // get the full path to the perf binary if targetContext.perfPath, err = getPerfPath(myTarget, localPerfPath); err != nil { err = fmt.Errorf("failed to find perf: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %v", err)) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %v", err)) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -816,11 +816,11 @@ func prepareMetrics(targetContext *targetContext, localTempDir string, channelEr return } // load metadata - statusUpdate(myTarget.GetName(), "collecting metadata") + _ = statusUpdate(myTarget.GetName(), "collecting metadata") var err error if targetContext.metadata, err = LoadMetadata(myTarget, flagNoRoot, targetContext.perfPath, localTempDir); err != nil { err = fmt.Errorf("failed to load metadata: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -830,7 +830,7 @@ func prepareMetrics(targetContext *targetContext, localTempDir string, channelEr var uncollectableEvents []string if targetContext.groupDefinitions, uncollectableEvents, err = LoadEventGroups(flagEventFilePath, targetContext.metadata); err != nil { err = fmt.Errorf("failed to load event definitions: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -838,7 +838,7 @@ func prepareMetrics(targetContext *targetContext, localTempDir string, channelEr // load metric definitions if targetContext.metricDefinitions, err = LoadMetricDefinitions(flagMetricFilePath, flagMetricsList, uncollectableEvents, targetContext.metadata); err != nil { err = fmt.Errorf("failed to load metric definitions: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -846,7 +846,7 @@ func prepareMetrics(targetContext *targetContext, localTempDir string, channelEr // configure metrics if err = ConfigureMetrics(targetContext.metricDefinitions, GetEvaluatorFunctions(), targetContext.metadata); err != nil { err = fmt.Errorf("failed to configure metrics: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) targetContext.err = err channelError <- targetError{target: myTarget, err: err} return @@ -877,7 +877,7 @@ func collectOnTarget(targetContext *targetContext, localTempDir string, localOut // get the perf command if processes, perfCommand, err = getPerfCommand(myTarget, targetContext.perfPath, targetContext.groupDefinitions, localTempDir); err != nil { err = fmt.Errorf("failed to get perf command: %w", err) - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) break } beginTimestamp := time.Now() @@ -887,7 +887,7 @@ func collectOnTarget(targetContext *targetContext, localTempDir string, localOut if perfErr != nil { if !getSignalReceived() { err = perfErr - statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("Error: %s", err.Error())) } break } @@ -916,21 +916,33 @@ func printMetrics(frameChannel chan []MetricFrame, targetName string, outputDir var printedFiles []string // block until next set of metric frames arrives, will exit loop when channel is closed for metricFrames := range frameChannel { - fileName := printMetricsTxt(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatTxt, !flagLive && util.StringInList(formatTxt, flagOutputFormat), outputDir) - if fileName != "" { + fileName, err := printMetricsTxt(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatTxt, !flagLive && util.StringInList(formatTxt, flagOutputFormat), outputDir) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + slog.Error(err.Error()) + } else if fileName != "" { printedFiles = util.UniqueAppend(printedFiles, fileName) } - fileName = printMetricsJSON(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatJSON, !flagLive && util.StringInList(formatJSON, flagOutputFormat), outputDir) - if fileName != "" { + fileName, err = printMetricsJSON(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatJSON, !flagLive && util.StringInList(formatJSON, flagOutputFormat), outputDir) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + slog.Error(err.Error()) + } else if fileName != "" { printedFiles = util.UniqueAppend(printedFiles, fileName) } // csv is always written to file unless no files are requested -- we need it to create the summary reports - fileName = printMetricsCSV(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatCSV, !flagLive, outputDir) - if fileName != "" { + fileName, err = printMetricsCSV(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatCSV, !flagLive, outputDir) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + slog.Error(err.Error()) + } else if fileName != "" { printedFiles = util.UniqueAppend(printedFiles, fileName) } - fileName = printMetricsWide(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatWide, !flagLive && util.StringInList(formatWide, flagOutputFormat), outputDir) - if fileName != "" { + fileName, err = printMetricsWide(metricFrames, targetName, flagLive && flagOutputFormat[0] == formatWide, !flagLive && util.StringInList(formatWide, flagOutputFormat), outputDir) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + slog.Error(err.Error()) + } else if fileName != "" { printedFiles = util.UniqueAppend(printedFiles, fileName) } } @@ -1170,7 +1182,11 @@ func runPerf(myTarget target.Target, noRoot bool, processes []Process, cmd *exec outputLines = [][]byte{} // empty it } if timeout != 0 && int(time.Since(startPerfTimestamp).Seconds()) > timeout { - localCommand.Process.Signal(os.Interrupt) + err = localCommand.Process.Signal(os.Interrupt) + if err != nil { + err = fmt.Errorf("failed to terminate perf: %v", err) + slog.Error(err.Error()) + } } } }() diff --git a/cmd/metrics/print.go b/cmd/metrics/print.go index 0a9acca..62b665f 100644 --- a/cmd/metrics/print.go +++ b/cmd/metrics/print.go @@ -6,7 +6,6 @@ package metrics import ( "encoding/json" "fmt" - "log/slog" "math" "os" "strconv" @@ -14,9 +13,9 @@ import ( "time" ) -func printMetricsJSON(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) string { +func printMetricsJSON(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) (filename string, err error) { if !printToStdout && !printToFile { - return "" + return } for _, metricFrame := range metricFrames { // can't Marshal NaN or Inf values in JSON, so no need to set them to a specific value @@ -29,43 +28,42 @@ func printMetricsJSON(metricFrames []MetricFrame, targetName string, printToStdo filteredMetricFrame.Metrics = append(filteredMetricFrame.Metrics, metric) } } - jsonBytes, err := json.Marshal(filteredMetricFrame) + var jsonBytes []byte + jsonBytes, err = json.Marshal(filteredMetricFrame) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - slog.Error(err.Error()) - return "" + return } if printToStdout { fmt.Println(string(jsonBytes)) } if printToFile { - file, err := os.OpenFile(outputDir+"/"+targetName+"_"+"metrics.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + var file *os.File + file, err = os.OpenFile(outputDir+"/"+targetName+"_"+"metrics.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - slog.Error(err.Error()) - return "" + return } defer file.Close() - file.WriteString(string(jsonBytes) + "\n") - return file.Name() + _, err = file.WriteString(string(jsonBytes) + "\n") + if err != nil { + return + } + filename = file.Name() + return // success } } - return "" + return } -func printMetricsCSV(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) string { +func printMetricsCSV(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) (filename string, err error) { if !printToStdout && !printToFile { - return "" + return } var file *os.File if printToFile { // open file for writing/appending - var err error file, err = os.OpenFile(outputDir+"/"+targetName+"_"+"metrics.csv", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - slog.Error(err.Error()) - return "" + return } defer file.Close() } @@ -76,7 +74,10 @@ func printMetricsCSV(metricFrames []MetricFrame, targetName string, printToStdou fmt.Print(contextHeaders) } if printToFile { - file.WriteString(contextHeaders) + _, err = file.WriteString(contextHeaders) + if err != nil { + return + } } names := make([]string, 0, len(metricFrame.Metrics)) for _, metric := range metricFrame.Metrics { @@ -87,7 +88,10 @@ func printMetricsCSV(metricFrames []MetricFrame, targetName string, printToStdou fmt.Println(metricNames) } if printToFile { - file.WriteString(metricNames + "\n") + _, err = file.WriteString(metricNames + "\n") + if err != nil { + return + } } } metricContext := fmt.Sprintf("%d,%s,%s,%s,", gCollectionStartTime.Unix()+int64(metricFrame.Timestamp), metricFrame.Socket, metricFrame.CPU, metricFrame.Cgroup) @@ -100,26 +104,27 @@ func printMetricsCSV(metricFrames []MetricFrame, targetName string, printToStdou fmt.Println(metricContext + metricValues) } if printToFile { - file.WriteString(metricContext + metricValues + "\n") - return file.Name() + _, err = file.WriteString(metricContext + metricValues + "\n") + if err != nil { + return + } + filename = file.Name() + return // success } } - return "" + return "", nil } -func printMetricsWide(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) string { +func printMetricsWide(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) (filename string, err error) { if !printToStdout && !printToFile { - return "" + return } var file *os.File if printToFile { // open file for writing/appending - var err error file, err = os.OpenFile(outputDir+"/"+targetName+"_"+"metrics_wide.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - slog.Error(err.Error()) - return "" + return } defer file.Close() } @@ -156,7 +161,10 @@ func printMetricsWide(metricFrames []MetricFrame, targetName string, printToStdo fmt.Println(header) } if printToFile { - file.WriteString(header + "\n") + _, err = file.WriteString(header + "\n") + if err != nil { + return + } } } // handle values @@ -195,16 +203,20 @@ func printMetricsWide(metricFrames []MetricFrame, targetName string, printToStdo fmt.Println(row) } if printToFile { - file.WriteString(row + "\n") - return file.Name() + _, err = file.WriteString(row + "\n") + if err != nil { + return + } + filename = file.Name() + return // success } } - return "" + return } -func printMetricsTxt(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) string { +func printMetricsTxt(metricFrames []MetricFrame, targetName string, printToStdout bool, printToFile bool, outputDir string) (filename string, err error) { if !printToStdout && !printToFile { - return "" + return } var outputLines []string if len(metricFrames) > 0 && metricFrames[0].Socket != "" { @@ -256,15 +268,18 @@ func printMetricsTxt(metricFrames []MetricFrame, targetName string, printToStdou } if printToFile { // open file for writing/appending - file, err := os.OpenFile(outputDir+"/"+targetName+"_"+"metrics.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + var file *os.File + file, err = os.OpenFile(outputDir+"/"+targetName+"_"+"metrics.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - slog.Error(err.Error()) - return "" + return } defer file.Close() - file.WriteString(strings.Join(outputLines, "\n") + "\n") - return file.Name() + _, err = file.WriteString(strings.Join(outputLines, "\n") + "\n") + if err != nil { + return + } + filename = file.Name() + return // success } - return "" + return } diff --git a/cmd/report/report.go b/cmd/report/report.go index 4ddacd0..48c189c 100644 --- a/cmd/report/report.go +++ b/cmd/report/report.go @@ -226,7 +226,7 @@ func getFlagGroups() []common.FlagGroup { } for _, cat := range categories { flags = append(flags, common.Flag{ - Name: fmt.Sprintf(cat.FlagName), + Name: cat.FlagName, Help: cat.Help, }) } diff --git a/cmd/root.go b/cmd/root.go index 4dc3b8d..754e9e7 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -230,7 +230,10 @@ func initializeApplication(cmd *cobra.Command, args []string) error { go func() { sig := <-sigChannel slog.Info("received signal", slog.String("signal", sig.String())) - terminateApplication(cmd, args) + err := terminateApplication(cmd, args) + if err != nil { + slog.Error("Error terminating application", slog.String("error", err.Error())) + } fmt.Println() os.Exit(1) }() diff --git a/cmd/telemetry/telemetry.go b/cmd/telemetry/telemetry.go index c1b3003..2f00ace 100644 --- a/cmd/telemetry/telemetry.go +++ b/cmd/telemetry/telemetry.go @@ -137,7 +137,7 @@ func getFlagGroups() []common.FlagGroup { } for _, cat := range categories { flags = append(flags, common.Flag{ - Name: fmt.Sprintf(cat.FlagName), + Name: cat.FlagName, Help: cat.Help, }) } diff --git a/internal/common/common.go b/internal/common/common.go index 143f1a0..3fc5882 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -377,27 +377,32 @@ func collectOnTarget(cmd *cobra.Command, myTarget target.Target, scriptsToRun [] // create a temporary directory on the target var targetTempDir string var err error - statusUpdate(myTarget.GetName(), "creating temporary directory") + _ = statusUpdate(myTarget.GetName(), "creating temporary directory") targetTempRoot, _ := cmd.Flags().GetString(FlagTargetTempDirName) if targetTempDir, err = myTarget.CreateTempDirectory(targetTempRoot); err != nil { - statusUpdate(myTarget.GetName(), fmt.Sprintf("error creating temporary directory: %v", err)) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("error creating temporary directory: %v", err)) err = fmt.Errorf("error creating temporary directory on %s: %v", myTarget.GetName(), err) channelError <- err return } // don't remove the directory if we're debugging if cmd.Parent().PersistentFlags().Lookup("debug").Value.String() != "true" { - defer myTarget.RemoveDirectory(targetTempDir) + defer func() { + err := myTarget.RemoveDirectory(targetTempDir) + if err != nil { + slog.Error("error removing target temporary directory", slog.String("error", err.Error())) + } + }() } // run the scripts on the target - statusUpdate(myTarget.GetName(), "collecting data") + _ = statusUpdate(myTarget.GetName(), "collecting data") scriptOutputs, err := script.RunScripts(myTarget, scriptsToRun, true, localTempDir) if err != nil { - statusUpdate(myTarget.GetName(), fmt.Sprintf("error collecting data: %v", err)) + _ = statusUpdate(myTarget.GetName(), fmt.Sprintf("error collecting data: %v", err)) err = fmt.Errorf("error running data collection scripts on %s: %v", myTarget.GetName(), err) channelError <- err return } - statusUpdate(myTarget.GetName(), "collection complete") + _ = statusUpdate(myTarget.GetName(), "collection complete") channelTargetScriptOutputs <- TargetScriptOutputs{targetName: myTarget.GetName(), scriptOutputs: scriptOutputs} } diff --git a/internal/report/report.go b/internal/report/report.go index 17ce6cc..7ad5c56 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -234,11 +234,11 @@ func renderXlsxTable(tableValues TableValues, f *excelize.File, sheetName string Bold: true, }, }) - f.SetCellValue(sheetName, cellName(col, *row), tableValues.Name) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), tableNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), tableValues.Name) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), tableNameStyle) *row++ if len(tableValues.Fields) == 0 || len(tableValues.Fields[0].Values) == 0 { - f.SetCellValue(sheetName, cellName(col, *row), noDataFound) + _ = f.SetCellValue(sheetName, cellName(col, *row), noDataFound) *row += 2 return } @@ -269,15 +269,15 @@ func renderXlsxTableMultiTarget(tableIdx int, allTargetsTableValues [][]TableVal }, }) - f.SetCellValue(sheetName, cellName(col, *row), allTargetsTableValues[0][tableIdx].Name) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), tableNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), allTargetsTableValues[0][tableIdx].Name) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), tableNameStyle) if !allTargetsTableValues[0][tableIdx].HasRows { col += 2 // print the target names for _, targetName := range targetNames { - f.SetCellValue(sheetName, cellName(col, *row), targetName) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), targetNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), targetName) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), targetNameStyle) col++ } *row++ @@ -285,15 +285,15 @@ func renderXlsxTableMultiTarget(tableIdx int, allTargetsTableValues [][]TableVal // print the field names and values from each target for fieldIdx, field := range allTargetsTableValues[0][tableIdx].Fields { col = 2 - f.SetCellValue(sheetName, cellName(col, *row), field.Name) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), fieldNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), field.Name) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), fieldNameStyle) col++ for targetIdx := 0; targetIdx < len(targetNames); targetIdx++ { var fieldValue string if len(allTargetsTableValues[targetIdx][tableIdx].Fields[fieldIdx].Values) > 0 { fieldValue = allTargetsTableValues[targetIdx][tableIdx].Fields[fieldIdx].Values[0] } - f.SetCellValue(sheetName, cellName(col, *row), fieldValue) + _ = f.SetCellValue(sheetName, cellName(col, *row), fieldValue) col++ } *row++ @@ -302,13 +302,13 @@ func renderXlsxTableMultiTarget(tableIdx int, allTargetsTableValues [][]TableVal for targetIdx, targetName := range targetNames { // print the target name col = 2 - f.SetCellValue(sheetName, cellName(col, *row), targetName) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), targetNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), targetName) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), targetNameStyle) *row++ // if no data found, print a message and skip to the next target if len(allTargetsTableValues[targetIdx][tableIdx].Fields) == 0 || len(allTargetsTableValues[targetIdx][tableIdx].Fields[0].Values) == 0 { - f.SetCellValue(sheetName, cellName(col, *row), noDataFound) + _ = f.SetCellValue(sheetName, cellName(col, *row), noDataFound) *row += 2 continue } @@ -316,8 +316,8 @@ func renderXlsxTableMultiTarget(tableIdx int, allTargetsTableValues [][]TableVal // print the field names as column headings across the top of the table col = 2 for _, field := range allTargetsTableValues[targetIdx][tableIdx].Fields { - f.SetCellValue(sheetName, cellName(col, *row), field.Name) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), fieldNameStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), field.Name) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), fieldNameStyle) col++ } *row++ @@ -327,7 +327,7 @@ func renderXlsxTableMultiTarget(tableIdx int, allTargetsTableValues [][]TableVal col = 2 for _, field := range allTargetsTableValues[targetIdx][tableIdx].Fields { value := getValueForCell(field.Values[tableRow]) - f.SetCellValue(sheetName, cellName(col, *row), value) + _ = f.SetCellValue(sheetName, cellName(col, *row), value) col++ } *row++ @@ -354,8 +354,8 @@ func DefaultXlsxTableRendererFunc(tableValues TableValues, f *excelize.File, she // print the field names as column headings across the top of the table col := 2 for _, field := range tableValues.Fields { - f.SetCellValue(sheetName, cellName(col, *row), field.Name) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), headerStyle) + _ = f.SetCellValue(sheetName, cellName(col, *row), field.Name) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), headerStyle) col++ } col = 2 @@ -365,8 +365,8 @@ func DefaultXlsxTableRendererFunc(tableValues TableValues, f *excelize.File, she for tableRow := 0; tableRow < tableRows; tableRow++ { for _, field := range tableValues.Fields { value := getValueForCell(field.Values[tableRow]) - f.SetCellValue(sheetName, cellName(col, *row), value) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), alignLeft) + _ = f.SetCellValue(sheetName, cellName(col, *row), value) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), alignLeft) col++ } col = 2 @@ -380,11 +380,11 @@ func DefaultXlsxTableRendererFunc(tableValues TableValues, f *excelize.File, she if len(tableValues.Fields[0].Values) > 0 { fieldValue = field.Values[0] } - f.SetCellValue(sheetName, cellName(col, *row), field.Name) + _ = f.SetCellValue(sheetName, cellName(col, *row), field.Name) col++ value := getValueForCell(fieldValue) - f.SetCellValue(sheetName, cellName(col, *row), value) - f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), alignLeft) + _ = f.SetCellValue(sheetName, cellName(col, *row), value) + _ = f.SetCellStyle(sheetName, cellName(col, *row), cellName(col, *row), alignLeft) col = 1 *row++ } @@ -399,16 +399,16 @@ const ( func createXlsxReport(allTableValues []TableValues) (out []byte, err error) { f := excelize.NewFile() sheetName := XlsxPrimarySheetName - f.SetSheetName("Sheet1", sheetName) - f.SetColWidth(sheetName, "A", "A", 25) - f.SetColWidth(sheetName, "B", "L", 25) + _ = f.SetSheetName("Sheet1", sheetName) + _ = f.SetColWidth(sheetName, "A", "A", 25) + _ = f.SetColWidth(sheetName, "B", "L", 25) row := 1 for _, tableValues := range allTableValues { if tableValues.Name == SystemSummaryTableName { row := 1 sheetName := XlsxBriefSheetName - f.NewSheet(sheetName) - f.SetColWidth(sheetName, "A", "L", 25) + _, _ = f.NewSheet(sheetName) + _ = f.SetColWidth(sheetName, "A", "L", 25) renderXlsxTable(tableValues, f, sheetName, &row) } else { renderXlsxTable(tableValues, f, sheetName, &row) @@ -428,17 +428,17 @@ func createXlsxReport(allTableValues []TableValues) (out []byte, err error) { func createXlsxReportMultiTarget(allTargetsTableValues [][]TableValues, targetNames []string) (out []byte, err error) { f := excelize.NewFile() sheetName := XlsxPrimarySheetName - f.SetSheetName("Sheet1", sheetName) - f.SetColWidth(sheetName, "A", "A", 15) - f.SetColWidth(sheetName, "B", "L", 25) + _ = f.SetSheetName("Sheet1", sheetName) + _ = f.SetColWidth(sheetName, "A", "A", 15) + _ = f.SetColWidth(sheetName, "B", "L", 25) row := 1 for tableIdx, tableValues := range allTargetsTableValues[0] { if tableValues.Name == SystemSummaryTableName { row := 1 sheetName := XlsxBriefSheetName - f.NewSheet(sheetName) - f.SetColWidth(sheetName, "A", "A", 15) - f.SetColWidth(sheetName, "B", "L", 25) + _, _ = f.NewSheet(sheetName) + _ = f.SetColWidth(sheetName, "A", "A", 15) + _ = f.SetColWidth(sheetName, "B", "L", 25) renderXlsxTableMultiTarget(tableIdx, allTargetsTableValues, targetNames, f, sheetName, &row) } else { renderXlsxTableMultiTarget(tableIdx, allTargetsTableValues, targetNames, f, sheetName, &row) diff --git a/internal/script/script.go b/internal/script/script.go index 25d8acf..4eacf29 100644 --- a/internal/script/script.go +++ b/internal/script/script.go @@ -124,7 +124,12 @@ func RunScripts(myTarget target.Target, scripts []ScriptDefinition, ignoreScript return nil, err } if len(installedLkms) > 0 { - defer myTarget.UninstallLkms(installedLkms) + defer func() { + err := myTarget.UninstallLkms(installedLkms) + if err != nil { + slog.Error("error uninstalling LKMs", slog.String("lkms", strings.Join(installedLkms, ", ")), slog.String("error", err.Error())) + } + }() } // if there's only 1 parallel script, run it sequentially @@ -237,7 +242,12 @@ func RunScriptAsync(myTarget target.Target, script ScriptDefinition, localTempDi return } if len(installedLkms) != 0 { - defer myTarget.UninstallLkms(installedLkms) + defer func() { + err := myTarget.UninstallLkms(installedLkms) + if err != nil { + slog.Error("error uninstalling LKMs", slog.String("lkms", strings.Join(installedLkms, ", ")), slog.String("error", err.Error())) + } + }() } cmd := prepareCommand(script, myTarget.GetTempDirectory()) err = myTarget.RunCommandAsync(cmd, stdoutChannel, stderrChannel, exitcodeChannel, script.Timeout, cmdChannel) diff --git a/internal/script/script_test.go b/internal/script/script_test.go index 3b33457..b3ea5c9 100644 --- a/internal/script/script_test.go +++ b/internal/script/script_test.go @@ -18,7 +18,12 @@ func TestRunScript(t *testing.T) { targets = append(targets, target.NewLocalTarget()) for _, tgt := range targets { targetTempDir, err := tgt.CreateTempDirectory("/tmp") - defer tgt.RemoveDirectory(targetTempDir) + defer func() { + err := tgt.RemoveDirectory(targetTempDir) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + }() if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/internal/target/target.go b/internal/target/target.go index ca7cd33..3e4331b 100644 --- a/internal/target/target.go +++ b/internal/target/target.go @@ -379,7 +379,10 @@ func (t *LocalTarget) CanElevatePrivileges() bool { stdin, _ := cmd.StdinPipe() go func() { defer stdin.Close() - io.WriteString(stdin, t.sudo+"\n") + _, err := io.WriteString(stdin, t.sudo+"\n") + if err != nil { + slog.Error("error writing sudo password", slog.String("error", err.Error())) + } }() _, _, _, err := t.RunCommand(cmd, 0) if err == nil {