summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/wiggin77/srslog/net_conn.go
blob: f3cfeb60c4c1ea23cf758506bcc9897f91041d91 (plain) (blame)
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
package srslog

import (
	"io"
	"net"
	"time"
)

// netConn has an internal net.Conn and adheres to the serverConn interface,
// allowing us to send syslog messages over the network.
type netConn struct {
	conn net.Conn
	done chan interface{}
}

// newNetConn creates a netConn instance that is monitored for unexpected socket closure.
func newNetConn(conn net.Conn) *netConn {
	nc := &netConn{conn: conn, done: make(chan interface{})}
	go monitor(nc.conn, nc.done)
	return nc
}

// writeString formats syslog messages using time.RFC3339 and includes the
// hostname, and sends the message to the connection.
func (n *netConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error {
	if framer == nil {
		framer = DefaultFramer
	}
	if formatter == nil {
		formatter = DefaultFormatter
	}
	formattedMessage := framer(formatter(p, hostname, tag, msg))
	_, err := n.conn.Write([]byte(formattedMessage))
	return err
}

// close the network connection
func (n *netConn) close() error {
	// signal monitor goroutine to exit
	close(n.done)
	// wake up monitor blocked on read (close usually is enough)
	_ = n.conn.SetReadDeadline(time.Now())
	// close the connection
	return n.conn.Close()
}

// monitor continuously tries to read from the connection to detect socket close.
// This is needed because syslog server uses a write only socket and Linux systems
// take a long time to detect a loss of connectivity on a socket when only writing;
// the writes simply fail without an error returned.
func monitor(conn net.Conn, done chan interface{}) {
	defer Logger.Println("monitor exit")

	buf := make([]byte, 1)
	for {
		Logger.Println("monitor loop")

		select {
		case <-done:
			return
		case <-time.After(1 * time.Second):
		}

		err := conn.SetReadDeadline(time.Now().Add(time.Second * 30))
		if err != nil {
			continue
		}

		_, err = conn.Read(buf)
		Logger.Println("monitor -- ", err)
		if err == io.EOF {
			Logger.Println("monitor close conn")
			conn.Close()
		}
	}
}