/
ChangeTracker.java
630 lines (542 loc) · 24 KB
/
ChangeTracker.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package com.couchbase.lite.replicator;
import com.couchbase.lite.Manager;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorImpl;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.URIUtils;
import com.couchbase.lite.util.Utils;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Reads the continuous-mode _changes feed of a database, and sends the
* individual change entries to its client's changeTrackerReceivedChange()
*
* @exclude
*/
@InterfaceAudience.Private
public class ChangeTracker implements Runnable {
private URL databaseURL;
private Object lastSequenceID;
private boolean continuous = false; // is enclosing replication continuous?
private Throwable error;
private ChangeTrackerClient client;
protected Map<String, Object> requestHeaders;
private Authenticator authenticator;
private boolean usePOST;
private ChangeTrackerMode mode;
private String filterName;
private Map<String, Object> filterParams;
private int limit;
private int heartBeatSeconds;
private List<String> docIDs;
private boolean paused = false;
private Object pausedObj = new Object();
private boolean includeConflicts;
private Thread thread;
private boolean running = false;
private HttpUriRequest request;
protected ChangeTrackerBackoff backoff;
private long startTime = 0;
public enum ChangeTrackerMode {
OneShot,
LongPoll,
Continuous // does not work, do not use it.
}
public ChangeTracker(URL databaseURL, ChangeTrackerMode mode, boolean includeConflicts,
Object lastSequenceID, ChangeTrackerClient client) {
this.databaseURL = databaseURL;
this.mode = mode;
this.includeConflicts = includeConflicts;
this.lastSequenceID = lastSequenceID;
this.client = client;
this.requestHeaders = new HashMap<String, Object>();
this.heartBeatSeconds = 300;
this.limit = 50;
}
public boolean isContinuous() {
return continuous;
}
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
public void setFilterName(String filterName) {
this.filterName = filterName;
}
public void setFilterParams(Map<String, Object> filterParams) {
this.filterParams = filterParams;
}
public void setClient(ChangeTrackerClient client) {
this.client = client;
}
public String getDatabaseName() {
String result = null;
if (databaseURL != null) {
result = databaseURL.getPath();
if (result != null) {
int pathLastSlashPos = result.lastIndexOf('/');
if (pathLastSlashPos > 0) {
result = result.substring(pathLastSlashPos);
}
}
}
return result;
}
public String getFeed() {
switch (mode) {
case OneShot:
return "normal";
case LongPoll:
return "longpoll";
case Continuous:
return "continuous";
}
return "normal";
}
public long getHeartbeatMilliseconds() {
return heartBeatSeconds * 1000;
}
public String getChangesFeedPath() {
if (usePOST) {
return "_changes";
}
String path = "_changes?feed=";
path += getFeed();
if (mode == ChangeTrackerMode.LongPoll) {
path += String.format("&limit=%s", limit);
}
path += String.format("&heartbeat=%s", getHeartbeatMilliseconds());
if (includeConflicts) {
path += "&style=all_docs";
}
if(lastSequenceID != null) {
path += "&since=" + URLEncoder.encode(lastSequenceID.toString());
}
if (docIDs != null && docIDs.size() > 0) {
filterName = "_doc_ids";
filterParams = new HashMap<String, Object>();
filterParams.put("doc_ids", docIDs);
}
if(filterName != null) {
path += "&filter=" + URLEncoder.encode(filterName);
if(filterParams != null) {
for (String filterParamKey : filterParams.keySet()) {
Object value = filterParams.get(filterParamKey);
if (!(value instanceof String)) {
try {
value = Manager.getObjectMapper().writeValueAsString(value);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
path += "&" + URLEncoder.encode(filterParamKey) + "=" + URLEncoder.encode(value.toString());
}
}
}
return path;
}
public URL getChangesFeedURL() {
String dbURLString = databaseURL.toExternalForm();
if(!dbURLString.endsWith("/")) {
dbURLString += "/";
}
dbURLString += getChangesFeedPath();
URL result = null;
try {
result = new URL(dbURLString);
} catch(MalformedURLException e) {
Log.e(Log.TAG_CHANGE_TRACKER, this + ": Changes feed ULR is malformed", e);
}
return result;
}
/**
* Set Authenticator for BASIC Authentication
*/
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void run() {
Log.d(Log.TAG_CHANGE_TRACKER, "Thread id => " + Thread.currentThread().getId());
try {
runLoop();
} finally {
// stopped() method should be called at end of run() method.
stopped();
}
}
protected void runLoop() {
paused = false;
running = true;
HttpClient httpClient;
if (client == null) {
// This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
// directly afterwards. What happens is that by the time the Changetracker thread fires up,
// the cbpuller has already set this.client to null. See issue #109
Log.w(Log.TAG_CHANGE_TRACKER, "%s: ChangeTracker run() loop aborting because client == null", this);
return;
}
if (mode == ChangeTrackerMode.Continuous) {
// there is a failing unit test for this, and from looking at the code the Replication
// object will never use Continuous mode anyway. Explicitly prevent its use until
// it is demonstrated to actually work.
throw new RuntimeException("ChangeTracker does not correctly support continuous mode");
}
httpClient = client.getHttpClient();
backoff = new ChangeTrackerBackoff();
while (running) {
startTime = System.currentTimeMillis();
URL url = getChangesFeedURL();
if (usePOST) {
HttpPost postRequest = new HttpPost(url.toString());
postRequest.setHeader("Content-Type", "application/json");
postRequest.addHeader("User-Agent", Manager.USER_AGENT);
// TODO: why not apply gzip? iOS also does not apply gizp for /{db}/_changes
StringEntity entity;
try {
entity = new StringEntity(changesFeedPOSTBody());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
postRequest.setEntity(entity);
request = postRequest;
} else {
request = new HttpGet(url.toString());
}
addRequestHeaders(request);
// Perform BASIC Authentication if needed
boolean isUrlBasedUserInfo = false;
// If the URL contains user info AND if this a DefaultHttpClient then preemptively set the auth credentials
String userInfo = url.getUserInfo();
if (userInfo != null) {
isUrlBasedUserInfo = true;
} else {
if (authenticator != null) {
AuthenticatorImpl auth = (AuthenticatorImpl) authenticator;
userInfo = auth.authUserInfo();
}
}
if (userInfo != null) {
if (userInfo.contains(":") && !userInfo.trim().equals(":")) {
String[] userInfoElements = userInfo.split(":");
String username = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[0]) : userInfoElements[0];
String password = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[1]) : userInfoElements[1];
final Credentials credentials = new UsernamePasswordCredentials(username, password);
if (httpClient instanceof DefaultHttpClient) {
DefaultHttpClient dhc = (DefaultHttpClient) httpClient;
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(credentials);
}
}
};
dhc.addRequestInterceptor(preemptiveAuth, 0);
}
} else {
Log.w(Log.TAG_CHANGE_TRACKER, "RemoteRequest Unable to parse user info, not setting credentials");
}
}
try {
String maskedRemoteWithoutCredentials = getChangesFeedURL().toString();
maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@", "://---:---@");
Log.v(Log.TAG_CHANGE_TRACKER, "%s: Making request to %s", this, maskedRemoteWithoutCredentials);
HttpResponse response = httpClient.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() >= 300 && !Utils.isTransientError(status)) {
Log.e(Log.TAG_CHANGE_TRACKER, "%s: Change tracker got error %d", this, status.getStatusCode());
this.error = new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
break;
}
HttpEntity entity = response.getEntity();
Log.v(Log.TAG_CHANGE_TRACKER, "%s: got response. status: %s mode: %s", this, status, mode);
if (entity != null) {
InputStream inputStream = null;
try {
Log.v(Log.TAG_CHANGE_TRACKER, "%s: /entity.getContent(). mode: %s", this, mode);
inputStream = entity.getContent();
if (mode == ChangeTrackerMode.LongPoll) { // continuous replications
// NOTE: 1. check content length, ObjectMapper().readValue() throws Exception if size is 0.
// NOTE: 2. HttpEntity.getContentLength() returns the number of bytes of the content, or a negative number if unknown.
boolean responseOK = false; // default value
if (entity.getContentLength() != 0) {
try {
Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue", this);
Map<String, Object> fullBody = Manager.getObjectMapper().readValue(inputStream, Map.class);
Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue. fullBody: %s", this, fullBody);
responseOK = receivedPollResponse(fullBody);
} catch (JsonParseException jpe) {
Log.w(Log.TAG_CHANGE_TRACKER, "%s: json parsing error; %s", this, jpe.toString());
}
}
Log.v(Log.TAG_CHANGE_TRACKER, "%s: responseOK: %s", this, responseOK);
if (responseOK) {
// TODO: this logic is questionable, there's lots
// TODO: of differences in the iOS changetracker code,
client.changeTrackerCaughtUp();
Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
backoff.resetBackoff();
continue;
} else {
long elapsed = (System.currentTimeMillis() - startTime) / 1000;
Log.w(Log.TAG_CHANGE_TRACKER, "%s: Longpoll connection closed (by proxy?) after %d sec", this, elapsed);
if (elapsed >= 30) {
// Looks like the connection got closed by a proxy (like AWS' load balancer) while the
// server was waiting for a change to send, due to lack of activity.
// Lower the heartbeat time to work around this, and reconnect:
this.heartBeatSeconds = Math.min(this.heartBeatSeconds, (int) (elapsed * 0.75));
Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
backoff.resetBackoff();
continue;
} else {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (LongPoll)", this);
client.changeTrackerFinished(this);
break;
}
}
} else { // one-shot replications
Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue (oneshot)", this);
JsonFactory factory = new JsonFactory();
JsonParser jp = factory.createParser(inputStream);
while (jp.nextToken() != JsonToken.START_ARRAY) {
// ignore these tokens
}
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String, Object> change = (Map) Manager.getObjectMapper().readValue(jp, Map.class);
if (!receivedChange(change)) {
Log.w(Log.TAG_CHANGE_TRACKER, "Received unparseable change line from server: %s", change);
}
}
if (jp != null) {
jp.close();
}
Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue (oneshot)", this);
client.changeTrackerCaughtUp();
if (isContinuous()) { // if enclosing replication is continuous
mode = ChangeTrackerMode.LongPoll;
} else {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (OneShot)", this);
client.changeTrackerFinished(this);
break;
}
}
backoff.resetBackoff();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
}
} catch (Exception e) {
if (!running && e instanceof IOException) {
// in this case, just silently absorb the exception because it
// frequently happens when we're shutting down and have to
// close the socket underneath our read.
} else {
Log.w(Log.TAG_CHANGE_TRACKER, this + ": Exception in change tracker", e);
this.error = e;
}
backoff.sleepAppropriateAmountOfTime();
}
}
Log.v(Log.TAG_CHANGE_TRACKER, "%s: Change tracker run loop exiting", this);
}
public boolean receivedChange(final Map<String,Object> change) {
// wait if paused flag is on.
waitIfPaused();
Object seq = change.get("seq");
if(seq == null) {
return false;
}
//pass the change to the client on the thread that created this change tracker
if(client != null) {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: changeTrackerReceivedChange: %s", this, change);
client.changeTrackerReceivedChange(change);
Log.d(Log.TAG_CHANGE_TRACKER, "%s: /changeTrackerReceivedChange: %s", this, change);
}
lastSequenceID = seq;
return true;
}
public boolean receivedPollResponse(Map<String,Object> response) {
List<Map<String,Object>> changes = (List)response.get("results");
if(changes == null) {
return false;
}
for (Map<String,Object> change : changes) {
if(!receivedChange(change)) {
return false;
}
}
return true;
}
public void setUpstreamError(String message) {
Log.w(Log.TAG_CHANGE_TRACKER, "Server error: %s", message);
this.error = new Throwable(message);
}
public boolean start() {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker asked to start", this);
this.error = null;
String maskedRemoteWithoutCredentials = databaseURL.toExternalForm();
maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@", "://---:---@");
thread = new Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials);
thread.start();
return true;
}
public void stop() {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker asked to stop", this);
running = false;
try {
if (thread != null) {
thread.interrupt(); // wake thread if it sleeps, waits, ...
}
} catch (Exception e) {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Exception interrupting thread: %s", this);
}
if(request != null) {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker aborting request: %s", this, request);
request.abort();
}
}
private void stopped() {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker in stopped()", this);
if (client != null) {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling changeTrackerStopped, client: %s", this, client);
client.changeTrackerStopped(ChangeTracker.this);
} else {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker not calling changeTrackerStopped, client == null", this);
}
client = null;
running = false; // in case stop() method was not called to stop
}
public void setRequestHeaders(Map<String, Object> requestHeaders) {
this.requestHeaders = requestHeaders;
}
private void addRequestHeaders(HttpUriRequest request) {
if (requestHeaders != null) {
for (String requestHeaderKey : requestHeaders.keySet()) {
request.addHeader(requestHeaderKey, requestHeaders.get(requestHeaderKey).toString());
}
}
}
public Throwable getLastError() {
Log.d(Log.TAG_CHANGE_TRACKER, "%s: getLastError() %s", this, error);
return error;
}
public boolean isRunning() {
return running;
}
public void setDocIDs(List<String> docIDs) {
this.docIDs = docIDs;
}
public String changesFeedPOSTBody() {
Map<String, Object> postBodyMap = changesFeedPOSTBodyMap();
try {
return Manager.getObjectMapper().writeValueAsString(postBodyMap);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean isUsePOST() {
return usePOST;
}
public void setUsePOST(boolean usePOST) {
this.usePOST = usePOST;
}
public Map<String, Object> changesFeedPOSTBodyMap() {
if (!usePOST) {
return null;
}
if (docIDs != null && docIDs.size() > 0) {
filterName = "_doc_ids";
filterParams = new HashMap<String, Object>();
filterParams.put("doc_ids", docIDs);
}
Map<String, Object> post = new HashMap<String, Object>();
post.put("feed", getFeed());
post.put("heartbeat", getHeartbeatMilliseconds());
if (includeConflicts) {
post.put("style","all_docs");
} else {
post.put("style", null);
}
if (lastSequenceID != null) {
try {
post.put("since", Long.parseLong(lastSequenceID.toString()));
} catch (NumberFormatException e) {
post.put("since", lastSequenceID.toString());
}
}
if (mode == ChangeTrackerMode.LongPoll && limit > 0) {
post.put("limit", limit);
} else {
post.put("limit", null);
}
if (filterName != null) {
post.put("filter", filterName);
post.putAll(filterParams);
}
return post;
}
public void setPaused(boolean paused) {
Log.v(Log.TAG, "setPaused: " + paused);
synchronized (pausedObj) {
if(this.paused != paused) {
this.paused = paused;
pausedObj.notifyAll();
}
}
}
protected void waitIfPaused(){
while (paused) {
Log.v(Log.TAG, "Waiting: " + paused);
synchronized (pausedObj) {
try {
pausedObj.wait();
} catch (InterruptedException e) {
}
}
}
}
}