1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-14 11:03:09 +02:00
sap-jenkins-library/pkg/ans/event.go

127 lines
4.0 KiB
Go
Raw Normal View History

package ans
import (
"bytes"
"encoding/json"
"fmt"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
uni *ut.UniversalTranslator
validate *validator.Validate
)
const (
authHeaderKey = "Authorization"
infoSeverity = "INFO"
noticeSeverity = "NOTICE"
warningSeverity = "WARNING"
errorSeverity = "ERROR"
fatalSeverity = "FATAL"
exceptionCategory = "EXCEPTION"
alertCategory = "ALERT"
notificationCategory = "NOTIFICATION"
)
// Event structure of the SAP Alert Notification Service
type Event struct {
EventType string `json:"eventType,omitempty"`
EventTimestamp int64 `json:"eventTimestamp,omitempty" validate:"omitempty,min=0"`
Severity string `json:"severity,omitempty" validate:"omitempty,oneof=INFO NOTICE WARNING ERROR FATAL"`
Category string `json:"category,omitempty" validate:"omitempty,oneof=EXCEPTION ALERT NOTIFICATION"`
Subject string `json:"subject,omitempty"`
Body string `json:"body,omitempty"`
Priority int `json:"priority,omitempty" validate:"omitempty,min=1,max=1000"`
Tags map[string]interface{} `json:"tags,omitempty"`
Resource *Resource `json:"resource,omitempty"`
}
// Resource structure of the SAP Alert Notification Service Event
type Resource struct {
ResourceName string `json:"resourceName,omitempty"`
ResourceType string `json:"resourceType,omitempty"`
ResourceInstance string `json:"resourceInstance,omitempty"`
Tags map[string]interface{} `json:"tags,omitempty"`
}
// MergeWithJSON unmarshalls an ANS Event JSON string and merges it with the existing receiver Event
func (event *Event) MergeWithJSON(eventJSON []byte) (err error) {
if err = strictUnmarshal(eventJSON, &event); err != nil {
return errors.Wrapf(err, "error unmarshalling ANS event from JSON string %q", eventJSON)
}
return
}
// Validate will validate the Event according to the 'validate' tags in the struct
func (event *Event) Validate() (err error) {
validate = validator.New()
if err = validate.Struct(event); err != nil {
translator := newTranslator(validate)
errs := err.(validator.ValidationErrors)
err = fmt.Errorf("event JSON failed the validation")
for _, fieldError := range errs.Translate(translator) {
err = errors.Wrap(err, fieldError)
}
}
return
}
[ANS] logrus hook (#3671) * Add ans implementation * Remove todo comment * Rename test function Co-authored-by: Linda Siebert <39100394+LindaSieb@users.noreply.github.com> * Better wording Co-authored-by: Linda Siebert <39100394+LindaSieb@users.noreply.github.com> * Add reading of response body function * Use http pkg ReadResponseBody * Check read error * Better test case description * Fix formatting * Create own package for read response body * Omit empty nested resource struct * Separate Resource struct from Event struct * Merge and unmarshall instead of only unmarshalling * Improve status code error message * Remove unchangeable event fields * Separate event parts * Change log level setter function * Restructure ans send test * Revert exporting readResponseBody function Instead the code is duplicated in the xsuaa and ans package * Add check correct ans setup request * Add set options function for mocking * Review fixes * Correct function name * Use strict unmarshalling * Validate event * Move functions * Add documentation comments * improve test * Validate event * Add logrus hook for ans * Set defaults on new hook creation * Fix log level on error * Don't alter entry log level * Set severity fatal on 'fatal error' log message * Ensure that log entries don't affect each other * Remove unnecessary correlationID * Use file path instead of event template string * Improve warning messages * Add empty log message check * Allow configuration from file and string * Add sourceEventId to tags * Change resourceType to Pipeline * Use structured config approach * Use new log level set function * Check correct setup and return error * Mock http requests * Only send log level warning or higher * Use new function name * One-liner ifs * Improve test name * Fix tests * Prevent double firing * Reduce Fire test size * Add error message to test * Reduce newANSHook test size * Further check error * Rename to defaultEvent in hook struct * Reduce ifs further * Fix set error category test The ansHook Fire test cannot run in parallel, as it would affect the other tests that use the error category. * Change function name to SetServiceKey * Validate event * Rename to eventTemplate in hook struct * Move copy to event.go * Fix function mix * Remove unnecessary cleanup * Remove parallel test The translation fails now and again when parallel is on. * Remove prefix test * Remove unused copyEvent function * Fix ifs * Add docu comment * Register ans hook from pkg * register hook and setup event template seperately * Exclusively read eventTemplate from environment * setupEventTemplate tests * adjust hook levels test * sync tests- wlill still fail * migrate TestANSHook_registerANSHook test * fixes * review - cleanup, reuse poke * Apply suggestions from code review * Change subject * Review fixes * Set stepName 'n/a' if not available * Fix fire tests Co-authored-by: Linda Siebert <39100394+LindaSieb@users.noreply.github.com> Co-authored-by: Roland Stengel <r.stengel@sap.com>
2022-06-17 16:40:45 +02:00
// Copy will copy an ANS Event
func (event *Event) Copy() (destination Event, err error) {
var sourceJSON []byte
if sourceJSON, err = json.Marshal(event); err != nil {
return
}
err = destination.MergeWithJSON(sourceJSON)
return
}
// SetSeverityAndCategory takes the logrus log level and sets the corresponding ANS severity and category string
func (event *Event) SetSeverityAndCategory(level logrus.Level) {
switch level {
case logrus.InfoLevel:
event.Severity = infoSeverity
event.Category = notificationCategory
case logrus.DebugLevel:
event.Severity = infoSeverity
event.Category = notificationCategory
case logrus.WarnLevel:
event.Severity = warningSeverity
event.Category = alertCategory
case logrus.ErrorLevel:
event.Severity = errorSeverity
event.Category = exceptionCategory
case logrus.FatalLevel:
event.Severity = fatalSeverity
event.Category = exceptionCategory
case logrus.PanicLevel:
event.Severity = fatalSeverity
event.Category = exceptionCategory
}
}
func strictUnmarshal(data []byte, v interface{}) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(v)
}
func newTranslator(validate *validator.Validate) ut.Translator {
eng := en.New()
uni = ut.New(eng, eng)
translator, _ := uni.GetTranslator("en")
en_translations.RegisterDefaultTranslations(validate, translator)
return translator
}