-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
80 lines (71 loc) · 1.78 KB
/
util.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
// Copyright 2019 The vogo Authors. All rights reserved.
// author: wongoo
package gracego
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strconv"
"strings"
)
func existFile(file string) bool {
if _, err := os.Stat(file); err == nil {
return true
} else if os.IsNotExist(err) {
return false
}
return false
}
func execCmd(cmdline string) ([]byte, error) {
cmd := exec.Command("/bin/sh", "-c", cmdline)
result, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
return bytes.ReplaceAll(result, []byte{'\n'}, nil), nil
}
func getPidFromAddr(addr string) (int, error) {
idx := strings.LastIndex(addr, ":")
if idx < 0 {
return 0, errors.New("can't get port from address")
}
port := addr[idx+1:]
result, err := execCmd(fmt.Sprintf("lsof -i:%s |grep LISTEN | tail -1 |awk '{print $2}'", port))
if err != nil {
return 0, fmt.Errorf("failed to get pid from port %s, error: %+v", port, err)
}
pid, err := strconv.Atoi(string(result))
if err != nil {
return 0, fmt.Errorf("failed to get pid from port %s, result: %s, error: %v", port, result, err)
}
return pid, nil
}
func checkSameBinProcess(pid int) (string, bool) {
cmdline, err := getCommandline(pid)
if err != nil {
graceLog("can't get command line for pid %d, error: %v", pid, err)
return "", false
}
if strings.Contains(cmdline, serverBin) {
return cmdline, true
}
return cmdline, false
}
func getCommandline(pid int) (string, error) {
linuxCmdlineFile := fmt.Sprintf("/proc/%d/cmdline", pid)
if existFile(linuxCmdlineFile) {
data, err := ioutil.ReadFile(linuxCmdlineFile)
if err != nil {
return "", err
}
return string(data), nil
}
result, err := execCmd(fmt.Sprintf("ps -o 'command' -p %d |tail -1", pid))
if err != nil {
return "", err
}
return string(result), nil
}