forked from openark/orchestrator
/
resolve.go
276 lines (244 loc) · 8.97 KB
/
resolve.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
Copyright 2014 Outbrain Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package inst
import (
"errors"
"fmt"
"github.com/github/orchestrator/go/config"
"github.com/openark/golib/log"
"github.com/patrickmn/go-cache"
"net"
"regexp"
"strings"
"sync"
"time"
)
type HostnameResolve struct {
hostname string
resolvedHostname string
}
func (this HostnameResolve) String() string {
return fmt.Sprintf("%s %s", this.hostname, this.resolvedHostname)
}
type HostnameUnresolve struct {
hostname string
unresolvedHostname string
}
func (this HostnameUnresolve) String() string {
return fmt.Sprintf("%s %s", this.hostname, this.unresolvedHostname)
}
type HostnameRegistration struct {
CreatedAt time.Time
Key InstanceKey
Hostname string
}
func NewHostnameRegistration(instanceKey *InstanceKey, hostname string) *HostnameRegistration {
return &HostnameRegistration{
CreatedAt: time.Now(),
Key: *instanceKey,
Hostname: hostname,
}
}
func NewHostnameDeregistration(instanceKey *InstanceKey) *HostnameRegistration {
return &HostnameRegistration{
CreatedAt: time.Now(),
Key: *instanceKey,
Hostname: "",
}
}
var hostnameResolvesLightweightCache *cache.Cache
var hostnameResolvesLightweightCacheInit = &sync.Mutex{}
var hostnameResolvesLightweightCacheLoadedOnceFromDB bool = false
func init() {
if config.Config.ExpiryHostnameResolvesMinutes < 1 {
config.Config.ExpiryHostnameResolvesMinutes = 1
}
}
func getHostnameResolvesLightweightCache() *cache.Cache {
hostnameResolvesLightweightCacheInit.Lock()
defer hostnameResolvesLightweightCacheInit.Unlock()
if hostnameResolvesLightweightCache == nil {
hostnameResolvesLightweightCache = cache.New(time.Duration(config.Config.ExpiryHostnameResolvesMinutes)*time.Minute, time.Minute)
}
return hostnameResolvesLightweightCache
}
func HostnameResolveMethodIsNone() bool {
return strings.ToLower(config.Config.HostnameResolveMethod) == "none"
}
// GetCNAME resolves an IP or hostname into a normalized valid CNAME
func GetCNAME(hostname string) (string, error) {
res, err := net.LookupCNAME(hostname)
if err != nil {
return hostname, err
}
res = strings.TrimRight(res, ".")
return res, nil
}
func resolveHostname(hostname string) (string, error) {
switch strings.ToLower(config.Config.HostnameResolveMethod) {
case "none":
return hostname, nil
case "default":
return hostname, nil
case "cname":
return GetCNAME(hostname)
}
return hostname, nil
}
// Attempt to resolve a hostname. This may return a database cached hostname or otherwise
// it may resolve the hostname via CNAME
func ResolveHostname(hostname string) (string, error) {
hostname = strings.TrimSpace(hostname)
if hostname == "" {
return hostname, errors.New("Will not resolve empty hostname")
}
if strings.Contains(hostname, ",") {
return hostname, fmt.Errorf("Will not resolve multi-hostname: %+v", hostname)
}
if (&InstanceKey{Hostname: hostname}).IsDetached() {
// quietly abort. Nothing to do. The hostname is detached for a reason: it
// will not be resolved, for sure.
return hostname, nil
}
// First go to lightweight cache
if resolvedHostname, found := getHostnameResolvesLightweightCache().Get(hostname); found {
return resolvedHostname.(string), nil
}
if !hostnameResolvesLightweightCacheLoadedOnceFromDB {
// A continuous-discovery will first make sure to load all resolves from DB.
// However cli does not do so.
// Anyway, it seems like the cache was not loaded from DB. Before doing real resolves,
// let's try and get the resolved hostname from database.
if !HostnameResolveMethodIsNone() {
go func() {
if resolvedHostname, err := ReadResolvedHostname(hostname); err == nil && resolvedHostname != "" {
getHostnameResolvesLightweightCache().Set(hostname, resolvedHostname, 0)
}
}()
}
}
// Unfound: resolve!
log.Debugf("Hostname unresolved yet: %s", hostname)
resolvedHostname, err := resolveHostname(hostname)
if config.Config.RejectHostnameResolvePattern != "" {
// Reject, don't even cache
if matched, _ := regexp.MatchString(config.Config.RejectHostnameResolvePattern, resolvedHostname); matched {
log.Warningf("ResolveHostname: %+v resolved to %+v but rejected due to RejectHostnameResolvePattern '%+v'", hostname, resolvedHostname, config.Config.RejectHostnameResolvePattern)
return hostname, nil
}
}
if err != nil {
// Problem. What we'll do is cache the hostname for just one minute, so as to avoid flooding requests
// on one hand, yet make it refresh shortly on the other hand. Anyway do not write to database.
getHostnameResolvesLightweightCache().Set(hostname, resolvedHostname, time.Minute)
return hostname, err
}
// Good result! Cache it, also to DB
log.Debugf("Cache hostname resolve %s as %s", hostname, resolvedHostname)
go UpdateResolvedHostname(hostname, resolvedHostname)
return resolvedHostname, nil
}
// UpdateResolvedHostname will store the given resolved hostname in cache
// Returns false when the key already existed with same resolved value (similar
// to AFFECTED_ROWS() in mysql)
func UpdateResolvedHostname(hostname string, resolvedHostname string) bool {
if resolvedHostname == "" {
return false
}
if existingResolvedHostname, found := getHostnameResolvesLightweightCache().Get(hostname); found && (existingResolvedHostname == resolvedHostname) {
return false
}
getHostnameResolvesLightweightCache().Set(hostname, resolvedHostname, 0)
if !HostnameResolveMethodIsNone() {
WriteResolvedHostname(hostname, resolvedHostname)
}
return true
}
func LoadHostnameResolveCache() error {
if !HostnameResolveMethodIsNone() {
return loadHostnameResolveCacheFromDatabase()
}
return nil
}
func loadHostnameResolveCacheFromDatabase() error {
allHostnamesResolves, err := ReadAllHostnameResolves()
if err != nil {
return err
}
for _, hostnameResolve := range allHostnamesResolves {
getHostnameResolvesLightweightCache().Set(hostnameResolve.hostname, hostnameResolve.resolvedHostname, 0)
}
hostnameResolvesLightweightCacheLoadedOnceFromDB = true
return nil
}
func FlushNontrivialResolveCacheToDatabase() error {
if !HostnameResolveMethodIsNone() {
return log.Errorf("FlushNontrivialResolveCacheToDatabase() called, but HostnameResolveMethod is %+v", config.Config.HostnameResolveMethod)
}
items, _ := HostnameResolveCache()
for hostname := range items {
resolvedHostname, found := getHostnameResolvesLightweightCache().Get(hostname)
if found && (resolvedHostname.(string) != hostname) {
WriteResolvedHostname(hostname, resolvedHostname.(string))
}
}
return nil
}
func ResetHostnameResolveCache() error {
err := deleteHostnameResolves()
getHostnameResolvesLightweightCache().Flush()
hostnameResolvesLightweightCacheLoadedOnceFromDB = false
return err
}
func HostnameResolveCache() (map[string]cache.Item, error) {
return getHostnameResolvesLightweightCache().Items(), nil
}
func UnresolveHostname(instanceKey *InstanceKey) (InstanceKey, bool, error) {
if *config.RuntimeCLIFlags.SkipUnresolve {
return *instanceKey, false, nil
}
unresolvedHostname, err := readUnresolvedHostname(instanceKey.Hostname)
if err != nil {
return *instanceKey, false, log.Errore(err)
}
if unresolvedHostname == instanceKey.Hostname {
// unchanged. Nothing to do
return *instanceKey, false, nil
}
// We unresovled to a different hostname. We will now re-resolve to double-check!
unresolvedKey := &InstanceKey{Hostname: unresolvedHostname, Port: instanceKey.Port}
instance, err := ReadTopologyInstance(unresolvedKey)
if err != nil {
return *instanceKey, false, log.Errore(err)
}
if instance.IsBinlogServer() && config.Config.SkipBinlogServerUnresolveCheck {
// Do nothing. Everything is assumed to be fine.
} else if instance.Key.Hostname != instanceKey.Hostname {
// Resolve(Unresolve(hostname)) != hostname ==> Bad; reject
if *config.RuntimeCLIFlags.SkipUnresolveCheck {
return *instanceKey, false, nil
}
return *instanceKey, false, log.Errorf("Error unresolving; hostname=%s, unresolved=%s, re-resolved=%s; mismatch. Skip/ignore with --skip-unresolve-check", instanceKey.Hostname, unresolvedKey.Hostname, instance.Key.Hostname)
}
return *unresolvedKey, true, nil
}
func RegisterHostnameUnresolve(registration *HostnameRegistration) (err error) {
if registration.Hostname == "" {
return DeleteHostnameUnresolve(®istration.Key)
}
if registration.CreatedAt.Add(time.Duration(config.Config.ExpiryHostnameResolvesMinutes) * time.Minute).Before(time.Now()) {
// already expired.
return nil
}
return WriteHostnameUnresolve(®istration.Key, registration.Hostname)
}