aboutsummaryrefslogtreecommitdiffstats
path: root/modules/log/event_writer_conn.go
blob: 022206aa4d51682f1393e4dacac64732e78349a4 (plain)
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
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package log

import (
	"io"
	"net"
)

type WriterConnOption struct {
	Addr           string
	Protocol       string
	Reconnect      bool
	ReconnectOnMsg bool
}

type eventWriterConn struct {
	*EventWriterBaseImpl
	connWriter connWriter
}

var _ EventWriter = (*eventWriterConn)(nil)

func NewEventWriterConn(writerName string, writerMode WriterMode) EventWriter {
	w := &eventWriterConn{EventWriterBaseImpl: NewEventWriterBase(writerName, "conn", writerMode)}
	opt := writerMode.WriterOption.(WriterConnOption)
	w.connWriter = connWriter{
		ReconnectOnMsg: opt.ReconnectOnMsg,
		Reconnect:      opt.Reconnect,
		Net:            opt.Protocol,
		Addr:           opt.Addr,
	}
	w.OutputWriteCloser = &w.connWriter
	return w
}

func init() {
	RegisterEventWriter("conn", NewEventWriterConn)
}

// below is copied from old code

type connWriter struct {
	innerWriter io.WriteCloser

	ReconnectOnMsg bool
	Reconnect      bool
	Net            string `json:"net"`
	Addr           string `json:"addr"`
}

var _ io.WriteCloser = (*connWriter)(nil)

// Close the inner writer
func (i *connWriter) Close() error {
	if i.innerWriter != nil {
		return i.innerWriter.Close()
	}
	return nil
}

// Write the data to the connection
func (i *connWriter) Write(p []byte) (int, error) {
	if i.neededConnectOnMsg() {
		if err := i.connect(); err != nil {
			return 0, err
		}
	}

	if i.ReconnectOnMsg {
		defer i.innerWriter.Close()
	}

	return i.innerWriter.Write(p)
}

func (i *connWriter) neededConnectOnMsg() bool {
	if i.Reconnect {
		i.Reconnect = false
		return true
	}

	if i.innerWriter == nil {
		return true
	}

	return i.ReconnectOnMsg
}

func (i *connWriter) connect() error {
	if i.innerWriter != nil {
		_ = i.innerWriter.Close()
		i.innerWriter = nil
	}

	conn, err := net.Dial(i.Net, i.Addr)
	if err != nil {
		return err
	}

	if tcpConn, ok := conn.(*net.TCPConn); ok {
		err = tcpConn.SetKeepAlive(true)
		if err != nil {
			return err
		}
	}

	i.innerWriter = conn
	return nil
}