This repository has been archived by the owner on Apr 15, 2021. It is now read-only.
forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
112 lines (87 loc) · 2.23 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package syslog
import (
"bufio"
"net"
"strconv"
"sync"
"github.com/jeromer/syslogparser/rfc3164"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
const concreteServerLogTag = "concreteServer"
type concreteServer struct {
port uint16
logger boshlog.Logger
listener net.Listener
lock sync.Mutex
listenerProvider func(protocol, address string) (net.Listener, error)
}
func NewServer(port uint16, listenerProvider func(protocol, address string) (net.Listener, error), logger boshlog.Logger) Server {
return &concreteServer{port: port, logger: logger, listenerProvider: listenerProvider}
}
func (s *concreteServer) Start(callback CallbackFunc) error {
var err error
s.lock.Lock()
s.listener, err = s.listenerProvider("tcp", "127.0.0.1:"+strconv.Itoa(int(s.port)))
if err != nil {
s.lock.Unlock()
return bosherr.WrapErrorf(err, "Listening on port %d", s.port)
}
// Should not defer unlock since there is a long-running loop
s.lock.Unlock()
for {
conn, err := s.listener.Accept()
if err != nil {
return err
}
go s.handleConnection(conn, callback)
}
}
func (s *concreteServer) Stop() error {
s.lock.Lock()
defer s.lock.Unlock()
if s.listener != nil {
return s.listener.Close()
}
return nil
}
func (s *concreteServer) handleConnection(conn net.Conn, callback CallbackFunc) {
defer func() {
if err := conn.Close(); err != nil {
s.logger.Error(concreteServerLogTag, "Failed to close connection: %s", err.Error())
}
}()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
bytes := scanner.Bytes()
p := rfc3164.NewParser(bytes)
err := p.Parse()
if err != nil {
s.logger.Error(
concreteServerLogTag,
"Failed to parse syslog message: %s error: %s",
string(bytes), err.Error(),
)
continue
}
content, ok := p.Dump()["content"].(string)
if !ok {
s.logger.Error(
concreteServerLogTag,
"Failed to retrieve syslog message string content: %s",
string(bytes),
)
continue
}
message := Msg{Content: content}
callback(message)
}
err := scanner.Err()
if err != nil {
s.logger.Error(
concreteServerLogTag,
"Scanner error while parsing syslog message: %s",
err.Error(),
)
}
}