@marcel91200 / caddy Mirror · read-only / commits / 9415feca
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

logging: Net writer redials if write fails (#3453)

* logging: Net writer redials if write fails https://caddy.community/t/v2-log-output-net-does-not-reconnect-after-lost-connection/8386?u=matt * Only replace connection if redial succeeds * Fix error handling

Matt Holt committed May 28, 2020 at 10:40 UTC 9415feca7cf0fe14b9d881c7318be2da20b2985f
1 file changed +55 -1
modules/logging/netwriter.go
+55 -1
@@ -18,6 +18,7 @@ import (
18 "fmt"
19 "io"
20 "net"
21 + "sync"
22
23 "github.com/caddyserver/caddy/v2"
24 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
@@ -73,7 +74,15 @@ func (nw NetWriter) WriterKey() string {
74
75 // OpenWriter opens a new network connection.
76 func (nw NetWriter) OpenWriter() (io.WriteCloser, error) {
76 - return net.Dial(nw.addr.Network, nw.addr.JoinHostPort(0))
77 + reconn := &redialerConn{nw: nw}
78 + conn, err := reconn.dial()
79 + if err != nil {
80 + return nil, err
81 + }
82 + reconn.connMu.Lock()
83 + reconn.Conn = conn
84 + reconn.connMu.Unlock()
85 + return reconn, nil
86 }
87
88 // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:
@@ -93,6 +102,51 @@ func (nw *NetWriter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
102 return nil
103 }
104
105 +// redialerConn wraps an underlying Conn so that if any
106 +// writes fail, the connection is redialed and the write
107 +// is retried.
108 +type redialerConn struct {
109 + net.Conn
110 + connMu sync.RWMutex
111 + nw NetWriter
112 +}
113 +
114 +// Write wraps the underlying Conn.Write method, but if that fails,
115 +// it will re-dial the connection anew and try writing again.
116 +func (reconn *redialerConn) Write(b []byte) (n int, err error) {
117 + reconn.connMu.RLock()
118 + conn := reconn.Conn
119 + reconn.connMu.RUnlock()
120 + if n, err = conn.Write(b); err == nil {
121 + return
122 + }
123 +
124 + // problem with the connection - lock it and try to fix it
125 + reconn.connMu.Lock()
126 + defer reconn.connMu.Unlock()
127 +
128 + // if multiple concurrent writes failed on the same broken conn, then
129 + // one of them might have already re-dialed by now; try writing again
130 + if n, err = reconn.Conn.Write(b); err == nil {
131 + return
132 + }
133 +
134 + // we're the lucky first goroutine to re-dial the connection
135 + conn2, err2 := reconn.dial()
136 + if err2 != nil {
137 + return
138 + }
139 + if n, err = conn2.Write(b); err == nil {
140 + reconn.Conn.Close()
141 + reconn.Conn = conn2
142 + }
143 + return
144 +}
145 +
146 +func (reconn *redialerConn) dial() (net.Conn, error) {
147 + return net.Dial(reconn.nw.addr.Network, reconn.nw.addr.JoinHostPort(0))
148 +}
149 +
150 // Interface guards
151 var (
152 _ caddy.Provisioner = (*NetWriter)(nil)