]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - rpc/conn.go
b2bcf28a05025317c729136cc7680579dffcfe36
[safcm/safcm.git] / rpc / conn.go
1 // Simple RPC-like protocol: implementation of connection and basic actions
2
3 // Copyright (C) 2021  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 package rpc
19
20 import (
21         "bufio"
22         "fmt"
23         "os/exec"
24         "strings"
25         "sync"
26
27         "ruderich.org/simon/safcm"
28 )
29
30 type Conn struct {
31         Events   <-chan ConnEvent
32         events   chan<- ConnEvent // same as Events, to publish events
33         eventsWg sync.WaitGroup
34
35         debug  bool
36         remote string
37
38         cmd  *exec.Cmd
39         conn *safcm.GobConn
40 }
41
42 type ConnEventType int
43
44 const (
45         _               ConnEventType = iota
46         ConnEventStderr               // stderr from spawned process
47         ConnEventDebug                // debug message
48         ConnEventUpload               // remote helper upload in progress
49 )
50
51 type ConnEvent struct {
52         Type ConnEventType
53         Data string
54 }
55
56 // NewConn creates a new connection. Events in the returned struct must be
57 // regularly read or the connection will stall. This must be done before
58 // DialSSH is called to open a connection.
59 func NewConn(debug bool) *Conn {
60         ch := make(chan ConnEvent)
61         return &Conn{
62                 Events: ch,
63                 events: ch,
64                 debug:  debug,
65         }
66 }
67
68 func (c *Conn) debugf(format string, a ...interface{}) {
69         if !c.debug {
70                 return
71         }
72         c.events <- ConnEvent{
73                 Type: ConnEventDebug,
74                 Data: fmt.Sprintf(format, a...),
75         }
76 }
77
78 // Wrap safcm.GobConn's Send() and Recv() to provide debug output.
79
80 // Send sends a single message to the remote.
81 func (c *Conn) Send(m safcm.Msg) error {
82         // No checks for invalid Conn, a stacktrace is more helpful
83
84         c.debugf("Send: sending %#v", m)
85         return c.conn.Send(m)
86 }
87
88 // Recv waits for a single message from the remote.
89 func (c *Conn) Recv() (safcm.Msg, error) {
90         // No checks for invalid Conn, a stacktrace is more helpful
91
92         c.debugf("Recv: waiting for message")
93         m, err := c.conn.Recv()
94         c.debugf("Recv: received msg=%#v err=%#v", m, err)
95         return m, err
96 }
97
98 // Wait waits for the connection to terminate. It's safe to call Wait (and
99 // Kill) multiple times.
100 func (c *Conn) Wait() error {
101         // But check here because Wait() can be called multiple times
102         if c.cmd == nil {
103                 return fmt.Errorf("Dial*() not called or already terminated")
104         }
105
106         c.debugf("Wait: waiting for connection to terminate")
107         return c.wait()
108 }
109 func (c *Conn) wait() error {
110         err := c.cmd.Wait()
111         c.cmd = nil
112
113         // Wait until we've received all events from the program's stderr.
114         c.eventsWg.Wait()
115         // Notify consumers that no more events will occur.
116         close(c.events)
117         // We cannot reuse this channel.
118         c.events = nil
119         // Don't set c.Events to nil because this creates a data race when
120         // another thread is still waiting.
121
122         return err
123 }
124
125 // Kill forcefully terminates the connection. It's safe to call Kill (and
126 // Wait) multiple times.
127 func (c *Conn) Kill() error {
128         if c.cmd == nil {
129                 return fmt.Errorf("Dial*() not called or already terminated")
130         }
131
132         c.debugf("Kill: killing connection")
133
134         c.cmd.Process.Kill()
135         return c.wait()
136 }
137
138 func (c *Conn) handleStderrAsEvents(cmd *exec.Cmd) error {
139         // cmd may differ from c.cmd here!
140         stderr, err := cmd.StderrPipe()
141         if err != nil {
142                 return err
143         }
144
145         c.eventsWg.Add(1)
146         go func() {
147                 r := bufio.NewReader(stderr)
148                 for {
149                         x, err := r.ReadString('\n')
150                         if err != nil {
151                                 break
152                         }
153                         x = strings.TrimRight(x, "\n")
154
155                         c.events <- ConnEvent{
156                                 Type: ConnEventStderr,
157                                 Data: x,
158                         }
159                 }
160                 c.eventsWg.Done()
161         }()
162
163         return nil
164 }