[WIP] Add restart command to instance

This commit is contained in:
Vladimir Stoilov
2024-09-26 13:51:42 +03:00
parent c9631daa3e
commit 61babe2822
15 changed files with 81 additions and 98 deletions

View File

@@ -4,14 +4,17 @@ import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
go_runtime "runtime"
"strings"
"sync/atomic"
"time"
"github.com/safing/portmaster/base/api"
"github.com/safing/portmaster/base/config"
"github.com/safing/portmaster/base/database/dbmodule"
"github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/metrics"
"github.com/safing/portmaster/base/notifications"
"github.com/safing/portmaster/base/rng"
@@ -101,7 +104,9 @@ type Instance struct {
sluice *sluice.SluiceModule
terminal *terminal.TerminalModule
CommandLineOperation func() error
CommandLineOperation func() error
isRunningAsService bool
defaultRestartCommand *exec.Cmd
}
func getCurrentBinaryFolder() (string, error) {
@@ -178,6 +183,8 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx
// Create instance to pass it to modules.
instance := &Instance{}
instance.ctx, instance.cancelCtx = context.WithCancel(context.Background())
instance.isRunningAsService = svcCfg.IsRunningAsService
instance.defaultRestartCommand = svcCfg.DefaultRestartCommand
var err error
@@ -671,7 +678,7 @@ func (i *Instance) Restart() {
i.core.EventRestart.Submit(struct{}{})
time.Sleep(10 * time.Millisecond)
i.shutdown(RestartExitCode)
i.serviceRestart()
}
// Shutdown asynchronously stops the instance.
@@ -700,6 +707,25 @@ func (i *Instance) shutdown(exitCode int) {
})
}
func (i *Instance) serviceRestart() {
if !i.isRunningAsService {
i.shutdown(RestartExitCode)
return
}
cmd := i.defaultRestartCommand
// Check if user defined custom command for restarting the service.
restartCommand, exists := os.LookupEnv("PORTMASTER_RESTART_COMMAND")
log.Debugf(`instance: running command "%s", %v`, restartCommand, exists)
if exists && restartCommand != "" {
commandSplit := strings.Split(restartCommand, " ")
cmd = exec.Command(commandSplit[0], commandSplit[1:]...)
}
log.Debugf("instance: running command %s", cmd.String())
_ = cmd.Run()
}
// Stopping returns whether the instance is shutting down.
func (i *Instance) Stopping() bool {
return i.ctx.Err() != nil