Debian Codegraph @

monitor.go

raw symbols SCIP
1 // This file is part of pluggable-monitor-protocol-handler.
2 //
3 // SPDX-FileCopyrightText: Arduino s.r.l. and/or its affiliated companies
4 // SPDX-License-Identifier: GPL-3.0-or-later
5
6 // Package monitor is a library for handling the Arduino Pluggable-Monitor protocol
7 // (https://github.com/arduino/tooling-rfcs/blob/main/RFCs/0004-pluggable-monitor.md#pluggable-monitor-api-via-stdinstdout)
8 //
9 // The library implements the state machine and the parsing logic to communicate with a pluggable-monitor client.
10 // All the commands issued by the client are conveniently translated into function calls, in particular
11 // the Monitor interface are the only functions that must be implemented to get a fully working pluggable monitor
12 // using this library.
13 //
14 // A usage example is provided in the dummy-monitor package.
15 package monitor
16
17 import (
18 "bufio"
19 "encoding/json"
20 "fmt"
21 "io"
22 "net"
23 "regexp"
24 "strconv"
25 "strings"
26 "sync"
27
28 "github.com/hashicorp/go-multierror"
29 )
30
31 // Monitor is an interface that represents the business logic that
32 // a pluggable monitor must implement. The communication protocol
33 // is completely hidden and it's handled by a MonitorServer.
34 type Monitor interface {
35 // Hello is called once at startup to provide the userAgent string
36 // and the protocolVersion negotiated with the client.
37 Hello(userAgent string, protocolVersion int) error
38
39 // Describe is called to obtain the description of the communication port
40 Describe() (*PortDescriptor, error)
41
42 // Configure allows to set the configuration parameters for the communication port
43 Configure(parameterName string, value string) error
44
45 // Open allows to open a communication with the board using TCP/IP
46 Open(boardPort string) (io.ReadWriter, error)
47
48 // Close will close the currently open port and TCP/IP connection
49 Close() error
50
51 // Quit is called just before the server terminates. This function can be
52 // used by the monitor as a last chance to gracefully close resources.
53 Quit()
54 }
55
56 // A Server is a pluggable monitor protocol handler,
57 // it must be created using the NewServer function.
58 type Server struct {
59 impl Monitor
60 out io.Writer
61 outMutex sync.Mutex
62 userAgent string
63 reqProtocolVersion int
64 initialized bool
65 clientConn net.Conn
66 closeFuncMutex sync.Mutex
67 }
68
69 // NewServer creates a new monitor server backed by the
70 // provided pluggable monitor implementation. To start the server
71 // use the Run method.
72 func NewServer(impl Monitor) *Server {
73 return &Server{
74 impl: impl,
75 }
76 }
77
78 // Run starts the protocol handling loop on the given input and
79 // output stream, usually `os.Stdin` and `os.Stdout` are used.
80 // The function blocks until the `QUIT` command is received or
81 // the input stream is closed. In case of IO error the error is
82 // returned.
83 func (d *Server) Run(in io.Reader, out io.Writer) error {
84 d.out = out
85 reader := bufio.NewReader(in)
86 for {
87 fullCmd, err := reader.ReadString('\n')
88 if err != nil {
89 d.outputMessage(messageError("command_error", err.Error()))
90 return err
91 }
92 fullCmd = strings.TrimSpace(fullCmd)
93 split := strings.Split(fullCmd, " ")
94 cmd := strings.ToUpper(split[0])
95
96 if !d.initialized && cmd != "HELLO" && cmd != "QUIT" {
97 d.outputMessage(messageError("command_error", fmt.Sprintf("First command must be HELLO, but got '%s'", cmd)))
98 continue
99 }
100
101 switch cmd {
102 case "HELLO":
103 d.hello(fullCmd[6:])
104 case "DESCRIBE":
105 d.describe()
106 case "CONFIGURE":
107 d.configure(fullCmd[10:])
108 case "OPEN":
109 d.open(fullCmd[5:])
110 case "CLOSE":
111 d.close("")
112 case "QUIT":
113 d.impl.Quit()
114 d.outputMessage(messageOk("quit"))
115 return nil
116 default:
117 d.outputMessage(messageError("command_error", fmt.Sprintf("Command %s not supported", cmd)))
118 }
119 }
120 }
121
122 func (d *Server) hello(cmd string) {
123 if d.initialized {
124 d.outputMessage(messageError("hello", "HELLO already called"))
125 return
126 }
127 re := regexp.MustCompile(`^(\d+) "([^"]+)"$`)
128 matches := re.FindStringSubmatch(cmd)
129 if len(matches) != 3 {
130 d.outputMessage(messageError("hello", "Invalid HELLO command"))
131 return
132 }
133 d.userAgent = matches[2]
134 v, err := strconv.ParseInt(matches[1], 10, 64)
135 if err != nil {
136 d.outputMessage(messageError("hello", "Invalid protocol version: "+matches[2]))
137 return
138 }
139 d.reqProtocolVersion = int(v)
140 if err := d.impl.Hello(d.userAgent, 1); err != nil {
141 d.outputMessage(messageError("hello", err.Error()))
142 return
143 }
144 d.outputMessage(&message{
145 EventType: "hello",
146 ProtocolVersion: 1, // Protocol version 1 is the only supported for now...
147 Message: "OK",
148 })
149 d.initialized = true
150 }
151
152 func (d *Server) describe() {
153 if !d.initialized {
154 d.outputMessage(messageError("describe", "Monitor not initialized"))
155 return
156 }
157 portDescription, err := d.impl.Describe()
158 if err != nil {
159 d.outputMessage(messageError("describe", err.Error()))
160 return
161 }
162 d.outputMessage(&message{
163 EventType: "describe",
164 Message: "OK",
165 PortDescription: portDescription,
166 })
167 }
168
169 func (d *Server) configure(cmd string) {
170 if !d.initialized {
171 d.outputMessage(messageError("configure", "Monitor not initialized"))
172 return
173 }
174 re := regexp.MustCompile(`^([\w.-]+) (.+)$`)
175 matches := re.FindStringSubmatch(cmd)
176 if len(matches) != 3 {
177 d.outputMessage(messageError("configure", "Invalid CONFIGURE command"))
178 return
179 }
180 parameterName := matches[1]
181 value := matches[2]
182 if err := d.impl.Configure(parameterName, value); err != nil {
183 d.outputMessage(messageError("configure", err.Error()))
184 return
185 }
186 d.outputMessage(&message{
187 EventType: "configure",
188 Message: "OK",
189 })
190 }
191
192 func (d *Server) open(cmd string) {
193 if !d.initialized {
194 d.outputMessage(messageError("open", "Monitor not initialized"))
195 return
196 }
197 parameters := strings.SplitN(cmd, " ", 2)
198 if len(parameters) != 2 {
199 d.outputMessage(messageError("open", "Invalid OPEN command"))
200 return
201 }
202 address := parameters[0]
203 portName := parameters[1]
204 port, err := d.impl.Open(portName)
205 if err != nil {
206 d.outputMessage(messageError("open", err.Error()))
207 return
208 }
209 d.clientConn, err = net.Dial("tcp", address)
210 if err != nil {
211 d.impl.Close()
212 d.outputMessage(messageError("open", err.Error()))
213 return
214 }
215 // io.Copy is used to bridge the Client's TCP connection to the port one and vice versa
216 go func() {
217 _, err := io.Copy(port, d.clientConn) // Copy is blocking, so we run it insiede a gorutine
218 if err != nil {
219 d.close(err.Error())
220 } else {
221 d.close("lost TCP/IP connection with the client!")
222 }
223 }()
224 go func() {
225 _, err := io.Copy(d.clientConn, port) // Copy is blocking, so we run it insiede a gorutine
226 if err != nil {
227 d.close(err.Error())
228 } else {
229 d.close("lost connection with the port")
230 }
231 }()
232 d.outputMessage(&message{
233 EventType: "open",
234 Message: "OK",
235 })
236 }
237
238 func (d *Server) close(messageErr string) {
239 d.closeFuncMutex.Lock()
240 defer d.closeFuncMutex.Unlock()
241 if d.clientConn == nil {
242 if messageErr == "" {
243 d.outputMessage(messageError("close", "port already closed"))
244 }
245 return
246 }
247 connErr := d.clientConn.Close()
248 portErr := d.impl.Close()
249 d.clientConn = nil
250 if messageErr != "" {
251 d.outputMessage(messageError("port_closed", messageErr))
252 return
253 }
254 if connErr != nil || portErr != nil {
255 var errs *multierror.Error
256 errs = multierror.Append(errs, connErr, portErr)
257 d.outputMessage(messageError("close", errs.Error()))
258 return
259 }
260 d.outputMessage(&message{
261 EventType: "close",
262 Message: "OK",
263 })
264 }
265
266 func (d *Server) outputMessage(msg *message) {
267 data, err := json.MarshalIndent(msg, "", " ")
268 if err != nil {
269 // We are certain that this will be marshalled correctly so we don't handle the error
270 data, _ = json.MarshalIndent(messageError("command_error", err.Error()), "", " ")
271 }
272 d.outMutex.Lock()
273 fmt.Fprintln(d.out, string(data))
274 d.outMutex.Unlock()
275 }