-
Notifications
You must be signed in to change notification settings - Fork 6
/
state.go
188 lines (149 loc) · 4.5 KB
/
state.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package caddy_geoip
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/maxmind/geoipupdate/v4/pkg/geoipupdate"
"github.com/maxmind/geoipupdate/v4/pkg/geoipupdate/database"
"github.com/oschwald/maxminddb-golang"
"go.uber.org/zap"
)
type state struct {
mu sync.Mutex
dbInst *maxminddb.Reader
done chan bool
dbPath string
config *geoipupdate.Config
logger *zap.Logger
}
func (state *state) Provision(m *GeoIP) error {
state.done = make(chan bool, 1)
state.dbPath = m.DbPath
// start the reload or the refresh timer
if m.AccountID > 0 && m.APIKey != "" && m.DownloadFrequency > 0 {
state.logger.Info("starting download ticker", zap.Duration("frequency", time.Duration(m.DownloadFrequency)))
directoryPath, filename := filepath.Split(state.dbPath)
edition := strings.Replace(filename, ".mmdb", "", 1)
state.config = &geoipupdate.Config{
AccountID: m.AccountID,
DatabaseDirectory: directoryPath,
LicenseKey: m.APIKey,
LockFile: filepath.Join(directoryPath, ".geoipupdate.lock"),
URL: "https://updates.maxmind.com",
EditionIDs: []string{edition},
Proxy: nil,
PreserveFileTimes: true,
Verbose: true,
RetryFor: 5 * time.Minute,
}
// download the database
go func() {
ticker := time.NewTicker(time.Duration(m.DownloadFrequency))
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := state.downloadDatabase()
if err != nil {
state.logger.Error("downloading database failed", zap.Error(err))
}
case <-state.done:
state.logger.Info("downloading stopped")
return
}
}
}()
return state.downloadDatabase()
} else if m.ReloadFrequency > 0 {
// start the reload frequency
state.logger.Info("starting reload ticker", zap.Duration("frequency", time.Duration(m.ReloadFrequency)))
go func() {
ticker := time.NewTicker(time.Duration(m.ReloadFrequency))
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := state.reloadDatabase()
if err != nil {
state.logger.Error("reload database failed", zap.Error(err))
}
case <-state.done:
state.logger.Info("reloading stopped")
return
}
}
}()
}
// assume the database is local
err := state.reloadDatabase()
if err != nil {
return fmt.Errorf("cannot open database file %s: %v", m.DbPath, err)
}
return nil
}
func (state *state) reloadDatabase() error {
state.logger.Info("reloading database")
state.mu.Lock()
defer state.mu.Unlock()
if _, err := os.Stat(state.dbPath); errors.Is(err, os.ErrNotExist) {
state.logger.Warn("database does not exist", zap.String("dbpath", state.dbPath))
return nil
}
newInstance, err := maxminddb.Open(state.dbPath)
if err != nil {
return err
}
// keep a reference to the old instance
oldInstance := state.dbInst
state.dbInst = newInstance
if oldInstance != nil {
state.logger.Info("closing old database")
return oldInstance.Close()
}
state.logger.Info("reload successful",
zap.Uint("epoch", state.dbInst.Metadata.BuildEpoch),
zap.Uint("major", state.dbInst.Metadata.BinaryFormatMajorVersion),
zap.Uint("minor", state.dbInst.Metadata.BinaryFormatMinorVersion))
return nil
}
func (state *state) downloadDatabase() error {
edition := state.config.EditionIDs[0]
state.logger.Info("starting download", zap.String("edition", edition))
client := geoipupdate.NewClient(state.config)
dbReader := database.NewHTTPDatabaseReader(client, state.config)
dbWriter, err := database.NewLocalFileDatabaseWriter(state.dbPath, state.config.LockFile, state.config.Verbose)
if err != nil {
state.logger.Error("creating maxmind db writer", zap.Error(err))
}
if err := dbReader.Get(dbWriter, edition); err != nil {
state.logger.Error("getting database", zap.Error(err))
}
state.logger.Info("finished download", zap.String("edition", edition))
return state.reloadDatabase()
}
func (state *state) logStatus() {
if state.dbInst == nil {
state.logger.Info("no geo database available")
} else {
state.logger.Debug("geo database available",
zap.Uint("epoch", state.dbInst.Metadata.BuildEpoch),
zap.Uint("major", state.dbInst.Metadata.BinaryFormatMajorVersion),
zap.Uint("minor", state.dbInst.Metadata.BinaryFormatMinorVersion))
}
}
func (state *state) Destruct() error {
state.mu.Lock()
defer state.mu.Unlock()
// stop all background tasks
if state.done != nil {
close(state.done)
}
if state.dbInst != nil {
return state.dbInst.Close()
}
return nil
}