-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
orchestrator.go
445 lines (396 loc) · 13.7 KB
/
orchestrator.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
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 logic
import (
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/patrickmn/go-cache"
"github.com/rcrowley/go-metrics"
"github.com/sjmudd/stopwatch"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/vtorc/collection"
"vitess.io/vitess/go/vt/vtorc/config"
"vitess.io/vitess/go/vt/vtorc/discovery"
"vitess.io/vitess/go/vt/vtorc/inst"
ometrics "vitess.io/vitess/go/vt/vtorc/metrics"
"vitess.io/vitess/go/vt/vtorc/process"
"vitess.io/vitess/go/vt/vtorc/util"
)
const (
discoveryMetricsName = "DISCOVERY_METRICS"
)
// discoveryQueue is a channel of deduplicated instanceKey-s
// that were requested for discovery. It can be continuously updated
// as discovery process progresses.
var discoveryQueue *discovery.Queue
var snapshotDiscoveryKeys chan inst.InstanceKey
var snapshotDiscoveryKeysMutex sync.Mutex
var hasReceivedSIGTERM int32
var discoveriesCounter = metrics.NewCounter()
var failedDiscoveriesCounter = metrics.NewCounter()
var instancePollSecondsExceededCounter = metrics.NewCounter()
var discoveryQueueLengthGauge = metrics.NewGauge()
var discoveryRecentCountGauge = metrics.NewGauge()
var isElectedGauge = metrics.NewGauge()
var isHealthyGauge = metrics.NewGauge()
var discoveryMetrics = collection.CreateOrReturnCollection(discoveryMetricsName)
var isElectedNode int64
var recentDiscoveryOperationKeys *cache.Cache
func init() {
snapshotDiscoveryKeys = make(chan inst.InstanceKey, 10)
_ = metrics.Register("discoveries.attempt", discoveriesCounter)
_ = metrics.Register("discoveries.fail", failedDiscoveriesCounter)
_ = metrics.Register("discoveries.instance_poll_seconds_exceeded", instancePollSecondsExceededCounter)
_ = metrics.Register("discoveries.queue_length", discoveryQueueLengthGauge)
_ = metrics.Register("discoveries.recent_count", discoveryRecentCountGauge)
_ = metrics.Register("elect.is_elected", isElectedGauge)
_ = metrics.Register("health.is_healthy", isHealthyGauge)
ometrics.OnMetricsTick(func() {
discoveryQueueLengthGauge.Update(int64(discoveryQueue.QueueLen()))
})
ometrics.OnMetricsTick(func() {
if recentDiscoveryOperationKeys == nil {
return
}
discoveryRecentCountGauge.Update(int64(recentDiscoveryOperationKeys.ItemCount()))
})
ometrics.OnMetricsTick(func() {
isElectedGauge.Update(atomic.LoadInt64(&isElectedNode))
})
ometrics.OnMetricsTick(func() {
isHealthyGauge.Update(atomic.LoadInt64(&process.LastContinousCheckHealthy))
})
}
func IsLeader() bool {
return atomic.LoadInt64(&isElectedNode) == 1
}
func IsLeaderOrActive() bool {
return atomic.LoadInt64(&isElectedNode) == 1
}
// used in several places
func instancePollSecondsDuration() time.Duration {
return time.Duration(config.Config.InstancePollSeconds) * time.Second
}
// acceptSighupSignal registers for SIGHUP signal from the OS to reload the configuration files.
func acceptSighupSignal() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
for range c {
log.Infof("Received SIGHUP. Reloading configuration")
_ = inst.AuditOperation("reload-configuration", nil, "Triggered via SIGHUP")
config.Reload()
discoveryMetrics.SetExpirePeriod(time.Duration(config.DiscoveryCollectionRetentionSeconds) * time.Second)
}
}()
}
// closeVTOrc runs all the operations required to cleanly shutdown VTOrc
func closeVTOrc() {
log.Infof("Starting VTOrc shutdown")
atomic.StoreInt32(&hasReceivedSIGTERM, 1)
discoveryMetrics.StopAutoExpiration()
// Poke other go routines to stop cleanly here ...
_ = inst.AuditOperation("shutdown", nil, "Triggered via SIGTERM")
// wait for the locks to be released
waitForLocksRelease()
log.Infof("VTOrc closed")
}
// waitForLocksRelease is used to wait for release of locks
func waitForLocksRelease() {
timeout := time.After(shutdownWaitTime)
for {
count := atomic.LoadInt32(&shardsLockCounter)
if count == 0 {
break
}
select {
case <-timeout:
log.Infof("wait for lock release timed out. Some locks might not have been released.")
default:
time.Sleep(50 * time.Millisecond)
continue
}
break
}
}
// handleDiscoveryRequests iterates the discoveryQueue channel and calls upon
// instance discovery per entry.
func handleDiscoveryRequests() {
discoveryQueue = discovery.CreateOrReturnQueue("DEFAULT")
// create a pool of discovery workers
for i := uint(0); i < config.DiscoveryMaxConcurrency; i++ {
go func() {
for {
instanceKey := discoveryQueue.Consume()
// Possibly this used to be the elected node, but has
// been demoted, while still the queue is full.
if !IsLeaderOrActive() {
log.Infof("Node apparently demoted. Skipping discovery of %+v. "+
"Remaining queue size: %+v", instanceKey, discoveryQueue.QueueLen())
discoveryQueue.Release(instanceKey)
continue
}
DiscoverInstance(instanceKey, false /* forceDiscovery */)
discoveryQueue.Release(instanceKey)
}
}()
}
}
// DiscoverInstance will attempt to discover (poll) an instance (unless
// it is already up to date) and will also ensure that its primary and
// replicas (if any) are also checked.
func DiscoverInstance(instanceKey inst.InstanceKey, forceDiscovery bool) {
if inst.InstanceIsForgotten(&instanceKey) {
log.Infof("discoverInstance: skipping discovery of %+v because it is set to be forgotten", instanceKey)
return
}
// create stopwatch entries
latency := stopwatch.NewNamedStopwatch()
_ = latency.AddMany([]string{
"backend",
"instance",
"total"})
latency.Start("total") // start the total stopwatch (not changed anywhere else)
defer func() {
latency.Stop("total")
discoveryTime := latency.Elapsed("total")
if discoveryTime > instancePollSecondsDuration() {
instancePollSecondsExceededCounter.Inc(1)
log.Warningf("discoverInstance exceeded InstancePollSeconds for %+v, took %.4fs", instanceKey, discoveryTime.Seconds())
}
}()
_, _ = instanceKey.ResolveHostname()
if !instanceKey.IsValid() {
return
}
// Calculate the expiry period each time as InstancePollSeconds
// _may_ change during the run of the process (via SIGHUP) and
// it is not possible to change the cache's default expiry..
if existsInCacheError := recentDiscoveryOperationKeys.Add(instanceKey.DisplayString(), true, instancePollSecondsDuration()); existsInCacheError != nil && !forceDiscovery {
// Just recently attempted
return
}
latency.Start("backend")
instance, found, _ := inst.ReadInstance(&instanceKey)
latency.Stop("backend")
if !forceDiscovery && found && instance.IsUpToDate && instance.IsLastCheckValid {
// we've already discovered this one. Skip!
return
}
discoveriesCounter.Inc(1)
// First we've ever heard of this instance. Continue investigation:
instance, err := inst.ReadTopologyInstanceBufferable(&instanceKey, latency)
// panic can occur (IO stuff). Therefore it may happen
// that instance is nil. Check it, but first get the timing metrics.
totalLatency := latency.Elapsed("total")
backendLatency := latency.Elapsed("backend")
instanceLatency := latency.Elapsed("instance")
if forceDiscovery {
log.Infof("Force discovered - %+v, err - %v", instance, err)
}
if instance == nil {
failedDiscoveriesCounter.Inc(1)
_ = discoveryMetrics.Append(&discovery.Metric{
Timestamp: time.Now(),
InstanceKey: instanceKey,
TotalLatency: totalLatency,
BackendLatency: backendLatency,
InstanceLatency: instanceLatency,
Err: err,
})
if util.ClearToLog("discoverInstance", instanceKey.StringCode()) {
log.Warningf(" DiscoverInstance(%+v) instance is nil in %.3fs (Backend: %.3fs, Instance: %.3fs), error=%+v",
instanceKey,
totalLatency.Seconds(),
backendLatency.Seconds(),
instanceLatency.Seconds(),
err)
}
return
}
_ = discoveryMetrics.Append(&discovery.Metric{
Timestamp: time.Now(),
InstanceKey: instanceKey,
TotalLatency: totalLatency,
BackendLatency: backendLatency,
InstanceLatency: instanceLatency,
Err: nil,
})
}
// onHealthTick handles the actions to take to discover/poll instances
func onHealthTick() {
wasAlreadyElected := IsLeader()
{
myIsElectedNode, err := process.AttemptElection()
if err != nil {
log.Error(err)
}
if myIsElectedNode {
atomic.StoreInt64(&isElectedNode, 1)
} else {
atomic.StoreInt64(&isElectedNode, 0)
}
if !myIsElectedNode {
if electedNode, _, err := process.ElectedNode(); err == nil {
log.Infof("Not elected as active node; active node: %v; polling", electedNode.Hostname)
} else {
log.Infof("Not elected as active node; active node: Unable to determine: %v; polling", err)
}
}
}
if !IsLeaderOrActive() {
return
}
instanceKeys, err := inst.ReadOutdatedInstanceKeys()
if err != nil {
log.Error(err)
}
if !wasAlreadyElected {
// Just turned to be leader!
go func() {
_, _ = process.RegisterNode(process.ThisNodeHealth)
}()
go func() {
_ = inst.ExpireMaintenance()
}()
}
func() {
// Normally onHealthTick() shouldn't run concurrently. It is kicked by a ticker.
// However it _is_ invoked inside a goroutine. I like to be safe here.
snapshotDiscoveryKeysMutex.Lock()
defer snapshotDiscoveryKeysMutex.Unlock()
countSnapshotKeys := len(snapshotDiscoveryKeys)
for i := 0; i < countSnapshotKeys; i++ {
instanceKeys = append(instanceKeys, <-snapshotDiscoveryKeys)
}
}()
// avoid any logging unless there's something to be done
if len(instanceKeys) > 0 {
for _, instanceKey := range instanceKeys {
if instanceKey.IsValid() {
discoveryQueue.Push(instanceKey)
}
}
}
}
// ContinuousDiscovery starts an asynchronuous infinite discovery process where instances are
// periodically investigated and their status captured, and long since unseen instances are
// purged and forgotten.
// nolint SA1015: using time.Tick leaks the underlying ticker
func ContinuousDiscovery() {
log.Infof("continuous discovery: setting up")
continuousDiscoveryStartTime := time.Now()
checkAndRecoverWaitPeriod := 3 * instancePollSecondsDuration()
recentDiscoveryOperationKeys = cache.New(instancePollSecondsDuration(), time.Second)
_ = inst.LoadHostnameResolveCache()
go handleDiscoveryRequests()
healthTick := time.Tick(config.HealthPollSeconds * time.Second)
instancePollTick := time.Tick(instancePollSecondsDuration())
caretakingTick := time.Tick(time.Minute)
recoveryTick := time.Tick(time.Duration(config.Config.RecoveryPollSeconds) * time.Second)
tabletTopoTick := OpenTabletDiscovery()
var recoveryEntrance int64
var snapshotTopologiesTick <-chan time.Time
if config.Config.SnapshotTopologiesIntervalHours > 0 {
snapshotTopologiesTick = time.Tick(time.Duration(config.Config.SnapshotTopologiesIntervalHours) * time.Hour)
}
runCheckAndRecoverOperationsTimeRipe := func() bool {
return time.Since(continuousDiscoveryStartTime) >= checkAndRecoverWaitPeriod
}
go func() {
_ = ometrics.InitMetrics()
}()
go acceptSighupSignal()
// On termination of the server, we should close VTOrc cleanly
servenv.OnTermSync(closeVTOrc)
log.Infof("continuous discovery: starting")
for {
select {
case <-healthTick:
go func() {
onHealthTick()
}()
case <-instancePollTick:
go func() {
// This tick does NOT do instance poll (these are handled by the oversampling discoveryTick)
// But rather should invoke such routinely operations that need to be as (or roughly as) frequent
// as instance poll
if IsLeaderOrActive() {
go inst.ExpireDowntime()
}
}()
case <-caretakingTick:
// Various periodic internal maintenance tasks
go func() {
if IsLeaderOrActive() {
go inst.ForgetLongUnseenInstances()
go inst.ForgetUnseenInstancesDifferentlyResolved()
go inst.ForgetExpiredHostnameResolves()
go inst.DeleteInvalidHostnameResolves()
go inst.ResolveUnknownPrimaryHostnameResolves()
go inst.ExpireMaintenance()
go inst.ExpireCandidateInstances()
go inst.ExpireHostnameUnresolve()
go inst.ExpireAudit()
go inst.FlushNontrivialResolveCacheToDatabase()
go inst.ExpireStaleInstanceBinlogCoordinates()
go process.ExpireNodesHistory()
go process.ExpireAvailableNodes()
go ExpireFailureDetectionHistory()
go ExpireTopologyRecoveryHistory()
go ExpireTopologyRecoveryStepsHistory()
} else {
// Take this opportunity to refresh yourself
go inst.LoadHostnameResolveCache()
}
}()
case <-recoveryTick:
go func() {
if IsLeaderOrActive() {
go ClearActiveFailureDetections()
go ClearActiveRecoveries()
go ExpireBlockedRecoveries()
go AcknowledgeCrashedRecoveries()
go inst.ExpireInstanceAnalysisChangelog()
go func() {
// This function is non re-entrant (it can only be running once at any point in time)
if atomic.CompareAndSwapInt64(&recoveryEntrance, 0, 1) {
defer atomic.StoreInt64(&recoveryEntrance, 0)
} else {
return
}
if runCheckAndRecoverOperationsTimeRipe() {
CheckAndRecover(nil, nil, false)
} else {
log.Infof("Waiting for %+v seconds to pass before running failure detection/recovery", checkAndRecoverWaitPeriod.Seconds())
}
}()
}
}()
case <-snapshotTopologiesTick:
go func() {
if IsLeaderOrActive() {
go inst.SnapshotTopologies()
}
}()
case <-tabletTopoTick:
go RefreshAllKeyspaces()
go refreshAllTablets()
}
}
}