Documentation
¶
Index ¶
- Constants
- Variables
- func GetAlertStatusColor(status model.AlertStatus) string
- func GetExtraDataFromContext(ctx context.Context) ([]json.RawMessage, bool)
- func JoinURLPath(base, additionalPath string, logger log.Logger) string
- func TruncateInBytes(s string, n int) (string, bool)
- func TruncateInRunes(s string, n int) (string, bool)
- type AlertStateType
- type Base
- type Call
- type CommaSeparatedStrings
- type DecryptFunc
- type EmailSender
- type EmailSenderConfig
- type EmbeddedContent
- type HMACConfig
- type HTTPCfg
- type Message
- type Metadata
- type MockWebhookSender
- type NotificationServiceMock
- type OptionalNumber
- type SendEmailSettings
- type SendWebhookSettings
- type TLSConfig
- type WebhookSender
Constants ¶
const ( ColorAlertFiring = "#D63232" ColorAlertResolved = "#36a64f" AlertStateAlerting AlertStateType = "alerting" AlertStateOK AlertStateType = "ok" )
const (
ExtraDataKey extraDataKey = iota
)
Variables ¶
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.
var SendHTTPRequest = func(ctx context.Context, url *url.URL, cfg HTTPCfg, logger log.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 { level.Error(logger).Log("msg", "failed to close response Body", "err", 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 { level.Warn(logger).Log("msg", "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) } level.Debug(logger).Log("msg", "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 GetExtraDataFromContext ¶
func GetExtraDataFromContext(ctx context.Context) ([]json.RawMessage, bool)
func TruncateInBytes ¶
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 ¶
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 {
Index int
Name string
Type string
UID string
DisableResolveMessage bool
// contains filtered or unexported fields
}
Base is the base implementation of a notifier. It contains the common fields across all notifier types.
func (*Base) GetDisableResolveMessage ¶
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 EmailSender ¶
type EmailSender interface {
SendEmail(ctx context.Context, cmd *SendEmailSettings) error
}
func NewEmailSender ¶
func NewEmailSender(cfg EmailSenderConfig) (EmailSender, error)
NewEmailSender takes a configuration and returns a new EmailSender.
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
SentBy string
// UseBCC indicates whether to send emails using BCC
// instead of the TO field when SingleEmail is false.
// If both UseBCC and SingleEmail are true, UseBCC is ignored
// and recipients are placed in the TO field.
UseBCC bool
}
type EmbeddedContent ¶
type HMACConfig ¶
type HMACConfig struct {
// Secret to use for HMAC signing.
Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`
// Header is the name of the header containing the HMAC signature.
Header string `json:"header,omitempty" yaml:"header,omitempty"`
// TimestampHeader is the name of the header containing the timestamp
// used to generate the HMAC signature. If empty, timestamp is not included.
TimestampHeader string `yaml:"timestampHeader,omitempty" json:"timestampHeader,omitempty"`
}
HMACConfig contains configuration for HMAC signing of HTTP requests
type Message ¶
type Message struct {
To []string
From string
Subject string
Body map[string]string
EmbeddedFiles []string
EmbeddedContents []EmbeddedContent
ReplyTo []string
SingleEmail bool
}
Message representats an email message.
type MockWebhookSender ¶
type MockWebhookSender struct {
Calls []Call
SendWebhookFunc func(ctx context.Context, cmd *SendWebhookSettings) error
}
func NewMockWebhookSender ¶
func NewMockWebhookSender() *MockWebhookSender
func (*MockWebhookSender) SendWebhook ¶
func (m *MockWebhookSender) SendWebhook(ctx context.Context, l log.Logger, cmd *SendWebhookSettings) error
type NotificationServiceMock ¶
type NotificationServiceMock struct {
WebhookCalls []SendWebhookSettings
Webhook SendWebhookSettings
EmailSync SendEmailSettings
ShouldError error
ResponseBody []byte
StatusCode int
}
func MockNotificationService ¶
func MockNotificationService() *NotificationServiceMock
func (*NotificationServiceMock) SendEmail ¶
func (ns *NotificationServiceMock) SendEmail(_ context.Context, cmd *SendEmailSettings) error
func (*NotificationServiceMock) SendWebhook ¶
func (ns *NotificationServiceMock) SendWebhook(_ context.Context, _ log.Logger, cmd *SendWebhookSettings) error
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
EmbeddedContents []EmbeddedContent
}
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 is a function that will validate the response body and statusCode of the webhook. Any returned error will cause the webhook request to be considered failed.
// This can be useful when a webhook service communicates failures in creative ways, such as using the response body instead of the status code.
Validation func(body []byte, statusCode int) error
TLSConfig *tls.Config
HMACConfig *HMACConfig
}
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
}