forked from alibaba/kt-connect
-
Notifications
You must be signed in to change notification settings - Fork 2
/
system.go
117 lines (96 loc) · 2.27 KB
/
system.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package util
import (
"fmt"
"io/ioutil"
"os"
"runtime"
"github.com/lextoumbourou/goodhosts"
"github.com/rs/zerolog/log"
)
var interrupt = make(chan bool)
// StopBackendProcess ...
func StopBackendProcess(stop bool, cancel func()) {
if cancel == nil {
return
}
cancel()
interrupt <- stop
}
// Interrupt ...
func Interrupt() chan bool {
return interrupt
}
// IsDaemonRunning check daemon is running or not
func IsDaemonRunning(pidFile string) bool {
if _, err := os.Stat(pidFile); os.IsNotExist(err) {
return false
}
return true
}
// HomeDir Current User home dir
func HomeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
if h := os.Getenv("USERPROFILE"); h != "" {
return h
}
return "/root"
}
// CreateDirIfNotExist create dir
func CreateDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
}
}
// WritePidFile write pid to file
func WritePidFile(pidFile string) (pid int, err error) {
pid = os.Getpid()
err = ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d", pid)), 0644)
return
}
// IsWindows check runtime is windows
func IsWindows() bool {
return runtime.GOOS == "windows"
}
// DropHosts ...
func DropHosts(hostsMap map[string]string) {
hosts, err := goodhosts.NewHosts()
if err != nil {
log.Warn().Msgf("Fail to read hosts from host %s, ignore", err.Error())
return
}
for name, ip := range hostsMap {
if hosts.Has(ip, name) {
if err = hosts.Remove(ip, name); err != nil {
log.Warn().Str("ip", ip).Str("name", name).Msg("remove host failed")
}
}
}
if err := hosts.Flush(); err != nil {
log.Error().Err(err).Msgf("Error Happen when flush hosts")
}
log.Info().Msgf("- drop hosts successful.")
}
// DumpHosts DumpToHosts
func DumpHosts(hostsMap map[string]string) {
hosts, err := goodhosts.NewHosts()
if err != nil {
log.Warn().Msgf("Fail to read hosts from host %s, ignore", err.Error())
return
}
for name, ip := range hostsMap {
if !hosts.Has(ip, name) {
if err = hosts.Add(ip, name); err != nil {
log.Warn().Str("ip", ip).Str("name", name).Msg("add host failed")
}
}
}
if err := hosts.Flush(); err != nil {
log.Error().Err(err).Msg("Error Happen when dump hosts")
}
log.Info().Msg("Dump hosts successful.")
}