diff options
author | Julien Dessaux | 2024-03-07 00:54:35 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-03-07 01:02:23 +0100 |
commit | 560becfd32dd7355547938f3c6229060dd395aab (patch) | |
tree | 42329f4e47c64349ae8a0205f867632ac52bcdc6 /pkg/services.go | |
parent | feat(stdlib): began adding systemd services support (diff) | |
download | gonf-560becfd32dd7355547938f3c6229060dd395aab.tar.gz gonf-560becfd32dd7355547938f3c6229060dd395aab.tar.bz2 gonf-560becfd32dd7355547938f3c6229060dd395aab.zip |
chore(repo): renamed gonf subfolder to something more traditional in go land
Diffstat (limited to 'pkg/services.go')
-rw-r--r-- | pkg/services.go | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/pkg/services.go b/pkg/services.go new file mode 100644 index 0000000..58c7383 --- /dev/null +++ b/pkg/services.go @@ -0,0 +1,96 @@ +package gonf + +import "log/slog" + +// ----- Globals --------------------------------------------------------------- +var services []*ServicePromise + +// service management function +var serviceFunction func(string, string) (Status, error) + +// ----- Init ------------------------------------------------------------------ +func init() { + services = make([]*ServicePromise, 0) +} + +// ----- Public ---------------------------------------------------------------- +func SetServiceFunction(f func(string, string) (Status, error)) { + serviceFunction = f +} + +func Service(names ...string) *ServicePromise { + return &ServicePromise{ + chain: nil, + err: nil, + names: names, + states: nil, + status: PROMISED, + } +} + +func (s *ServicePromise) State(states ...string) *ServicePromise { + s.states = states + return s +} + +type ServicePromise struct { + chain []Promise + err error + names []string + states []string + status Status +} + +func (s *ServicePromise) IfRepaired(ps ...Promise) Promise { + s.chain = ps + return s +} + +func (s *ServicePromise) Promise() Promise { + services = append(services, s) + return s +} + +func (s *ServicePromise) Resolve() { + for _, name := range s.names { + var repaired = false + for _, state := range s.states { + s.status, s.err = serviceFunction(name, state) + if s.status == BROKEN { + slog.Error("service", "name", name, "state", state, "status", s.status, "error", s.err) + return + } else if s.status == REPAIRED { + repaired = true + } + } + if repaired { + s.status = REPAIRED + slog.Info("service", "name", name, "state", s.states, "status", s.status) + } else { + s.status = KEPT + slog.Debug("service", "name", name, "state", s.states, "status", s.status) + } + } + if s.status == REPAIRED { + for _, pp := range s.chain { + pp.Resolve() + } + } +} + +// ----- Internal -------------------------------------------------------------- +func resolveServices() (status Status) { + status = KEPT + for _, c := range services { + if c.status == PROMISED { + c.Resolve() + switch c.status { + case BROKEN: + return BROKEN + case REPAIRED: + status = REPAIRED + } + } + } + return +} |