| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net" |
| 8 | |
| 9 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 10 | log "github.com/sirupsen/logrus" |
| 11 | ) |
| 12 | |
| 13 | type NotificationSender struct { |
| 14 | notificationCh chan types.NotificationMessage |
| 15 | socket string |
| 16 | } |
| 17 | |
| 18 | func NewNotificationSender(socket string) *NotificationSender { |
| 19 | if socket == "" { |
| 20 | return &NotificationSender{ |
| 21 | socket: "", |
| 22 | notificationCh: nil, |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | return &NotificationSender{ |
| 27 | socket: socket, |
| 28 | notificationCh: make(chan types.NotificationMessage, 100), |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func (s *NotificationSender) Send(notification types.NotificationMessage) { |
| 33 | if s.notificationCh == nil { |
| 34 | return |
| 35 | } |
| 36 | select { |
| 37 | case s.notificationCh <- notification: |
| 38 | default: |
| 39 | log.Warn("unable to send notification") |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func (s *NotificationSender) Start(ctx context.Context) { |
| 44 | if s.notificationCh == nil { |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | for { |
| 49 | select { |
| 50 | case <-ctx.Done(): |
| 51 | return |
| 52 | case notification := <-s.notificationCh: |
| 53 | if err := s.sendToSocket(notification); err != nil { |
| 54 | log.Errorf("failed to send notification: %v", err) |
| 55 | continue |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func (s *NotificationSender) sendToSocket(notification types.NotificationMessage) error { |
| 62 | if s.socket == "" { |
| 63 | return nil |
| 64 | } |
| 65 | conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: s.socket, Net: "unix"}) |
| 66 | if err != nil { |
| 67 | return fmt.Errorf("cannot dial notification socket: %w", err) |
| 68 | } |
| 69 | defer conn.Close() |
| 70 | enc := json.NewEncoder(conn) |
| 71 | if err := enc.Encode(notification); err != nil { |
| 72 | return fmt.Errorf("failed to encode notification: %w", err) |
| 73 | } |
| 74 | return nil |
| 75 | } |