Cleanly stop replication at checkpoint time if no longer owner
This is a cherry-pick of:
https://github.com/cloudant/couch_replicator/commit/e5ef7c8a0ee2566b9cd4c02397ee94883d015fa0
diff --git a/src/couch_replicator.erl b/src/couch_replicator.erl
index 6e86a8f..3a744cd 100644
--- a/src/couch_replicator.erl
+++ b/src/couch_replicator.erl
@@ -475,13 +475,20 @@
{noreply, State#rep_state{target = NewTarget}};
handle_cast(checkpoint, State) ->
- case do_checkpoint(State) of
- {ok, NewState} ->
- couch_stats:increment_counter([couch_replicator, checkpoints, success]),
- {noreply, NewState#rep_state{timer = start_timer(State)}};
- Error ->
- couch_stats:increment_counter([couch_replicator, checkpoints, failure]),
- {stop, Error, State}
+ #rep_state{rep_details = #rep{id = RepId} = Rep} = State,
+ case couch_replicator_manager:owner(RepId) of
+ Owner when Owner == node() ->
+ case do_checkpoint(State) of
+ {ok, NewState} ->
+ couch_stats:increment_counter([couch_replicator, checkpoints, success]),
+ {noreply, NewState#rep_state{timer = start_timer(State)}};
+ Error ->
+ couch_stats:increment_counter([couch_replicator, checkpoints, failure]),
+ {stop, Error, State}
+ end;
+ Owner ->
+ couch_replicator_manager:replication_usurped(Rep, Owner),
+ {stop, shutdown, State}
end;
handle_cast({report_seq, Seq},
diff --git a/src/couch_replicator_manager.erl b/src/couch_replicator_manager.erl
index 6e83879..7bb5078 100644
--- a/src/couch_replicator_manager.erl
+++ b/src/couch_replicator_manager.erl
@@ -17,7 +17,7 @@
% public API
-export([replication_started/1, replication_completed/2, replication_error/2]).
--export([owner/1]).
+-export([owner/1, replication_usurped/2]).
-export([before_doc_update/2, after_doc_read/2]).
@@ -108,6 +108,17 @@
end.
+replication_usurped(#rep{id = RepId}, By) ->
+ case rep_state(RepId) of
+ nil ->
+ ok;
+ #rep_state{rep = #rep{doc_id = DocId}} ->
+ ok = gen_server:call(?MODULE, {rep_complete, RepId}, infinity),
+ couch_log:notice("Replication `~s` usurped by ~s (triggered by document `~s`)",
+ [pp_rep_id(RepId), By, DocId])
+ end.
+
+
replication_error(#rep{id = {BaseId, _} = RepId}, Error) ->
case rep_state(RepId) of
nil ->