Skip to content

Commit

Permalink
Enable ErrCheck (#5386)
Browse files Browse the repository at this point in the history
* Enable ErrCheck
  • Loading branch information
ogaca-dd committed May 14, 2020
1 parent d80e0e0 commit af24c65
Show file tree
Hide file tree
Showing 107 changed files with 259 additions and 243 deletions.
18 changes: 17 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ run:
- pkg/network

issues:
# Do not limit the number of issues per linter.
max-issues-per-linter: 0

# Do not limit the number of times a same issue is reported.
max-same-issues: 0

exclude:
- "`eventContext` is unused"
- "`\\(\\*DatadogLogger\\).changeLogLevel` is unused"
Expand All @@ -34,7 +40,11 @@ issues:
# ignore warning on linux about fields used only on windows
- "`context` is unused"
- "`id` is unused"

exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- errcheck

linters:
disable-all: true
Expand All @@ -47,3 +57,9 @@ linters:
- misspell # Finds commonly misspelled English words in comments
- gofmt # Gofmt checks whether code was gofmt-ed
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
- errcheck # errcheck is a program for checking for unchecked errors in go programs.

linters-settings:
errcheck:
# Disable warnings for `fmt` and `log` packages. Also ignore `Write` functions from `net/http` package.
ignore: fmt:.*,github.com/DataDog/datadog-agent/pkg/util/log:.*,net/http:Write
2 changes: 1 addition & 1 deletion cmd/agent/api/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ func setRuntimeConfig(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
setting := vars["setting"]
log.Infof("Got a request to change a setting: %s", setting)
r.ParseForm()
r.ParseForm() //nolint:errcheck
value := html.UnescapeString(r.Form.Get("value"))

if err := config.SetRuntimeSetting(setting, value); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/api/agent/agent_jmx.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func getJMXConfigs(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), 500)
return
}
w.Write(jsonPayload)
w.Write(jsonPayload) //nolint:errcheck
}

func setJMXStatus(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func StartServer() error {
}
tlsListener := tls.NewListener(listener, &tlsConfig)

go srv.Serve(tlsListener)
go srv.Serve(tlsListener) //nolint:errcheck
return nil
}

