dae/cmd/reload.go

103 lines
2.4 KiB
Go
Raw Normal View History

2023-02-27 13:07:36 +07:00
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) 2022-2024, daeuniverse Organization <dae@v2raya.org>
2023-02-27 13:07:36 +07:00
*/
package cmd
import (
2023-03-13 23:34:38 +07:00
"fmt"
2023-02-27 13:07:36 +07:00
"os"
"strconv"
2023-03-13 23:34:38 +07:00
"strings"
2023-02-27 13:07:36 +07:00
"syscall"
"time"
"github.com/daeuniverse/dae/cmd/internal"
"github.com/daeuniverse/dae/common/consts"
"github.com/spf13/cobra"
2023-02-27 13:07:36 +07:00
)
func readSignalProgressFile() (code byte, content string, err error) {
b, err := os.ReadFile(SignalProgressFilePath)
if err != nil {
return 0, "", err
}
var firstLine string
firstLine, content, _ = strings.Cut(string(b), "\n")
if len(firstLine) != 1 {
return 0, "", fmt.Errorf("unexpected format: %v", string(b))
}
code = firstLine[0]
return code, content, nil
}
2023-02-27 13:07:36 +07:00
var (
abort bool
2023-02-27 13:07:36 +07:00
reloadCmd = &cobra.Command{
2023-03-13 23:46:45 +07:00
Use: "reload [pid]",
Short: "To reload config file without interrupt connections.",
2023-02-27 13:07:36 +07:00
Run: func(cmd *cobra.Command, args []string) {
2023-03-13 23:34:38 +07:00
internal.AutoSu()
2023-02-27 13:07:36 +07:00
if len(args) == 0 {
2023-03-13 23:34:38 +07:00
_pid, err := os.ReadFile(PidFilePath)
if err != nil {
fmt.Println("Failed to read pid file:", err)
os.Exit(1)
}
args = []string{strings.TrimSpace(string(_pid))}
2023-02-27 13:07:36 +07:00
}
pid, err := strconv.Atoi(args[0])
if err != nil {
cmd.Help()
os.Exit(1)
}
if abort {
if f, err := os.Create(AbortFile); err == nil {
f.Close()
}
}
// Read the first line of SignalProgressFilePath.
code, _, err := readSignalProgressFile()
if err == nil && code != consts.ReloadDone && code != consts.ReloadError {
// In progress.
fmt.Printf("%v shows another reload operation is in progress.\n", SignalProgressFilePath)
return
}
// Set the progress as ReloadSend.
os.WriteFile(SignalProgressFilePath, []byte{consts.ReloadSend}, 0644)
// Send signal.
2023-03-13 23:34:38 +07:00
if err = syscall.Kill(pid, syscall.SIGUSR1); err != nil {
fmt.Println(err)
os.Exit(1)
}
time.Sleep(500 * time.Millisecond)
code, _, _ = readSignalProgressFile()
if code == consts.ReloadSend {
// Old version dae is running.
goto fallback
}
for {
time.Sleep(200 * time.Millisecond)
code, content, err := readSignalProgressFile()
if err != nil {
// Unexpecetd case.
goto fallback
}
if code == consts.ReloadDone || code == consts.ReloadError {
fmt.Println(content)
return
}
}
fallback:
2023-03-13 23:34:38 +07:00
fmt.Println("OK")
2023-02-27 13:07:36 +07:00
},
}
)
2023-03-13 23:34:38 +07:00
func init() {
rootCmd.AddCommand(reloadCmd)
reloadCmd.PersistentFlags().BoolVarP(&abort, "abort", "a", false, "Abort established connections.")
2023-03-13 23:46:45 +07:00
}