gaper/gaper.go

231 lines
5.4 KiB
Go
Raw Normal View History

// Package gaper implements a supervisor restarts a go project
// when it crashes or a watched file changes
package gaper
import (
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
shellwords "github.com/mattn/go-shellwords"
)
// DefaultBuildPath is the default build and watched path
var DefaultBuildPath = "."
// DefaultExtensions is the default watched extension
var DefaultExtensions = []string{"go"}
// DefaultPoolInterval is the time in ms used by the watcher to wait between scans
var DefaultPoolInterval = 500
2018-07-12 08:27:07 -05:00
// No restart types
var (
NoRestartOnError = "error"
NoRestartOnSuccess = "success"
NoRestartOnExit = "exit"
)
// exit statuses
var exitStatusSuccess = 0
var exitStatusError = 1
// Config contains all settings supported by gaper
type Config struct {
BinName string
BuildPath string
BuildArgs []string
BuildArgsMerged string
ProgramArgs []string
ProgramArgsMerged string
WatchItems []string
IgnoreItems []string
PollInterval int
Extensions []string
NoRestartOn string
DisableDefaultIgnore bool
WorkingDirectory string
}
2018-07-12 08:27:07 -05:00
// Run starts the whole gaper process watching for file changes or exit codes
// and restarting the program
2018-07-12 08:27:07 -05:00
func Run(cfg *Config, chOSSiginal chan os.Signal) error {
logger.Debug("Starting gaper")
2018-07-12 08:27:07 -05:00
if err := setupConfig(cfg); err != nil {
return err
}
2021-12-18 05:01:38 -06:00
logger.Debugf("Config: %+v", cfg)
wCfg := WatcherConfig{
DefaultIgnore: !cfg.DisableDefaultIgnore,
PollInterval: cfg.PollInterval,
WatchItems: cfg.WatchItems,
IgnoreItems: cfg.IgnoreItems,
Extensions: cfg.Extensions,
}
2018-07-12 08:27:07 -05:00
builder := NewBuilder(cfg.BuildPath, cfg.BinName, cfg.WorkingDirectory, cfg.BuildArgs)
runner := NewRunner(os.Stdout, os.Stderr, filepath.Join(cfg.WorkingDirectory, builder.Binary()), cfg.ProgramArgs)
watcher, err := NewWatcher(wCfg)
if err != nil {
2018-07-12 08:27:07 -05:00
return fmt.Errorf("watcher error: %v", err)
}
2018-07-12 08:27:07 -05:00
return run(cfg, chOSSiginal, builder, runner, watcher)
}
// nolint: gocyclo
func run(cfg *Config, chOSSiginal chan os.Signal, builder Builder, runner Runner, watcher Watcher) error {
2018-07-12 08:27:07 -05:00
if err := builder.Build(); err != nil {
return fmt.Errorf("build error: %v", err)
}
2018-07-12 08:27:07 -05:00
// listen for OS signals
signal.Notify(chOSSiginal, os.Interrupt, syscall.SIGTERM)
2018-07-12 08:27:07 -05:00
if _, err := runner.Run(); err != nil {
return fmt.Errorf("run error: %v", err)
}
2018-06-24 19:05:22 -05:00
// flag to know if an exit was caused by a restart from a file changing
changeRestart := false
go watcher.Watch()
for {
select {
2018-07-12 08:27:07 -05:00
case event := <-watcher.Events():
2018-09-08 08:27:10 -05:00
logger.Debug("Detected new changed file:", event)
if changeRestart {
logger.Debug("Skip restart due to existing on going restart")
continue
}
changeRestart = runner.IsRunning()
if err := restart(builder, runner); err != nil {
return err
}
2018-07-12 08:27:07 -05:00
case err := <-watcher.Errors():
return fmt.Errorf("error on watching files: %v", err)
case err := <-runner.Errors():
2018-09-08 08:27:10 -05:00
logger.Debug("Detected program exit:", err)
2018-06-24 19:05:22 -05:00
// ignore exit by change
if changeRestart {
changeRestart = false
2018-06-24 19:05:22 -05:00
continue
}
if err = handleProgramExit(builder, runner, err, cfg.NoRestartOn); err != nil {
return err
}
2018-07-12 08:27:07 -05:00
case signal := <-chOSSiginal:
2018-09-08 08:27:10 -05:00
logger.Debug("Got signal:", signal)
2018-07-12 08:27:07 -05:00
if err := runner.Kill(); err != nil {
2018-09-08 08:27:10 -05:00
logger.Error("Error killing:", err)
2018-07-12 08:27:07 -05:00
}
return fmt.Errorf("OS signal: %v", signal)
default:
time.Sleep(time.Duration(cfg.PollInterval) * time.Millisecond)
}
}
}
func restart(builder Builder, runner Runner) error {
logger.Debug("Restarting program")
// kill process if it is running
if !runner.Exited() {
if err := runner.Kill(); err != nil {
return fmt.Errorf("kill error: %v", err)
}
}
if err := builder.Build(); err != nil {
2018-09-08 08:27:10 -05:00
logger.Error("Error building binary during a restart:", err)
return nil
}
if _, err := runner.Run(); err != nil {
2018-09-08 08:27:10 -05:00
logger.Error("Error starting process during a restart:", err)
return nil
}
return nil
}
func handleProgramExit(builder Builder, runner Runner, err error, noRestartOn string) error {
2018-07-12 08:27:07 -05:00
exitStatus := runner.ExitStatus(err)
// if "error", an exit code of 0 will still restart.
2018-07-12 08:27:07 -05:00
if noRestartOn == NoRestartOnError && exitStatus == exitStatusError {
return nil
}
// if "success", no restart only if exit code is 0.
2018-07-12 08:27:07 -05:00
if noRestartOn == NoRestartOnSuccess && exitStatus == exitStatusSuccess {
return nil
}
// if "exit", no restart regardless of exit code.
2018-07-12 08:27:07 -05:00
if noRestartOn == NoRestartOnExit {
return nil
}
return restart(builder, runner)
}
2018-07-12 08:27:07 -05:00
func setupConfig(cfg *Config) error {
var err error
2018-07-12 08:27:07 -05:00
if len(cfg.BuildPath) == 0 {
cfg.BuildPath = DefaultBuildPath
}
2018-07-12 08:27:07 -05:00
cfg.BuildArgs, err = parseInnerArgs(cfg.BuildArgs, cfg.BuildArgsMerged)
if err != nil {
return err
}
cfg.ProgramArgs, err = parseInnerArgs(cfg.ProgramArgs, cfg.ProgramArgsMerged)
if err != nil {
return err
}
cfg.WorkingDirectory, err = os.Getwd()
if err != nil {
return err
}
if len(cfg.WatchItems) == 0 {
cfg.WatchItems = append(cfg.WatchItems, cfg.BuildPath)
}
var extensions []string
for i := range cfg.Extensions {
values := strings.Split(cfg.Extensions[i], ",")
for _, e := range values {
extensions = append(extensions, e)
}
}
cfg.Extensions = extensions
2018-07-12 08:27:07 -05:00
return nil
}
func parseInnerArgs(args []string, argsm string) ([]string, error) {
if len(args) > 0 || len(argsm) == 0 {
return args, nil
}
return shellwords.Parse(argsm)
}