1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-14 11:03:09 +02:00
sap-jenkins-library/pkg/log/ansHook.go
Oliver Feldmann c5b83de7e1
[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

142 lines
4.3 KiB
Go

package log
import (
"fmt"
"github.com/SAP/jenkins-library/pkg/ans"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"os"
"strings"
)
// ANSHook is used to set the hook features for the logrus hook
type ANSHook struct {
client ans.Client
eventTemplate ans.Event
firing bool
}
// Levels returns the supported log level of the hook.
func (ansHook *ANSHook) Levels() []logrus.Level {
return []logrus.Level{logrus.WarnLevel, logrus.ErrorLevel, logrus.PanicLevel, logrus.FatalLevel}
}
// Fire creates a new event from the logrus and sends an event to the ANS backend
func (ansHook *ANSHook) Fire(entry *logrus.Entry) (err error) {
if ansHook.firing {
return fmt.Errorf("ANS hook has already been fired")
}
ansHook.firing = true
defer func() { ansHook.firing = false }()
if len(strings.TrimSpace(entry.Message)) == 0 {
return
}
var event ans.Event
if event, err = ansHook.eventTemplate.Copy(); err != nil {
return
}
logLevel := entry.Level
event.SetSeverityAndCategory(logLevel)
var stepName string
if entry.Data["stepName"] != nil {
stepName = fmt.Sprint(entry.Data["stepName"])
} else {
stepName = "n/a"
}
event.Tags["pipeline:stepName"] = stepName
if errorCategory := GetErrorCategory().String(); errorCategory != "undefined" {
event.Tags["pipeline:errorCategory"] = errorCategory
}
event.EventTimestamp = entry.Time.Unix()
if event.Subject == "" {
event.Subject = fmt.Sprintf("Pipeline step '%s' sends '%s'", stepName, event.Severity)
}
event.Body = entry.Message
event.Tags["pipeline:logLevel"] = logLevel.String()
return ansHook.client.Send(event)
}
type registrationUtil interface {
ans.Client
registerHook(hook *ANSHook)
}
type registrationUtilImpl struct {
ans.Client
}
func (u *registrationUtilImpl) registerHook(hook *ANSHook) {
RegisterHook(hook)
}
func (u *registrationUtilImpl) registerSecret(secret string) {
RegisterSecret(secret)
}
// RegisterANSHookIfConfigured creates a new ANS hook for logrus if it is configured and registers it
func RegisterANSHookIfConfigured(correlationID string) error {
return registerANSHookIfConfigured(correlationID, &registrationUtilImpl{Client: &ans.ANS{}})
}
func registerANSHookIfConfigured(correlationID string, util registrationUtil) error {
ansServiceKeyJSON := os.Getenv("PIPER_ansHookServiceKey")
if len(ansServiceKeyJSON) == 0 {
return nil
}
ansServiceKey, err := ans.UnmarshallServiceKeyJSON(ansServiceKeyJSON)
if err != nil {
return errors.Wrap(err, "cannot initialize SAP Alert Notification Service due to faulty serviceKey json")
}
RegisterSecret(ansServiceKey.ClientSecret)
util.SetServiceKey(ansServiceKey)
if err = util.CheckCorrectSetup(); err != nil {
return errors.Wrap(err, "check http request to SAP Alert Notification Service failed; not setting up the ANS hook")
}
eventTemplate, err := setupEventTemplate(os.Getenv("PIPER_ansEventTemplate"), correlationID)
if err != nil {
return err
}
util.registerHook(&ANSHook{
client: util,
eventTemplate: eventTemplate,
})
return nil
}
func setupEventTemplate(customerEventTemplate, correlationID string) (ans.Event, error) {
event := ans.Event{
EventType: "Piper",
Tags: map[string]interface{}{"ans:correlationId": correlationID, "ans:sourceEventId": correlationID},
Resource: &ans.Resource{
ResourceType: "Pipeline",
ResourceName: "Pipeline",
},
}
if len(customerEventTemplate) > 0 {
if err := event.MergeWithJSON([]byte(customerEventTemplate)); err != nil {
Entry().WithField("stepName", "ANS").Warnf("provided SAP Alert Notification Service event template '%s' could not be unmarshalled: %v", customerEventTemplate, err)
return ans.Event{}, errors.Wrapf(err, "provided SAP Alert Notification Service event template '%s' could not be unmarshalled", customerEventTemplate)
}
}
if len(event.Severity) > 0 {
Entry().WithField("stepName", "ANS").Warnf("event severity set to '%s' will be overwritten according to the log level", event.Severity)
event.Severity = ""
}
if len(event.Category) > 0 {
Entry().WithField("stepName", "ANS").Warnf("event category set to '%s' will be overwritten according to the log level", event.Category)
event.Category = ""
}
if err := event.Validate(); err != nil {
return ans.Event{}, errors.Wrap(err, "did not initialize SAP Alert Notification Service due to faulty event template json")
}
return event, nil
}