github.com/helmwave/helmwave@v0.36.4-0.20240509190856-b35563eba4c6/pkg/monitor/prometheus/config.go (about)

     1  package prometheus
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/prometheus/client_golang/api"
     8  	v1 "github.com/prometheus/client_golang/api/prometheus/v1"
     9  	"github.com/prometheus/common/model"
    10  	log "github.com/sirupsen/logrus"
    11  )
    12  
    13  const (
    14  	TYPE = "prometheus"
    15  )
    16  
    17  // Config is the main monitor Config.
    18  type Config struct {
    19  	client   v1.API     `yaml:"-" json:"-"`
    20  	log      *log.Entry `yaml:"-" json:"-"`
    21  	URL      string     `yaml:"url" json:"url" jsonschema:"required,title=Prometheus URL"`
    22  	Expr     string     `yaml:"expr" json:"expr" jsonschema:"required,title=Prometheus expression"`
    23  	Insecure bool       `yaml:"insecure" json:"insecure" jsonschema:"default=false"`
    24  }
    25  
    26  func NewConfig() *Config {
    27  	return &Config{}
    28  }
    29  
    30  func (c *Config) Init(_ context.Context, logger *log.Entry) error {
    31  	client, err := api.NewClient(api.Config{Address: c.URL})
    32  	if err != nil {
    33  		return NewPrometheusClientError(err)
    34  	}
    35  
    36  	c.client = v1.NewAPI(client)
    37  	c.log = logger
    38  
    39  	return nil
    40  }
    41  
    42  func (c *Config) Run(ctx context.Context) error {
    43  	l := c.log
    44  
    45  	now := time.Now()
    46  
    47  	result, warns, err := c.client.Query(ctx, c.Expr, now)
    48  
    49  	if len(warns) > 0 {
    50  		l = l.WithField("warnings", warns)
    51  	}
    52  
    53  	if err != nil {
    54  		return NewPrometheusClientError(err)
    55  	}
    56  
    57  	l.WithField("result", result).Trace("monitor response")
    58  
    59  	v, ok := result.(model.Vector)
    60  	if !ok {
    61  		err = ErrResultNotVector
    62  	}
    63  
    64  	if len(v) == 0 {
    65  		err = ErrResultEmpty
    66  	}
    67  
    68  	return err
    69  }
    70  
    71  func (c *Config) Validate() error {
    72  	if c.URL == "" {
    73  		return ErrURLEmpty
    74  	}
    75  
    76  	if c.Expr == "" {
    77  		return ErrExprEmpty
    78  	}
    79  
    80  	return nil
    81  }