-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider_file_cache.go
More file actions
95 lines (75 loc) · 2.54 KB
/
Copy pathprovider_file_cache.go
File metadata and controls
95 lines (75 loc) · 2.54 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
// Pachage main
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
)
type dnsProviderFileCache struct {
LastUpdate time.Time `json:"last_update"`
Records map[string][]Record `json:"records"`
Zones []Zone `json:"zones"`
Version int `json:"version"`
}
// ============================================================================
// CACHE FILE SYSTEM
// ============================================================================
func saveDNSProviderCacheToFile(providerName, cachePath string, zones []Zone, recordCache *ZoneRecordCache) error {
if recordCache == nil {
return fmt.Errorf("%s", phrases().ErrRecordCacheNil)
}
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
return fmt.Errorf("%s: %w", phrases().ErrCacheDirCreate, err)
}
cache := dnsProviderFileCache{
Version: 1,
Zones: zones,
Records: make(map[string][]Record),
LastUpdate: time.Now(),
}
totalRecords := 0
for _, zone := range zones {
if records, exists := recordCache.Get(zone.ID); exists {
cache.Records[zone.ID] = records
totalRecords += len(records)
}
}
jsonData, err := json.MarshalIndent(cache, "", " ")
if err != nil {
return fmt.Errorf("%s: %w", phrases().ErrCacheMarshal, err)
}
if err := writeFileAtomic(cachePath, jsonData); err != nil {
return fmt.Errorf("%s: %w", phrases().ErrCacheWrite, err)
}
debugLog("CACHE", "", fmt.Sprintf(phrases().CacheSavedZones, providerName, len(zones), totalRecords))
return nil
}
func loadDNSProviderCacheFromFile(providerName, cachePath string) ([]Zone, *ZoneRecordCache, error) {
data, err := os.ReadFile(cachePath)
if err != nil {
if os.IsNotExist(err) {
debugLog("CACHE", "", fmt.Sprintf(phrases().CacheFileNotFound, providerName))
return nil, nil, nil
}
return nil, nil, fmt.Errorf("%s: %w", phrases().ErrBodyRead, err)
}
var cache dnsProviderFileCache
if err := json.Unmarshal(data, &cache); err != nil {
return nil, nil, fmt.Errorf("%s: %w", phrases().ErrCacheMarshal, err)
}
if cache.Version == 0 {
cache.Version = 1
}
if cache.Version != 1 {
return nil, nil, fmt.Errorf(phrases().ErrAPIGeneric+": unsupported version %d", cache.Version)
}
recordCache := NewZoneRecordCache()
for zoneID, records := range cache.Records {
recordCache.SetAt(zoneID, records, cache.LastUpdate)
}
age := time.Since(cache.LastUpdate)
debugLog("CACHE", "", fmt.Sprintf(phrases().CacheLoadedZones, providerName, len(cache.Zones), age.Round(time.Second)))
return cache.Zones, recordCache, nil
}