Best Testkube code snippet using slacknotifier.SendEvent
watcher_service.go
Source:watcher_service.go
1package monitoring2import (3 "fmt"4 "io/ioutil"5 "sync"6 "github.com/pkg/errors"7 "github.com/sirupsen/logrus"8 "k8s.io/api/core/v1"9 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"10 "k8s.io/apimachinery/pkg/watch"11 corev1 "k8s.io/client-go/kubernetes/typed/core/v1"12)13const (14 tailLines = 200015 logsLimitBytes = 1048576 // 1MB16)17// SlackNotifier allows sending notification about messages to Slack channel.18type SlackNotifier interface {19 Notify(id, header, details string) error20}21// WatcherService allows to watch events for a given Pod and send notification to Slack if received event Type is different that `Normal`22type WatcherService struct {23 coreCli corev1.CoreV1Interface24 slackNotifier SlackNotifier25 log logrus.FieldLogger26 watchedObj map[string]*watchObj27 mux *sync.RWMutex28}29type watchObj struct {30 watcher watch.Interface31 // TODO: We used as a value the empty struct which in Go empty struct has a width of zero ( It occupies zero bytes of storage).32 // This map will be released by the GC when we will stop watching given Pod.33 // We expect that there will not be too many different events sent to Pod, so we should not have a problem with allocated memory.34 sendEvent map[string]struct{}35}36// NewWatcherService returns new instance of the WatcherService37func NewWatcherService(eventCli corev1.CoreV1Interface, slackNotifier SlackNotifier, log logrus.FieldLogger) *WatcherService {38 return &WatcherService{39 coreCli: eventCli,40 slackNotifier: slackNotifier,41 log: log.WithField("service", "monitoring:event-watcher"),42 mux: &sync.RWMutex{},43 watchedObj: make(map[string]*watchObj),44 }45}46// Register registers given obj and starts watching events from it.47// Error is not returned when object with the same Name is already registered.48func (s *WatcherService) Register(ref *v1.ObjectReference) error {49 s.mux.Lock()50 defer s.mux.Unlock()51 key := s.refKey(ref)52 if _, found := s.watchedObj[key]; found {53 return nil54 }55 nsEventCli := s.coreCli.Events(ref.Namespace)56 selector := nsEventCli.GetFieldSelector(s.selectorArgsFromRefObj(ref))57 eventWatcher, err := nsEventCli.Watch(metav1.ListOptions{58 FieldSelector: selector.String(),59 })60 if err != nil {61 return errors.Wrapf(err, "while creating watch Event interface for object %q", key)62 }63 s.watchedObj[key] = &watchObj{64 watcher: eventWatcher,65 sendEvent: make(map[string]struct{}),66 }67 go s.startWatching(ref, eventWatcher.ResultChan())68 return nil69}70func (*WatcherService) refKey(ref *v1.ObjectReference) string {71 return fmt.Sprintf("%s/%s", ref.Namespace, ref.Name)72}73func (s *WatcherService) startWatching(ref *v1.ObjectReference, events <-chan watch.Event) {74 // We will also get the restart events here, so we are not checking the status of the pod directly75 for r := range events {76 event := r.Object.(*v1.Event)77 if event.Type != v1.EventTypeNormal {78 id := s.eventKey(event)79 failLogger := s.log.WithField("ID", id)80 obj := s.watchedObj[s.refKey(ref)]81 if _, found := obj.sendEvent[id]; found {82 continue83 }84 eventMsg := fmt.Sprintf("Event type: %s, reason: %s, message: %s", event.Type, event.Reason, event.Message)85 dumpedLogs, err := s.podLogs(ref)86 if err != nil {87 failLogger.Errorf("Got error while getting log from pod: %v", err)88 }89 failureReasonHeader := fmt.Sprintf("*[Phase: MONITORING]* _Discover that Pod %s has problems_", ref.Name)90 err = s.slackNotifier.Notify(id, failureReasonHeader, eventMsg)91 if err != nil {92 failLogger.Errorf("Got error while sending notification to Slack: %v", err)93 continue94 } else {95 obj.sendEvent[id] = struct{}{}96 }97 failLogger.Infof(eventMsg)98 failLogger.Infof("Logs from Pod %s/%s: %s", ref.Namespace, ref.Name, dumpedLogs)99 }100 }101}102func (s *WatcherService) eventKey(event *v1.Event) string {103 return fmt.Sprintf("%s/%s", event.Namespace, event.Name)104}105func (s *WatcherService) podLogs(ref *v1.ObjectReference) (string, error) {106 req := s.coreCli.Pods(ref.Namespace).GetLogs(ref.Name, &v1.PodLogOptions{107 TailLines: s.int64Ptr(tailLines),108 LimitBytes: s.int64Ptr(logsLimitBytes),109 })110 readCloser, err := req.Stream()111 if err != nil {112 return "", errors.Wrap(err, "while getting log stream")113 }114 defer readCloser.Close()115 logs, err := ioutil.ReadAll(readCloser)116 if err != nil {117 return "", errors.Wrapf(err, "while reading logs from pod %s", ref.Name)118 }119 return string(logs), nil120}121// Unregister removes obj from watcher list and stop watching the events from it.122// Error is not returned when object was not registered.123func (s *WatcherService) Unregister(ref *v1.ObjectReference) error {124 s.mux.Lock()125 defer s.mux.Unlock()126 key := s.refKey(ref)127 obj, found := s.watchedObj[key]128 if !found {129 return nil130 }131 obj.watcher.Stop()132 delete(s.watchedObj, key)133 return nil134}135func (s *WatcherService) selectorArgsFromRefObj(ref *v1.ObjectReference) (*string, *string, *string, *string) {136 return s.strPtr(ref.Name), s.strPtr(ref.Namespace), s.strPtr(ref.Kind), s.strPtr(string(ref.UID))137}138func (*WatcherService) strPtr(s string) *string {139 return &s140}141func (*WatcherService) int64Ptr(i int64) *int64 {142 return &i143}...
slack.go
Source:slack.go
...17 channel: channel,18 client: slack.New(token),19 }20}21// SendEvent sends event notification to slack22func (s *SlackNotifier) SendEvent(ctx context.Context, event Event) error {23 s.log.Debug("Sending message to slack")24 targetChannel := event.Channel25 if targetChannel == "" {26 targetChannel = s.channel27 }28 var err error29 if event.IsAttachment {30 err = s.sendAttachmentMessage(ctx, event, targetChannel)31 } else {32 err = s.sendMessage(ctx, event, targetChannel)33 }34 return err35}36func (s *SlackNotifier) sendAttachmentMessage(ctx context.Context, event Event, targetChannel string) error {...
listener.go
Source:listener.go
...37 "events": fmt.Sprintf("%v", l.Events()),38 }39}40func (l *SlackListener) Notify(event testkube.Event) (result testkube.EventResult) {41 err := slacknotifier.SendEvent(event)42 if err != nil {43 return testkube.NewFailedEventResult(event.Id, err)44 }45 return testkube.NewSuccessEventResult(event.Id, "event sent to slack")46}47func (l *SlackListener) Kind() string {48 return "slack"49}...
SendEvent
Using AI Code Generation
1import (2func main() {3 message := slack.NewMessage("Hello")4 err := notifier.Send(message)5 if err != nil {6 fmt.Println(err)7 }8}9{ok true}10import (11func main() {12 message := slack.NewMessage("Hello")13 attachment := slack.Attachment{}14 attachment.AddField(slack.Field{Title: "Title", Value: "Value"})15 message.AddAttachment(attachment)16 err := notifier.Send(message)17 if err != nil {18 fmt.Println(err)19 }20}21{ok true}22import (23func main() {
SendEvent
Using AI Code Generation
1import (2func main() {3 slacknotifier.SendEvent("Hello World")4 fmt.Println("Done")5}6import (7type slackPayload struct {8}9func SendEvent(message string) {10 slackPayload := &slackPayload{Text: message}11 slackPayloadJSON, err := json.Marshal(slackPayload)12 if err != nil {13 fmt.Println(err)14 }15 if err != nil {16 fmt.Println(err)17 }18 req.Header.Set("Content-Type", "application/json")19 client := &http.Client{}20 resp, err := client.Do(req)21 if err != nil {22 fmt.Println(err)23 }24 defer resp.Body.Close()25}26require (27import (28func main() {29 slacknotifier.SendEvent("Hello World")30 fmt.Println("Done")31}32import (33func TestSendEvent(t *testing.T) {34 SendEvent("Hello World")35}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!