diff --git a/Makefile b/Makefile index b4cc0eef9..6d407ddb7 100644 --- a/Makefile +++ b/Makefile @@ -14,13 +14,8 @@ include Makefile.common STATICCHECK_IGNORE = \ - github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go:SA1019 \ - github.com/prometheus/prometheus/discovery/kubernetes/node.go:SA1019 \ - github.com/prometheus/prometheus/documentation/examples/remote_storage/remote_storage_adapter/main.go:SA1019 \ github.com/prometheus/prometheus/pkg/textparse/promlex.l.go:SA4006 \ github.com/prometheus/prometheus/pkg/textparse/openmetricslex.l.go:SA4006 \ - github.com/prometheus/prometheus/pkg/pool/pool.go:SA6002 \ - github.com/prometheus/prometheus/promql/engine.go:SA6002 \ github.com/prometheus/prometheus/prompb/rpc.pb.gw.go:SA1019 DOCKER_IMAGE_NAME ?= prometheus diff --git a/Makefile.common b/Makefile.common index a0a808a3e..fff85f922 100644 --- a/Makefile.common +++ b/Makefile.common @@ -73,6 +73,8 @@ endif PROMU_VERSION ?= 0.2.0 PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_VERSION)/promu-$(PROMU_VERSION).$(GO_BUILD_PLATFORM).tar.gz +STATICCHECK_VERSION ?= 2019.1 +STATICCHECK_URL := https://github.com/dominikh/go-tools/releases/download/$(STATICCHECK_VERSION)/staticcheck_$(GOHOSTOS)_$(GOHOSTARCH) PREFIX ?= $(shell pwd) BIN_DIR ?= $(shell pwd) @@ -138,8 +140,12 @@ common-vet: .PHONY: common-staticcheck common-staticcheck: $(STATICCHECK) @echo ">> running staticcheck" + chmod +x $(STATICCHECK) ifdef GO111MODULE - GO111MODULE=$(GO111MODULE) $(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" -checks "SA*" $(pkgs) +# 'go list' needs to be executed before staticcheck to prepopulate the modules cache. +# Otherwise staticcheck might fail randomly for some reason not yet explained. + GO111MODULE=$(GO111MODULE) $(GO) list -e -compiled -test=true -export=false -deps=true -find=false -tags= -- ./... > /dev/null + GO111MODULE=$(GO111MODULE) $(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" $(pkgs) else $(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" $(pkgs) endif @@ -200,21 +206,9 @@ proto: @echo ">> generating code from proto files" @./scripts/genproto.sh -.PHONY: $(STATICCHECK) $(STATICCHECK): -ifdef GO111MODULE -# Get staticcheck from a temporary directory to avoid modifying the local go.{mod,sum}. -# See https://github.com/golang/go/issues/27643. -# For now, we are using the next branch of staticcheck because master isn't compatible yet with Go modules. - tmpModule=$$(mktemp -d 2>&1) && \ - mkdir -p $${tmpModule}/staticcheck && \ - cd "$${tmpModule}"/staticcheck && \ - GO111MODULE=on $(GO) mod init example.com/staticcheck && \ - GO111MODULE=on GOOS= GOARCH= $(GO) get -u honnef.co/go/tools/cmd/staticcheck@next && \ - rm -rf $${tmpModule}; -else - GOOS= GOARCH= GO111MODULE=off $(GO) get -u honnef.co/go/tools/cmd/staticcheck -endif + mkdir -p $(FIRST_GOPATH)/bin + curl -s -L $(STATICCHECK_URL) > $(STATICCHECK) ifdef GOVENDOR .PHONY: $(GOVENDOR) diff --git a/cmd/promtool/archive.go b/cmd/promtool/archive.go index b3fc1ac3e..dc375610d 100644 --- a/cmd/promtool/archive.go +++ b/cmd/promtool/archive.go @@ -22,12 +22,6 @@ import ( const filePerm = 0644 -type archiver interface { - write(filename string, b []byte) error - close() error - filename() string -} - type tarGzFileWriter struct { tarWriter *tar.Writer gzWriter *gzip.Writer @@ -72,7 +66,3 @@ func (w *tarGzFileWriter) write(filename string, b []byte) error { } return nil } - -func (w *tarGzFileWriter) filename() string { - return w.file.Name() -} diff --git a/cmd/promtool/http.go b/cmd/promtool/http.go index 70cee13ce..a0bf34d35 100644 --- a/cmd/promtool/http.go +++ b/cmd/promtool/http.go @@ -24,11 +24,6 @@ import ( const defaultTimeout = 2 * time.Minute -type httpClient interface { - do(req *http.Request) (*http.Response, []byte, error) - urlJoin(path string) string -} - type prometheusHTTPClient struct { requestTimeout time.Duration httpClient api.Client diff --git a/cmd/promtool/unittest.go b/cmd/promtool/unittest.go index 4b49922aa..7c0599cd8 100644 --- a/cmd/promtool/unittest.go +++ b/cmd/promtool/unittest.go @@ -84,7 +84,7 @@ func ruleUnitTest(filename string) []error { groupOrderMap := make(map[string]int) for i, gn := range unitTestInp.GroupEvalOrder { if _, ok := groupOrderMap[gn]; ok { - return []error{fmt.Errorf("Group name repeated in evaluation order: %s", gn)} + return []error{fmt.Errorf("group name repeated in evaluation order: %s", gn)} } groupOrderMap[gn] = i } diff --git a/config/config_test.go b/config/config_test.go index 650802d93..5aa860c65 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -756,23 +756,23 @@ var expectedErrors = []struct { }, { filename: "azure_client_id_missing.bad.yml", - errMsg: "Azure SD configuration requires a client_id", + errMsg: "azure SD configuration requires a client_id", }, { filename: "azure_client_secret_missing.bad.yml", - errMsg: "Azure SD configuration requires a client_secret", + errMsg: "azure SD configuration requires a client_secret", }, { filename: "azure_subscription_id_missing.bad.yml", - errMsg: "Azure SD configuration requires a subscription_id", + errMsg: "azure SD configuration requires a subscription_id", }, { filename: "azure_tenant_id_missing.bad.yml", - errMsg: "Azure SD configuration requires a tenant_id", + errMsg: "azure SD configuration requires a tenant_id", }, { filename: "azure_authentication_method.bad.yml", - errMsg: "Unknown authentication_type \"invalid\". Supported types are \"OAuth\" or \"ManagedIdentity\"", + errMsg: "unknown authentication_type \"invalid\". Supported types are \"OAuth\" or \"ManagedIdentity\"", }, { filename: "empty_scrape_config.bad.yml", diff --git a/discovery/azure/azure.go b/discovery/azure/azure.go index 4164325d6..ba71cc743 100644 --- a/discovery/azure/azure.go +++ b/discovery/azure/azure.go @@ -85,7 +85,7 @@ type SDConfig struct { func validateAuthParam(param, name string) error { if len(param) == 0 { - return fmt.Errorf("Azure SD configuration requires a %s", name) + return fmt.Errorf("azure SD configuration requires a %s", name) } return nil } @@ -116,7 +116,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { } if c.AuthenticationMethod != authMethodOAuth && c.AuthenticationMethod != authMethodManagedIdentity { - return fmt.Errorf("Unknown authentication_type %q. Supported types are %q or %q", c.AuthenticationMethod, authMethodOAuth, authMethodManagedIdentity) + return fmt.Errorf("unknown authentication_type %q. Supported types are %q or %q", c.AuthenticationMethod, authMethodOAuth, authMethodManagedIdentity) } return nil diff --git a/discovery/consul/consul.go b/discovery/consul/consul.go index 7ba8ad721..dd03e82b4 100644 --- a/discovery/consul/consul.go +++ b/discovery/consul/consul.go @@ -131,7 +131,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return err } if strings.TrimSpace(c.Server) == "" { - return fmt.Errorf("Consul SD configuration requires a server address") + return fmt.Errorf("consul SD configuration requires a server address") } return nil } @@ -267,7 +267,7 @@ func (d *Discovery) getDatacenter() error { dc, ok := info["Config"]["Datacenter"].(string) if !ok { - err := fmt.Errorf("Invalid value '%v' for Config.Datacenter", info["Config"]["Datacenter"]) + err := fmt.Errorf("invalid value '%v' for Config.Datacenter", info["Config"]["Datacenter"]) level.Error(d.logger).Log("msg", "Error retrieving datacenter name", "err", err) return err } diff --git a/discovery/kubernetes/endpoints.go b/discovery/kubernetes/endpoints.go index b201239ad..12cd44a5d 100644 --- a/discovery/kubernetes/endpoints.go +++ b/discovery/kubernetes/endpoints.go @@ -178,7 +178,7 @@ func convertToEndpoints(o interface{}) (*apiv1.Endpoints, error) { return endpoints, nil } - return nil, fmt.Errorf("Received unexpected object: %v", o) + return nil, fmt.Errorf("received unexpected object: %v", o) } func endpointsSource(ep *apiv1.Endpoints) string { diff --git a/discovery/kubernetes/ingress.go b/discovery/kubernetes/ingress.go index 40d922869..00f3d186e 100644 --- a/discovery/kubernetes/ingress.go +++ b/discovery/kubernetes/ingress.go @@ -118,7 +118,7 @@ func convertToIngress(o interface{}) (*v1beta1.Ingress, error) { return ingress, nil } - return nil, fmt.Errorf("Received unexpected object: %v", o) + return nil, fmt.Errorf("received unexpected object: %v", o) } func ingressSource(s *v1beta1.Ingress) string { diff --git a/discovery/kubernetes/kubernetes.go b/discovery/kubernetes/kubernetes.go index 485fbb908..a71d66edd 100644 --- a/discovery/kubernetes/kubernetes.go +++ b/discovery/kubernetes/kubernetes.go @@ -80,7 +80,7 @@ func (c *Role) UnmarshalYAML(unmarshal func(interface{}) error) error { case RoleNode, RolePod, RoleService, RoleEndpoint, RoleIngress: return nil default: - return fmt.Errorf("Unknown Kubernetes SD role %q", *c) + return fmt.Errorf("unknown Kubernetes SD role %q", *c) } } diff --git a/discovery/kubernetes/node.go b/discovery/kubernetes/node.go index a99eca08c..648af1481 100644 --- a/discovery/kubernetes/node.go +++ b/discovery/kubernetes/node.go @@ -127,7 +127,7 @@ func convertToNode(o interface{}) (*apiv1.Node, error) { return node, nil } - return nil, fmt.Errorf("Received unexpected object: %v", o) + return nil, fmt.Errorf("received unexpected object: %v", o) } func nodeSource(n *apiv1.Node) string { diff --git a/discovery/kubernetes/pod.go b/discovery/kubernetes/pod.go index a6e281ae8..a8bd801df 100644 --- a/discovery/kubernetes/pod.go +++ b/discovery/kubernetes/pod.go @@ -131,7 +131,7 @@ func convertToPod(o interface{}) (*apiv1.Pod, error) { return pod, nil } - return nil, fmt.Errorf("Received unexpected object: %v", o) + return nil, fmt.Errorf("received unexpected object: %v", o) } const ( diff --git a/discovery/kubernetes/service.go b/discovery/kubernetes/service.go index c369328d2..8d8009d51 100644 --- a/discovery/kubernetes/service.go +++ b/discovery/kubernetes/service.go @@ -123,7 +123,7 @@ func convertToService(o interface{}) (*apiv1.Service, error) { if ok { return service, nil } - return nil, fmt.Errorf("Received unexpected object: %v", o) + return nil, fmt.Errorf("received unexpected object: %v", o) } func serviceSource(s *apiv1.Service) string { diff --git a/discovery/marathon/marathon.go b/discovery/marathon/marathon.go index b32eb175a..12db4f8af 100644 --- a/discovery/marathon/marathon.go +++ b/discovery/marathon/marathon.go @@ -356,7 +356,7 @@ func fetchApps(client *http.Client, url string) (*AppList, error) { defer resp.Body.Close() if (resp.StatusCode < 200) || (resp.StatusCode >= 300) { - return nil, fmt.Errorf("Non 2xx status '%v' response during marathon service discovery", resp.StatusCode) + return nil, fmt.Errorf("non 2xx status '%v' response during marathon service discovery", resp.StatusCode) } var apps AppList diff --git a/discovery/openstack/openstack.go b/discovery/openstack/openstack.go index c6c434240..2172fc55a 100644 --- a/discovery/openstack/openstack.go +++ b/discovery/openstack/openstack.go @@ -104,7 +104,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return fmt.Errorf("role missing (one of: instance, hypervisor)") } if c.Region == "" { - return fmt.Errorf("Openstack SD configuration requires a region") + return fmt.Errorf("openstack SD configuration requires a region") } return nil } diff --git a/discovery/triton/triton.go b/discovery/triton/triton.go index 14e2a054f..d6a92f3af 100644 --- a/discovery/triton/triton.go +++ b/discovery/triton/triton.go @@ -41,7 +41,6 @@ const ( tritonLabelMachineBrand = tritonLabel + "machine_brand" tritonLabelMachineImage = tritonLabel + "machine_image" tritonLabelServerID = tritonLabel + "server_id" - namespace = "prometheus" ) var ( @@ -84,16 +83,16 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return err } if c.Account == "" { - return fmt.Errorf("Triton SD configuration requires an account") + return fmt.Errorf("triton SD configuration requires an account") } if c.DNSSuffix == "" { - return fmt.Errorf("Triton SD configuration requires a dns_suffix") + return fmt.Errorf("triton SD configuration requires a dns_suffix") } if c.Endpoint == "" { - return fmt.Errorf("Triton SD configuration requires an endpoint") + return fmt.Errorf("triton SD configuration requires an endpoint") } if c.RefreshInterval <= 0 { - return fmt.Errorf("Triton SD configuration requires RefreshInterval to be a positive integer") + return fmt.Errorf("triton SD configuration requires RefreshInterval to be a positive integer") } return nil } diff --git a/documentation/examples/custom-sd/adapter-usage/main.go b/documentation/examples/custom-sd/adapter-usage/main.go index 40bb07e2a..5315cbc47 100644 --- a/documentation/examples/custom-sd/adapter-usage/main.go +++ b/documentation/examples/custom-sd/adapter-usage/main.go @@ -43,18 +43,12 @@ var ( addressLabel = model.MetaLabelPrefix + "consul_address" // nodeLabel is the name for the label containing a target's node name. nodeLabel = model.MetaLabelPrefix + "consul_node" - // metaDataLabel is the prefix for the labels mapping to a target's metadata. - metaDataLabel = model.MetaLabelPrefix + "consul_metadata_" // tagsLabel is the name of the label containing the tags assigned to the target. tagsLabel = model.MetaLabelPrefix + "consul_tags" - // serviceLabel is the name of the label containing the service name. - serviceLabel = model.MetaLabelPrefix + "consul_service" // serviceAddressLabel is the name of the label containing the (optional) service address. serviceAddressLabel = model.MetaLabelPrefix + "consul_service_address" //servicePortLabel is the name of the label containing the service port. servicePortLabel = model.MetaLabelPrefix + "consul_service_port" - // datacenterLabel is the name of the label containing the datacenter ID. - datacenterLabel = model.MetaLabelPrefix + "consul_dc" // serviceIDLabel is the name of the label containing the service ID. serviceIDLabel = model.MetaLabelPrefix + "consul_service_id" ) @@ -89,12 +83,11 @@ type sdConfig struct { // Note: This is the struct with your implementation of the Discoverer interface (see Run function). // Discovery retrieves target information from a Consul server and updates them via watches. type discovery struct { - address string - refreshInterval int - clientDatacenter string - tagSeparator string - logger log.Logger - oldSourceList map[string]bool + address string + refreshInterval int + tagSeparator string + logger log.Logger + oldSourceList map[string]bool } func (d *discovery) parseServiceNodes(resp *http.Response, name string) (*targetgroup.Group, error) { diff --git a/promql/engine.go b/promql/engine.go index c10a9609d..2bf8705cb 100644 --- a/promql/engine.go +++ b/promql/engine.go @@ -175,7 +175,7 @@ func (q *query) Exec(ctx context.Context) *Result { span.SetTag(queryTag, q.stmt.String()) } - res, err, warnings := q.ng.exec(ctx, q) + res, warnings, err := q.ng.exec(ctx, q) return &Result{Err: err, Value: res, Warnings: warnings} } @@ -353,7 +353,7 @@ func (ng *Engine) newTestQuery(f func(context.Context) error) Query { // // At this point per query only one EvalStmt is evaluated. Alert and record // statements are not handled by the Engine. -func (ng *Engine) exec(ctx context.Context, q *query) (Value, error, storage.Warnings) { +func (ng *Engine) exec(ctx context.Context, q *query) (Value, storage.Warnings, error) { ng.metrics.currentQueries.Inc() defer ng.metrics.currentQueries.Dec() @@ -366,7 +366,7 @@ func (ng *Engine) exec(ctx context.Context, q *query) (Value, error, storage.War queueSpanTimer, _ := q.stats.GetSpanTimer(ctx, stats.ExecQueueTime, ng.metrics.queryQueueTime) if err := ng.gate.Start(ctx); err != nil { - return nil, contextErr(err, "query queue"), nil + return nil, nil, contextErr(err, "query queue") } defer ng.gate.Done() @@ -382,14 +382,14 @@ func (ng *Engine) exec(ctx context.Context, q *query) (Value, error, storage.War // The base context might already be canceled on the first iteration (e.g. during shutdown). if err := contextDone(ctx, env); err != nil { - return nil, err, nil + return nil, nil, err } switch s := q.Statement().(type) { case *EvalStmt: return ng.execEvalStmt(ctx, q, s) case testStmt: - return nil, s(ctx), nil + return nil, nil, s(ctx) } panic(fmt.Errorf("promql.Engine.exec: unhandled statement of type %T", q.Statement())) @@ -404,9 +404,9 @@ func durationMilliseconds(d time.Duration) int64 { } // execEvalStmt evaluates the expression of an evaluation statement for the given time range. -func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) (Value, error, storage.Warnings) { +func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) (Value, storage.Warnings, error) { prepareSpanTimer, ctxPrepare := query.stats.GetSpanTimer(ctx, stats.QueryPreparationTime, ng.metrics.queryPrepareTime) - querier, err, warnings := ng.populateSeries(ctxPrepare, query.queryable, s) + querier, warnings, err := ng.populateSeries(ctxPrepare, query.queryable, s) prepareSpanTimer.Finish() // XXX(fabxc): the querier returned by populateSeries might be instantiated @@ -417,7 +417,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( } if err != nil { - return nil, err, warnings + return nil, warnings, err } evalSpanTimer, _ := query.stats.GetSpanTimer(ctx, stats.InnerEvalTime, ng.metrics.queryInnerEval) @@ -435,7 +435,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( } val, err := evaluator.Eval(s.Expr) if err != nil { - return nil, err, warnings + return nil, warnings, err } evalSpanTimer.Finish() @@ -454,11 +454,11 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( // timestamp as that is when we ran the evaluation. vector[i] = Sample{Metric: s.Metric, Point: Point{V: s.Points[0].V, T: start}} } - return vector, nil, warnings + return vector, warnings, nil case ValueTypeScalar: - return Scalar{V: mat[0].Points[0].V, T: start}, nil, warnings + return Scalar{V: mat[0].Points[0].V, T: start}, warnings, nil case ValueTypeMatrix: - return mat, nil, warnings + return mat, warnings, nil default: panic(fmt.Errorf("promql.Engine.exec: unexpected expression type %q", s.Expr.Type())) } @@ -477,7 +477,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( } val, err := evaluator.Eval(s.Expr) if err != nil { - return nil, err, warnings + return nil, warnings, err } evalSpanTimer.Finish() @@ -488,7 +488,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( query.matrix = mat if err := contextDone(ctx, "expression evaluation"); err != nil { - return nil, err, warnings + return nil, warnings, err } // TODO(fabxc): order ensured by storage? @@ -497,7 +497,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *EvalStmt) ( sort.Sort(mat) sortSpanTimer.Finish() - return mat, nil, warnings + return mat, warnings, nil } // cumulativeSubqueryOffset returns the sum of range and offset of all subqueries in the path. @@ -512,7 +512,7 @@ func (ng *Engine) cumulativeSubqueryOffset(path []Node) time.Duration { return subqOffset } -func (ng *Engine) populateSeries(ctx context.Context, q storage.Queryable, s *EvalStmt) (storage.Querier, error, storage.Warnings) { +func (ng *Engine) populateSeries(ctx context.Context, q storage.Queryable, s *EvalStmt) (storage.Querier, storage.Warnings, error) { var maxOffset time.Duration Inspect(s.Expr, func(node Node, path []Node) error { subqOffset := ng.cumulativeSubqueryOffset(path) @@ -539,7 +539,7 @@ func (ng *Engine) populateSeries(ctx context.Context, q storage.Queryable, s *Ev querier, err := q.Querier(ctx, timestamp.FromTime(mint), timestamp.FromTime(s.End)) if err != nil { - return nil, err, nil + return nil, nil, err } var warnings storage.Warnings @@ -592,7 +592,7 @@ func (ng *Engine) populateSeries(ctx context.Context, q storage.Queryable, s *Ev } return nil }) - return querier, err, warnings + return querier, warnings, err } // extractFuncFromPath walks up the path and searches for the first instance of @@ -1243,6 +1243,7 @@ func getPointSlice(sz int) []Point { } func putPointSlice(p []Point) { + //lint:ignore SA6002 relax staticcheck verification. pointPool.Put(p[:0]) } @@ -1665,21 +1666,6 @@ func vectorElemBinop(op ItemType, lhs, rhs float64) (float64, bool) { panic(fmt.Errorf("operator %q not allowed for operations between Vectors", op)) } -// intersection returns the metric of common label/value pairs of two input metrics. -func intersection(ls1, ls2 labels.Labels) labels.Labels { - res := make(labels.Labels, 0, 5) - - for _, l1 := range ls1 { - for _, l2 := range ls2 { - if l1.Name == l2.Name && l1.Value == l2.Value { - res = append(res, l1) - continue - } - } - } - return res -} - type groupedAggregation struct { labels labels.Labels value float64 diff --git a/promql/printer.go b/promql/printer.go index 098220f89..05f6d114d 100644 --- a/promql/printer.go +++ b/promql/printer.go @@ -155,7 +155,7 @@ func (node *MatrixSelector) String() string { func (node *SubqueryExpr) String() string { step := "" if node.Step != 0 { - step = fmt.Sprintf("%s", model.Duration(node.Step)) + step = model.Duration(node.Step).String() } return fmt.Sprintf("%s[%s:%s]", node.Expr.String(), model.Duration(node.Range), step) } diff --git a/promql/value.go b/promql/value.go index 11e6880fb..fe37b403b 100644 --- a/promql/value.go +++ b/promql/value.go @@ -311,10 +311,7 @@ func (ssi *storageSeriesIterator) At() (t int64, v float64) { func (ssi *storageSeriesIterator) Next() bool { ssi.curr++ - if ssi.curr >= len(ssi.points) { - return false - } - return true + return ssi.curr < len(ssi.points) } func (ssi *storageSeriesIterator) Err() error { diff --git a/rules/alerting.go b/rules/alerting.go index e7cec6666..3afb0d9ac 100644 --- a/rules/alerting.go +++ b/rules/alerting.go @@ -206,10 +206,6 @@ func (r *AlertingRule) Annotations() labels.Labels { return r.annotations } -func (r *AlertingRule) equal(o *AlertingRule) bool { - return r.name == o.name && labels.Equal(r.labels, o.labels) -} - func (r *AlertingRule) sample(alert *Alert, ts time.Time) promql.Sample { lb := labels.NewBuilder(r.labels) diff --git a/scrape/scrape.go b/scrape/scrape.go index 5c8650dcb..29553aea2 100644 --- a/scrape/scrape.go +++ b/scrape/scrape.go @@ -927,6 +927,7 @@ type sample struct { v float64 } +//lint:ignore U1000 staticcheck falsely reports that samples is unused. type samples []sample func (s samples) Len() int { return len(s) } diff --git a/storage/remote/codec.go b/storage/remote/codec.go index 21c3cd06f..ff982cf19 100644 --- a/storage/remote/codec.go +++ b/storage/remote/codec.go @@ -302,13 +302,13 @@ func (c *concreteSeriesIterator) Err() error { func validateLabelsAndMetricName(ls labels.Labels) error { for _, l := range ls { if l.Name == labels.MetricName && !model.IsValidMetricName(model.LabelValue(l.Value)) { - return fmt.Errorf("Invalid metric name: %v", l.Value) + return fmt.Errorf("invalid metric name: %v", l.Value) } if !model.LabelName(l.Name).IsValid() { - return fmt.Errorf("Invalid label name: %v", l.Name) + return fmt.Errorf("invalid label name: %v", l.Name) } if !model.LabelValue(l.Value).IsValid() { - return fmt.Errorf("Invalid label value: %v", l.Value) + return fmt.Errorf("invalid label value: %v", l.Value) } } return nil diff --git a/storage/remote/queue_manager.go b/storage/remote/queue_manager.go index 4c5368382..e76912e1b 100644 --- a/storage/remote/queue_manager.go +++ b/storage/remote/queue_manager.go @@ -401,10 +401,6 @@ func (t *QueueManager) newShards(numShards int) *shards { return s } -func (s *shards) len() int { - return len(s.queues) -} - func (s *shards) start() { for i := 0; i < len(s.queues); i++ { go s.runShard(i) @@ -426,7 +422,6 @@ func (s *shards) stop(deadline time.Duration) { // Force an unclean shutdown. s.cancel() <-s.done - return } func (s *shards) enqueue(sample *model.Sample) bool { diff --git a/storage/remote/queue_manager_test.go b/storage/remote/queue_manager_test.go index 6fd8f89ea..d70c7789a 100644 --- a/storage/remote/queue_manager_test.go +++ b/storage/remote/queue_manager_test.go @@ -323,7 +323,7 @@ func TestShutdown(t *testing.T) { start := time.Now() m.Stop() - duration := time.Now().Sub(start) + duration := time.Since(start) if duration > deadline+(deadline/10) { t.Errorf("Took too long to shutdown: %s > %s", duration, deadline) } diff --git a/util/httputil/compression_test.go b/util/httputil/compression_test.go index e7901a8da..2204d1364 100644 --- a/util/httputil/compression_test.go +++ b/util/httputil/compression_test.go @@ -118,7 +118,7 @@ func TestCompressionHandler_Gzip(t *testing.T) { t.Error("unexpected error while reading from response body") } - actual := string(buf.Bytes()) + actual := buf.String() expected := "Hello World!" if expected != actual { t.Errorf("expected response with content %s, but got %s", expected, actual) @@ -168,7 +168,7 @@ func TestCompressionHandler_Deflate(t *testing.T) { t.Error("unexpected error while reading from response body") } - actual := string(buf.Bytes()) + actual := buf.String() expected := "Hello World!" if expected != actual { t.Errorf("expected response with content %s, but got %s", expected, actual) diff --git a/util/treecache/treecache.go b/util/treecache/treecache.go index 11ecae7dc..f1083e7db 100644 --- a/util/treecache/treecache.go +++ b/util/treecache/treecache.go @@ -63,12 +63,11 @@ func (zl ZookeeperLogger) Printf(s string, i ...interface{}) { // A ZookeeperTreeCache keeps data from all children of a Zookeeper path // locally cached and updated according to received events. type ZookeeperTreeCache struct { - conn *zk.Conn - prefix string - events chan ZookeeperTreeCacheEvent - zkEvents chan zk.Event - stop chan struct{} - head *zookeeperTreeCacheNode + conn *zk.Conn + prefix string + events chan ZookeeperTreeCacheEvent + stop chan struct{} + head *zookeeperTreeCacheNode logger log.Logger } diff --git a/web/api/v1/api.go b/web/api/v1/api.go index 0e602c1f3..4e0b91f9b 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -923,7 +923,7 @@ func (api *API) remoteRead(w http.ResponseWriter, r *http.Request) { func (api *API) deleteSeries(r *http.Request) apiFuncResult { if !api.enableAdmin { - return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("Admin APIs disabled")}, nil, nil} + return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("admin APIs disabled")}, nil, nil} } db := api.db() if db == nil { @@ -980,7 +980,7 @@ func (api *API) deleteSeries(r *http.Request) apiFuncResult { func (api *API) snapshot(r *http.Request) apiFuncResult { if !api.enableAdmin { - return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("Admin APIs disabled")}, nil, nil} + return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("admin APIs disabled")}, nil, nil} } var ( skipHead bool @@ -1019,7 +1019,7 @@ func (api *API) snapshot(r *http.Request) apiFuncResult { func (api *API) cleanTombstones(r *http.Request) apiFuncResult { if !api.enableAdmin { - return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("Admin APIs disabled")}, nil, nil} + return apiFuncResult{nil, &apiError{errorUnavailable, errors.New("admin APIs disabled")}, nil, nil} } db := api.db() if db == nil { diff --git a/web/api/v2/api.go b/web/api/v2/api.go index fd284c969..8ccda6d9d 100644 --- a/web/api/v2/api.go +++ b/web/api/v2/api.go @@ -36,7 +36,6 @@ import ( "github.com/prometheus/tsdb" tsdbLabels "github.com/prometheus/tsdb/labels" - "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/timestamp" pb "github.com/prometheus/prometheus/prompb" ) @@ -114,16 +113,6 @@ var ( maxTime = time.Unix(math.MaxInt64/1000-62135596801, 999999999) ) -func labelsToProto(lset labels.Labels) pb.Labels { - r := pb.Labels{ - Labels: make([]pb.Label, 0, len(lset)), - } - for _, l := range lset { - r.Labels = append(r.Labels, pb.Label{Name: l.Name, Value: l.Value}) - } - return r -} - // AdminDisabled implements the administration interface that informs // that the API endpoints are disabled. type AdminDisabled struct { diff --git a/web/federate.go b/web/federate.go index b0d94a9d7..9ec7961d5 100644 --- a/web/federate.go +++ b/web/federate.go @@ -90,7 +90,7 @@ func (h *Handler) federation(w http.ResponseWriter, req *http.Request) { s, wrns, err := q.Select(params, mset...) if wrns != nil { level.Debug(h.logger).Log("msg", "federation select returned warnings", "warnings", wrns) - federationErrors.Add(float64(len(wrns))) + federationWarnings.Add(float64(len(wrns))) } if err != nil { federationErrors.Inc() diff --git a/web/web.go b/web/web.go index 8cc63a7f4..1e18a7cfe 100644 --- a/web/web.go +++ b/web/web.go @@ -124,20 +124,18 @@ type Handler struct { apiV1 *api_v1.API - router *route.Router - quitCh chan struct{} - reloadCh chan chan error - options *Options - config *config.Config - configString string - versionInfo *PrometheusVersion - birth time.Time - cwd string - flagsMap map[string]string - - externalLabels model.LabelSet - mtx sync.RWMutex - now func() model.Time + router *route.Router + quitCh chan struct{} + reloadCh chan chan error + options *Options + config *config.Config + versionInfo *PrometheusVersion + birth time.Time + cwd string + flagsMap map[string]string + + mtx sync.RWMutex + now func() model.Time ready uint32 // ready is uint32 rather than boolean to be able to use atomic functions. }