Expand Down
8 changes: 4 additions & 4 deletions cmd/agent/app/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func init() {
checkCmd.Flags().StringVarP(&breakPoint, "breakpoint", "b", "", "set a breakpoint at a particular line number (Python checks only)")
checkCmd.Flags().BoolVarP(&profileMemory, "profile-memory", "m", false, "run the memory profiler (Python checks only)")
checkCmd.Flags().BoolVar(&fullSketches, "full-sketches", false, "output sketches with bins information")
config.Datadog.BindPFlag("cmd.check.fullsketches", checkCmd.Flags().Lookup("full-sketches"))
config.Datadog.BindPFlag("cmd.check.fullsketches", checkCmd.Flags().Lookup("full-sketches")) //nolint:errcheck

// Power user flags - mark as hidden
createHiddenStringFlag(&profileMemoryDir, "m-dir", "", "an existing directory in which to store memory profiling data, ignoring clean-up")
Expand Down Expand Up @@ -104,7 +104,7 @@ var checkCmd = &cobra.Command{
if len(args) != 0 {
checkName = args[0]
} else {
cmd.Help()
cmd.Help() //nolint:errcheck
return nil
}

Expand Down Expand Up @@ -460,7 +460,7 @@ func getMetricsData(agg *aggregator.BufferedAggregator) map[string]interface{} {
// https://github.com/DataDog/datadog-agent/blob/b2d9527ec0ec0eba1a7ae64585df443c5b761610/pkg/metrics/series.go#L109-L122
var data map[string]interface{}
sj, _ := json.Marshal(series)
json.Unmarshal(sj, &data)
json.Unmarshal(sj, &data) //nolint:errcheck

aggData["metrics"] = data["series"]
}
Expand All @@ -487,7 +487,7 @@ func singleCheckRun() bool {

func createHiddenStringFlag(p *string, name string, value string, usage string) {
checkCmd.Flags().StringVar(p, name, value, usage)
checkCmd.Flags().MarkHidden(name)
checkCmd.Flags().MarkHidden(name) //nolint:errcheck
}

func populateMemoryProfileConfig(initConfig map[string]interface{}) error {
Expand Down
8 changes: 4 additions & 4 deletions cmd/agent/app/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func requestConfig() (string, error) {
r, err := util.DoGet(c, apiConfigURL)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
return "", fmt.Errorf(e)
Expand All @@ -125,7 +125,7 @@ func listRuntimeConfigurableValue(cmd *cobra.Command, args []string) error {
r, err := util.DoGet(c, url)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
return fmt.Errorf(e)
Expand Down Expand Up @@ -162,7 +162,7 @@ func setConfigValue(cmd *cobra.Command, args []string) error {
r, err := util.DoPost(c, url, "application/x-www-form-urlencoded", bytes.NewBuffer([]byte(body)))
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
return fmt.Errorf(e)
Expand Down Expand Up @@ -190,7 +190,7 @@ func getConfigValue(cmd *cobra.Command, args []string) error {
r, err := util.DoGet(c, url)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
return fmt.Errorf(e)
Expand Down
4 changes: 2 additions & 2 deletions cmd/agent/app/dogstatsd_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func requestDogstatsdStats() error {
r, e := util.DoGet(c, urlstr)
if e != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if err, found := errMap["error"]; found {
e = fmt.Errorf(err)
Expand All @@ -97,7 +97,7 @@ func requestDogstatsdStats() error {
// The rendering is done in the client so that the agent has less work to do
if prettyPrintJSON {
var prettyJSON bytes.Buffer
json.Indent(&prettyJSON, r, "", " ")
json.Indent(&prettyJSON, r, "", " ") //nolint:errcheck
s = prettyJSON.String()
} else if jsonStatus {
s = string(r)
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/app/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func requestHealth() error {
r, err := util.DoGet(c, urlstr)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
err = fmt.Errorf(e)
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/app/integrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func init() {
integrationCmd.PersistentFlags().StringVarP(&pythonMajorVersion, "python", "", "", "the version of Python to act upon (2 or 3). defaults to the python_version setting in datadog.yaml")

// Power user flags - mark as hidden
integrationCmd.PersistentFlags().MarkHidden("use-sys-python")
integrationCmd.PersistentFlags().MarkHidden("use-sys-python") //nolint:errcheck

showCmd.Flags().BoolVarP(&versionOnly, "show-version-only", "q", false, "only display version information")
installCmd.Flags().BoolVarP(
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/app/launchgui.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func launchGui(cmd *cobra.Command, args []string) error {
csrfToken, err := util.DoGet(c, urlstr)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(csrfToken, &errMap)
json.Unmarshal(csrfToken, &errMap) //nolint:errcheck
if e, found := errMap["error"]; found {
err = fmt.Errorf(e)
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/agent/app/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func StartAgent() error {
if config.Datadog.GetBool("telemetry.enabled") {
http.Handle("/telemetry", telemetry.Handler())
}
go http.ListenAndServe("127.0.0.1:"+port, http.DefaultServeMux)
go http.ListenAndServe("127.0.0.1:"+port, http.DefaultServeMux) //nolint:errcheck

// Setup healthcheck port
var healthPort = config.Datadog.GetInt("health_port")
Expand Down Expand Up @@ -249,7 +249,7 @@ func StartAgent() error {
}
common.Forwarder = forwarder.NewDefaultForwarder(forwarder.NewOptions(keysPerDomain))
log.Debugf("Starting forwarder")
common.Forwarder.Start()
common.Forwarder.Start() //nolint:errcheck
log.Debugf("Forwarder started")

agentName := "agent"
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/app/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func showSecretInfo() error {
r, err := util.DoGet(c, apiConfigURL)
if err != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if e, found := errMap["error"]; found {
return fmt.Errorf("%s", e)
Expand Down
4 changes: 2 additions & 2 deletions cmd/agent/app/standalone/jmx.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ func loadJMXConfigs(runner *jmxfetch.JMXFetch, selectedChecks []string) {
c.Instances = instances

jmx.AddScheduledConfig(c)
runner.ConfigureFromInitConfig(c.InitConfig)
runner.ConfigureFromInitConfig(c.InitConfig) //nolint:errcheck
for _, instance := range c.Instances {
runner.ConfigureFromInstance(instance)
runner.ConfigureFromInstance(instance) //nolint:errcheck
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions cmd/agent/app/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func requestStatus() error {
// The rendering is done in the client so that the agent has less work to do
if prettyPrintJSON {
var prettyJSON bytes.Buffer
json.Indent(&prettyJSON, r, "", " ")
json.Indent(&prettyJSON, r, "", " ") //nolint:errcheck
s = prettyJSON.String()
} else if jsonStatus {
s = string(r)
Expand All @@ -125,7 +125,7 @@ func requestStatus() error {
}

if statusFilePath != "" {
ioutil.WriteFile(statusFilePath, []byte(s), 0644)
ioutil.WriteFile(statusFilePath, []byte(s), 0644) //nolint:errcheck
} else {
fmt.Println(s)
}
Expand Down Expand Up @@ -180,14 +180,14 @@ func componentStatus(component string) error {
// The rendering is done in the client so that the agent has less work to do
if prettyPrintJSON {
var prettyJSON bytes.Buffer
json.Indent(&prettyJSON, r, "", " ")
json.Indent(&prettyJSON, r, "", " ") //nolint:errcheck
s = prettyJSON.String()
} else {
s = string(r)
}

if statusFilePath != "" {
ioutil.WriteFile(statusFilePath, []byte(s), 0644)
ioutil.WriteFile(statusFilePath, []byte(s), 0644) //nolint:errcheck
} else {
fmt.Println(s)
}
Expand All @@ -208,7 +208,7 @@ func makeRequest(url string) ([]byte, error) {
r, e := util.DoGet(c, url)
if e != nil {
var errMap = make(map[string]string)
json.Unmarshal(r, &errMap)
json.Unmarshal(r, &errMap) //nolint:errcheck
// If the error has been marshalled into a json object, check it and return it properly
if err, found := errMap["error"]; found {
e = fmt.Errorf(err)
Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/clcrunnerapi/clc_runner_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func StartCLCRunnerServer() error {
}
tlsListener := tls.NewListener(clcListener, &tlsConfig)

go srv.Serve(tlsListener)
go srv.Serve(tlsListener) //nolint:errcheck
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/common/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ func copyFile(src, dst string, overwrite bool, transformations []TransformationF
}
}

ioutil.WriteFile(dst, data, 0640)
ioutil.WriteFile(dst, data, 0640) //nolint:errcheck

ddGroup, errGroup := user.LookupGroup("dd-agent")
ddUser, errUser := user.LookupId("dd-agent")
Expand Down
6 changes: 3 additions & 3 deletions cmd/agent/gui/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func runCheck(w http.ResponseWriter, r *http.Request) {
instances := collector.GetChecksByNameForConfigs(name, common.AC.GetAllConfigs())

for _, ch := range instances {
common.Coll.RunCheck(ch)
common.Coll.RunCheck(ch) //nolint:errcheck
}
log.Infof("Scheduled new check: " + name)
w.Write([]byte("Scheduled new check:" + name))
Expand Down Expand Up @@ -223,13 +223,13 @@ func setCheckConfigFile(w http.ResponseWriter, r *http.Request) {

// Attempt to write new configs to custom checks directory
path := filepath.Join(checkConfFolderPath, fileName)
os.MkdirAll(checkConfFolderPath, os.FileMode(0755))
os.MkdirAll(checkConfFolderPath, os.FileMode(0755)) //nolint:errcheck
e = ioutil.WriteFile(path, data, 0600)

// If the write didn't work, try writing to the default checks directory
if e != nil && strings.Contains(e.Error(), "no such file or directory") {
path = filepath.Join(defaultCheckConfFolderPath, fileName)
os.MkdirAll(defaultCheckConfFolderPath, os.FileMode(0755))
os.MkdirAll(defaultCheckConfFolderPath, os.FileMode(0755)) //nolint:errcheck
e = ioutil.WriteFile(path, data, 0600)
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/agent/gui/gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func StartGUIServer(port string) error {
if e != nil {
return e
}
go http.Serve(listener, router)
go http.Serve(listener, router) //nolint:errcheck
log.Infof("GUI server is listening at 127.0.0.1:" + port)

// Create a CSRF token (unique to each session)
Expand Down
4 changes: 2 additions & 2 deletions cmd/agent/gui/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type Data struct {
func renderStatus(rawData []byte, request string) (string, error) {
var b = new(bytes.Buffer)
stats := make(map[string]interface{})
json.Unmarshal(rawData, &stats)
json.Unmarshal(rawData, &stats) //nolint:errcheck

data := Data{Stats: stats}
e := fillTemplate(b, data, request+"Status")
Expand All @@ -50,7 +50,7 @@ func renderRunningChecks() (string, error) {

runnerStatsJSON := []byte(expvar.Get("runner").String())
runnerStats := make(map[string]interface{})
json.Unmarshal(runnerStatsJSON, &runnerStats)
json.Unmarshal(runnerStatsJSON, &runnerStats) //nolint:errcheck
loaderErrs := collector.GetLoaderErrors()
configErrs := autodiscovery.GetConfigErrors()

Expand Down
2 changes: 1 addition & 1 deletion cmd/cluster-agent-cloudfoundry/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ func run(cmd *cobra.Command, args []string) error {
log.Error("Misconfiguration of agent endpoints: ", err)
}
f := forwarder.NewDefaultForwarder(forwarder.NewOptions(keysPerDomain))
f.Start()
f.Start() //nolint:errcheck
s := serializer.NewSerializer(f)

aggregatorInstance := aggregator.InitAggregator(s, hostname, aggregator.ClusterAgentName)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cluster-agent/admission/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func RunServer(mainCtx context.Context) error {
}
go func() error {
return log.Error(server.ListenAndServeTLS("", ""))
}()
}() //nolint:errcheck

<-mainCtx.Done()

Expand Down
6 changes: 3 additions & 3 deletions cmd/cluster-agent/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ func StartServer(sc clusteragent.ServerContext) error {
return fmt.Errorf("Unable to create the api server: %v", err)
}
// Internal token
util.CreateAndSetAuthToken()
util.CreateAndSetAuthToken() //nolint:errcheck

// DCA client token
util.InitDCAAuthToken()
util.InitDCAAuthToken() //nolint:errcheck

// create cert
hosts := []string{"127.0.0.1", "localhost"}
Expand Down Expand Up @@ -90,7 +90,7 @@ func StartServer(sc clusteragent.ServerContext) error {

tlsListener := tls.NewListener(listener, &tlsConfig)

go srv.Serve(tlsListener)
go srv.Serve(tlsListener) //nolint:errcheck
return nil
}

Expand Down
Loading

0 comments on commit af24c65

Please sign in to comment.