| 1 |
// This file is part of pluggable-discovery-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 discovery |
| 7 |
|
| 8 |
import ( |
| 9 |
"encoding/json" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"strings" |
| 14 |
"sync" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/arduino/go-paths-helper" |
| 18 |
) |
| 19 |
|
| 20 |
// Client is a tool that detects communication ports to interact |
| 21 |
// with the boards. |
| 22 |
type Client struct { |
| 23 |
id string |
| 24 |
processArgs []string |
| 25 |
process *paths.Process |
| 26 |
outgoingCommandsPipe io.Writer |
| 27 |
incomingMessagesChan <-chan *discoveryMessage |
| 28 |
userAgent string |
| 29 |
logger ClientLogger |
| 30 |
|
| 31 |
// All the following fields are guarded by statusMutex |
| 32 |
statusMutex sync.Mutex |
| 33 |
incomingMessagesError error |
| 34 |
eventChan chan<- *Event |
| 35 |
} |
| 36 |
|
| 37 |
// ClientLogger is the interface that must be implemented by a logger |
| 38 |
// to be used in the discovery client. |
| 39 |
type ClientLogger interface { |
| 40 |
Debugf(format string, args ...any) |
| 41 |
Errorf(format string, args ...any) |
| 42 |
} |
| 43 |
|
| 44 |
type nullClientLogger struct{} |
| 45 |
|
| 46 |
func (l *nullClientLogger) Debugf(_ string, _ ...any) {} |
| 47 |
func (l *nullClientLogger) Errorf(_ string, _ ...any) {} |
| 48 |
|
| 49 |
type discoveryMessage struct { |
| 50 |
EventType string `json:"eventType"` |
| 51 |
Message string `json:"message"` |
| 52 |
Error bool `json:"error"` |
| 53 |
ProtocolVersion int `json:"protocolVersion"` // Used in HELLO command |
| 54 |
Ports []*Port `json:"ports"` // Used in LIST command |
| 55 |
Port *Port `json:"port"` // Used in add and remove events |
| 56 |
} |
| 57 |
|
| 58 |
func (msg discoveryMessage) String() string { |
| 59 |
s := fmt.Sprintf("type: %s", msg.EventType) |
| 60 |
if msg.Message != "" { |
| 61 |
s += fmt.Sprintf(", message: %s", msg.Message) |
| 62 |
} |
| 63 |
if msg.ProtocolVersion != 0 { |
| 64 |
s += fmt.Sprintf(", protocol version: %d", msg.ProtocolVersion) |
| 65 |
} |
| 66 |
if len(msg.Ports) > 0 { |
| 67 |
s += fmt.Sprintf(", ports: %s", msg.Ports) |
| 68 |
} |
| 69 |
if msg.Port != nil { |
| 70 |
s += fmt.Sprintf(", port: %s", msg.Port) |
| 71 |
} |
| 72 |
return s |
| 73 |
} |
| 74 |
|
| 75 |
// Event is a pluggable discovery event |
| 76 |
type Event struct { |
| 77 |
Type string |
| 78 |
Port *Port |
| 79 |
DiscoveryID string |
| 80 |
} |
| 81 |
|
| 82 |
// NewClient create a new pluggable discovery client |
| 83 |
func NewClient(id string, args ...string) *Client { |
| 84 |
return &Client{ |
| 85 |
id: id, |
| 86 |
processArgs: args, |
| 87 |
userAgent: "pluggable-discovery-protocol-handler", |
| 88 |
logger: &nullClientLogger{}, |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
// SetUserAgent sets the user agent to be used in the discovery |
| 93 |
func (disc *Client) SetUserAgent(userAgent string) { |
| 94 |
disc.userAgent = userAgent |
| 95 |
} |
| 96 |
|
| 97 |
// SetLogger sets the logger to be used in the discovery |
| 98 |
func (disc *Client) SetLogger(logger ClientLogger) { |
| 99 |
disc.logger = logger |
| 100 |
} |
| 101 |
|
| 102 |
// GetID returns the identifier for this discovery |
| 103 |
func (disc *Client) GetID() string { |
| 104 |
return disc.id |
| 105 |
} |
| 106 |
|
| 107 |
func (disc *Client) String() string { |
| 108 |
return disc.id |
| 109 |
} |
| 110 |
|
| 111 |
func (disc *Client) jsonDecodeLoop(in io.Reader, outChan chan<- *discoveryMessage) { |
| 112 |
decoder := json.NewDecoder(in) |
| 113 |
closeAndReportError := func(err error) { |
| 114 |
disc.statusMutex.Lock() |
| 115 |
disc.incomingMessagesError = err |
| 116 |
disc.stopSync() |
| 117 |
disc.killProcess() |
| 118 |
disc.statusMutex.Unlock() |
| 119 |
close(outChan) |
| 120 |
if err != nil { |
| 121 |
disc.logger.Errorf("Stopped decode loop: %v", err) |
| 122 |
} else { |
| 123 |
disc.logger.Debugf("Stopped decode loop") |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
for { |
| 128 |
var msg discoveryMessage |
| 129 |
if err := decoder.Decode(&msg); err != nil { |
| 130 |
closeAndReportError(err) |
| 131 |
return |
| 132 |
} |
| 133 |
disc.logger.Debugf("Received message %s", msg) |
| 134 |
switch msg.EventType { |
| 135 |
case "add": |
| 136 |
if msg.Port == nil { |
| 137 |
closeAndReportError(errors.New("invalid 'add' message: missing port")) |
| 138 |
return |
| 139 |
} |
| 140 |
disc.statusMutex.Lock() |
| 141 |
if disc.eventChan != nil { |
| 142 |
disc.eventChan <- &Event{"add", msg.Port, disc.GetID()} |
| 143 |
} |
| 144 |
disc.statusMutex.Unlock() |
| 145 |
case "remove": |
| 146 |
if msg.Port == nil { |
| 147 |
closeAndReportError(errors.New("invalid 'remove' message: missing port")) |
| 148 |
return |
| 149 |
} |
| 150 |
disc.statusMutex.Lock() |
| 151 |
if disc.eventChan != nil { |
| 152 |
disc.eventChan <- &Event{"remove", msg.Port, disc.GetID()} |
| 153 |
} |
| 154 |
disc.statusMutex.Unlock() |
| 155 |
default: |
| 156 |
outChan <- &msg |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
// Alive returns true if the discovery is running and false otherwise. |
| 162 |
func (disc *Client) Alive() bool { |
| 163 |
disc.statusMutex.Lock() |
| 164 |
defer disc.statusMutex.Unlock() |
| 165 |
return disc.process != nil |
| 166 |
} |
| 167 |
|
| 168 |
func (disc *Client) waitMessage(timeout time.Duration) (*discoveryMessage, error) { |
| 169 |
select { |
| 170 |
case msg := <-disc.incomingMessagesChan: |
| 171 |
if msg == nil { |
| 172 |
disc.statusMutex.Lock() |
| 173 |
err := disc.incomingMessagesError |
| 174 |
disc.statusMutex.Unlock() |
| 175 |
return nil, err |
| 176 |
} |
| 177 |
return msg, nil |
| 178 |
case <-time.After(timeout): |
| 179 |
return nil, fmt.Errorf("timeout waiting for message from %s", disc) |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
func (disc *Client) sendCommand(command string) error { |
| 184 |
disc.logger.Debugf("Sending command %s", strings.TrimSpace(command)) |
| 185 |
data := []byte(command) |
| 186 |
for { |
| 187 |
n, err := disc.outgoingCommandsPipe.Write(data) |
| 188 |
if err != nil { |
| 189 |
return err |
| 190 |
} |
| 191 |
if n == len(data) { |
| 192 |
return nil |
| 193 |
} |
| 194 |
data = data[n:] |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
func (disc *Client) runProcess() error { |
| 199 |
disc.logger.Debugf("Starting discovery process") |
| 200 |
proc, err := paths.NewProcess(nil, disc.processArgs...) |
| 201 |
if err != nil { |
| 202 |
return err |
| 203 |
} |
| 204 |
stdout, err := proc.StdoutPipe() |
| 205 |
if err != nil { |
| 206 |
return err |
| 207 |
} |
| 208 |
stdin, err := proc.StdinPipe() |
| 209 |
if err != nil { |
| 210 |
return err |
| 211 |
} |
| 212 |
disc.outgoingCommandsPipe = stdin |
| 213 |
|
| 214 |
messageChan := make(chan *discoveryMessage) |
| 215 |
disc.incomingMessagesChan = messageChan |
| 216 |
go disc.jsonDecodeLoop(stdout, messageChan) |
| 217 |
|
| 218 |
if err := proc.Start(); err != nil { |
| 219 |
return err |
| 220 |
} |
| 221 |
|
| 222 |
disc.statusMutex.Lock() |
| 223 |
defer disc.statusMutex.Unlock() |
| 224 |
disc.process = proc |
| 225 |
disc.logger.Debugf("Discovery process started") |
| 226 |
return nil |
| 227 |
} |
| 228 |
|
| 229 |
func (disc *Client) killProcess() { |
| 230 |
disc.logger.Debugf("Killing discovery process") |
| 231 |
if process := disc.process; process != nil { |
| 232 |
disc.process = nil |
| 233 |
if err := process.Kill(); err != nil { |
| 234 |
disc.logger.Errorf("Killing discovery process: %v", err) |
| 235 |
} |
| 236 |
if err := process.Wait(); err != nil { |
| 237 |
disc.logger.Errorf("Waiting discovery process termination: %v", err) |
| 238 |
} |
| 239 |
} |
| 240 |
disc.logger.Debugf("Discovery process killed") |
| 241 |
} |
| 242 |
|
| 243 |
// Run starts the discovery executable process and sends the HELLO command to the discovery to agree on the |
| 244 |
// pluggable discovery protocol. This must be the first command to run in the communication with the discovery. |
| 245 |
// If the process is started but the HELLO command fails the process is killed. |
| 246 |
func (disc *Client) Run() (err error) { |
| 247 |
if err = disc.runProcess(); err != nil { |
| 248 |
return err |
| 249 |
} |
| 250 |
|
| 251 |
defer func() { |
| 252 |
// If the discovery process is started successfully but the HELLO handshake |
| 253 |
// fails the discovery is an unusable state, we kill the process to avoid |
| 254 |
// further issues down the line. |
| 255 |
if err == nil { |
| 256 |
return |
| 257 |
} |
| 258 |
disc.statusMutex.Lock() |
| 259 |
disc.killProcess() |
| 260 |
disc.statusMutex.Unlock() |
| 261 |
}() |
| 262 |
|
| 263 |
if err = disc.sendCommand("HELLO 1 \"arduino-cli " + disc.userAgent + "\"\n"); err != nil { |
| 264 |
return err |
| 265 |
} |
| 266 |
if msg, err := disc.waitMessage(time.Second * 10); err != nil { |
| 267 |
return fmt.Errorf("calling HELLO: %w", err) |
| 268 |
} else if msg.EventType != "hello" { |
| 269 |
return fmt.Errorf("event out of sync, expected 'hello', received '%s'", msg.EventType) |
| 270 |
} else if msg.Error { |
| 271 |
return fmt.Errorf("command failed: %s", msg.Message) |
| 272 |
} else if strings.ToUpper(msg.Message) != "OK" { |
| 273 |
return fmt.Errorf("communication out of sync, expected 'OK', received '%s'", msg.Message) |
| 274 |
} else if msg.ProtocolVersion > 1 { |
| 275 |
return fmt.Errorf("protocol version not supported: requested 1, got %d", msg.ProtocolVersion) |
| 276 |
} |
| 277 |
return nil |
| 278 |
} |
| 279 |
|
| 280 |
// Start initializes and start the discovery internal subroutines. This command must be |
| 281 |
// called before List. |
| 282 |
func (disc *Client) Start() error { |
| 283 |
if err := disc.sendCommand("START\n"); err != nil { |
| 284 |
return err |
| 285 |
} |
| 286 |
if msg, err := disc.waitMessage(time.Second * 10); err != nil { |
| 287 |
return fmt.Errorf("calling START: %w", err) |
| 288 |
} else if msg.EventType != "start" { |
| 289 |
return fmt.Errorf("event out of sync, expected 'start', received '%s'", msg.EventType) |
| 290 |
} else if msg.Error { |
| 291 |
return fmt.Errorf("command failed: %s", msg.Message) |
| 292 |
} else if strings.ToUpper(msg.Message) != "OK" { |
| 293 |
return fmt.Errorf("communication out of sync, expected 'OK', received '%s'", msg.Message) |
| 294 |
} |
| 295 |
return nil |
| 296 |
} |
| 297 |
|
| 298 |
// Stop stops the discovery internal subroutines and possibly free the internally |
| 299 |
// used resources. This command should be called if the client wants to pause the |
| 300 |
// discovery for a while. |
| 301 |
func (disc *Client) Stop() error { |
| 302 |
if err := disc.sendCommand("STOP\n"); err != nil { |
| 303 |
return err |
| 304 |
} |
| 305 |
if msg, err := disc.waitMessage(time.Second * 10); err != nil { |
| 306 |
return fmt.Errorf("calling STOP: %w", err) |
| 307 |
} else if msg.EventType != "stop" { |
| 308 |
return fmt.Errorf("event out of sync, expected 'stop', received '%s'", msg.EventType) |
| 309 |
} else if msg.Error { |
| 310 |
return fmt.Errorf("command failed: %s", msg.Message) |
| 311 |
} else if strings.ToUpper(msg.Message) != "OK" { |
| 312 |
return fmt.Errorf("communication out of sync, expected 'OK', received '%s'", msg.Message) |
| 313 |
} |
| 314 |
disc.statusMutex.Lock() |
| 315 |
defer disc.statusMutex.Unlock() |
| 316 |
disc.stopSync() |
| 317 |
return nil |
| 318 |
} |
| 319 |
|
| 320 |
func (disc *Client) stopSync() { |
| 321 |
if disc.eventChan != nil { |
| 322 |
disc.eventChan <- &Event{"stop", nil, disc.GetID()} |
| 323 |
close(disc.eventChan) |
| 324 |
disc.eventChan = nil |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
// Quit terminates the discovery. No more commands can be accepted by the discovery. |
| 329 |
func (disc *Client) Quit() { |
| 330 |
_ = disc.sendCommand("QUIT\n") |
| 331 |
if _, err := disc.waitMessage(time.Second * 5); err != nil { |
| 332 |
disc.logger.Errorf("Quitting discovery: %s", err) |
| 333 |
} |
| 334 |
disc.statusMutex.Lock() |
| 335 |
disc.stopSync() |
| 336 |
disc.killProcess() |
| 337 |
disc.statusMutex.Unlock() |
| 338 |
} |
| 339 |
|
| 340 |
// List executes an enumeration of the ports and returns a list of the available |
| 341 |
// ports at the moment of the call. |
| 342 |
func (disc *Client) List() ([]*Port, error) { |
| 343 |
if err := disc.sendCommand("LIST\n"); err != nil { |
| 344 |
return nil, err |
| 345 |
} |
| 346 |
msg, err := disc.waitMessage(time.Second * 10) |
| 347 |
if err != nil { |
| 348 |
return nil, fmt.Errorf("calling LIST: %w", err) |
| 349 |
} else if msg.EventType != "list" { |
| 350 |
return nil, fmt.Errorf("event out of sync, expected 'list', received '%s'", msg.EventType) |
| 351 |
} else if msg.Error { |
| 352 |
return nil, fmt.Errorf("command failed: %s", msg.Message) |
| 353 |
} |
| 354 |
return msg.Ports, nil |
| 355 |
} |
| 356 |
|
| 357 |
// StartSync puts the discovery in "events" mode: the discovery will send "add" |
| 358 |
// and "remove" events each time a new port is detected or removed respectively. |
| 359 |
// After calling StartSync an initial burst of "add" events may be generated to |
| 360 |
// report all the ports available at the moment of the start. |
| 361 |
// It also creates a channel used to receive events from the pluggable discovery. |
| 362 |
// The event channel must be consumed as quickly as possible since it may block the |
| 363 |
// discovery if it becomes full. The channel size is configurable. |
| 364 |
func (disc *Client) StartSync(size int) (eventChan <-chan *Event, retErr error) { |
| 365 |
// Create the event channel *before* sending START_SYNC. |
| 366 |
// |
| 367 |
// A discovery may emit its initial "add" events very quickly after receiving the |
| 368 |
// START_SYNC command, and those events can reach the client's decode loop |
| 369 |
// before disc.waitMessage returns (the discovery emits events from |
| 370 |
// a separate goroutine, so the "start_sync OK" and the "add" reply race on the |
| 371 |
// wire). If the event channel is still nil when such an "add" is decoded, |
| 372 |
// jsonDecodeLoop silently drops it (see the eventChan nil checks there), and |
| 373 |
// the port is lost until the next re-sync. Creating the channel up-front |
| 374 |
// guarantees these initial events are delivered. |
| 375 |
disc.statusMutex.Lock() |
| 376 |
disc.stopSync() |
| 377 |
c := make(chan *Event, size) |
| 378 |
disc.eventChan = c |
| 379 |
disc.statusMutex.Unlock() |
| 380 |
|
| 381 |
// If START_SYNC does not complete successfully, tear down the event channel we |
| 382 |
// just created so we don't leave a dangling channel that jsonDecodeLoop would |
| 383 |
// keep feeding. |
| 384 |
defer func() { |
| 385 |
if retErr != nil { |
| 386 |
disc.statusMutex.Lock() |
| 387 |
disc.stopSync() |
| 388 |
disc.statusMutex.Unlock() |
| 389 |
} |
| 390 |
}() |
| 391 |
|
| 392 |
if err := disc.sendCommand("START_SYNC\n"); err != nil { |
| 393 |
return nil, err |
| 394 |
} |
| 395 |
|
| 396 |
if msg, err := disc.waitMessage(time.Second * 10); err != nil { |
| 397 |
return nil, fmt.Errorf("calling START_SYNC: %w", err) |
| 398 |
} else if msg.EventType != "start_sync" { |
| 399 |
return nil, fmt.Errorf("evemt out of sync, expected 'start_sync', received '%s'", msg.EventType) |
| 400 |
} else if msg.Error { |
| 401 |
return nil, fmt.Errorf("command failed: %s", msg.Message) |
| 402 |
} else if strings.ToUpper(msg.Message) != "OK" { |
| 403 |
return nil, fmt.Errorf("communication out of sync, expected 'OK', received '%s'", msg.Message) |
| 404 |
} |
| 405 |
|
| 406 |
return c, nil |
| 407 |
} |