dashboard / erock/pubsub / refactor: remote client writer that implement io.Writer #31 rss

accepted · opened on 2024-11-12T20:57:56Z by erock
Help
checkout latest patchset:
ssh pr.pico.sh print pr-31 | git am -3
checkout any patchset in a patch request:
ssh pr.pico.sh print ps-X | git am -3
add changes to patch request:
git format-patch main --stdout | ssh pr.pico.sh pr add 31
add review to patch request:
git format-patch main --stdout | ssh pr.pico.sh pr add --review 31
accept PR:
ssh pr.pico.sh pr accept 31
close PR:
ssh pr.pico.sh pr close 31

Logs

erock created pr with ps-65 on 2024-11-12T20:57:56Z
erock changed status on 2024-11-14T15:44:45Z {"status":"accepted"}

Patchsets

ps-65 by erock on 2024-11-12T20:57:56Z

Patchset ps-65

Back to top

refactor: remote client writer that implement io.Writer

It also acts as a supervisor, keeping the ssh connection alive
log/log.go link
+6 -176
  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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
diff --git a/log/log.go b/log/log.go
index 98bfddc..cf87c7e 100644
--- a/log/log.go
+++ b/log/log.go
@@ -3,15 +3,12 @@ package log
 import (
 	"context"
 	"errors"
-	"fmt"
 	"io"
 	"log/slog"
 	"slices"
 	"sync"
-	"time"
 
 	"github.com/picosh/pubsub"
-	"golang.org/x/crypto/ssh"
 )
 
 type MultiHandler struct {
@@ -19,6 +16,8 @@ type MultiHandler struct {
 	mu       sync.Mutex
 }
 
+var _ slog.Handler = (*MultiHandler)(nil)
+
 func (m *MultiHandler) Enabled(ctx context.Context, l slog.Level) bool {
 	m.mu.Lock()
 	defer m.mu.Unlock()
@@ -80,181 +79,15 @@ func (m *MultiHandler) WithGroup(name string) slog.Handler {
 	}
 }
 
-type PubSubLogWriter struct {
-	SSHClient        *ssh.Client
-	Session          *ssh.Session
-	StdinPipe        io.WriteCloser
-	Done             chan struct{}
-	Messages         chan []byte
-	Timeout          time.Duration
-	BufferSize       int
-	closeOnce        sync.Once
-	closeMessageOnce sync.Once
-	startOnce        sync.Once
-	connecMu         sync.Mutex
-	ConnectionInfo   *pubsub.RemoteClientInfo
-}
-
-func (c *PubSubLogWriter) Close() error {
-	c.connecMu.Lock()
-	defer c.connecMu.Unlock()
-
-	if c.Done != nil {
-		c.closeOnce.Do(func() {
-			close(c.Done)
-		})
-	}
-
-	if c.Messages != nil {
-		c.closeMessageOnce.Do(func() {
-			close(c.Messages)
-		})
-	}
-
-	var errs []error
-
-	if c.StdinPipe != nil {
-		errs = append(errs, c.StdinPipe.Close())
-	}
-
-	if c.Session != nil {
-		errs = append(errs, c.Session.Close())
-	}
-
-	if c.SSHClient != nil {
-		errs = append(errs, c.SSHClient.Close())
-	}
-
-	return errors.Join(errs...)
-}
-
-func (c *PubSubLogWriter) Open() error {
-	c.Close()
-
-	c.connecMu.Lock()
-
-	c.Done = make(chan struct{})
-	c.Messages = make(chan []byte, c.BufferSize)
-
-	sshClient, err := pubsub.CreateRemoteClient(c.ConnectionInfo)
-	if err != nil {
-		c.connecMu.Unlock()
-		return err
-	}
-
-	session, err := sshClient.NewSession()
-	if err != nil {
-		c.connecMu.Unlock()
-		return err
-	}
-
-	stdinPipe, err := session.StdinPipe()
-	if err != nil {
-		c.connecMu.Unlock()
-		return err
-	}
-
-	err = session.Start("pub log-drain -b=false")
-	if err != nil {
-		c.connecMu.Unlock()
-		return err
-	}
-
-	c.SSHClient = sshClient
-	c.Session = session
-	c.StdinPipe = stdinPipe
-
-	c.closeOnce = sync.Once{}
-	c.startOnce = sync.Once{}
-
-	c.connecMu.Unlock()
-
-	c.Start()
-
-	return nil
-}
-
-func (c *PubSubLogWriter) Start() {
-	c.startOnce.Do(func() {
-		go func() {
-			defer c.Reconnect()
-
-			for {
-				select {
-				case data, ok := <-c.Messages:
-					_, err := c.StdinPipe.Write(data)
-					if !ok || err != nil {
-						slog.Error("received error on write, reopening logger", "error", err)
-						return
-					}
-				case <-c.Done:
-					return
-				}
-			}
-		}()
-	})
-}
-
-func (c *PubSubLogWriter) Write(data []byte) (int, error) {
-	var (
-		n   int
-		err error
-	)
-
-	ok := c.connecMu.TryLock()
-
-	if !ok {
-		return n, fmt.Errorf("unable to acquire lock to write")
-	}
-
-	defer c.connecMu.Unlock()
-
-	if c.Messages == nil || c.Done == nil {
-		return n, fmt.Errorf("logger not viable")
-	}
-
-	select {
-	case c.Messages <- slices.Clone(data):
-		n = len(data)
-	case <-time.After(c.Timeout):
-		err = fmt.Errorf("unable to send data within timeout")
-	case <-c.Done:
-		break
-	}
-
-	return n, err
-}
-
-func (c *PubSubLogWriter) Reconnect() {
-	go func() {
-		for {
-			err := c.Open()
-			if err != nil {
-				slog.Error("unable to open send logger. retrying in 10 seconds", "error", err)
-			} else {
-				return
-			}
-
-			<-time.After(10 * time.Second)
-		}
-	}()
-}
-
-func SendLogRegister(logger *slog.Logger, connectionInfo *pubsub.RemoteClientInfo, buffer int) (*slog.Logger, error) {
+func SendLogRegister(logger *slog.Logger, info *pubsub.RemoteClientInfo, buffer int) (*slog.Logger, error) {
 	if buffer < 0 {
 		buffer = 0
 	}
 
-	currentHandler := logger.Handler()
-
-	logWriter := &PubSubLogWriter{
-		Timeout:        10 * time.Millisecond,
-		BufferSize:     buffer,
-		ConnectionInfo: connectionInfo,
-	}
-
-	logWriter.Reconnect()
+	logWriter := pubsub.NewRemoteClientWriter(info, logger, buffer)
+	go logWriter.KeepAlive("pub log-drain -b=false")
 
+	currentHandler := logger.Handler()
 	return slog.New(
 		&MultiHandler{
 			Handlers: []slog.Handler{
@@ -268,9 +101,6 @@ func SendLogRegister(logger *slog.Logger, connectionInfo *pubsub.RemoteClientInf
 	), nil
 }
 
-var _ io.Writer = (*PubSubLogWriter)(nil)
-var _ slog.Handler = (*MultiHandler)(nil)
-
 func ConnectToLogs(ctx context.Context, connectionInfo *pubsub.RemoteClientInfo) (io.Reader, error) {
 	return pubsub.RemoteSub("sub log-drain -k", ctx, connectionInfo)
 }
remote_client.go link
+174 -1
  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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
diff --git a/remote_client.go b/remote_client.go
index 84c48f4..57345f1 100644
--- a/remote_client.go
+++ b/remote_client.go
@@ -2,16 +2,189 @@ package pubsub
 
 import (
 	"context"
+	"errors"
 	"fmt"
 	"io"
+	"log/slog"
 	"net"
 	"os"
 	"path/filepath"
+	"slices"
 	"strings"
+	"sync"
+	"time"
 
 	"golang.org/x/crypto/ssh"
 )
 
+type RemoteClientWriter struct {
+	SSHClient        *ssh.Client
+	Session          *ssh.Session
+	StdinPipe        io.WriteCloser
+	Done             chan struct{}
+	Messages         chan []byte
+	Timeout          time.Duration
+	BufferSize       int
+	closeOnce        sync.Once
+	closeMessageOnce sync.Once
+	startOnce        sync.Once
+	connecMu         sync.Mutex
+	Info             *RemoteClientInfo
+	Logger           *slog.Logger
+}
+
+var _ io.Writer = (*RemoteClientWriter)(nil)
+
+func NewRemoteClientWriter(info *RemoteClientInfo, logger *slog.Logger, buffer int) *RemoteClientWriter {
+	return &RemoteClientWriter{
+		Timeout:    10 * time.Millisecond,
+		Info:       info,
+		BufferSize: buffer,
+		Logger:     logger,
+	}
+}
+
+func (c *RemoteClientWriter) Close() error {
+	c.connecMu.Lock()
+	defer c.connecMu.Unlock()
+
+	if c.Done != nil {
+		c.closeOnce.Do(func() {
+			close(c.Done)
+		})
+	}
+
+	if c.Messages != nil {
+		c.closeMessageOnce.Do(func() {
+			close(c.Messages)
+		})
+	}
+
+	var errs []error
+
+	if c.StdinPipe != nil {
+		errs = append(errs, c.StdinPipe.Close())
+	}
+
+	if c.Session != nil {
+		errs = append(errs, c.Session.Close())
+	}
+
+	if c.SSHClient != nil {
+		errs = append(errs, c.SSHClient.Close())
+	}
+
+	return errors.Join(errs...)
+}
+
+func (c *RemoteClientWriter) Open(cmd string) error {
+	c.Close()
+
+	c.connecMu.Lock()
+
+	c.Done = make(chan struct{})
+	c.Messages = make(chan []byte, c.BufferSize)
+
+	sshClient, err := CreateRemoteClient(c.Info)
+	if err != nil {
+		c.connecMu.Unlock()
+		return err
+	}
+
+	session, err := sshClient.NewSession()
+	if err != nil {
+		c.connecMu.Unlock()
+		return err
+	}
+
+	stdinPipe, err := session.StdinPipe()
+	if err != nil {
+		c.connecMu.Unlock()
+		return err
+	}
+
+	err = session.Start(cmd)
+	if err != nil {
+		c.connecMu.Unlock()
+		return err
+	}
+
+	c.SSHClient = sshClient
+	c.Session = session
+	c.StdinPipe = stdinPipe
+
+	c.closeOnce = sync.Once{}
+	c.startOnce = sync.Once{}
+
+	c.connecMu.Unlock()
+
+	c.start()
+
+	return nil
+}
+
+func (c *RemoteClientWriter) start() {
+	c.startOnce.Do(func() {
+		go func() {
+			for {
+				select {
+				case data, ok := <-c.Messages:
+					_, err := c.StdinPipe.Write(data)
+					if !ok || err != nil {
+						c.Logger.Error("received error on write, reopening conn", "error", err)
+						return
+					}
+				case <-c.Done:
+					return
+				}
+			}
+		}()
+	})
+}
+
+func (c *RemoteClientWriter) Write(data []byte) (int, error) {
+	var (
+		n   int
+		err error
+	)
+
+	ok := c.connecMu.TryLock()
+
+	if !ok {
+		return n, fmt.Errorf("unable to acquire lock to write")
+	}
+
+	defer c.connecMu.Unlock()
+
+	if c.Messages == nil || c.Done == nil {
+		return n, fmt.Errorf("conn not viable")
+	}
+
+	select {
+	case c.Messages <- slices.Clone(data):
+		n = len(data)
+	case <-time.After(c.Timeout):
+		err = fmt.Errorf("unable to send data within timeout")
+	case <-c.Done:
+		break
+	}
+
+	return n, err
+}
+
+func (c *RemoteClientWriter) KeepAlive(cmd string) {
+	for {
+		err := c.Open(cmd)
+		if err != nil {
+			c.Logger.Error("unable to open send to ssh conn. retrying in 10 seconds", "error", err)
+		} else {
+			return
+		}
+
+		<-time.After(10 * time.Second)
+	}
+}
+
 type RemoteClientInfo struct {
 	RemoteHost     string
 	KeyLocation    string
@@ -22,7 +195,7 @@ type RemoteClientInfo struct {
 
 func CreateRemoteClient(info *RemoteClientInfo) (*ssh.Client, error) {
 	if info == nil {
-		return nil, fmt.Errorf("connection info is invalid")
+		return nil, fmt.Errorf("conn info is invalid")
 	}
 
 	if !strings.Contains(info.RemoteHost, ":") {