-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathmediator.go
227 lines (200 loc) · 6.87 KB
/
mediator.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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package storage
import (
"errors"
"sync"
"time"
"github.com/m3db/m3/src/dbnode/clock"
"github.com/m3db/m3/src/dbnode/persist/fs/commitlog"
"github.com/uber-go/tally"
)
type mediatorState int
const (
fileOpCheckInterval = time.Second
tickCheckInterval = 5 * time.Second
mediatorNotOpen mediatorState = iota
mediatorOpen
mediatorClosed
)
var (
errMediatorAlreadyOpen = errors.New("mediator is already open")
errMediatorNotOpen = errors.New("mediator is not open")
errMediatorAlreadyClosed = errors.New("mediator is already closed")
)
type mediatorMetrics struct {
bootstrapStatus tally.Gauge
cleanupStatus tally.Gauge
flushStatus tally.Gauge
repairStatus tally.Gauge
}
func newMediatorMetrics(scope tally.Scope) mediatorMetrics {
return mediatorMetrics{
bootstrapStatus: scope.Gauge("bootstrapped"),
cleanupStatus: scope.Gauge("cleanup"),
flushStatus: scope.Gauge("flush"),
repairStatus: scope.Gauge("repair"),
}
}
type mediator struct {
sync.RWMutex
database database
databaseBootstrapManager
databaseFileSystemManager
databaseTickManager
databaseRepairer
opts Options
nowFn clock.NowFn
sleepFn sleepFn
metrics mediatorMetrics
state mediatorState
closedCh chan struct{}
}
func newMediator(database database, commitlog commitlog.CommitLog, opts Options) (databaseMediator, error) {
scope := opts.InstrumentOptions().MetricsScope()
d := &mediator{
database: database,
opts: opts,
nowFn: opts.ClockOptions().NowFn(),
sleepFn: time.Sleep,
metrics: newMediatorMetrics(scope),
state: mediatorNotOpen,
closedCh: make(chan struct{}),
}
fsm := newFileSystemManager(database, commitlog, opts)
d.databaseFileSystemManager = fsm
d.databaseRepairer = newNoopDatabaseRepairer()
if opts.RepairEnabled() {
var err error
d.databaseRepairer, err = newDatabaseRepairer(database, opts)
if err != nil {
return nil, err
}
}
d.databaseTickManager = newTickManager(database, opts)
d.databaseBootstrapManager = newBootstrapManager(database, d, opts)
return d, nil
}
func (m *mediator) Open() error {
m.Lock()
defer m.Unlock()
if m.state != mediatorNotOpen {
return errMediatorAlreadyOpen
}
m.state = mediatorOpen
go m.reportLoop()
go m.ongoingTick()
m.databaseRepairer.Start()
return nil
}
func (m *mediator) DisableFileOps() {
status := m.databaseFileSystemManager.Disable()
for status == fileOpInProgress {
m.sleepFn(fileOpCheckInterval)
status = m.databaseFileSystemManager.Status()
}
}
func (m *mediator) EnableFileOps() {
m.databaseFileSystemManager.Enable()
}
// Tick mediates the relationship between ticks and flushes/snapshots/cleanups.
//
// For example, the requirements to perform a flush are:
// 1) currentTime > blockStart.Add(blockSize).Add(bufferPast)
// 2) node is not bootstrapping (technically shard is not bootstrapping)
// 3) at least one complete tick has occurred since blockStart.Add(blockSize).Add(bufferPast)
// 4) at least one complete tick has occurred since bootstrap completed (can be the same tick
// that satisfies condition #3)
//
// The mediator helps ensure conditions #3 and #4 are met by measuring the tickStart time and the shard bootstrap
// states *before* the tick, and then propagating those values to downstream components so they can use that
// information to make decisions about whether to flush / snapshot / run cleanups.
//
// Measuring the tickStart before the tick and propagating that also helps the tick and flush logic to coordinate.
// For example, there is logic in the Tick flow for removing shard flush states from a map so that it doesn't
// grow infinitely for nodes that are not restarted. If the Tick path measured the current time when it made that
// decision instead of using the same measurement that is shared with the flush logic, it might end up removing
// a shard flush state (due to it expiring), but since the flush logic is using a slightly more stale timestamp it
// will think that the old block hasn't been flushed (even thought it has) and try to flush it even though the data
// is potentially still on disk (if it hasn't been cleaned up yet).
func (m *mediator) Tick(runType runType, forceType forceType) error {
tickStart := m.nowFn()
dbBootstrapStateAtTickStart := m.database.BootstrapState()
if err := m.databaseTickManager.Tick(forceType, tickStart); err != nil {
return err
}
// NB(r): Cleanup and/or flush if required to cleanup files and/or
// flush blocks to disk. Note this has to run after the tick as
// blocks may only have just become available during a tick beginning
// from the tick begin marker.
m.databaseFileSystemManager.Run(tickStart, dbBootstrapStateAtTickStart, syncRun, forceType)
return nil
}
func (m *mediator) Report() {
m.databaseBootstrapManager.Report()
m.databaseRepairer.Report()
m.databaseFileSystemManager.Report()
}
func (m *mediator) Close() error {
m.Lock()
defer m.Unlock()
if m.state == mediatorNotOpen {
return errMediatorNotOpen
}
if m.state == mediatorClosed {
return errMediatorAlreadyClosed
}
m.state = mediatorClosed
close(m.closedCh)
m.databaseRepairer.Stop()
return nil
}
func (m *mediator) ongoingTick() {
for {
select {
case <-m.closedCh:
return
default:
// NB(xichen): if we attempt to tick while another tick
// is in progress, throttle a little to avoid constantly
// checking whether the ongoing tick is finished
err := m.Tick(asyncRun, noForce)
if err == errTickInProgress {
m.sleepFn(tickCheckInterval)
} else if err != nil {
log := m.opts.InstrumentOptions().Logger()
log.Errorf("error within ongoingTick: %v", err)
}
}
}
}
func (m *mediator) reportLoop() {
interval := m.opts.InstrumentOptions().ReportInterval()
t := time.NewTicker(interval)
for {
select {
case <-t.C:
m.Report()
case <-m.closedCh:
t.Stop()
return
}
}
}