github.com/hhrutter/nomad@v0.6.0-rc2.0.20170723054333-80c4b03f0705/client/driver/logging/syslog_server.go (about)

     1  package logging
     2  
     3  import (
     4  	"bufio"
     5  	"log"
     6  	"net"
     7  	"sync"
     8  )
     9  
    10  // SyslogServer is a server which listens to syslog messages and parses them
    11  type SyslogServer struct {
    12  	listener net.Listener
    13  	messages chan *SyslogMessage
    14  	parser   *DockerLogParser
    15  
    16  	doneCh   chan interface{}
    17  	done     bool
    18  	doneLock sync.Mutex
    19  
    20  	logger *log.Logger
    21  }
    22  
    23  // NewSyslogServer creates a new syslog server
    24  func NewSyslogServer(l net.Listener, messages chan *SyslogMessage, logger *log.Logger) *SyslogServer {
    25  	parser := NewDockerLogParser(logger)
    26  	return &SyslogServer{
    27  		listener: l,
    28  		messages: messages,
    29  		parser:   parser,
    30  		logger:   logger,
    31  		doneCh:   make(chan interface{}),
    32  	}
    33  }
    34  
    35  // Start starts accepting syslog connections
    36  func (s *SyslogServer) Start() {
    37  	for {
    38  		select {
    39  		case <-s.doneCh:
    40  			s.listener.Close()
    41  			return
    42  		default:
    43  			connection, err := s.listener.Accept()
    44  			if err != nil {
    45  				s.logger.Printf("[ERR] logcollector.server: error in accepting connection: %v", err)
    46  				continue
    47  			}
    48  			go s.read(connection)
    49  		}
    50  	}
    51  }
    52  
    53  // read reads the bytes from a connection
    54  func (s *SyslogServer) read(connection net.Conn) {
    55  	defer connection.Close()
    56  	scanner := bufio.NewScanner(bufio.NewReader(connection))
    57  
    58  	for {
    59  		select {
    60  		case <-s.doneCh:
    61  			return
    62  		default:
    63  		}
    64  		if scanner.Scan() {
    65  			b := scanner.Bytes()
    66  			msg := s.parser.Parse(b)
    67  			s.messages <- msg
    68  		} else {
    69  			return
    70  		}
    71  	}
    72  }
    73  
    74  // Shutdown shutsdown the syslog server
    75  func (s *SyslogServer) Shutdown() {
    76  	s.doneLock.Lock()
    77  	s.doneLock.Unlock()
    78  
    79  	if !s.done {
    80  		close(s.doneCh)
    81  		close(s.messages)
    82  		s.done = true
    83  	}
    84  }