Fix most golint warnings.

This is with `golint -min_confidence=0.5`.

I left several lint warnings untouched because they were either
incorrect or I felt it was better not to change them at the moment.
This commit is contained in:
Julius Volz 2015-08-24 15:07:27 +02:00 committed by Fabian Reinartz
parent 0830b0cd70
commit bb0ba8d68f
23 changed files with 124 additions and 117 deletions

View file

@ -46,6 +46,7 @@ func main() {
os.Exit(Main())
}
// Main manages the startup and shutdown lifecycle of the entire Prometheus server.
func Main() int {
if err := parse(os.Args[1:]); err != nil {
return 2

View file

@ -68,19 +68,19 @@ func LoadFile(filename string) (*Config, error) {
// The defaults applied before parsing the respective config sections.
var (
// The default top-level configuration.
// DefaultConfig is the default top-level configuration.
DefaultConfig = Config{
GlobalConfig: DefaultGlobalConfig,
}
// The default global configuration.
// DefaultGlobalConfig is the default global configuration.
DefaultGlobalConfig = GlobalConfig{
ScrapeInterval: Duration(1 * time.Minute),
ScrapeTimeout: Duration(10 * time.Second),
EvaluationInterval: Duration(1 * time.Minute),
}
// The default scrape configuration.
// DefaultScrapeConfig is the default scrape configuration.
DefaultScrapeConfig = ScrapeConfig{
// ScrapeTimeout and ScrapeInterval default to the
// configured globals.
@ -89,30 +89,30 @@ var (
HonorLabels: false,
}
// The default Relabel configuration.
// DefaultRelabelConfig is the default Relabel configuration.
DefaultRelabelConfig = RelabelConfig{
Action: RelabelReplace,
Separator: ";",
}
// The default DNS SD configuration.
// DefaultDNSSDConfig is the default DNS SD configuration.
DefaultDNSSDConfig = DNSSDConfig{
RefreshInterval: Duration(30 * time.Second),
Type: "SRV",
}
// The default file SD configuration.
// DefaultFileSDConfig is the default file SD configuration.
DefaultFileSDConfig = FileSDConfig{
RefreshInterval: Duration(5 * time.Minute),
}
// The default Consul SD configuration.
// DefaultConsulSDConfig is the default Consul SD configuration.
DefaultConsulSDConfig = ConsulSDConfig{
TagSeparator: ",",
Scheme: "http",
}
// The default Serverset SD configuration.
// DefaultServersetSDConfig is the default Serverset SD configuration.
DefaultServersetSDConfig = ServersetSDConfig{
Timeout: Duration(10 * time.Second),
}
@ -122,7 +122,7 @@ var (
RefreshInterval: Duration(30 * time.Second),
}
// The default Kubernetes SD configuration
// DefaultKubernetesSDConfig is the default Kubernetes SD configuration
DefaultKubernetesSDConfig = KubernetesSDConfig{
KubeletPort: 10255,
RequestTimeout: Duration(10 * time.Second),
@ -130,7 +130,7 @@ var (
}
)
// This custom URL type allows validating at configuration load time.
// URL is a custom URL type that allows validation at configuration load time.
type URL struct {
*url.URL
}
@ -633,6 +633,7 @@ func (c *MarathonSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) erro
return checkOverflow(c.XXX, "marathon_sd_config")
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (c *KubernetesSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultKubernetesSDConfig
type plain KubernetesSDConfig
@ -655,15 +656,15 @@ func (c *KubernetesSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) er
type RelabelAction string
const (
// Performs a regex replacement.
// RelabelReplace performs a regex replacement.
RelabelReplace RelabelAction = "replace"
// Drops targets for which the input does not match the regex.
// RelabelKeep drops targets for which the input does not match the regex.
RelabelKeep RelabelAction = "keep"
// Drops targets for which the input does match the regex.
// RelabelDrop drops targets for which the input does match the regex.
RelabelDrop RelabelAction = "drop"
// Sets a label to the modulus of a hash of labels.
// RelabelHashMod sets a label to the modulus of a hash of labels.
RelabelHashMod RelabelAction = "hashmod"
// Copy labels to other labelnames based on a regex.
// RelabelLabelMap copies labels to other labelnames based on a regex.
RelabelLabelMap RelabelAction = "labelmap"
)

View file

@ -179,7 +179,6 @@ func (e *ParenExpr) Type() model.ValueType { return e.Expr.Type() }
func (e *StringLiteral) Type() model.ValueType { return model.ValString }
func (e *UnaryExpr) Type() model.ValueType { return e.Expr.Type() }
func (e *VectorSelector) Type() model.ValueType { return model.ValVector }
func (e *BinaryExpr) Type() model.ValueType {
if e.LHS.Type() == model.ValScalar && e.RHS.Type() == model.ValScalar {
return model.ValScalar
@ -197,7 +196,7 @@ func (*StringLiteral) expr() {}
func (*UnaryExpr) expr() {}
func (*VectorSelector) expr() {}
// VectorMatchCardinaly describes the cardinality relationship
// VectorMatchCardinality describes the cardinality relationship
// of two vectors in a binary operation.
type VectorMatchCardinality int
@ -235,9 +234,10 @@ type VectorMatching struct {
Include model.LabelNames
}
// A Visitor's Visit method is invoked for each node encountered by Walk.
// If the result visitor w is not nil, Walk visits each of the children
// of node with the visitor w, followed by a call of w.Visit(nil).
// Visitor allows visiting a Node and its child nodes. The Visit method is
// invoked for each node encountered by Walk. If the result visitor w is not
// nil, Walk visits each of the children of node with the visitor w, followed
// by a call of w.Visit(nil).
type Visitor interface {
Visit(node Node) (w Visitor)
}

View file

@ -225,11 +225,11 @@ func init() {
key["nan"] = itemNumber
}
func (t itemType) String() string {
if s, ok := itemTypeStr[t]; ok {
func (i itemType) String() string {
if s, ok := itemTypeStr[i]; ok {
return s
}
return fmt.Sprintf("<item %d>", t)
return fmt.Sprintf("<item %d>", i)
}
func (i item) desc() string {
@ -242,8 +242,8 @@ func (i item) desc() string {
return fmt.Sprintf("%s %s", i.typ.desc(), i)
}
func (t itemType) desc() string {
switch t {
func (i itemType) desc() string {
switch i {
case itemError:
return "error"
case itemEOF:
@ -261,7 +261,7 @@ func (t itemType) desc() string {
case itemDuration:
return "duration"
}
return fmt.Sprintf("%q", t)
return fmt.Sprintf("%q", i)
}
const eof = -1

View file

@ -24,7 +24,7 @@ func TestEvaluations(t *testing.T) {
t.Fatal(err)
}
for _, fn := range files {
test, err := NewTestFromFile(t, fn)
test, err := newTestFromFile(t, fn)
if err != nil {
t.Errorf("error creating test for %s: %s", fn, err)
}

View file

@ -68,7 +68,7 @@ func NewTest(t testutil.T, input string) (*Test, error) {
return test, err
}
func NewTestFromFile(t testutil.T, filename string) (*Test, error) {
func newTestFromFile(t testutil.T, filename string) (*Test, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
@ -477,6 +477,7 @@ func (t *Test) clear() {
t.queryEngine = NewEngine(t.storage, nil)
}
// Close closes resources associated with the Test.
func (t *Test) Close() {
t.queryEngine.Stop()
t.closeStorage()

View file

@ -32,22 +32,22 @@ const (
consulWatchTimeout = 30 * time.Second
consulRetryInterval = 15 * time.Second
// ConsuleAddressLabel is the name for the label containing a target's address.
ConsulAddressLabel = model.MetaLabelPrefix + "consul_address"
// ConsuleNodeLabel is the name for the label containing a target's node name.
ConsulNodeLabel = model.MetaLabelPrefix + "consul_node"
// ConsulTagsLabel is the name of the label containing the tags assigned to the target.
ConsulTagsLabel = model.MetaLabelPrefix + "consul_tags"
// ConsulServiceLabel is the name of the label containing the service name.
ConsulServiceLabel = model.MetaLabelPrefix + "consul_service"
// ConsulServiceAddressLabel is the name of the label containing the (optional) service address.
ConsulServiceAddressLabel = model.MetaLabelPrefix + "consul_service_address"
// ConsulServicePortLabel is the name of the label containing the service port.
ConsulServicePortLabel = model.MetaLabelPrefix + "consul_service_port"
// ConsulDCLabel is the name of the label containing the datacenter ID.
ConsulDCLabel = model.MetaLabelPrefix + "consul_dc"
// ConsulServiceIDLabel is the name of the label containing the service ID.
ConsulServiceIDLabel = model.MetaLabelPrefix + "consul_service_id"
// consulAddressLabel is the name for the label containing a target's address.
consulAddressLabel = model.MetaLabelPrefix + "consul_address"
// consulNodeLabel is the name for the label containing a target's node name.
consulNodeLabel = model.MetaLabelPrefix + "consul_node"
// consulTagsLabel is the name of the label containing the tags assigned to the target.
consulTagsLabel = model.MetaLabelPrefix + "consul_tags"
// consulServiceLabel is the name of the label containing the service name.
consulServiceLabel = model.MetaLabelPrefix + "consul_service"
// consulServiceAddressLabel is the name of the label containing the (optional) service address.
consulServiceAddressLabel = model.MetaLabelPrefix + "consul_service_address"
// consulServicePortLabel is the name of the label containing the service port.
consulServicePortLabel = model.MetaLabelPrefix + "consul_service_port"
// consulDCLabel is the name of the label containing the datacenter ID.
consulDCLabel = model.MetaLabelPrefix + "consul_dc"
// consulServiceIDLabel is the name of the label containing the service ID.
consulServiceIDLabel = model.MetaLabelPrefix + "consul_service_id"
)
// ConsulDiscovery retrieves target information from a Consul server
@ -226,8 +226,8 @@ func (cd *ConsulDiscovery) watchServices(update chan<- *consulService, done <-ch
cd.services[name] = srv
}
srv.tgroup.Labels = model.LabelSet{
ConsulServiceLabel: model.LabelValue(name),
ConsulDCLabel: model.LabelValue(cd.clientDatacenter),
consulServiceLabel: model.LabelValue(name),
consulDCLabel: model.LabelValue(cd.clientDatacenter),
}
update <- srv
}
@ -272,12 +272,12 @@ func (cd *ConsulDiscovery) watchService(srv *consulService, ch chan<- *config.Ta
srv.tgroup.Targets = append(srv.tgroup.Targets, model.LabelSet{
model.AddressLabel: model.LabelValue(addr),
ConsulAddressLabel: model.LabelValue(node.Address),
ConsulNodeLabel: model.LabelValue(node.Node),
ConsulTagsLabel: model.LabelValue(tags),
ConsulServiceAddressLabel: model.LabelValue(node.ServiceAddress),
ConsulServicePortLabel: model.LabelValue(strconv.Itoa(node.ServicePort)),
ConsulServiceIDLabel: model.LabelValue(node.ServiceID),
consulAddressLabel: model.LabelValue(node.Address),
consulNodeLabel: model.LabelValue(node.Node),
consulTagsLabel: model.LabelValue(tags),
consulServiceAddressLabel: model.LabelValue(node.ServiceAddress),
consulServicePortLabel: model.LabelValue(strconv.Itoa(node.ServicePort)),
consulServiceIDLabel: model.LabelValue(node.ServiceID),
})
}

View file

@ -31,7 +31,7 @@ import (
const (
resolvConf = "/etc/resolv.conf"
DNSNameLabel = model.MetaLabelPrefix + "dns_name"
dnsNameLabel = model.MetaLabelPrefix + "dns_name"
// Constants for instrumentation.
namespace = "prometheus"
@ -161,7 +161,7 @@ func (dd *DNSDiscovery) refresh(name string, ch chan<- *config.TargetGroup) erro
}
tg.Targets = append(tg.Targets, model.LabelSet{
model.AddressLabel: target,
DNSNameLabel: model.LabelValue(name),
dnsNameLabel: model.LabelValue(name),
})
}

View file

@ -29,7 +29,7 @@ import (
"github.com/prometheus/prometheus/config"
)
const FileSDFilepathLabel = model.MetaLabelPrefix + "filepath"
const fileSDFilepathLabel = model.MetaLabelPrefix + "filepath"
// FileDiscovery provides service discovery functionality based
// on files that contain target groups in JSON or YAML format. Refreshing
@ -245,7 +245,7 @@ func readFile(filename string) ([]*config.TargetGroup, error) {
if tg.Labels == nil {
tg.Labels = model.LabelSet{}
}
tg.Labels[FileSDFilepathLabel] = model.LabelValue(filename)
tg.Labels[fileSDFilepathLabel] = model.LabelValue(filename)
}
return targetGroups, nil
}

View file

@ -18,8 +18,9 @@ import (
"github.com/prometheus/prometheus/retrieval/discovery/kubernetes"
)
func NewKubernetesDiscovery(conf *config.KubernetesSDConfig) (*kubernetes.KubernetesDiscovery, error) {
kd := &kubernetes.KubernetesDiscovery{
// NewKubernetesDiscovery creates a Kubernetes service discovery based on the passed-in configuration.
func NewKubernetesDiscovery(conf *config.KubernetesSDConfig) (*kubernetes.Discovery, error) {
kd := &kubernetes.Discovery{
Conf: conf,
}
err := kd.Initialize()

View file

@ -65,8 +65,8 @@ const (
serviceEndpointsURL = apiPrefix + "/namespaces/%s/endpoints/%s"
)
// KubernetesDiscovery implements a TargetProvider for Kubernetes services.
type KubernetesDiscovery struct {
// Discovery implements a TargetProvider for Kubernetes services.
type Discovery struct {
client *http.Client
Conf *config.KubernetesSDConfig
@ -81,7 +81,7 @@ type KubernetesDiscovery struct {
}
// Initialize sets up the discovery for usage.
func (kd *KubernetesDiscovery) Initialize() error {
func (kd *Discovery) Initialize() error {
client, err := newKubernetesHTTPClient(kd.Conf)
if err != nil {
@ -97,7 +97,7 @@ func (kd *KubernetesDiscovery) Initialize() error {
}
// Sources implements the TargetProvider interface.
func (kd *KubernetesDiscovery) Sources() []string {
func (kd *Discovery) Sources() []string {
res, err := kd.client.Get(kd.Conf.Server + nodesURL)
if err != nil {
// If we can't list nodes then we can't watch them. Assume this is a misconfiguration
@ -163,7 +163,7 @@ func (kd *KubernetesDiscovery) Sources() []string {
}
// Run implements the TargetProvider interface.
func (kd *KubernetesDiscovery) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) {
func (kd *Discovery) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) {
defer close(ch)
select {
@ -215,7 +215,7 @@ func (kd *KubernetesDiscovery) Run(ch chan<- *config.TargetGroup, done <-chan st
}
}
func (kd *KubernetesDiscovery) updateNodesTargetGroup() *config.TargetGroup {
func (kd *Discovery) updateNodesTargetGroup() *config.TargetGroup {
kd.nodesMu.Lock()
defer kd.nodesMu.Unlock()
@ -239,7 +239,7 @@ func (kd *KubernetesDiscovery) updateNodesTargetGroup() *config.TargetGroup {
return tg
}
func (kd *KubernetesDiscovery) updateNode(node *Node, eventType EventType) {
func (kd *Discovery) updateNode(node *Node, eventType EventType) {
kd.nodesMu.Lock()
defer kd.nodesMu.Unlock()
updatedNodeName := node.ObjectMeta.Name
@ -254,7 +254,7 @@ func (kd *KubernetesDiscovery) updateNode(node *Node, eventType EventType) {
}
// watchNodes watches nodes as they come & go.
func (kd *KubernetesDiscovery) watchNodes(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
func (kd *Discovery) watchNodes(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
until(func() {
req, err := http.NewRequest("GET", kd.Conf.Server+nodesURL, nil)
if err != nil {
@ -294,7 +294,7 @@ func (kd *KubernetesDiscovery) watchNodes(events chan interface{}, done <-chan s
}
// watchServices watches services as they come & go.
func (kd *KubernetesDiscovery) watchServices(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
func (kd *Discovery) watchServices(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
until(func() {
req, err := http.NewRequest("GET", kd.Conf.Server+servicesURL, nil)
if err != nil {
@ -334,7 +334,7 @@ func (kd *KubernetesDiscovery) watchServices(events chan interface{}, done <-cha
}, retryInterval, done)
}
func (kd *KubernetesDiscovery) updateService(service *Service, eventType EventType) *config.TargetGroup {
func (kd *Discovery) updateService(service *Service, eventType EventType) *config.TargetGroup {
kd.servicesMu.Lock()
defer kd.servicesMu.Unlock()
@ -355,7 +355,7 @@ func (kd *KubernetesDiscovery) updateService(service *Service, eventType EventTy
return nil
}
func (kd *KubernetesDiscovery) deleteService(service *Service) *config.TargetGroup {
func (kd *Discovery) deleteService(service *Service) *config.TargetGroup {
tg := &config.TargetGroup{Source: serviceSource(service)}
delete(kd.services[service.ObjectMeta.Namespace], service.ObjectMeta.Name)
@ -366,7 +366,7 @@ func (kd *KubernetesDiscovery) deleteService(service *Service) *config.TargetGro
return tg
}
func (kd *KubernetesDiscovery) addService(service *Service) *config.TargetGroup {
func (kd *Discovery) addService(service *Service) *config.TargetGroup {
namespace, ok := kd.services[service.ObjectMeta.Namespace]
if !ok {
namespace = map[string]*Service{}
@ -386,16 +386,16 @@ func (kd *KubernetesDiscovery) addService(service *Service) *config.TargetGroup
return nil
}
var endpoints Endpoints
if err := json.NewDecoder(res.Body).Decode(&endpoints); err != nil {
var eps Endpoints
if err := json.NewDecoder(res.Body).Decode(&eps); err != nil {
log.Errorf("Error getting service endpoints: %s", err)
return nil
}
return kd.updateServiceTargetGroup(service, &endpoints)
return kd.updateServiceTargetGroup(service, &eps)
}
func (kd *KubernetesDiscovery) updateServiceTargetGroup(service *Service, endpoints *Endpoints) *config.TargetGroup {
func (kd *Discovery) updateServiceTargetGroup(service *Service, eps *Endpoints) *config.TargetGroup {
tg := &config.TargetGroup{
Source: serviceSource(service),
Labels: model.LabelSet{
@ -415,10 +415,10 @@ func (kd *KubernetesDiscovery) updateServiceTargetGroup(service *Service, endpoi
}
// Now let's loop through the endpoints & add them to the target group with appropriate labels.
for _, eps := range endpoints.Subsets {
epPort := eps.Ports[0].Port
for _, ss := range eps.Subsets {
epPort := ss.Ports[0].Port
for _, addr := range eps.Addresses {
for _, addr := range ss.Addresses {
ipAddr := addr.IP
if len(ipAddr) == net.IPv6len {
ipAddr = "[" + ipAddr + "]"
@ -435,7 +435,7 @@ func (kd *KubernetesDiscovery) updateServiceTargetGroup(service *Service, endpoi
}
// watchServiceEndpoints watches service endpoints as they come & go.
func (kd *KubernetesDiscovery) watchServiceEndpoints(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
func (kd *Discovery) watchServiceEndpoints(events chan interface{}, done <-chan struct{}, retryInterval time.Duration) {
until(func() {
req, err := http.NewRequest("GET", kd.Conf.Server+endpointsURL, nil)
if err != nil {
@ -475,7 +475,7 @@ func (kd *KubernetesDiscovery) watchServiceEndpoints(events chan interface{}, do
}, retryInterval, done)
}
func (kd *KubernetesDiscovery) updateServiceEndpoints(endpoints *Endpoints, eventType EventType) *config.TargetGroup {
func (kd *Discovery) updateServiceEndpoints(endpoints *Endpoints, eventType EventType) *config.TargetGroup {
kd.servicesMu.Lock()
defer kd.servicesMu.Unlock()

View file

@ -49,11 +49,11 @@ type serversetEndpoint struct {
Port int
}
type ZookeeperLogger struct {
type zookeeperLogger struct {
}
// Implements zk.Logger
func (zl ZookeeperLogger) Printf(s string, i ...interface{}) {
func (zl zookeeperLogger) Printf(s string, i ...interface{}) {
log.Infof(s, i...)
}
@ -72,7 +72,7 @@ type ServersetDiscovery struct {
// NewServersetDiscovery returns a new ServersetDiscovery for the given config.
func NewServersetDiscovery(conf *config.ServersetSDConfig) *ServersetDiscovery {
conn, _, err := zk.Connect(conf.Servers, time.Duration(conf.Timeout))
conn.SetLogger(ZookeeperLogger{})
conn.SetLogger(zookeeperLogger{})
if err != nil {
return nil
}
@ -84,7 +84,7 @@ func NewServersetDiscovery(conf *config.ServersetSDConfig) *ServersetDiscovery {
sources: map[string]*config.TargetGroup{},
}
go sd.processUpdates()
sd.treeCache = NewZookeeperTreeCache(conn, conf.Paths[0], updates)
sd.treeCache = newZookeeperTreeCache(conn, conf.Paths[0], updates)
return sd
}
@ -194,7 +194,7 @@ type zookeeperTreeCacheNode struct {
children map[string]*zookeeperTreeCacheNode
}
func NewZookeeperTreeCache(conn *zk.Conn, path string, events chan zookeeperTreeCacheEvent) *zookeeperTreeCache {
func newZookeeperTreeCache(conn *zk.Conn, path string, events chan zookeeperTreeCacheEvent) *zookeeperTreeCache {
tc := &zookeeperTreeCache{
conn: conn,
prefix: path,

View file

@ -90,11 +90,11 @@ func (t TargetHealth) value() model.SampleValue {
}
const (
// Unknown is the state of a Target before it is first scraped.
// HealthUnknown is the state of a Target before it is first scraped.
HealthUnknown TargetHealth = iota
// Healthy is the state of a Target that has been successfully scraped.
// HealthGood is the state of a Target that has been successfully scraped.
HealthGood
// Unhealthy is the state of a Target that was scraped unsuccessfully.
// HealthBad is the state of a Target that was scraped unsuccessfully.
HealthBad
)
@ -258,7 +258,7 @@ func newHTTPClient(cfg *config.ScrapeConfig) (*http.Client, error) {
// Load CA cert.
caCert, err := ioutil.ReadFile(cfg.CACert)
if err != nil {
return nil, fmt.Errorf("Unable to use specified CA cert %s: %s", cfg.CACert, err)
return nil, fmt.Errorf("unable to use specified CA cert %s: %s", cfg.CACert, err)
}
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
@ -268,7 +268,7 @@ func newHTTPClient(cfg *config.ScrapeConfig) (*http.Client, error) {
if cfg.ClientCert != nil && len(cfg.ClientCert.Cert) > 0 && len(cfg.ClientCert.Key) > 0 {
cert, err := tls.LoadX509KeyPair(cfg.ClientCert.Cert, cfg.ClientCert.Key)
if err != nil {
return nil, fmt.Errorf("Unable to use specified client cert (%s) & key (%s): %s", cfg.ClientCert.Cert, cfg.ClientCert.Key, err)
return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", cfg.ClientCert.Cert, cfg.ClientCert.Key, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
@ -285,12 +285,13 @@ func newHTTPClient(cfg *config.ScrapeConfig) (*http.Client, error) {
// Authorization header correctly on each request.
bearerToken := cfg.BearerToken
if len(bearerToken) == 0 && len(cfg.BearerTokenFile) > 0 {
if b, err := ioutil.ReadFile(cfg.BearerTokenFile); err != nil {
return nil, fmt.Errorf("Unable to read bearer token file %s: %s", cfg.BearerTokenFile, err)
} else {
bearerToken = string(b)
b, err := ioutil.ReadFile(cfg.BearerTokenFile)
if err != nil {
return nil, fmt.Errorf("unable to read bearer token file %s: %s", cfg.BearerTokenFile, err)
}
bearerToken = string(b)
}
if len(bearerToken) > 0 {
rt = httputil.NewBearerAuthRoundTripper(bearerToken, rt)
}

View file

@ -550,7 +550,7 @@ func (sd *StaticProvider) Run(ch chan<- *config.TargetGroup, done <-chan struct{
<-done
}
// TargetGroups returns the provider's target groups.
// Sources returns the provider's sources.
func (sd *StaticProvider) Sources() (srcs []string) {
for _, tg := range sd.TargetGroups {
srcs = append(srcs, tg.Source)

View file

@ -52,13 +52,13 @@ func (s AlertState) String() string {
}
const (
// Inactive alerts are neither firing nor pending.
// StateInactive is the state of an alert that is either firing nor pending.
StateInactive AlertState = iota
// Pending alerts have been active for less than the configured
// threshold duration.
// StatePending is the state of an alert that has been active for less than
// the configured threshold duration.
StatePending
// Firing alerts have been active for longer than the configured
// threshold duration.
// StateFiring is the state of an alert that has been active for longer than
// the configured threshold duration.
StateFiring
)

View file

@ -269,7 +269,7 @@ func (m *Manager) runIteration() {
float64(duration / time.Millisecond),
)
default:
panic(fmt.Errorf("Unknown rule type: %T", rule))
panic(fmt.Errorf("unknown rule type: %T", rule))
}
for _, s := range vector {

View file

@ -638,16 +638,16 @@ func (it *memorySeriesIterator) chunkIterator(i int) chunkIterator {
type nopSeriesIterator struct{}
// ValueAtTime implements SeriesIterator.
func (_ nopSeriesIterator) ValueAtTime(t model.Time) []model.SamplePair {
func (i nopSeriesIterator) ValueAtTime(t model.Time) []model.SamplePair {
return []model.SamplePair{}
}
// BoundaryValues implements SeriesIterator.
func (_ nopSeriesIterator) BoundaryValues(in metric.Interval) []model.SamplePair {
func (i nopSeriesIterator) BoundaryValues(in metric.Interval) []model.SamplePair {
return []model.SamplePair{}
}
// RangeValues implements SeriesIterator.
func (_ nopSeriesIterator) RangeValues(in metric.Interval) []model.SamplePair {
func (i nopSeriesIterator) RangeValues(in metric.Interval) []model.SamplePair {
return []model.SamplePair{}
}

View file

@ -101,7 +101,8 @@ func query(q string, timestamp model.Time, queryEngine *promql.Engine) (queryRes
return result, nil
}
type templateExpander struct {
// Expander executes templates in text or HTML mode with a common set of Prometheus template functions.
type Expander struct {
text string
name string
data interface{}
@ -109,8 +110,8 @@ type templateExpander struct {
}
// NewTemplateExpander returns a template expander ready to use.
func NewTemplateExpander(text string, name string, data interface{}, timestamp model.Time, queryEngine *promql.Engine, pathPrefix string) *templateExpander {
return &templateExpander{
func NewTemplateExpander(text string, name string, data interface{}, timestamp model.Time, queryEngine *promql.Engine, pathPrefix string) *Expander {
return &Expander{
text: text,
name: name,
data: data,
@ -249,16 +250,16 @@ func NewTemplateExpander(text string, name string, data interface{}, timestamp m
}
}
// Funcs adds the functions in fm to the templateExpander's function map.
// Funcs adds the functions in fm to the Expander's function map.
// Existing functions will be overwritten in case of conflict.
func (te templateExpander) Funcs(fm text_template.FuncMap) {
func (te Expander) Funcs(fm text_template.FuncMap) {
for k, v := range fm {
te.funcMap[k] = v
}
}
// Expand a template.
func (te templateExpander) Expand() (result string, resultErr error) {
// Expand expands a template in text (non-HTML) mode.
func (te Expander) Expand() (result string, resultErr error) {
// It'd better to have no alert description than to kill the whole process
// if there's a bug in the template.
defer func() {
@ -283,8 +284,8 @@ func (te templateExpander) Expand() (result string, resultErr error) {
return buffer.String(), nil
}
// Expand a template with HTML escaping, with templates read from the given files.
func (te templateExpander) ExpandHTML(templateFiles []string) (result string, resultErr error) {
// ExpandHTML expands a template with HTML escaping, with templates read from the given files.
func (te Expander) ExpandHTML(templateFiles []string) (result string, resultErr error) {
defer func() {
if r := recover(); r != nil {
var ok bool

View file

@ -77,7 +77,7 @@ func (c callbackCloser) Close() {
// NewCallbackCloser returns a Closer that calls the provided function upon
// closing.
func NewCallbackCloser(fn func()) *callbackCloser {
func NewCallbackCloser(fn func()) Closer {
return &callbackCloser{
fn: fn,
}

View file

@ -32,7 +32,7 @@ type API struct {
QueryEngine *promql.Engine
}
// RegisterHandler registers the handler for the various endpoints below /api.
// Register registers the handler for the various endpoints below /api.
func (api *API) Register(router *route.Router) {
router.Get("/query", handle("query", api.Query))
router.Get("/query_range", handle("query_range", api.QueryRange))

View file

@ -225,7 +225,7 @@ func (api *API) Metrics(w http.ResponseWriter, r *http.Request) {
resultBytes, err := json.Marshal(metricNames)
if err != nil {
log.Error("Error marshalling metric names: ", err)
httpJSONError(w, fmt.Errorf("Error marshalling metric names: %s", err), http.StatusInternalServerError)
httpJSONError(w, fmt.Errorf("error marshalling metric names: %s", err), http.StatusInternalServerError)
return
}
w.Write(resultBytes)

View file

@ -27,6 +27,7 @@ import (
"github.com/prometheus/common/model"
)
// Federation implements a web handler to serve scrape federation requests.
type Federation struct {
Storage local.Storage
}

View file

@ -337,11 +337,11 @@ func (h *Handler) consolesPath() string {
func (h *Handler) getTemplate(name string) (string, error) {
baseTmpl, err := h.getTemplateFile("_base")
if err != nil {
return "", fmt.Errorf("Error reading base template: %s", err)
return "", fmt.Errorf("error reading base template: %s", err)
}
pageTmpl, err := h.getTemplateFile(name)
if err != nil {
return "", fmt.Errorf("Error reading page template %s: %s", name, err)
return "", fmt.Errorf("error reading page template %s: %s", name, err)
}
return baseTmpl + pageTmpl, nil
}