receivers

package
v0.0.0-...-be61d61 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2024 License: AGPL-3.0 Imports: 23 Imported by: 4

Documentation

Index

Constants

View Source
const (
	ColorAlertFiring   = "#D63232"
	ColorAlertResolved = "#36a64f"

	AlertStateAlerting AlertStateType = "alerting"
	AlertStateOK       AlertStateType = "ok"
)

Variables

View Source
var GetBoundary = func() string {
	return ""
}

GetBoundary is used for overriding the behaviour for tests and set a boundary for multipart Body. DO NOT set this outside tests.

View Source
var SendHTTPRequest = func(ctx context.Context, url *url.URL, cfg HTTPCfg, logger logging.Logger) ([]byte, error) {
	var reader io.Reader
	if len(cfg.Body) > 0 {
		reader = bytes.NewReader(cfg.Body)
	}
	request, err := http.NewRequestWithContext(ctx, http.MethodPost, url.String(), reader)
	if err != nil {
		return nil, fmt.Errorf("failed to create HTTP request: %w", err)
	}
	if cfg.User != "" && cfg.Password != "" {
		request.SetBasicAuth(cfg.User, cfg.Password)
	}

	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("User-Agent", "Grafana")
	netTransport := &http.Transport{
		TLSClientConfig: &tls.Config{
			Renegotiation: tls.RenegotiateFreelyAsClient,
		},
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout: 30 * time.Second,
		}).DialContext,
		TLSHandshakeTimeout: 5 * time.Second,
	}
	netClient := &http.Client{
		Timeout:   time.Second * 30,
		Transport: netTransport,
	}
	resp, err := netClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			logger.Warn("failed to close response Body", "error", err)
		}
	}()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response Body: %w", err)
	}

	if resp.StatusCode/100 != 2 {
		logger.Warn("HTTP request failed", "url", request.URL.String(), "statusCode", resp.Status, "Body",
			string(respBody))
		return nil, fmt.Errorf("failed to send HTTP request - status code %d", resp.StatusCode)
	}

	logger.Debug("sending HTTP request succeeded", "url", request.URL.String(), "statusCode", resp.Status)
	return respBody, nil
}

SendHTTPRequest sends an HTTP request. Stubbable by tests.

Functions

func GetAlertStatusColor

func GetAlertStatusColor(status model.AlertStatus) string

func JoinURLPath

func JoinURLPath(base, additionalPath string, logger logging.Logger) string

func NewEmailSenderFactory

func NewEmailSenderFactory(cfg EmailSenderConfig) func(Metadata) (EmailSender, error)

NewEmailSenderFactory takes a configuration and returns a new EmailSender factory function.

func NewTLSClient

func NewTLSClient(tlsConfig *tls.Config) *http.Client

NewTLSClient creates a new HTTP client with the provided TLS configuration or with default settings.

func TruncateInBytes

func TruncateInBytes(s string, n int) (string, bool)

TruncateInBytes truncates a string to fit the given size in Bytes. TODO: This is more advanced than the upstream's TruncateInBytes. We should consider upstreaming this, and removing it from here.

func TruncateInRunes

func TruncateInRunes(s string, n int) (string, bool)

Copied from https://github.com/prometheus/alertmanager/blob/main/notify/util.go, please remove once we're on-par with upstream. TruncateInrunes truncates a string to fit the given size in Runes.

Types

type AlertStateType

type AlertStateType string

type Base

type Base struct {
	Name                  string
	Type                  string
	UID                   string
	DisableResolveMessage bool
}

Base is the base implementation of a notifier. It contains the common fields across all notifier types.

func NewBase

func NewBase(cfg Metadata) *Base

func (*Base) GetDisableResolveMessage

func (n *Base) GetDisableResolveMessage() bool

type CommaSeparatedStrings

type CommaSeparatedStrings []string

func (*CommaSeparatedStrings) MarshalJSON

func (r *CommaSeparatedStrings) MarshalJSON() ([]byte, error)

func (*CommaSeparatedStrings) MarshalYAML

