Removed dist and added cache to monitor
This commit is contained in:
+32
-11
@@ -1,27 +1,38 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ScriptsDir string `json:"scriptsDir"`
|
||||
ScriptsDir string
|
||||
CacheTimeout time.Duration
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
creationTime time.Time
|
||||
|
||||
output string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
Config *Config
|
||||
|
||||
scriptPaths map[string]string
|
||||
scriptPaths map[string]string
|
||||
scriptOutputCache map[string]cacheEntry
|
||||
}
|
||||
|
||||
func NewService(config *Config) *Service {
|
||||
return &Service{
|
||||
Config: config,
|
||||
|
||||
scriptPaths: map[string]string{},
|
||||
scriptOutputCache: map[string]cacheEntry{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,21 +52,31 @@ func (s *Service) LoadScripts() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO: Add caching
|
||||
func (s *Service) GetLastOutput(command string) (string, error) {
|
||||
func (s *Service) GetOutput(command string) (string, error) {
|
||||
// check if output is present in cache
|
||||
if entry, found := s.scriptOutputCache[command]; found {
|
||||
// check if cached value is expired
|
||||
if time.Now().Before(entry.creationTime.Add(s.Config.CacheTimeout)) {
|
||||
log.Printf("Retrieving output of %q from cache", command)
|
||||
return entry.output, nil
|
||||
}
|
||||
}
|
||||
|
||||
args := strings.Fields(command)
|
||||
|
||||
log.Printf("Running script %q with args %v", args[0], args[1:])
|
||||
|
||||
scriptPath := s.scriptPaths[args[0]]
|
||||
|
||||
cmd := exec.Command(scriptPath, args[1:]...)
|
||||
var b bytes.Buffer
|
||||
cmd.Stdout = &b
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
bytes, err := exec.Command(scriptPath, args[1:]...).Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
output := string(bytes)
|
||||
|
||||
log.Printf("Caching output of %q", command)
|
||||
s.scriptOutputCache[command] = cacheEntry{time.Now(), output}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user