-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_lifecycle.go
More file actions
275 lines (252 loc) · 6.23 KB
/
Copy pathproxy_lifecycle.go
File metadata and controls
275 lines (252 loc) · 6.23 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/clovapi/switcher/internal/config"
"github.com/clovapi/switcher/internal/profile"
"github.com/clovapi/switcher/internal/syslog"
)
type proxyPIDRecord struct {
PID int `json:"pid"`
Host string `json:"host"`
Port int `json:"port"`
StartedAt string `json:"started_at"`
}
func proxyPIDPath() (string, error) {
dir, err := config.Dir()
if err != nil {
return "", err
}
return filepath.Join(dir, "proxy.pid"), nil
}
func writeProxyPIDFile(pid int, cfg profile.ProxyConfig) error {
if pid <= 0 {
return errors.New("proxy pid is invalid")
}
path, err := proxyPIDPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
rec := proxyPIDRecord{
PID: pid,
Host: strings.TrimSpace(cfg.Host),
Port: cfg.Port,
StartedAt: time.Now().UTC().Format(time.RFC3339Nano),
}
data, err := json.Marshal(rec)
if err != nil {
return err
}
return os.WriteFile(path, append(data, '\n'), 0o600)
}
func readProxyPIDFile() (proxyPIDRecord, error) {
path, err := proxyPIDPath()
if err != nil {
return proxyPIDRecord{}, err
}
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return proxyPIDRecord{}, err
}
return proxyPIDRecord{}, err
}
var rec proxyPIDRecord
if err := json.Unmarshal(bytesTrimSpace(data), &rec); err != nil {
return proxyPIDRecord{}, err
}
return rec, nil
}
func bytesTrimSpace(data []byte) []byte {
return []byte(strings.TrimSpace(string(data)))
}
func removeProxyPIDFile() {
path, err := proxyPIDPath()
if err != nil {
return
}
_ = os.Remove(path)
}
func removeProxyPIDFileIfPID(pid int) {
rec, err := readProxyPIDFile()
if err != nil || rec.PID != pid {
return
}
removeProxyPIDFile()
}
func processAlive(pid int) bool {
if pid <= 0 {
return false
}
proc, err := os.FindProcess(pid)
if err != nil {
return false
}
if runtime.GOOS == "windows" {
// FindProcess always succeeds on Windows; use exit code probe via tasklist.
cmd := exec.Command("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/NH")
out, err := cmd.Output()
if err != nil {
return false
}
return strings.Contains(string(out), strconv.Itoa(pid))
}
err = proc.Signal(syscall.Signal(0))
return err == nil
}
func killProcessTree(pid int) error {
if pid <= 0 {
return nil
}
if runtime.GOOS == "windows" {
cmd := exec.Command("taskkill", "/PID", strconv.Itoa(pid), "/T", "/F")
if out, err := cmd.CombinedOutput(); err != nil {
text := strings.TrimSpace(string(out))
if strings.Contains(text, "not found") {
return nil
}
return fmt.Errorf("taskkill pid %d: %w: %s", pid, err, text)
}
return nil
}
proc, err := os.FindProcess(pid)
if err != nil {
return nil
}
_ = proc.Signal(syscall.SIGTERM)
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if !processAlive(pid) {
return nil
}
time.Sleep(100 * time.Millisecond)
}
_ = proc.Kill()
return nil
}
func findListenPID(port int) (int, error) {
if port <= 0 {
return 0, errors.New("port is invalid")
}
if runtime.GOOS == "windows" {
cmd := exec.Command("cmd", "/c", fmt.Sprintf("netstat -ano -p tcp | findstr :%d | findstr LISTENING", port))
out, err := cmd.Output()
if err != nil {
return 0, err
}
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(strings.TrimSpace(line))
if len(fields) < 5 {
continue
}
pid, err := strconv.Atoi(fields[len(fields)-1])
if err == nil && pid > 0 {
return pid, nil
}
}
return 0, errors.New("no listener found")
}
cmd := exec.Command("lsof", "-ti", fmt.Sprintf("tcp:%d", port), "-sTCP:LISTEN")
out, err := cmd.Output()
if err != nil {
return 0, err
}
for _, field := range strings.Fields(string(out)) {
pid, err := strconv.Atoi(field)
if err == nil && pid > 0 {
return pid, nil
}
}
return 0, errors.New("no listener found")
}
var (
probeProxyHealthForStop = probeProxyHealth
processAliveForStop = processAlive
killProcessTreeForStop = killProcessTree
findListenPIDForStop = findListenPID
)
func waitProxyDown(cfg profile.ProxyConfig, deadline time.Duration) error {
deadlineAt := time.Now().Add(deadline)
for time.Now().Before(deadlineAt) {
ok, err := probeProxyHealth(cfg)
if err != nil {
return err
}
if !ok {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("proxy still healthy at %s", proxyHealthURL(cfg))
}
func verifyPortListenerIsClovapiProxy(cfg profile.ProxyConfig, pid int) error {
ok, err := probeProxyHealthForStop(cfg)
if err != nil {
return err
}
if ok {
return nil
}
return fmt.Errorf("refusing to stop process %d listening on %s: health endpoint does not identify as clovapi proxy", pid, proxyBaseURL(cfg))
}
func runProxyStop(cfg profile.ProxyConfig, verbose bool) error {
wasHealthy, _ := probeProxyHealthForStop(cfg)
if wasHealthy {
_ = shutdownProxyViaHTTP(cfg)
_ = waitProxyDown(cfg, 5*time.Second)
}
rec, pidErr := readProxyPIDFile()
if pidErr == nil && rec.PID > 0 {
if processAliveForStop(rec.PID) {
if err := killProcessTreeForStop(rec.PID); err != nil && verbose {
fmt.Fprintf(os.Stderr, "warning: kill proxy pid %d: %v\n", rec.PID, err)
}
}
}
if listenPID, err := findListenPIDForStop(cfg.Port); err == nil && listenPID > 0 {
if pidErr != nil || listenPID != rec.PID {
if err := verifyPortListenerIsClovapiProxy(cfg, listenPID); err != nil {
return err
}
_ = killProcessTreeForStop(listenPID)
}
}
removeProxyPIDFile()
if wasHealthy {
if err := waitProxyDown(cfg, 2*time.Second); err != nil {
return err
}
}
syslog.LogProxyStopped("cli-stop")
if verbose {
fmt.Printf("clovapi proxy stopped (%s)\n", proxyBaseURL(cfg))
}
return nil
}
func shutdownProxyViaHTTP(cfg profile.ProxyConfig) bool {
url := proxyBaseURL(cfg) + "/__debug/shutdown"
req, err := http.NewRequest(http.MethodPost, url, nil)
if err != nil {
return false
}
client := http.Client{Timeout: 2 * time.Second}
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}