receivers

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: AGPL-3.0 Imports: 16 Imported by: 0

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 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 HTTPCfg

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

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 {
	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 SendEmailAttachFile

type SendEmailAttachFile struct {
	Name    string
	Content []byte
}

SendEmailAttachFile is a definition of the attached files without path

type SendEmailSettings

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

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
}

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