forked from facebookarchive/scribe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStoreQueue.cpp
More file actions
417 lines (345 loc) · 10.4 KB
/
Copy pathStoreQueue.cpp
File metadata and controls
417 lines (345 loc) · 10.4 KB
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
// Copyright (c) 2007-2008 Facebook
//
// 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.
//
// See accompanying file LICENSE or visit the Scribe site at:
// http://developers.facebook.com/scribe/
//
// @author Bobby Johnson
// @author James Wang
// @author Jason Sobel
// @author Anthony Giardullo
// @author John Song
#include "Common.h"
#include "ScribeServer.h"
using namespace scribe::thrift;
static const uint64_t kDefaultTargetWriteSize = 16384;
static const time_t kDefaultMaxWriteInterval = 1;
namespace scribe {
shared_ptr<ThreadFactory> StoreQueue::threadFactory_(
new PosixThreadFactory(PosixThreadFactory::ROUND_ROBIN,
PosixThreadFactory::NORMAL,
1,
false)
);
class StoreQueueTask : public Runnable {
private:
StoreQueue* queue_;
public:
StoreQueueTask(StoreQueue* queue)
: queue_(queue) {
}
virtual ~StoreQueueTask() {}
virtual void run() {
queue_->threadMember();
}
};
StoreQueue::StoreQueue(const string& type, const string& category,
unsigned checkPeriod, bool isModel, bool multiCategory)
: msgQueueSize_(0),
hasWork_(false),
stopping_(false),
isModel_(isModel),
multiCategory_(multiCategory),
categoryHandled_(category),
checkPeriod_(checkPeriod),
targetWriteSize_(kDefaultTargetWriteSize),
maxWriteInterval_(kDefaultMaxWriteInterval),
mustSucceed_(true) {
store_ = Store::createStore(this, type, category,
false, multiCategory_);
if (!store_) {
throw std::runtime_error("createStore failed in StoreQueue constructor. "
"Invalid type?");
}
storeInitCommon();
}
StoreQueue::StoreQueue(const StoreQueuePtr example,
const string &category)
: msgQueueSize_(0),
hasWork_(false),
stopping_(false),
isModel_(false),
multiCategory_(example->multiCategory_),
categoryHandled_(category),
checkPeriod_(example->checkPeriod_),
targetWriteSize_(example->targetWriteSize_),
maxWriteInterval_(example->maxWriteInterval_),
mustSucceed_(example->mustSucceed_) {
store_ = example->copyStore(category);
if (!store_) {
throw std::runtime_error("createStore failed copying model store");
}
storeInitCommon();
}
StoreQueue::~StoreQueue() {
}
void StoreQueue::addMessage(LogEntryPtr entry) {
if (isModel_) {
LOG_OPER("ERROR: called addMessage on model store");
} else {
bool waitForWork = false;
{
Guard g(msgMutex_);
msgQueue_->push_back(entry);
msgQueueSize_ += entry->message.size();
waitForWork = (msgQueueSize_ >= targetWriteSize_) ? true : false;
}
// Wake up store thread if we have enough messages
if (waitForWork == true) {
// signal that there is work to do if not already signaled
Synchronized s(hasWorkCond_);
if (!hasWork_) {
hasWork_ = true;
hasWorkCond_.notify();
}
}
}
}
void StoreQueue::configureAndOpen(StoreConfPtr configuration) {
// model store has to handle this inline since it has no queue
if (isModel_) {
configureInline(configuration);
} else {
{
Guard g(cmdMutex_);
StoreCommand cmd(CMD_CONFIGURE, configuration);
cmdQueue_.push(cmd);
}
// signal that there is work to do if not already signaled
{
Synchronized s(hasWorkCond_);
if (!hasWork_) {
hasWork_ = true;
hasWorkCond_.notify();;
}
}
}
}
void StoreQueue::stop() {
if (isModel_) {
LOG_OPER("ERROR: called stop() on model store");
} else if(!stopping_) {
{
Guard g(cmdMutex_);
StoreCommand cmd(CMD_STOP);
cmdQueue_.push(cmd);
stopping_ = true;
}
// signal that there is work to do if not already signaled
{
Synchronized s(hasWorkCond_);
if (!hasWork_) {
hasWork_ = true;
hasWorkCond_.notify();
}
}
storeThread_->join();
}
}
void StoreQueue::open() {
if (isModel_) {
LOG_OPER("ERROR: called open() on model store");
} else {
{
Guard g(cmdMutex_);
StoreCommand cmd(CMD_OPEN);
cmdQueue_.push(cmd);
}
// signal that there is work to do if not already signaled
{
Synchronized s(hasWorkCond_);
if (!hasWork_) {
hasWork_ = true;
hasWorkCond_.notify();
}
}
}
}
StorePtr StoreQueue::copyStore(const string &category) {
return store_->copy(category);
}
string StoreQueue::getCategoryHandled() {
return categoryHandled_;
}
string StoreQueue::getStatus() {
return store_->getStatus();
}
string StoreQueue::getBaseType() {
return store_->getType();
}
void StoreQueue::threadMember() {
LOG_OPER("store thread starting");
if (isModel_) {
LOG_OPER("ERROR: store thread starting on model store, exiting");
return;
}
if (!store_) {
LOG_OPER("store is NULL, store thread exiting");
return;
}
// init time of last periodic check to time of 0
time_t lastPeriodicCheck = 0;
time_t lastHandleMessages;
time(&lastHandleMessages);
bool stop = false;
bool open = false;
while (!stop) {
time_t thisLoop;
// handle commands
//
{
Guard g(cmdMutex_);
while (!cmdQueue_.empty()) {
StoreCommand cmd = cmdQueue_.front();
cmdQueue_.pop();
switch (cmd.command) {
case CMD_CONFIGURE:
configureInline(cmd.configuration);
openInline();
open = true;
break;
case CMD_OPEN:
openInline();
open = true;
break;
case CMD_STOP:
stop = true;
break;
default:
LOG_OPER("LOGIC ERROR: unknown command to store queue");
break;
}
}
// handle periodic tasks
time(&thisLoop);
if (!stop && ((thisLoop - lastPeriodicCheck) >= checkPeriod_)) {
if (open) {
store_->periodicCheck();
}
lastPeriodicCheck = thisLoop;
}
}
LogEntryVectorPtr messages;
{
Guard g(msgMutex_);
// handle messages if stopping, enough time has passed, or queue is large
//
if (stop ||
(thisLoop - lastHandleMessages >= maxWriteInterval_) ||
msgQueueSize_ >= targetWriteSize_) {
if (failedMessages_) {
// process any messages we were not able to process last time
messages = failedMessages_;
failedMessages_ = LogEntryVectorPtr();
} else if (msgQueueSize_ > 0) {
// process message in queue
messages = msgQueue_;
msgQueue_.reset(new LogEntryVector);
msgQueueSize_ = 0;
}
// reset timer
lastHandleMessages = thisLoop;
}
}
if (messages) {
// all pending messages will be either gone or requeued
g_handler->stats.addCounter(StatCounters::kStoreQueueOut,
messages->size());
if (!store_->handleMessages(messages)) {
// Store could not handle these messages,
// we might requeue these messages or they might get lost.
processFailedMessages(messages);
} else {
// Successfully dequeued messages
g_handler->stats.incStoreQueueSize(-(int64_t)messages->size());
}
store_->flush();
}
if (!stop) {
// set timeout to when we need to handle messages or do a periodic check
uint64_t waitTime = 1000 * std::min(lastPeriodicCheck + checkPeriod_,
lastHandleMessages + maxWriteInterval_);
waitTime -= clock::nowInMsec();
// wait until there's some work to do or we timeout
{
Synchronized s(hasWorkCond_);
if (!hasWork_) {
try {
hasWorkCond_.wait(waitTime);
} catch (TimedOutException&) {
// wake up to do some work
} catch (std::exception& e) {
LOG_OPER("[%s] ERROR: thrift::Monitor::wait() throws exception: %s",
categoryHandled_.c_str(), e.what());
}
}
hasWork_ = false;
}
}
} // while (!stop)
store_->close();
}
void StoreQueue::processFailedMessages(LogEntryVectorPtr messages) {
// If the store was not able to process these messages, we will either
// requeue them or give up depending on the value of mustSucceed_
if (mustSucceed_) {
// Save failed messages
failedMessages_ = messages;
LOG_OPER("[%s] WARNING: Re-queueing %lu messages!",
categoryHandled_.c_str(), messages->size());
g_handler->incCounter(categoryHandled_, "requeue", messages->size());
g_handler->stats.addCounter(StatCounters::kStoreQueueRequeue,
messages->size());
} else {
// record messages as being lost
LOG_OPER("[%s] WARNING: Lost %lu messages!",
categoryHandled_.c_str(), messages->size());
g_handler->incCounter(categoryHandled_, "lost", messages->size());
g_handler->stats.addCounter(StatCounters::kStoreQueueLost,
messages->size());
}
}
void StoreQueue::storeInitCommon() {
// model store doesn't need this stuff
if (!isModel_) {
msgQueue_.reset(new LogEntryVector);
storeThread_ = threadFactory_->newThread(
shared_ptr<Runnable>(new StoreQueueTask(this))
);
storeThread_->start();
}
}
void StoreQueue::configureInline(StoreConfPtr configuration) {
// Constructor defaults are fine if these don't exist
configuration->getUint64("target_write_size", &targetWriteSize_);
configuration->getUnsigned("max_write_interval",
(unsigned long*) &maxWriteInterval_);
if (maxWriteInterval_ == 0) {
maxWriteInterval_ = 1;
}
string tmp;
if (configuration->getString("must_succeed", &tmp) && tmp == "no") {
mustSucceed_ = false;
}
store_->configure(configuration, StoreConfPtr());
}
void StoreQueue::openInline() {
if (store_->isOpen()) {
store_->close();
}
if (!isModel_) {
store_->open();
}
}
} //! namespace scribe