-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
121 lines (101 loc) · 2.7 KB
/
config.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
118
119
120
121
package main
import (
"encoding/json"
"flag"
"log"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
type configDuration time.Duration
func (d *configDuration) UnmarshalJSON(b []byte) error {
duration, err := time.ParseDuration(strings.Trim(string(b), " \""))
*d = configDuration(duration)
return err
}
func (d *configDuration) MarshalJSON() ([]byte, error) {
return ([]byte)("\"" + (*time.Duration)(d).String() + "\""), nil
}
type grayLogConfig struct {
Remote string `json:"remote"`
socket *net.UDPConn // udp connection
Level int `json:"level"`
AddFields map[string]interface{} `json:"addfields"`
}
// Config represents not only configuration but also current running state
type Config struct {
LogDir string `json:"logdir"`
LogPrefix string `json:"logfileprefix"`
LogSuffixDate string `json:"logsuffixdate"`
LogDate string `json:"logdate"`
LogReopen *configDuration `json:"logreopen"`
GrayLog grayLogConfig `json:"graylog"`
Tasks map[string]*Task `json:"tasks"`
Limits []configRLimit `json:"limits"`
HTTP struct {
Addr string `json:"address"`
Port int `json:"port"`
ServerCert string `json:"servercert"`
ServerKey string `json:"serverkey"`
ClientCert string `json:"clientcert"`
User string `json:"user"`
Pass string `json:"password"`
} `json:"http"`
}
var (
aConfig atomic.Pointer[Config]
configChangeLock sync.Mutex
)
var (
configfile = flag.String("config", "/etc/minisv.json",
"minisv config file in json format")
)
func readConfig() bool {
data, err := os.ReadFile(*configfile)
if nil != err {
log.Println("Error reading config file: ", err)
return false
}
var config Config
err = json.Unmarshal(data, &config)
if nil != err {
log.Println("Error parsing config file: ", err)
return false
}
for name, task := range config.Tasks {
task.name = name
}
if config.GrayLog.Remote != "" {
addr, err := net.ResolveUDPAddr("udp", config.GrayLog.Remote)
if err != nil {
log.Println("invalid graylog remote: ", err)
} else {
config.GrayLog.socket, err = net.DialUDP("udp", nil, addr)
if err != nil {
log.Println("unable to create UDP socket for graylog: ", err)
}
}
}
aConfig.Store(&config)
return true
}
var (
saveMutex sync.Mutex
)
func saveConfig() {
saveMutex.Lock()
defer saveMutex.Unlock()
data, err := json.MarshalIndent(aConfig.Load(), "", " ")
if nil != err {
log.Println("Error json encoding config for save:", err)
return
}
err = os.WriteFile(*configfile, data, 0644)
if nil != err {
log.Println("Error on config save:", err)
return
}
}