/
OplogTailThread.java
280 lines (255 loc) · 8.39 KB
/
OplogTailThread.java
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
// Copyright (C) 2012 Wordnik, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package com.wordnik.system.mongodb;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.ArrayList;
import org.bson.types.BSONTimestamp;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.wordnik.util.PrintFormat;
public class OplogTailThread extends Thread {
protected boolean enableOutput = true;
protected boolean running = false;
protected boolean killMe = false;
protected long reportInterval = 10000;
protected List<String> inclusions;
protected List<String> exclusions;
protected List<OplogRecordProcessor> processors = new ArrayList<OplogRecordProcessor>();
protected DBCollection oplog;
protected String OPLOG_LAST_FILENAME = "last_timestamp.txt";
protected boolean exitOnStopThread = false;
public OplogTailThread(OplogRecordProcessor processor, DBCollection oplog){
this.oplog = oplog;
this.processors.add(processor);
setName("oplog");
}
public OplogTailThread(OplogRecordProcessor processor, DBCollection oplog, String threadName){
this.oplog = oplog;
this.processors.add(processor);
setName(threadName);
}
public void setOutputEnabled(boolean enabled) {
this.enableOutput = enabled;
}
public void setStopFilename(String filename) {
this.OPLOG_LAST_FILENAME = filename;
}
public void addOplogProcessor(OplogRecordProcessor processor) {
this.processors.add(processor);
}
public void setBaseDir(String dir){
if(dir != null){
OPLOG_LAST_FILENAME = dir + File.separator + OPLOG_LAST_FILENAME;
}
}
public void setBaseDir(String dir, String fileName){
if(dir != null && fileName != null){
OPLOG_LAST_FILENAME = dir + File.separator + fileName;
}
}
public void setExitOnStopThread(Boolean isExit){
exitOnStopThread = isExit;
}
public void setInclusions(List<String> inclusions){
this.inclusions = inclusions;
}
public void setExclusions(List<String> exclusions){
this.exclusions = exclusions;
}
public void writeLastTimestamp(BSONTimestamp ts){
if(ts == null){
return;
}
Writer writer = null;
try{
OutputStream out = new FileOutputStream(new File(OPLOG_LAST_FILENAME));
writer = new OutputStreamWriter(out, "UTF-8");
writer.write(Integer.toString(ts.getTime()) + "|" + Integer.toString(ts.getInc()));
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(writer != null){
try{writer.close();}
catch(Exception e){}
}
}
}
public void writeTimestampToStartFromNow(){
Writer writer = null;
try{
OutputStream out = new FileOutputStream(new File(OPLOG_LAST_FILENAME));
writer = new OutputStreamWriter(out, "UTF-8");
writer.write(Integer.toString((int) ((System.currentTimeMillis() / 1000L)-1)) + "|" + Integer.toString(1)); // -1 is for reliabilty just in case
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(writer != null){
try{writer.close();}
catch(Exception e){}
}
}
}
public BSONTimestamp getLastTimestamp() {
BufferedReader input = null;
try{
File file = new File(OPLOG_LAST_FILENAME);
if(!file.exists()){
return null;
}
input = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF8"));
String line = input.readLine();
String[] parts = line.split("\\|");
return new BSONTimestamp(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]));
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(input != null){
try{input.close();}
catch(Exception e){}
}
}
return null;
}
public void run(){
running = true;
BSONTimestamp lastTimestamp = null;
try{
lastTimestamp = getLastTimestamp();
long lastWrite = 0;
long startTime = System.currentTimeMillis();
long lastOutput = System.currentTimeMillis();
while(true){
try{
if(killMe) {
System.out.println("exiting thread");
return;
}
DBCursor cursor = null;
if(lastTimestamp != null){
cursor = oplog.find( new BasicDBObject( "ts" , new BasicDBObject( "$gt" , lastTimestamp ) ) );
cursor.addOption( Bytes.QUERYOPTION_OPLOGREPLAY );
}
else{
cursor = oplog.find();
}
cursor.addOption( Bytes.QUERYOPTION_TAILABLE );
cursor.addOption( Bytes.QUERYOPTION_AWAITDATA );
long count = 0;
long skips = 0;
while (!killMe && cursor.hasNext() ){
DBObject x = cursor.next();
if(!killMe) {
lastTimestamp = (BSONTimestamp)x.get("ts");
if(shouldWrite(x)){
for(OplogRecordProcessor processor : processors)
processor.processRecord((BasicDBObject)x);
count++;
}
else {
skips++;
}
if(System.currentTimeMillis() - lastWrite > 1000){
writeLastTimestamp(lastTimestamp);
lastWrite = System.currentTimeMillis();
}
long duration = System.currentTimeMillis() - lastOutput;
if(duration > reportInterval){
report(this.getName(), count, skips, System.currentTimeMillis() - startTime);
lastOutput = System.currentTimeMillis();
}
}
}
}
catch(com.mongodb.MongoException.CursorNotFound ex){
writeLastTimestamp(lastTimestamp);
System.out.println("Cursor not found, waiting");
Thread.sleep(2000);
}
catch(com.mongodb.MongoInternalException ex){
System.out.println("Cursor not found, waiting");
writeLastTimestamp(lastTimestamp);
ex.printStackTrace();
}
catch(com.mongodb.MongoException ex){
writeLastTimestamp(lastTimestamp);
System.out.println("Internal exception, waiting");
Thread.sleep(2000);
}
catch(Exception ex){
killMe = true;
writeLastTimestamp(lastTimestamp);
ex.printStackTrace();
break;
}
}
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
writeLastTimestamp(lastTimestamp);
try{
for(OplogRecordProcessor processor : processors) {
processor.close("oplog");
}
}
catch(Exception e){
e.printStackTrace();
}
}
running = false;
}
boolean shouldWrite(DBObject obj){
String ns = (String)obj.get("ns");
if(ns == null || "".equals(ns)){
return false;
}
if(exclusions.size() == 0 && inclusions.size() == 0){
return true;
}
if(exclusions.contains(ns)){
return false;
}
if(inclusions.contains(ns) || inclusions.contains("*")){
return true;
}
// check database-level inclusion
if(ns.indexOf('.') > 0 && inclusions.contains(ns.substring(0, ns.indexOf('.')))){
return true;
}
return false;
}
void report(String collectionName, long count, long skips, long duration){
double brate = (double)count / ((duration) / 1000.0);
if(enableOutput)
System.out.println(collectionName + ": " + PrintFormat.LONG_FORMAT.format(count) + " records, " + PrintFormat.LONG_FORMAT.format(brate) + " req/sec, " + PrintFormat.LONG_FORMAT.format(skips) + " skips");
}
}