Major fixes and improvements

This commit is contained in:
TwinProduction
2021-07-15 22:07:30 -04:00
committed by Chris
parent fed32d3909
commit d3a81a2d57
14 changed files with 378 additions and 158 deletions

View File

@ -6,6 +6,7 @@ import (
"time"
"github.com/TwinProduction/gatus/storage/store"
"github.com/TwinProduction/gatus/storage/store/database"
"github.com/TwinProduction/gatus/storage/store/memory"
)
@ -38,36 +39,52 @@ func Initialize(cfg *Config) error {
initialized = true
var err error
if cancelFunc != nil {
// Stop the active autoSave task
// Stop the active autoSaveStore task, if there's already one
cancelFunc()
}
if cfg == nil || len(cfg.File) == 0 {
log.Println("[storage][Initialize] Creating storage provider")
provider, _ = memory.NewStore("")
if cfg == nil {
cfg = &Config{}
}
if len(cfg.File) == 0 {
log.Printf("[storage][Initialize] Creating storage provider with type=%s", cfg.Type)
} else {
ctx, cancelFunc = context.WithCancel(context.Background())
log.Printf("[storage][Initialize] Creating storage provider with file=%s", cfg.File)
provider, err = memory.NewStore(cfg.File)
log.Printf("[storage][Initialize] Creating storage provider with type=%s and file=%s", cfg.Type, cfg.File)
}
ctx, cancelFunc = context.WithCancel(context.Background())
switch cfg.Type {
case TypeSQLite:
provider, err = database.NewStore(string(cfg.Type), cfg.File)
if err != nil {
return err
}
go autoSave(7*time.Minute, ctx)
case TypeInMemory:
fallthrough
default:
if len(cfg.File) > 0 {
provider, err = memory.NewStore(cfg.File)
if err != nil {
return err
}
go autoSaveStore(ctx, provider, 7*time.Minute)
} else {
provider, _ = memory.NewStore("")
}
}
return nil
}
// autoSave automatically calls the SaveFunc function of the provider at every interval
func autoSave(interval time.Duration, ctx context.Context) {
// autoSaveStore automatically calls the Save function of the provider at every interval
func autoSaveStore(ctx context.Context, provider store.Store, interval time.Duration) {
for {
select {
case <-ctx.Done():
log.Printf("[storage][autoSave] Stopping active job")
log.Printf("[storage][autoSaveStore] Stopping active job")
return
case <-time.After(interval):
log.Printf("[storage][autoSave] Saving")
log.Printf("[storage][autoSaveStore] Saving")
err := provider.Save()
if err != nil {
log.Println("[storage][autoSave] Save failed:", err.Error())
log.Println("[storage][autoSaveStore] Save failed:", err.Error())
}
}
}