github.com/binkynet/BinkyNet@v1.12.1-0.20240421190447-da4e34c20be0/netlog/receiver.go (about)

     1  // Copyright 2021 Ewout Prangsma
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // Author Ewout Prangsma
    16  //
    17  
    18  package netlog
    19  
    20  import (
    21  	"fmt"
    22  	"log"
    23  	"net"
    24  
    25  	"github.com/rs/zerolog"
    26  )
    27  
    28  // NetLogReceiver receives log messages over UDP.
    29  type NetLogReceiver struct {
    30  	conns []*net.UDPConn
    31  }
    32  
    33  type NetLogMessage struct {
    34  	Level   zerolog.Level
    35  	Message []byte
    36  	Address string
    37  }
    38  
    39  type NetLogCallback func(NetLogMessage)
    40  
    41  const (
    42  	maxDatagramSize = 8192
    43  )
    44  
    45  // NewLogReceiver constructs a new UDP log receiver
    46  func NewLogReceiver(cb NetLogCallback) (*NetLogReceiver, error) {
    47  	addr, err := net.ResolveUDPAddr("udp", logAddr)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	r := &NetLogReceiver{}
    52  	itfs, err := net.Interfaces()
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  	expectedFlags := net.FlagMulticast | net.FlagUp
    57  	for _, itf := range itfs {
    58  		if itf.Flags&expectedFlags == expectedFlags {
    59  			fmt.Printf("Interface: %s\n", itf.Name)
    60  			c, err := net.ListenMulticastUDP("udp", &itf, addr)
    61  			if err != nil {
    62  				fmt.Printf("Cannot listen on %s: %s\n", itf.Name, err)
    63  				continue
    64  			}
    65  			c.SetReadBuffer(maxDatagramSize)
    66  			r.conns = append(r.conns, c)
    67  			go r.run(c, cb)
    68  
    69  		}
    70  	}
    71  	return r, nil
    72  }
    73  
    74  func (r *NetLogReceiver) run(conn *net.UDPConn, cb NetLogCallback) {
    75  	b := make([]byte, maxDatagramSize)
    76  	for {
    77  		n, addr, err := conn.ReadFromUDP(b)
    78  		if err != nil {
    79  			log.Fatal("ReadFromUDP failed:", err)
    80  		} else if n > 0 {
    81  			cb(NetLogMessage{
    82  				Level:   zerolog.Level(b[0]),
    83  				Message: b[1:n],
    84  				Address: addr.String(),
    85  			})
    86  		}
    87  	}
    88  }