Skip to content

Commit

Permalink
Protect from being able to start multiple schedulers.
Browse files Browse the repository at this point in the history
  • Loading branch information
symbiont-stevan-andjelkovic committed Dec 17, 2020
1 parent 0b870e6 commit 7635ba0
Showing 1 changed file with 32 additions and 10 deletions.
42 changes: 32 additions & 10 deletions src/cli/cmd/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,62 +11,84 @@ import (
"github.com/spf13/cobra"
)

const pidFile = "detsys-scheduler.pid"

var schedulerCmd = &cobra.Command{
Use: "scheduler [command]",
Short: "Start or stop the scheduler",
Long: ``,
Args: cobra.ExactArgs(1),
}

func pidFile() string {
return filepath.Join(os.TempDir(), "detsys-scheduler.pid")
}

var schedulerUpCmd = &cobra.Command{
Use: "up",
Short: "Start the scheduler",
Long: ``,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, args []string) {
pid, err := readPid()
if err == nil {
fmt.Printf("Already running on pid: %d (%s)\n", pid, pidFile())
os.Exit(1)
}

cmd := exec.Command("detsys-scheduler")

err := cmd.Start()
err = cmd.Start()

if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

pid := []byte(strconv.Itoa(cmd.Process.Pid))
pidBs := []byte(strconv.Itoa(cmd.Process.Pid))

ioutil.WriteFile(filepath.Join(os.TempDir(), pidFile), pid, 0600)
fmt.Printf("%s\n", pid)
ioutil.WriteFile(pidFile(), pidBs, 0600)
fmt.Printf("%s\n", pidBs)
},
}

func readPid() (int, error) {
bs, err := ioutil.ReadFile(pidFile())
if err != nil {
return -1, err
}

pid, err := strconv.Atoi(string(bs))
if err != nil {
return -1, err
}
return pid, nil
}

var schedulerDownCmd = &cobra.Command{
Use: "down",
Short: "Stop the scheduler",
Long: ``,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, args []string) {
bs, err := ioutil.ReadFile(filepath.Join(os.TempDir(), pidFile))

pid, err := readPid()
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

pid, err := strconv.Atoi(string(bs))
process, err := os.FindProcess(pid)
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

process, err := os.FindProcess(pid)
err = process.Kill()
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

err = process.Kill()
err = os.Remove(pidFile())
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
Expand Down

0 comments on commit 7635ba0

Please sign in to comment.