-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.go
More file actions
122 lines (101 loc) · 2.12 KB
/
Copy pathdaemon.go
File metadata and controls
122 lines (101 loc) · 2.12 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
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"syscall"
"github.com/thekhanj/avail/common"
"github.com/thekhanj/avail/config"
)
type DaemonOption = func(ping *Daemon)
type Daemon struct {
cfg *config.Config
log *log.Logger
}
func NewDaemon(cfg *config.Config, opts ...DaemonOption) *Daemon {
base := &Daemon{
cfg: cfg,
log: log.New(os.Stderr, "daemon: ", 0),
}
for _, o := range opts {
o(base)
}
return base
}
func DaemonWithLog(log *log.Logger) DaemonOption {
return func(d *Daemon) {
d.log = log
}
}
func (this *Daemon) Run(ctx context.Context) error {
err := this.writePid()
if err != nil {
return err
}
defer this.cleanup()
pings := make([]*Ping, len(this.cfg.Sites))
for i, pingCfg := range this.cfg.Sites {
ping, err := NewPingFromConfig(&pingCfg)
if err != nil {
return err
}
pings[i] = ping
}
this.runPings(ctx, pings)
return nil
}
func (this *Daemon) runPings(ctx context.Context, pings []*Ping) {
var wg sync.WaitGroup
wg.Add(len(pings))
for _, ping := range pings {
go func() {
defer wg.Done()
ping.Run(ctx)
}()
}
wg.Wait()
}
func (this *Daemon) cleanup() {
err := os.Remove(this.cfg.GetPidFile())
if err != nil {
this.log.Println(err)
}
err = os.Remove(common.GetPidVarDir(syscall.Getpid()))
if err != nil {
this.log.Println(err)
}
}
func (this *Daemon) writePid() error {
pidFile := this.cfg.GetPidFile()
stat, err := os.Stat(pidFile)
if err == nil {
if stat.IsDir() {
return fmt.Errorf("PID file already exists and is a directory: %s", pidFile)
}
this.log.Printf("warning: PID file already exists: %s\n", pidFile)
pid, err := common.GetPid(pidFile)
if err != nil {
return err
}
if common.ProcessExists(pid) {
return fmt.Errorf("a process with PID %d already exists\n", pid)
}
}
dir := filepath.Dir(pidFile)
stat, err = os.Stat(dir)
if err == nil && !stat.IsDir() {
return fmt.Errorf("file already exists and is not a directory: %s", dir)
}
err = os.MkdirAll(dir, 0755)
if err != nil {
return err
}
return os.WriteFile(
pidFile,
[]byte(fmt.Sprintf("%d\n", syscall.Getpid())),
0655,
)
}