forked from couchbase/ep-engine
/
flusher.cc
373 lines (328 loc) · 11.5 KB
/
flusher.cc
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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 NorthScale, 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.
*/
#include "config.h"
#include <stdlib.h>
#include "flusher.hh"
bool FlusherStepper::callback(Dispatcher &d, TaskId t) {
return flusher->step(d, t);
}
bool Flusher::stop(bool isForceShutdown) {
forceShutdownReceived = isForceShutdown;
enum flusher_state to = forceShutdownReceived ? stopped : stopping;
return transition_state(to);
}
static const char* hrtime2text(hrtime_t t, char *buffer, size_t size) {
static const char * const extensions[] = {"s", "ms", "us", "ns"}; //TODO: get a greek Mu in here correctly
int id = sizeof(extensions)/sizeof(extensions[0]) - 1;
while (t > 9999 && id > 0) {
id--;
t /= 1000;
}
if (id == 0 && t > 599) {
int hour = static_cast<int>(t / 3600);
t -= hour * 3600;
int min = static_cast<int>(t / 60);
t -= min * 60;
snprintf(buffer, size, "%dh:%dm:%ds", hour, min, (int)t);
} else {
snprintf(buffer, size, "%d %s", (int) t, extensions[id]);
}
return buffer;
}
void Flusher::wait(void) {
hrtime_t startt(gethrtime());
while (_state != stopped) {
usleep(1000);
}
hrtime_t endt(gethrtime());
char buffer[80];
if ((endt - startt) > 1000) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Had to wait %s for shutdown\n",
hrtime2text(endt - startt, buffer, sizeof(buffer)));
}
}
bool Flusher::pause(void) {
return transition_state(pausing);
}
bool Flusher::resume(void) {
return transition_state(running);
}
static bool validTransition(enum flusher_state from,
enum flusher_state to)
{
// we may go to stopping from all of the stats except stopped
if (to == stopping) {
return from != stopped;
}
switch (from) {
case initializing:
return (to == loading_keys || to == loading_data);
case loading_keys:
return (to == loading_data);
case loading_data:
return (to == warmup_complete);
case warmup_complete:
return (to == running);
case running:
return (to == pausing);
case pausing:
return (to == paused);
case paused:
return (to == running);
case stopping:
return (to == stopped);
case stopped:
return false;
}
// THis should be impossible (unless someone added new states)
abort();
}
const char * Flusher::stateName(enum flusher_state st) const {
static const char * const stateNames[] = {
"initializing", "loading keys", "loading data", "warmup complete",
"running", "pausing", "paused", "stopping", "stopped"
};
assert(st >= initializing && st <= stopped);
return stateNames[st];
}
bool Flusher::transition_state(enum flusher_state to) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Attempting transition from %s to %s\n",
stateName(_state), stateName(to));
if (!forceShutdownReceived && !validTransition(_state, to)) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Invalid transitioning from %s to %s\n",
stateName(_state), stateName(to));
return false;
}
fireStateChange(static_cast<enum flusher_state>(_state), to);
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Transitioning from %s to %s\n",
stateName(_state), stateName(to));
_state = to;
//Reschedule the task
LockHolder lh(taskMutex);
assert(task.get());
dispatcher->cancel(task);
schedule_UNLOCKED();
return true;
}
const char * Flusher::stateName() const {
return stateName(_state);
}
enum flusher_state Flusher::state() const {
return _state;
}
void Flusher::initialize(TaskId tid) {
assert(task.get() == tid.get());
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Initializing flusher; warming up");
warmupStartTime = gethrtime();
initialVbState = store->loadVBucketState();
if (store->getMutationLog()->isEnabled()
|| store->getROUnderlying()->isKeyDumpSupported()) {
transition_state(loading_keys);
} else {
transition_state(loading_data);
}
}
void Flusher::schedule_UNLOCKED() {
dispatcher->schedule(shared_ptr<FlusherStepper>(new FlusherStepper(this)),
&task, Priority::FlusherPriority);
assert(task.get());
}
void Flusher::start(void) {
LockHolder lh(taskMutex);
schedule_UNLOCKED();
}
void Flusher::wake(void) {
LockHolder lh(taskMutex);
assert(task.get());
dispatcher->wake(task, &task);
}
bool Flusher::step(Dispatcher &d, TaskId tid) {
try {
switch (_state) {
case initializing:
initialize(tid);
return true;
case loading_keys:
store->warmup(initialVbState, true);
store->stats.warmupKeysTime.set((gethrtime() - warmupStartTime) / 1000);
if (store->stats.warmupKeysTime > 0) {
char buffer[80];
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Keys loaded in %s",
hrtime2text(store->stats.warmupKeysTime * 1000,
buffer, sizeof(buffer)));
}
// We knows about all keays and their meta-data, so we can
// safely allow mutation operations as of now..
store->warmupCompleted();
store->stats.warmupComplete.set(true);
transition_state(loading_data);
return true;
case loading_data:
store->warmup(initialVbState, false);
transition_state(warmup_complete);
return true;
case warmup_complete:
if (!store->getROUnderlying()->isKeyDumpSupported()) {
// This backend didn't support a two-phase loading..
// Enable data mutations!
store->warmupCompleted();
store->stats.warmupComplete.set(true);
store->stats.warmupTime.set((gethrtime() - warmupStartTime) / 1000);
if (store->stats.warmupTime > 0) {
char buffer[80];
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"warmup completed in %s",
hrtime2text(store->stats.warmupTime * 1000,
buffer, sizeof(buffer)));
}
}
transition_state(running);
return true;
case paused:
return false;
case pausing:
transition_state(paused);
return false;
case running:
{
doFlush();
if (_state == running) {
double tosleep = computeMinSleepTime();
if (tosleep > 0) {
d.snooze(tid, tosleep);
}
return true;
} else {
return false;
}
}
case stopping:
{
std::stringstream ss;
ss << "Shutting down flusher (Write of all dirty items)"
<< std::endl;
getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "%s",
ss.str().c_str());
}
store->stats.min_data_age = 0;
completeFlush();
getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Flusher stopped\n");
transition_state(stopped);
return false;
case stopped:
return false;
default:
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Unexpected state in flusher: %s", stateName());
assert(false);
}
} catch(std::runtime_error &e) {
std::stringstream ss;
ss << "Exception in flusher loop: " << e.what() << std::endl;
getLogger()->log(EXTENSION_LOG_WARNING, NULL, "%s",
ss.str().c_str());
assert(false);
}
// We should _NEVER_ get here (unless you compile with -DNDEBUG causing
// the assertions to be removed.. It's a bug, so we should abort and
// create a coredump
abort();
}
void Flusher::completeFlush() {
doFlush();
while (flushQueue) {
doFlush();
}
}
double Flusher::computeMinSleepTime() {
// If we were preempted, keep going!
if (flushQueue && !flushQueue->empty()) {
flushRv = 0;
prevFlushRv = 0;
return 0.0;
}
if (flushRv + prevFlushRv == 0) {
minSleepTime = std::min(minSleepTime * 2, 1.0);
} else {
minSleepTime = DEFAULT_MIN_SLEEP_TIME;
}
prevFlushRv = flushRv;
return std::max(static_cast<double>(flushRv), minSleepTime);
}
int Flusher::doFlush() {
// On a fresh entry, flushQueue is null and we need to build one.
if (!flushQueue) {
flushRv = store->stats.min_data_age;
flushQueue = store->beginFlush();
if (flushQueue) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Beginning a write queue flush.\n");
rejectQueue = new std::queue<queued_item>();
flushStart = ep_current_time();
}
}
// Now do the every pass thing.
if (flushQueue) {
if (!flushQueue->empty()) {
int n = store->flushSome(flushQueue, rejectQueue);
if (_state == pausing) {
transition_state(paused);
}
flushRv = std::min(n, flushRv);
}
if (flushQueue->empty()) {
if (!rejectQueue->empty()) {
// Requeue the rejects.
store->requeueRejectedItems(rejectQueue);
} else {
store->completeFlush(flushStart);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Completed a flush, age of oldest item was %ds\n",
flushRv);
delete rejectQueue;
rejectQueue = NULL;
flushQueue = NULL;
}
}
}
return flushRv;
}
void Flusher::addFlusherStateListener(FlusherStateListener *listener) {
LockHolder lh(stateListeners.mutex);
stateListeners.listeners.push_back(listener);
}
void Flusher::removeFlusherStateListener(FlusherStateListener *listener) {
LockHolder lh(stateListeners.mutex);
stateListeners.listeners.remove(listener);
}
void Flusher::fireStateChange(const enum flusher_state &from,
const enum flusher_state &to)
{
LockHolder lh(stateListeners.mutex);
std::list<FlusherStateListener*>::iterator ii;
for (ii = stateListeners.listeners.begin();
ii != stateListeners.listeners.end();
++ii) {
(*ii)->stateChanged(from, to);
}
}