Files
nmon/internal/simagent/pool.go

55 lines
1.2 KiB
Go

package simagent
import (
"context"
"errors"
"fmt"
"sync"
)
// Pool hosts many agents in one process, one UDP socket each.
type Pool struct {
mu sync.Mutex
agents []*Agent
}
// Start launches one agent per config and appends them to the pool. If any
// fails, the ones started by this call are closed and the error is returned.
func (p *Pool) Start(ctx context.Context, cfgs []Config) error {
started := make([]*Agent, 0, len(cfgs))
for i, c := range cfgs {
a, err := Start(ctx, c)
if err != nil {
for _, s := range started {
_ = s.Close() // best-effort rollback; the start error is the one to report
}
return fmt.Errorf("agent %d: %w", i, err)
}
started = append(started, a)
}
p.mu.Lock()
p.agents = append(p.agents, started...)
p.mu.Unlock()
return nil
}
// Agents returns the running agents in start order.
func (p *Pool) Agents() []*Agent {
p.mu.Lock()
defer p.mu.Unlock()
return append([]*Agent(nil), p.agents...)
}
// Close stops every agent.
func (p *Pool) Close() error {
p.mu.Lock()
agents := p.agents
p.agents = nil
p.mu.Unlock()
var errs []error
for _, a := range agents {
errs = append(errs, a.Close())
}
return errors.Join(errs...)
}