func (r *CommaSeparatedStrings) MarshalYAML() ([]byte, error)

func (*CommaSeparatedStrings) UnmarshalJSON

func (r *CommaSeparatedStrings) UnmarshalJSON(b []byte) error

func (*CommaSeparatedStrings) UnmarshalYAML

func (r *CommaSeparatedStrings) UnmarshalYAML(b []byte) error

type DecryptFunc

type DecryptFunc func(key string, fallback string) string

type EmailSender

type EmailSender interface {
	SendEmail(ctx context.Context, cmd *SendEmailSettings) error
}

type EmailSenderConfig

type EmailSenderConfig struct {
	AuthPassword   string
	AuthUser       string
	CertFile       string
	ContentTypes   []string
	EhloIdentity   string
	ExternalURL    string
	FromName       string
	FromAddress    string
	Host           string
	KeyFile        string
	SkipVerify     bool
	StartTLSPolicy string
	StaticHeaders  map[string]string
	Version        string
}

type HTTPCfg

type HTTPCfg struct {
	Body     []byte
	User     string
	Password string
}

type Message

type Message struct {
	To            []string
	From          string
	Subject       string
	Body          map[string]string
	EmbeddedFiles []string
	ReplyTo       []string
	SingleEmail   bool
}

Message representats an email message.

type Metadata

type Metadata struct {
	UID                   string
	Name                  string
	Type                  string
	DisableResolveMessage bool
}

Metadata contains the metadata of the notifier.

type NotificationServiceMock

type NotificationServiceMock struct {
	WebhookCalls []SendWebhookSettings
	Webhook      SendWebhookSettings
	EmailSync    SendEmailSettings
	ShouldError  error
}

func MockNotificationService

func MockNotificationService() *NotificationServiceMock

func (*NotificationServiceMock) SendEmail

func (*NotificationServiceMock) SendWebhook

type OptionalNumber

type OptionalNumber string

OptionalNumber represents a string that may be a number. It implements a special JSON decoder to accept either a string or a number. The difference from json.Number implementation is that it supports empty string. The json.Number fails if the field is an empty string. The reason we need this is that some notifiers used to accept strings as numbers (even invalid and empty strings), and treated all non-numbers as 0 (see simplejson). This implementation will not allow invalid strings but still more relaxed than json.Number or int64. It will be removed in the future

func (OptionalNumber) Int64

func (o OptionalNumber) Int64() (int64, error)

Int64 returns the number as an int64. If string is empty, it returns 0.

func (OptionalNumber) String

func (o OptionalNumber) String() string

func (*OptionalNumber) UnmarshalJSON

func (o *OptionalNumber) UnmarshalJSON(bytes []byte) error

type SendEmailSettings

type SendEmailSettings struct {
	To            []string
	SingleEmail   bool
	Template      string
	Subject       string
	Data          map[string]interface{}
	ReplyTo       []string
	EmbeddedFiles []string
}

SendEmailSettings is the command for sending emails

type SendWebhookSettings

type SendWebhookSettings struct {
	URL         string
	User        string
	Password    string
	Body        string
	HTTPMethod  string
	HTTPHeader  map[string]string
	ContentType string
	Validation  func(body []byte, statusCode int) error
	TLSConfig   *tls.Config
}

type TLSConfig

type TLSConfig struct {
	CACertificate      string `json:"caCertificate,omitempty" yaml:"caCertificate,omitempty"`
	ClientCertificate  string `json:"clientCertificate,omitempty" yaml:"clientCertificate,omitempty"`
	ClientKey          string `json:"clientKey,omitempty" yaml:"clientKey,omitempty"`
	InsecureSkipVerify bool   `json:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty"`
	ServerName         string
}

func (*TLSConfig) ToCryptoTLSConfig

func (cfg *TLSConfig) ToCryptoTLSConfig() (*tls.Config, error)

type WebhookSender

type WebhookSender interface {
	SendWebhook(ctx context.Context, cmd *SendWebhookSettings) error
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL