AFAIRE
sdk
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sdk/workers/pool.go

98 lines
2.0 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### sdk ####### Copyright (c) 2021-2022 losyme ################################################# MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package workers
import (
"context"
"forge.chapril.org/dune/sdk"
"forge.chapril.org/losyme/zombie"
"github.com/Showmax/go-fqdn"
)
type pool struct {
host string
runner sdk.Runner
logger Logger
state *state
workers map[string]*worker
stopCh chan bool
zombie *zombie.GWithContext
}
func newPool(cfg *Config, state *state) *pool {
fqdn, err := fqdn.FqdnHostname()
if err != nil {
fqdn = "?"
}
return &pool{
host: fqdn,
runner: cfg.Runner,
logger: cfg.Logger,
state: state,
workers: make(map[string]*worker),
stopCh: make(chan bool, _maxPoolSize),
}
}
func (p *pool) size() int {
return len(p.workers)
}
func (p *pool) startOneWorker(stoppedCh chan<- string) {
worker := newWorker(p.host, p.runner, p.logger, p.state)
fn := func(ctx context.Context) { worker.run(ctx, p.stopCh, stoppedCh) }
p.workers[worker.id] = worker
if p.zombie == nil {
p.zombie = zombie.GoWithContext(
context.Background(),
1,
fn,
zombie.WithName("worker"),
zombie.WithLogger(p.logger),
)
} else {
p.zombie.Go(1, fn)
}
}
func (p *pool) stopOneWorker() {
p.stopCh <- true
}
func (p *pool) workerStopped(wID string, end bool) int {
worker, ok := p.workers[wID]
if ok {
delete(p.workers, worker.id)
if !end && p.logger != nil {
p.logger.Warning("A worker has stopped", "worker", wID) //::::::::::::::::::::::::::::::::::::::::::::::::::
}
}
return len(p.workers)
}
func (p *pool) stop() {
if z := p.zombie; z != nil {
z.Stop()
}
}
func (p *pool) wait() {
if z := p.zombie; z != nil {
z.Wait()
}
}
/*
######################################################################################################## @(°_°)@ #######
*/