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
|
package notifier
import (
"context"
"fmt"
"os"
"codeberg.org/snonux/gorum/internal/config"
)
type Notifier struct{}
func New() Notifier {
return Notifier{}
}
func (notifier Notifier) Start(ctx context.Context, conf config.Config, scoreCh <-chan string) {
go func() {
for scoresStr := range scoreCh {
if err := notifier.persist(conf, scoresStr); err != nil {
emailNotifyError(conf, err)
}
}
}()
}
func (notifier Notifier) persist(conf config.Config, scoresStr string) error {
if err := emailNotify(conf, "GORUM: Quorum changed", scoresStr); err != nil {
return err
}
if _, err := os.Stat(conf.StateDir); os.IsNotExist(err) {
if err := os.MkdirAll(conf.StateDir, 0755); err != nil {
return err
}
}
return writeFileViaTmp(fmt.Sprintf("%s/%s", conf.StateDir, conf.ScoreFile), scoresStr)
}
// Create tmp file first, and then, once written, rename it.
func writeFileViaTmp(filePath, content string) error {
tmpFilePath := fmt.Sprintf("%s.tmp", filePath)
fd, err := os.Create(tmpFilePath)
if err != nil {
return err
}
defer fd.Close()
if _, err := fd.WriteString(content); err != nil {
return err
}
if err := fd.Sync(); err != nil {
return err
}
return os.Rename(tmpFilePath, filePath)
}
|