Debian Codegraph @

config/config.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package config
5
6 import (
7 "fmt"
8 "os"
9 "path/filepath"
10 "sync"
11
12 "github.com/etix/mirrorbits/core"
13 "github.com/etix/mirrorbits/utils"
14 "github.com/op/go-logging"
15 "gopkg.in/yaml.v3"
16 )
17
18 var (
19 // TEMPLATES_PATH is set at compile time
20 TEMPLATES_PATH = ""
21 )
22
23 var (
24 log = logging.MustGetLogger("main")
25 config *Configuration
26 configMutex sync.RWMutex
27
28 subscribers []chan bool
29 subscribersLock sync.RWMutex
30 )
31
32 func defaultConfig() Configuration {
33 return Configuration{
34 Repository: "",
35 Templates: TEMPLATES_PATH,
36 LocalJSPath: "",
37 OutputMode: "auto",
38 ListenAddress: ":8080",
39 Gzip: false,
40 AllowHTTPToHTTPSRedirects: true,
41 SameDownloadInterval: 600,
42 RedisAddress: "127.0.0.1:6379",
43 RedisPassword: "",
44 RedisDB: 0,
45 LogDir: "",
46 TraceFileLocation: "",
47 GeoipDatabasePath: "/var/lib/GeoIP/",
48 GeographicalSort: true,
49 ConcurrentSync: 5,
50 ScanInterval: 30,
51 CheckInterval: 1,
52 RepositoryScanInterval: 5,
53 MaxLinkHeaders: 10,
54 FixTimezoneOffsets: false,
55 Hashes: hashing{
56 SHA1: false,
57 SHA256: true,
58 MD5: false,
59 },
60 DisallowRedirects: false,
61 WeightDistributionRange: 1.5,
62 DisableOnMissingFile: false,
63 RPCListenAddress: "localhost:3390",
64 RPCPassword: "",
65 }
66 }
67
68 // Configuration contains all the option available in the yaml file
69 type Configuration struct {
70 Repository string `yaml:"Repository"`
71 Templates string `yaml:"Templates"`
72 LocalJSPath string `yaml:"LocalJSPath"`
73 OutputMode string `yaml:"OutputMode"`
74 ListenAddress string `yaml:"ListenAddress"`
75 Gzip bool `yaml:"Gzip"`
76 AllowHTTPToHTTPSRedirects bool `yaml:"AllowHTTPToHTTPSRedirects"`
77 SameDownloadInterval int `yaml:"SameDownloadInterval"`
78 RedisAddress string `yaml:"RedisAddress"`
79 RedisPassword string `yaml:"RedisPassword"`
80 RedisDB int `yaml:"RedisDB"`
81 LogDir string `yaml:"LogDir"`
82 TraceFileLocation string `yaml:"TraceFileLocation"`
83 GeoipDatabasePath string `yaml:"GeoipDatabasePath"`
84 GeographicalSort bool `yaml:"GeographicalSort"`
85 ConcurrentSync int `yaml:"ConcurrentSync"`
86 ScanInterval int `yaml:"ScanInterval"`
87 CheckInterval int `yaml:"CheckInterval"`
88 RepositoryScanInterval int `yaml:"RepositoryScanInterval"`
89 MaxLinkHeaders int `yaml:"MaxLinkHeaders"`
90 FixTimezoneOffsets bool `yaml:"FixTimezoneOffsets"`
91 Hashes hashing `yaml:"Hashes"`
92 DisallowRedirects bool `yaml:"DisallowRedirects"`
93 WeightDistributionRange float32 `yaml:"WeightDistributionRange"`
94 DisableOnMissingFile bool `yaml:"DisableOnMissingFile"`
95 AllowOutdatedFiles []OutdatedFilesConfig `yaml:"AllowOutdatedFiles"`
96 Fallbacks []Fallback `yaml:"Fallbacks"`
97
98 RedisSentinelMasterName string `yaml:"RedisSentinelMasterName"`
99 RedisSentinels []sentinels `yaml:"RedisSentinels"`
100
101 RPCListenAddress string `yaml:"RPCListenAddress"`
102 RPCPassword string `yaml:"RPCPassword"`
103 }
104
105 type Fallback struct {
106 URL string `yaml:"URL"`
107 CountryCode string `yaml:"CountryCode"`
108 ContinentCode string `yaml:"ContinentCode"`
109 }
110
111 type sentinels struct {
112 Host string `yaml:"Host"`
113 }
114
115 type hashing struct {
116 SHA1 bool `yaml:"SHA1"`
117 SHA256 bool `yaml:"SHA256"`
118 MD5 bool `yaml:"MD5"`
119 }
120
121 type OutdatedFilesConfig struct {
122 Prefix string `yaml:"Prefix"`
123 Minutes int `yaml:"Minutes"`
124 }
125
126 // LoadConfig loads the configuration file if it has not yet been loaded
127 func LoadConfig() {
128 if config != nil {
129 return
130 }
131 err := ReloadConfig()
132 if err != nil {
133 log.Fatal(err)
134 }
135 }
136
137 // ReloadConfig reloads the configuration file and update it globally
138 func ReloadConfig() error {
139 if core.ConfigFile == "" {
140 if fileExists("/etc/mirrorbits.conf") {
141 core.ConfigFile = "/etc/mirrorbits.conf"
142 }
143 }
144
145 content, err := os.ReadFile(core.ConfigFile)
146 if err != nil {
147 fmt.Println("Configuration could not be found.\n\tUse -config <path>")
148 os.Exit(1)
149 }
150
151 if os.Getenv("DEBUG") != "" {
152 fmt.Println("Reading configuration from", core.ConfigFile)
153 }
154
155 c := defaultConfig()
156
157 // Overload the default configuration with the user's one
158 err = yaml.Unmarshal(content, &c)
159 if err != nil {
160 return fmt.Errorf("%s in %s", err, core.ConfigFile)
161 }
162
163 // Sanitize
164 if c.WeightDistributionRange <= 0 {
165 return fmt.Errorf("WeightDistributionRange must be > 0")
166 }
167 if !utils.IsInSlice(c.OutputMode, []string{"auto", "json", "redirect"}) {
168 return fmt.Errorf("Config: outputMode can only be set to 'auto', 'json' or 'redirect'")
169 }
170 if c.Repository == "" {
171 return fmt.Errorf("Path to local repository not configured (see mirrorbits.conf)")
172 }
173 c.Repository, err = filepath.Abs(c.Repository)
174 if err != nil {
175 return fmt.Errorf("Invalid local repository path: %s", err)
176 }
177 if c.RepositoryScanInterval < 0 {
178 c.RepositoryScanInterval = 0
179 }
180 for i := range c.Fallbacks {
181 c.Fallbacks[i].URL = utils.NormalizeURL(c.Fallbacks[i].URL)
182 }
183 for _, rule := range c.AllowOutdatedFiles {
184 if len(rule.Prefix) > 0 && rule.Prefix[0] != '/' {
185 return fmt.Errorf("AllowOutdatedFiles.Prefix must start with '/'")
186 }
187 if rule.Minutes < 0 {
188 return fmt.Errorf("AllowOutdatedFiles.Minutes must be >= 0")
189 }
190 }
191
192 if config != nil &&
193 (c.RedisAddress != config.RedisAddress ||
194 c.RedisPassword != config.RedisPassword ||
195 !testSentinelsEq(c.RedisSentinels, config.RedisSentinels)) {
196 // TODO reload redis connections
197 // Currently established connections will be updated only in case of disconnection
198 }
199
200 // Lock the pointer during the swap
201 configMutex.Lock()
202 config = &c
203 configMutex.Unlock()
204
205 // Notify all subscribers that the configuration has been reloaded
206 notifySubscribers()
207
208 return nil
209 }
210
211 // GetConfig returns a pointer to a configuration object
212 // FIXME reading from the pointer could cause a race!
213 func GetConfig() *Configuration {
214 configMutex.RLock()
215 defer configMutex.RUnlock()
216
217 if config == nil {
218 panic("Configuration not loaded")
219 }
220
221 return config
222 }
223
224 // SetConfiguration is only used for testing purpose
225 func SetConfiguration(c *Configuration) {
226 config = c
227 }
228
229 // SubscribeConfig allows subscribers to get notified when
230 // the configuration is updated.
231 func SubscribeConfig(subscriber chan bool) {
232 subscribersLock.Lock()
233 defer subscribersLock.Unlock()
234
235 subscribers = append(subscribers, subscriber)
236 }
237
238 func notifySubscribers() {
239 subscribersLock.RLock()
240 defer subscribersLock.RUnlock()
241
242 for _, subscriber := range subscribers {
243 select {
244 case subscriber <- true:
245 default:
246 // Don't block if the subscriber is unavailable
247 // and discard the message.
248 }
249 }
250 }
251
252 func fileExists(filename string) bool {
253 _, err := os.Stat(filename)
254 return err == nil
255 }
256
257 func testSentinelsEq(a, b []sentinels) bool {
258 if len(a) != len(b) {
259 return false
260 }
261
262 for i := range a {
263 if a[i].Host != b[i].Host {
264 return false
265 }
266 }
267
268 return true
269 }