2020-08-25 19:38:50 -04:00
|
|
|
package storage
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
|
|
|
|
)
|
|
|
|
|
|
2022-05-27 00:59:47 +00:00
|
|
|
func countServers(allServers models.AllServers) (count int) {
|
|
|
|
|
for _, servers := range allServers.ProviderToServers {
|
|
|
|
|
count += len(servers.Servers)
|
|
|
|
|
}
|
|
|
|
|
return count
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|
|
|
|
|
|
2022-05-28 22:51:19 +00:00
|
|
|
// syncServers merges the hardcoded servers with the ones from the file.
|
|
|
|
|
func (s *Storage) syncServers() (err error) {
|
2022-05-28 22:36:16 +00:00
|
|
|
hardcodedVersions := make(map[string]uint16, len(s.hardcodedServers.ProviderToServers))
|
|
|
|
|
for provider, servers := range s.hardcodedServers.ProviderToServers {
|
|
|
|
|
hardcodedVersions[provider] = servers.Version
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
serversOnFile, err := s.readFromFile(s.filepath, hardcodedVersions)
|
2020-12-29 17:49:38 +00:00
|
|
|
if err != nil {
|
2023-04-01 16:53:04 +00:00
|
|
|
return fmt.Errorf("reading servers from file: %w", err)
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|
|
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
hardcodedCount := countServers(s.hardcodedServers)
|
2020-12-29 17:49:38 +00:00
|
|
|
countOnFile := countServers(serversOnFile)
|
|
|
|
|
|
2022-06-05 14:58:46 +00:00
|
|
|
s.mergedMutex.Lock()
|
|
|
|
|
defer s.mergedMutex.Unlock()
|
|
|
|
|
|
2020-12-29 17:49:38 +00:00
|
|
|
if countOnFile == 0 {
|
2021-08-27 19:10:03 +00:00
|
|
|
s.logger.Info(fmt.Sprintf(
|
|
|
|
|
"creating %s with %d hardcoded servers",
|
|
|
|
|
s.filepath, hardcodedCount))
|
|
|
|
|
s.mergedServers = s.hardcodedServers
|
2020-12-29 17:49:38 +00:00
|
|
|
} else {
|
2021-08-27 19:10:03 +00:00
|
|
|
s.logger.Info(fmt.Sprintf(
|
|
|
|
|
"merging by most recent %d hardcoded servers and %d servers read from %s",
|
|
|
|
|
hardcodedCount, countOnFile, s.filepath))
|
2020-12-29 17:49:38 +00:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
s.mergedServers = s.mergeServers(s.hardcodedServers, serversOnFile)
|
2020-12-29 17:49:38 +00:00
|
|
|
}
|
2020-08-25 19:38:50 -04:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
// Eventually write file
|
2025-11-17 15:29:41 +00:00
|
|
|
if reflect.DeepEqual(serversOnFile, s.mergedServers) {
|
2021-08-27 19:10:03 +00:00
|
|
|
return nil
|
2021-05-06 21:10:28 +00:00
|
|
|
}
|
|
|
|
|
|
2022-06-05 14:58:46 +00:00
|
|
|
err = s.flushToFile(s.filepath)
|
|
|
|
|
if err != nil {
|
2025-11-17 19:04:13 +00:00
|
|
|
s.logger.Warn("failed writing servers to file: " + err.Error())
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
2021-08-27 19:10:03 +00:00
|
|
|
return nil
|
2020-08-25 19:38:50 -04:00
|
|
|
}
|