Like Prometheus, but for logs.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
loki/pkg/tool/client/rules.go

110 lines
2.4 KiB

package client
import (
"context"
"fmt"
"io"
"net/url"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/grafana/loki/v3/pkg/tool/rules/rwrulefmt"
)
// CreateRuleGroup creates a new rule group
func (r *LokiClient) CreateRuleGroup(ctx context.Context, namespace string, rg rwrulefmt.RuleGroup) error {
payload, err := yaml.Marshal(&rg)
if err != nil {
return err
}
escapedNamespace := url.PathEscape(namespace)
path := r.apiPath + "/" + escapedNamespace
res, err := r.doRequest(ctx, path, "POST", payload)
if err != nil {
return err
}
res.Body.Close()
return nil
}
// DeleteRuleGroup creates a new rule group
func (r *LokiClient) DeleteRuleGroup(ctx context.Context, namespace, groupName string) error {
escapedNamespace := url.PathEscape(namespace)
escapedGroupName := url.PathEscape(groupName)
path := r.apiPath + "/" + escapedNamespace + "/" + escapedGroupName
res, err := r.doRequest(ctx, path, "DELETE", nil)
if err != nil {
return err
}
res.Body.Close()
return nil
}
// GetRuleGroup retrieves a rule group
func (r *LokiClient) GetRuleGroup(ctx context.Context, namespace, groupName string) (*rwrulefmt.RuleGroup, error) {
escapedNamespace := url.PathEscape(namespace)
escapedGroupName := url.PathEscape(groupName)
path := r.apiPath + "/" + escapedNamespace + "/" + escapedGroupName
fmt.Println(path)
res, err := r.doRequest(ctx, path, "GET", nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
rg := rwrulefmt.RuleGroup{}
err = yaml.Unmarshal(body, &rg)
if err != nil {
log.WithFields(log.Fields{
"body": string(body),
}).Debugln("failed to unmarshal rule group from response")
return nil, errors.Wrap(err, "unable to unmarshal response")
}
return &rg, nil
}
// ListRules retrieves a rule group
func (r *LokiClient) ListRules(ctx context.Context, namespace string) (map[string][]rwrulefmt.RuleGroup, error) {
path := r.apiPath
if namespace != "" {
path = path + "/" + namespace
}
res, err := r.doRequest(ctx, path, "GET", nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
ruleSet := map[string][]rwrulefmt.RuleGroup{}
err = yaml.Unmarshal(body, &ruleSet)
if err != nil {
return nil, err
}
return ruleSet, nil
}