From 3d0a69d5a35a1da6ccfcda2d4d3aae4eabf5c072 Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Fri, 26 May 2023 20:01:27 -0400 Subject: [PATCH] Added a convenient Service type --- service/service.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/service/service.go b/service/service.go index 7bffa30..edc7ce2 100644 --- a/service/service.go +++ b/service/service.go @@ -1,2 +1,61 @@ // Package service provides a toolkit for creating Hnakra services. package service + +import "os" +import "log" +import "time" +import "hnakra/rotate" +import "hnakra/routines" + +// Service is capable of managing multiple mounts. It also sets up logging +// automatically. +type Service []Mount + +// Run runs the mounts within the service, and only exits when all of them have +// exited. It will automatically start logging to the directory specified by +// $HNAKRA_LOG_DIR. If that variable is unset, it will just log to stdout. +func (service Service) Run () error { + // set up logging + logDir := os.Getenv("HNAKRA_LOG_DIR") + if logDir != "" { + logger, err := rotate.New(logDir) + if err != nil { log.Fatal("cannot access log dir:", err) } + log.SetOutput(logger) + } + + // set up routine manager + manager := routines.Manager { RestartDeadline: time.Second * 8 } + manager.Routines = make([]routines.Routine, len(service)) + for index, mount := range manager.Routines { + manager.Routines[index] = mount + } + + // send it + err := manager.Run() + if err != nil { log.Println("XXX", err) } + return err +} + +// Close abruptly closes all mounts in the service. This will cause Run() to +// exit. +func (service Service) Close () (err error) { + for _, mount := range service { + singleErr := mount.Close() + if singleErr != nil { + err = singleErr + } + } + return +} + +// Shutdown gracefully shuts down each mount in the service. This will cause +// Run() to exit. +func (service Service) Shutdown () (err error) { + for _, mount := range service { + singleErr := mount.Shutdown() + if singleErr != nil { + err = singleErr + } + } + return +}