-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
193 lines (168 loc) · 4.26 KB
/
main.go
File metadata and controls
193 lines (168 loc) · 4.26 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
package main
import (
"context"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/v4/process"
"golang.org/x/sync/errgroup"
"io/fs"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// https://kubernetes.io/zh-cn/docs/tasks/configure-pod-container/share-process-namespace/
// https://cctoctofx.netlify.app/post/cloud-computing/k8s-config-update/
func main() {
time.Sleep(10 * time.Second)
err := NewNginxReloadWatcher().Start()
if err != nil {
log.Println("[ERROR] start watcher err")
}
}
type NginxReloadWatcher struct {
sync.Mutex
nginxMasterPid int32
timer *time.Timer
timeAfterSeconds time.Duration
// file watch 的目录,用逗号分割
// 如 /etc/nginx,/etc/nginx/conf.d
watchDirs []string
}
func NewNginxReloadWatcher() *NginxReloadWatcher {
timeAfterSecondsEnv := os.Getenv("TIME_AFTER_SECONDS")
var timeAfter = 30
atoi, err := strconv.Atoi(timeAfterSecondsEnv)
if err == nil {
timeAfter = atoi
}
log.Println("TIME_AFTER_SECONDS: ", timeAfter)
watchDirsEnv := os.Getenv("WATCH_DIRS")
log.Println("WATCH_DIRS: ", watchDirsEnv)
watchDirs := strings.Split(watchDirsEnv, ",")
log.Println("WATCH_DIRS after split: ", watchDirs)
return &NginxReloadWatcher{
timeAfterSeconds: time.Duration(timeAfter) * time.Second,
watchDirs: watchDirs,
}
}
func (n *NginxReloadWatcher) findNginxMaterPid() (int32, error) {
processes, err := process.Processes()
if err != nil {
return 0, err
}
for _, p := range processes {
name, err := p.Name()
if err != nil {
return 0, errors.Wrap(err, "process Name err")
}
if name != "nginx" {
continue
}
ppid, err := p.Ppid()
if err != nil {
return 0, errors.Wrap(err, "process ppid err")
}
if ppid == 0 {
return p.Pid, nil
}
}
return 0, errors.New("not found nginx master")
}
func (n *NginxReloadWatcher) Start() error {
pid, err := n.findNginxMaterPid()
if err != nil {
return err
}
log.Println(fmt.Sprintf("nginx master id %d", pid))
n.nginxMasterPid = pid
g, gctx := errgroup.WithContext(context.TODO())
g.Go(func() error {
killSignal := make(chan os.Signal, 1)
signal.Notify(killSignal, os.Interrupt, syscall.SIGTERM, os.Kill)
<-killSignal
return errors.New("kill signal")
})
g.Go(func() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// Add a path.
for _, parentDir := range n.watchDirs {
parentDir = fmt.Sprintf("/proc/%d/root%s", pid, parentDir)
err = watcher.Add(parentDir)
if err != nil {
return err
}
err = filepath.WalkDir(parentDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Printf("无法访问路径 %q: %v\n", path, err)
return err // 继续遍历其他文件/目录
}
if d.IsDir() {
watcher.Add(path)
}
return nil
})
if err != nil {
return errors.Wrap(err, "遍历目录时出错")
}
}
watchList := watcher.WatchList()
for _, item := range watchList {
log.Println(item)
}
for {
select {
case <-gctx.Done():
return errors.New("gctx done")
case event, ok := <-watcher.Events:
if !ok {
continue
}
log.Println("event:", event)
if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) || event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Chmod) {
n.timerHubSignal(event.String())
}
case err, ok := <-watcher.Errors:
if !ok {
continue
}
log.Println("error:", err)
}
}
})
return g.Wait()
}
func (n *NginxReloadWatcher) timerHubSignal(event string) {
n.Lock()
defer n.Unlock()
if n.timer != nil {
log.Println("[INFO] stop preview timer")
n.timer.Stop()
}
//
log.Println("[INFO] set new timer ", event)
n.timer = time.AfterFunc(n.timeAfterSeconds, func() {
n.Lock()
defer n.Unlock()
n.timer = nil
command := exec.Command("/bin/bash", "-c", fmt.Sprintf("kill -HUP %d", n.nginxMasterPid))
output, err := command.CombinedOutput()
s := string(output)
if err != nil {
log.Println(fmt.Sprintf("kill -HUP %d err, err %v, output %s, event %s", n.nginxMasterPid, err, s, event))
return
}
log.Println(fmt.Sprintf("kill -HUP %d success, output %s, event %s", n.nginxMasterPid, s, event))
})
}