Commit 574553ec by Arve Knudsen Committed by GitHub

Chore: Fix issues found by staticcheck (#28802)

* Fix linting issues

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent dff84f6a
...@@ -50,20 +50,20 @@ func New(hash string) *Avatar { ...@@ -50,20 +50,20 @@ func New(hash string) *Avatar {
} }
} }
func (this *Avatar) Expired() bool { func (a *Avatar) Expired() bool {
return time.Since(this.timestamp) > (time.Minute * 10) return time.Since(a.timestamp) > (time.Minute * 10)
} }
func (this *Avatar) Encode(wr io.Writer) error { func (a *Avatar) Encode(wr io.Writer) error {
_, err := wr.Write(this.data.Bytes()) _, err := wr.Write(a.data.Bytes())
return err return err
} }
func (this *Avatar) Update() (err error) { func (a *Avatar) Update() (err error) {
select { select {
case <-time.After(time.Second * 3): case <-time.After(time.Second * 3):
err = fmt.Errorf("get gravatar image %s timeout", this.hash) err = fmt.Errorf("get gravatar image %s timeout", a.hash)
case err = <-thunder.GoFetch(gravatarSource+this.hash+"?"+this.reqParams, this): case err = <-thunder.GoFetch(gravatarSource+a.hash+"?"+a.reqParams, a):
} }
return err return err
} }
...@@ -75,7 +75,7 @@ type CacheServer struct { ...@@ -75,7 +75,7 @@ type CacheServer struct {
var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$") var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$")
func (this *CacheServer) Handler(ctx *models.ReqContext) { func (a *CacheServer) Handler(ctx *models.ReqContext) {
hash := ctx.Params("hash") hash := ctx.Params("hash")
if len(hash) != 32 || !validMD5.MatchString(hash) { if len(hash) != 32 || !validMD5.MatchString(hash) {
...@@ -84,7 +84,7 @@ func (this *CacheServer) Handler(ctx *models.ReqContext) { ...@@ -84,7 +84,7 @@ func (this *CacheServer) Handler(ctx *models.ReqContext) {
} }
var avatar *Avatar var avatar *Avatar
obj, exists := this.cache.Get(hash) obj, exists := a.cache.Get(hash)
if exists { if exists {
avatar = obj.(*Avatar) avatar = obj.(*Avatar)
} else { } else {
...@@ -95,14 +95,14 @@ func (this *CacheServer) Handler(ctx *models.ReqContext) { ...@@ -95,14 +95,14 @@ func (this *CacheServer) Handler(ctx *models.ReqContext) {
// The cache item is either expired or newly created, update it from the server // The cache item is either expired or newly created, update it from the server
if err := avatar.Update(); err != nil { if err := avatar.Update(); err != nil {
log.Tracef("avatar update error: %v", err) log.Tracef("avatar update error: %v", err)
avatar = this.notFound avatar = a.notFound
} }
} }
if avatar.notFound { if avatar.notFound {
avatar = this.notFound avatar = a.notFound
} else if !exists { } else if !exists {
if err := this.cache.Add(hash, avatar, gocache.DefaultExpiration); err != nil { if err := a.cache.Add(hash, avatar, gocache.DefaultExpiration); err != nil {
log.Tracef("Error adding avatar to cache: %s", err) log.Tracef("Error adding avatar to cache: %s", err)
} }
} }
...@@ -195,9 +195,9 @@ type thunderTask struct { ...@@ -195,9 +195,9 @@ type thunderTask struct {
err error err error
} }
func (this *thunderTask) Fetch() { func (a *thunderTask) Fetch() {
this.err = this.fetch() a.err = a.fetch()
this.Done() a.Done()
} }
var client = &http.Client{ var client = &http.Client{
...@@ -205,11 +205,11 @@ var client = &http.Client{ ...@@ -205,11 +205,11 @@ var client = &http.Client{
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
} }
func (this *thunderTask) fetch() error { func (a *thunderTask) fetch() error {
this.Avatar.timestamp = time.Now() a.Avatar.timestamp = time.Now()
log.Debugf("avatar.fetch(fetch new avatar): %s", this.Url) log.Debugf("avatar.fetch(fetch new avatar): %s", a.Url)
req, _ := http.NewRequest("GET", this.Url, nil) req, _ := http.NewRequest("GET", a.Url, nil)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8") req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8")
req.Header.Set("Accept-Encoding", "deflate,sdch") req.Header.Set("Accept-Encoding", "deflate,sdch")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
...@@ -217,19 +217,19 @@ func (this *thunderTask) fetch() error { ...@@ -217,19 +217,19 @@ func (this *thunderTask) fetch() error {
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36")
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
this.Avatar.notFound = true a.Avatar.notFound = true
return fmt.Errorf("gravatar unreachable, %v", err) return fmt.Errorf("gravatar unreachable, %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
this.Avatar.notFound = true a.Avatar.notFound = true
return fmt.Errorf("status code: %d", resp.StatusCode) return fmt.Errorf("status code: %d", resp.StatusCode)
} }
this.Avatar.data = &bytes.Buffer{} a.Avatar.data = &bytes.Buffer{}
writer := bufio.NewWriter(this.Avatar.data) writer := bufio.NewWriter(a.Avatar.data)
_, err = io.Copy(writer, resp.Body) _, err = io.Copy(writer, resp.Body)
return err return err
......
...@@ -179,7 +179,7 @@ func (e *ApplicationInsightsDatasource) executeQuery(ctx context.Context, query ...@@ -179,7 +179,7 @@ func (e *ApplicationInsightsDatasource) executeQuery(ctx context.Context, query
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
azlog.Debug("Request failed", "status", res.Status, "body", string(body)) azlog.Debug("Request failed", "status", res.Status, "body", string(body))
return nil, fmt.Errorf("Request failed status: %v", res.Status) return nil, fmt.Errorf("request failed, status: %s", res.Status)
} }
mr := MetricsResult{} mr := MetricsResult{}
...@@ -204,7 +204,7 @@ func (e *ApplicationInsightsDatasource) createRequest(ctx context.Context, dsInf ...@@ -204,7 +204,7 @@ func (e *ApplicationInsightsDatasource) createRequest(ctx context.Context, dsInf
// find plugin // find plugin
plugin, ok := plugins.DataSources[dsInfo.Type] plugin, ok := plugins.DataSources[dsInfo.Type]
if !ok { if !ok {
return nil, errors.New("Unable to find datasource plugin Azure Application Insights") return nil, errors.New("unable to find datasource plugin Azure Application Insights")
} }
cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor") cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor")
......
...@@ -207,7 +207,7 @@ func (e *AzureLogAnalyticsDatasource) createRequest(ctx context.Context, dsInfo ...@@ -207,7 +207,7 @@ func (e *AzureLogAnalyticsDatasource) createRequest(ctx context.Context, dsInfo
req, err := http.NewRequest(http.MethodGet, u.String(), nil) req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil { if err != nil {
azlog.Debug("Failed to create request", "error", err) azlog.Debug("Failed to create request", "error", err)
return nil, errutil.Wrap("Failed to create request", err) return nil, errutil.Wrap("failed to create request", err)
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
...@@ -216,7 +216,7 @@ func (e *AzureLogAnalyticsDatasource) createRequest(ctx context.Context, dsInfo ...@@ -216,7 +216,7 @@ func (e *AzureLogAnalyticsDatasource) createRequest(ctx context.Context, dsInfo
// find plugin // find plugin
plugin, ok := plugins.DataSources[dsInfo.Type] plugin, ok := plugins.DataSources[dsInfo.Type]
if !ok { if !ok {
return nil, errors.New("Unable to find datasource plugin Azure Monitor") return nil, errors.New("unable to find datasource plugin Azure Monitor")
} }
cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor") cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor")
...@@ -272,7 +272,7 @@ func (e *AzureLogAnalyticsDatasource) unmarshalResponse(res *http.Response) (Azu ...@@ -272,7 +272,7 @@ func (e *AzureLogAnalyticsDatasource) unmarshalResponse(res *http.Response) (Azu
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
azlog.Debug("Request failed", "status", res.Status, "body", string(body)) azlog.Debug("Request failed", "status", res.Status, "body", string(body))
return AzureLogAnalyticsResponse{}, fmt.Errorf("Request failed status: %v: %w", res.Status, fmt.Errorf(string(body))) return AzureLogAnalyticsResponse{}, fmt.Errorf("request failed, status: %s, body: %s", res.Status, string(body))
} }
var data AzureLogAnalyticsResponse var data AzureLogAnalyticsResponse
......
...@@ -220,7 +220,7 @@ func (e *AzureMonitorDatasource) createRequest(ctx context.Context, dsInfo *mode ...@@ -220,7 +220,7 @@ func (e *AzureMonitorDatasource) createRequest(ctx context.Context, dsInfo *mode
// find plugin // find plugin
plugin, ok := plugins.DataSources[dsInfo.Type] plugin, ok := plugins.DataSources[dsInfo.Type]
if !ok { if !ok {
return nil, errors.New("Unable to find datasource plugin Azure Monitor") return nil, errors.New("unable to find datasource plugin Azure Monitor")
} }
cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor") cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor")
...@@ -263,7 +263,7 @@ func (e *AzureMonitorDatasource) unmarshalResponse(res *http.Response) (AzureMon ...@@ -263,7 +263,7 @@ func (e *AzureMonitorDatasource) unmarshalResponse(res *http.Response) (AzureMon
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
azlog.Debug("Request failed", "status", res.Status, "body", string(body)) azlog.Debug("Request failed", "status", res.Status, "body", string(body))
return AzureMonitorResponse{}, fmt.Errorf("Request failed status: %v", res.Status) return AzureMonitorResponse{}, fmt.Errorf("request failed, status: %s", res.Status)
} }
var data AzureMonitorResponse var data AzureMonitorResponse
......
...@@ -66,7 +66,7 @@ func (e *AzureMonitorExecutor) Query(ctx context.Context, dsInfo *models.DataSou ...@@ -66,7 +66,7 @@ func (e *AzureMonitorExecutor) Query(ctx context.Context, dsInfo *models.DataSou
case "Insights Analytics": case "Insights Analytics":
insightsAnalyticsQueries = append(insightsAnalyticsQueries, query) insightsAnalyticsQueries = append(insightsAnalyticsQueries, query)
default: default:
return nil, fmt.Errorf("Alerting not supported for %s", queryType) return nil, fmt.Errorf("alerting not supported for %q", queryType)
} }
} }
......
...@@ -139,7 +139,7 @@ func (e *InsightsAnalyticsDatasource) executeQuery(ctx context.Context, query *I ...@@ -139,7 +139,7 @@ func (e *InsightsAnalyticsDatasource) executeQuery(ctx context.Context, query *I
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
azlog.Debug("Request failed", "status", res.Status, "body", string(body)) azlog.Debug("Request failed", "status", res.Status, "body", string(body))
return queryResultError(fmt.Errorf("Request failed status: %v %w", res.Status, fmt.Errorf(string(body)))) return queryResultError(fmt.Errorf("request failed, status: %s, body: %s", res.Status, body))
} }
var logResponse AzureLogAnalyticsResponse var logResponse AzureLogAnalyticsResponse
d := json.NewDecoder(bytes.NewReader(body)) d := json.NewDecoder(bytes.NewReader(body))
...@@ -180,7 +180,7 @@ func (e *InsightsAnalyticsDatasource) createRequest(ctx context.Context, dsInfo ...@@ -180,7 +180,7 @@ func (e *InsightsAnalyticsDatasource) createRequest(ctx context.Context, dsInfo
// find plugin // find plugin
plugin, ok := plugins.DataSources[dsInfo.Type] plugin, ok := plugins.DataSources[dsInfo.Type]
if !ok { if !ok {
return nil, errors.New("Unable to find datasource plugin Azure Application Insights") return nil, errors.New("unable to find datasource plugin Azure Application Insights")
} }
cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor") cloudName := dsInfo.JsonData.Get("cloudName").MustString("azuremonitor")
......
...@@ -126,7 +126,7 @@ func (m *kqlMacroEngine) evaluateMacro(name string, defaultTimeField string, arg ...@@ -126,7 +126,7 @@ func (m *kqlMacroEngine) evaluateMacro(name string, defaultTimeField string, arg
case "escapeMulti": case "escapeMulti":
return "", fmt.Errorf("escapeMulti macro not formatted correctly") return "", fmt.Errorf("escapeMulti macro not formatted correctly")
default: default:
return "", fmt.Errorf("Unknown macro %v", name) return "", fmt.Errorf("unknown macro %q", name)
} }
} }
......
...@@ -28,7 +28,7 @@ func (tg *TimeGrain) createISO8601DurationFromIntervalMS(interval int64) (string ...@@ -28,7 +28,7 @@ func (tg *TimeGrain) createISO8601DurationFromIntervalMS(interval int64) (string
timeValueString := formatted[0 : len(formatted)-1] timeValueString := formatted[0 : len(formatted)-1]
timeValue, err := strconv.Atoi(timeValueString) timeValue, err := strconv.Atoi(timeValueString)
if err != nil { if err != nil {
return "", fmt.Errorf("Could not parse interval %v to an ISO 8061 duration", interval) return "", fmt.Errorf("could not parse interval %q to an ISO 8061 duration: %w", interval, err)
} }
unit := formatted[len(formatted)-1:] unit := formatted[len(formatted)-1:]
......
...@@ -103,7 +103,7 @@ func (e *CloudMonitoringExecutor) getGCEDefaultProject(ctx context.Context, tsdb ...@@ -103,7 +103,7 @@ func (e *CloudMonitoringExecutor) getGCEDefaultProject(ctx context.Context, tsdb
gceDefaultProject, err := e.getDefaultProject(ctx) gceDefaultProject, err := e.getDefaultProject(ctx)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to retrieve default project from GCE metadata server. error: %v", err) return nil, fmt.Errorf("failed to retrieve default project from GCE metadata server, error: %w", err)
} }
queryResult.Meta.Set("defaultProject", gceDefaultProject) queryResult.Meta.Set("defaultProject", gceDefaultProject)
...@@ -769,7 +769,7 @@ func (e *CloudMonitoringExecutor) createRequest(ctx context.Context, dsInfo *mod ...@@ -769,7 +769,7 @@ func (e *CloudMonitoringExecutor) createRequest(ctx context.Context, dsInfo *mod
req, err := http.NewRequest(http.MethodGet, "https://monitoring.googleapis.com/", nil) req, err := http.NewRequest(http.MethodGet, "https://monitoring.googleapis.com/", nil)
if err != nil { if err != nil {
slog.Error("Failed to create request", "error", err) slog.Error("Failed to create request", "error", err)
return nil, fmt.Errorf("Failed to create request. error: %v", err) return nil, fmt.Errorf("failed to create request: %w", err)
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
...@@ -778,7 +778,7 @@ func (e *CloudMonitoringExecutor) createRequest(ctx context.Context, dsInfo *mod ...@@ -778,7 +778,7 @@ func (e *CloudMonitoringExecutor) createRequest(ctx context.Context, dsInfo *mod
// find plugin // find plugin
plugin, ok := plugins.DataSources[dsInfo.Type] plugin, ok := plugins.DataSources[dsInfo.Type]
if !ok { if !ok {
return nil, errors.New("Unable to find datasource plugin CloudMonitoring") return nil, errors.New("unable to find datasource plugin CloudMonitoring")
} }
var cloudMonitoringRoute *plugins.AppPluginRoute var cloudMonitoringRoute *plugins.AppPluginRoute
...@@ -799,14 +799,14 @@ func (e *CloudMonitoringExecutor) getDefaultProject(ctx context.Context) (string ...@@ -799,14 +799,14 @@ func (e *CloudMonitoringExecutor) getDefaultProject(ctx context.Context) (string
if authenticationType == gceAuthentication { if authenticationType == gceAuthentication {
defaultCredentials, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/monitoring.read") defaultCredentials, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/monitoring.read")
if err != nil { if err != nil {
return "", fmt.Errorf("Failed to retrieve default project from GCE metadata server. error: %v", err) return "", fmt.Errorf("failed to retrieve default project from GCE metadata server: %w", err)
} }
token, err := defaultCredentials.TokenSource.Token() token, err := defaultCredentials.TokenSource.Token()
if err != nil { if err != nil {
return "", fmt.Errorf("Failed to retrieve GCP credential token. error: %v", err) return "", fmt.Errorf("failed to retrieve GCP credential token: %w", err)
} }
if !token.Valid() { if !token.Valid() {
return "", errors.New("Failed to validate GCP credentials") return "", errors.New("failed to validate GCP credentials")
} }
return defaultCredentials.ProjectID, nil return defaultCredentials.ProjectID, nil
......
...@@ -68,7 +68,7 @@ func (e *GraphiteExecutor) Query(ctx context.Context, dsInfo *models.DataSource, ...@@ -68,7 +68,7 @@ func (e *GraphiteExecutor) Query(ctx context.Context, dsInfo *models.DataSource,
if target == "" { if target == "" {
glog.Error("No targets in query model", "models without targets", strings.Join(emptyQueries, "\n")) glog.Error("No targets in query model", "models without targets", strings.Join(emptyQueries, "\n"))
return nil, errors.New("No query target found for the alert rule") return nil, errors.New("no query target found for the alert rule")
} }
formData["target"] = []string{target} formData["target"] = []string{target}
...@@ -140,7 +140,7 @@ func (e *GraphiteExecutor) parseResponse(res *http.Response) ([]TargetResponseDT ...@@ -140,7 +140,7 @@ func (e *GraphiteExecutor) parseResponse(res *http.Response) ([]TargetResponseDT
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
glog.Info("Request failed", "status", res.Status, "body", string(body)) glog.Info("Request failed", "status", res.Status, "body", string(body))
return nil, fmt.Errorf("Request failed status: %v", res.Status) return nil, fmt.Errorf("request failed, status: %s", res.Status)
} }
var data []TargetResponseDTO var data []TargetResponseDTO
...@@ -163,7 +163,7 @@ func (e *GraphiteExecutor) createRequest(dsInfo *models.DataSource, data url.Val ...@@ -163,7 +163,7 @@ func (e *GraphiteExecutor) createRequest(dsInfo *models.DataSource, data url.Val
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(data.Encode())) req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(data.Encode()))
if err != nil { if err != nil {
glog.Info("Failed to create request", "error", err) glog.Info("Failed to create request", "error", err)
return nil, fmt.Errorf("Failed to create request. error: %v", err) return nil, fmt.Errorf("failed to create request: %w", err)
} }
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
......
...@@ -125,7 +125,7 @@ func (fb *frameBuilder) Init(metadata *query.FluxTableMetadata) error { ...@@ -125,7 +125,7 @@ func (fb *frameBuilder) Init(metadata *query.FluxTableMetadata) error {
if col != nil { if col != nil {
fb.timeColumn = col.Name() fb.timeColumn = col.Name()
fb.timeDisplay = "Time" fb.timeDisplay = "Time"
if "_time" != fb.timeColumn { if fb.timeColumn != "_time" {
fb.timeDisplay = col.Name() fb.timeDisplay = col.Name()
} }
return nil return nil
......
...@@ -85,7 +85,7 @@ func (e *InfluxDBExecutor) Query(ctx context.Context, dsInfo *models.DataSource, ...@@ -85,7 +85,7 @@ func (e *InfluxDBExecutor) Query(ctx context.Context, dsInfo *models.DataSource,
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode/100 != 2 { if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("Influxdb returned statuscode invalid status code: %v", resp.Status) return nil, fmt.Errorf("InfluxDB returned statuscode invalid status code: %s", resp.Status)
} }
var response Response var response Response
......
...@@ -129,6 +129,6 @@ func (m *msSqlMacroEngine) evaluateMacro(name string, args []string) (string, er ...@@ -129,6 +129,6 @@ func (m *msSqlMacroEngine) evaluateMacro(name string, args []string) (string, er
} }
return "", err return "", err
default: default:
return "", fmt.Errorf("Unknown macro %v", name) return "", fmt.Errorf("unknown macro %q", name)
} }
} }
...@@ -35,7 +35,7 @@ func (m *mySqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRa ...@@ -35,7 +35,7 @@ func (m *mySqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRa
matches := restrictedRegExp.FindAllStringSubmatch(sql, 1) matches := restrictedRegExp.FindAllStringSubmatch(sql, 1)
if len(matches) > 0 { if len(matches) > 0 {
m.logger.Error("show grants, session_user(), current_user(), system_user() or user() not allowed in query") m.logger.Error("show grants, session_user(), current_user(), system_user() or user() not allowed in query")
return "", errors.New("Invalid query. Inspect Grafana server log for details") return "", errors.New("invalid query - inspect Grafana server log for details")
} }
rExp, _ := regexp.Compile(sExpr) rExp, _ := regexp.Compile(sExpr)
...@@ -135,6 +135,6 @@ func (m *mySqlMacroEngine) evaluateMacro(name string, args []string) (string, er ...@@ -135,6 +135,6 @@ func (m *mySqlMacroEngine) evaluateMacro(name string, args []string) (string, er
} }
return "", err return "", err
default: default:
return "", fmt.Errorf("Unknown macro %v", name) return "", fmt.Errorf("unknown macro %v", name)
} }
} }
...@@ -181,7 +181,7 @@ func TestMacroEngine(t *testing.T) { ...@@ -181,7 +181,7 @@ func TestMacroEngine(t *testing.T) {
for _, tc := range tcs { for _, tc := range tcs {
_, err := engine.Interpolate(nil, nil, tc) _, err := engine.Interpolate(nil, nil, tc)
So(err.Error(), ShouldEqual, "Invalid query. Inspect Grafana server log for details") So(err.Error(), ShouldEqual, "invalid query - inspect Grafana server log for details")
} }
}) })
}) })
......
...@@ -150,4 +150,4 @@ func (t *mysqlQueryResultTransformer) TransformQueryError(err error) error { ...@@ -150,4 +150,4 @@ func (t *mysqlQueryResultTransformer) TransformQueryError(err error) error {
return err return err
} }
var errQueryFailed = errors.New("Query failed. Please inspect Grafana server log for details") var errQueryFailed = errors.New("query failed - please inspect Grafana server log for details")
...@@ -88,13 +88,13 @@ func (e *OpenTsdbExecutor) createRequest(dsInfo *models.DataSource, data OpenTsd ...@@ -88,13 +88,13 @@ func (e *OpenTsdbExecutor) createRequest(dsInfo *models.DataSource, data OpenTsd
postData, err := json.Marshal(data) postData, err := json.Marshal(data)
if err != nil { if err != nil {
plog.Info("Failed marshaling data", "error", err) plog.Info("Failed marshaling data", "error", err)
return nil, fmt.Errorf("Failed to create request. error: %v", err) return nil, fmt.Errorf("failed to create request: %w", err)
} }
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(string(postData))) req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(string(postData)))
if err != nil { if err != nil {
plog.Info("Failed to create request", "error", err) plog.Info("Failed to create request", "error", err)
return nil, fmt.Errorf("Failed to create request. error: %v", err) return nil, fmt.Errorf("failed to create request: %w", err)
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
...@@ -117,7 +117,7 @@ func (e *OpenTsdbExecutor) parseResponse(query OpenTsdbQuery, res *http.Response ...@@ -117,7 +117,7 @@ func (e *OpenTsdbExecutor) parseResponse(query OpenTsdbQuery, res *http.Response
if res.StatusCode/100 != 2 { if res.StatusCode/100 != 2 {
plog.Info("Request failed", "status", res.Status, "body", string(body)) plog.Info("Request failed", "status", res.Status, "body", string(body))
return nil, fmt.Errorf("Request failed status: %v", res.Status) return nil, fmt.Errorf("request failed, status: %s", res.Status)
} }
var data []OpenTsdbResponse var data []OpenTsdbResponse
......
...@@ -159,6 +159,6 @@ func (m *postgresMacroEngine) evaluateMacro(name string, args []string) (string, ...@@ -159,6 +159,6 @@ func (m *postgresMacroEngine) evaluateMacro(name string, args []string) (string,
} }
return "", err return "", err
default: default:
return "", fmt.Errorf("Unknown macro %v", name) return "", fmt.Errorf("unknown macro %q", name)
} }
} }
...@@ -193,7 +193,7 @@ func parseResponse(value model.Value, query *PrometheusQuery) (*tsdb.QueryResult ...@@ -193,7 +193,7 @@ func parseResponse(value model.Value, query *PrometheusQuery) (*tsdb.QueryResult
data, ok := value.(model.Matrix) data, ok := value.(model.Matrix)
if !ok { if !ok {
return queryRes, fmt.Errorf("Unsupported result format: %s", value.Type().String()) return queryRes, fmt.Errorf("unsupported result format: %q", value.Type().String())
} }
for _, v := range data { for _, v := range data {
......
...@@ -343,7 +343,7 @@ func (e *sqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core.R ...@@ -343,7 +343,7 @@ func (e *sqlQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core.R
} }
if cfg.timeIndex == -1 { if cfg.timeIndex == -1 {
return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or ")) return fmt.Errorf("found no column named %q", strings.Join(e.timeColumnNames, " or "))
} }
if cfg.fillMissing { if cfg.fillMissing {
...@@ -666,7 +666,10 @@ func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (n ...@@ -666,7 +666,10 @@ func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (n
case nil: case nil:
value.Valid = false value.Valid = false
default: default:
return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue) return null.NewFloat(0, false), fmt.Errorf(
"value column must have numeric datatype, column: %s, type: %T, value: %v",
columnName, typedValue, typedValue,
)
} }
return value, nil return value, nil
......
...@@ -57,7 +57,7 @@ func DecodeBasicAuthHeader(header string) (string, string, error) { ...@@ -57,7 +57,7 @@ func DecodeBasicAuthHeader(header string) (string, string, error) {
userAndPass := strings.SplitN(string(decoded), ":", 2) userAndPass := strings.SplitN(string(decoded), ":", 2)
if len(userAndPass) != 2 { if len(userAndPass) != 2 {
return "", "", errors.New("Invalid basic auth header") return "", "", errors.New("invalid basic auth header")
} }
return userAndPass[0], userAndPass[1], nil return userAndPass[0], userAndPass[1], nil
......
...@@ -63,7 +63,7 @@ func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollow ...@@ -63,7 +63,7 @@ func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollow
// vout("SymLink Path: %v, links to: %v", resolvedPath, path2) // vout("SymLink Path: %v, links to: %v", resolvedPath, path2)
if symlinkPathsFollowed != nil { if symlinkPathsFollowed != nil {
if _, ok := symlinkPathsFollowed[path2]; ok { if _, ok := symlinkPathsFollowed[path2]; ok {
errMsg := "Potential SymLink Infinite Loop. Path: %v, Link To: %v" errMsg := "potential symLink infinite loop, path: %v, link to: %v"
return fmt.Errorf(errMsg, resolvedPath, path2) return fmt.Errorf(errMsg, resolvedPath, path2)
} }
symlinkPathsFollowed[path2] = true symlinkPathsFollowed[path2] = true
......
...@@ -53,7 +53,7 @@ func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddres ...@@ -53,7 +53,7 @@ func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddres
addrEnd := strings.LastIndex(input, "]") addrEnd := strings.LastIndex(input, "]")
if addrEnd < 0 { if addrEnd < 0 {
// Malformed address // Malformed address
return addr, fmt.Errorf("Malformed IPv6 address: '%s'", input) return addr, fmt.Errorf("malformed IPv6 address: '%s'", input)
} }
start = addrEnd start = addrEnd
...@@ -83,7 +83,7 @@ func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddres ...@@ -83,7 +83,7 @@ func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddres
// SplitHostPort splits ip address/hostname string by host and port // SplitHostPort splits ip address/hostname string by host and port
func SplitHostPort(input string) (NetworkAddress, error) { func SplitHostPort(input string) (NetworkAddress, error) {
if len(input) == 0 { if len(input) == 0 {
return NetworkAddress{}, fmt.Errorf("Input is empty") return NetworkAddress{}, fmt.Errorf("input is empty")
} }
return SplitHostPortDefault(input, "", "") return SplitHostPortDefault(input, "", "")
} }
...@@ -32,7 +32,7 @@ func TestParseIPAddress_Invalid(t *testing.T) { ...@@ -32,7 +32,7 @@ func TestParseIPAddress_Invalid(t *testing.T) {
}{ }{
{ {
input: "[::1", input: "[::1",
err: "failed to split network address \"[::1\" by host and port: Malformed IPv6 address: '[::1'", err: "failed to split network address \"[::1\" by host and port: malformed IPv6 address: '[::1'",
}, },
{ {
input: "::1]", input: "::1]",
...@@ -40,7 +40,7 @@ func TestParseIPAddress_Invalid(t *testing.T) { ...@@ -40,7 +40,7 @@ func TestParseIPAddress_Invalid(t *testing.T) {
}, },
{ {
input: "", input: "",
err: "failed to split network address \"\" by host and port: Input is empty", err: "failed to split network address \"\" by host and port: input is empty",
}, },
} }
for _, testcase := range tests { for _, testcase := range tests {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment