-
Notifications
You must be signed in to change notification settings - Fork 165
/
reload.go
102 lines (95 loc) · 2.42 KB
/
reload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) 2022-2024, daeuniverse Organization <dae@v2raya.org>
*/
package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"syscall"
"time"
"github.com/daeuniverse/dae/cmd/internal"
"github.com/daeuniverse/dae/common/consts"
"github.com/spf13/cobra"
)
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
}
var (
abort bool
reloadCmd = &cobra.Command{
Use: "reload [pid]",
Short: "To reload config file without interrupt connections.",
Run: func(cmd *cobra.Command, args []string) {
internal.AutoSu()
if len(args) == 0 {
_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))}
}
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.
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:
fmt.Println("OK")
},
}
)
func init() {
rootCmd.AddCommand(reloadCmd)
reloadCmd.PersistentFlags().BoolVarP(&abort, "abort", "a", false, "Abort established connections.")
}