-
Notifications
You must be signed in to change notification settings - Fork 214
/
PersistencePingActor.java
248 lines (216 loc) · 10.7 KB
/
PersistencePingActor.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
/*
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.internal.utils.persistentactors;
import java.util.Optional;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.entity.id.EntityId;
import org.eclipse.ditto.base.model.entity.type.EntityType;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.internal.utils.pekko.PingCommand;
import org.eclipse.ditto.internal.utils.pekko.PingCommandResponse;
import org.eclipse.ditto.internal.utils.pekko.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.pekko.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.internal.utils.persistence.mongo.streaming.MongoReadJournal;
import org.eclipse.ditto.internal.utils.persistentactors.config.PingConfig;
import org.eclipse.ditto.internal.utils.persistentactors.config.RateConfig;
import org.eclipse.ditto.json.JsonValue;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.AbstractActor;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.Cancellable;
import org.apache.pekko.actor.Props;
import org.apache.pekko.japi.pf.ReceiveBuilder;
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.javadsl.Source;
/**
* Actor which pings an {@link AbstractPersistenceActor}s containing journal entries tagged with
* a configured {@link org.eclipse.ditto.internal.utils.persistentactors.config.PingConfig#getJournalTag()} automatically on a (cold) startup of the cluster.
* <p>
* Also periodically sends out ping messages to e.g. mitigate crashes of {@code AbstractPersistenceActor}s
* which should be always kept alive.
*/
public final class PersistencePingActor extends AbstractActor {
/**
* The name of this Actor.
*/
public static final String ACTOR_NAME = "persistencePing";
private static final String CORRELATION_ID_PREFIX = "persistence-ping-actor-triggered:";
private final ThreadSafeDittoLoggingAdapter log = DittoLoggerFactory.getThreadSafeDittoLoggingAdapter(this);
private final ActorRef persistenceActorShardRegion;
private final Supplier<Source<String, NotUsed>> persistenceIdsSourceSupplier;
private final PingConfig pingConfig;
private final Materializer materializer;
@Nullable private Cancellable pingCheck = null;
private boolean pingInProgress = false;
@SuppressWarnings("unused")
private PersistencePingActor(final ActorRef persistenceActorShardRegion, final PingConfig pingConfig,
final Supplier<Source<String, NotUsed>> persistenceIdsSourceSupplier) {
this.persistenceActorShardRegion = persistenceActorShardRegion;
this.persistenceIdsSourceSupplier = persistenceIdsSourceSupplier;
this.pingConfig = pingConfig;
materializer = Materializer.createMaterializer(this::getContext);
}
@SuppressWarnings("unused")
private PersistencePingActor(final ActorRef persistenceActorShardRegion, final PingConfig pingConfig,
final MongoReadJournal readJournal) {
this.persistenceActorShardRegion = persistenceActorShardRegion;
this.pingConfig = pingConfig;
materializer = Materializer.createMaterializer(this::getContext);
final PingConfig.StreamingOrder streamingOrder = pingConfig.getStreamingOrder();
switch (streamingOrder) {
case TAGS:
persistenceIdsSourceSupplier = () ->
readJournal.getJournalPidsWithTagOrderedByPriorityTag(pingConfig.getJournalTag(),
pingConfig.getInterval());
break;
case ID:
default:
persistenceIdsSourceSupplier = () -> readJournal.getJournalPidsWithTag(pingConfig.getJournalTag(),
pingConfig.getReadJournalBatchSize(),
pingConfig.getInterval(),
materializer,
false);
}
readJournal.ensureTagPidIndex().exceptionally(e -> {
log.error(e, "Failed to create TagPidIndex");
return null;
});
}
/**
* Creates Pekko configuration object Props for this Actor.
*
* @param persistenceActorShardRegion the shard region of the target PersistenceActor.
* @param pingConfig the Configuration to apply for this ping actor.
* @param readJournal readJournal to extract current PIDs from.
* @return the Pekko configuration Props object.
*/
public static Props props(final ActorRef persistenceActorShardRegion, final PingConfig pingConfig,
final MongoReadJournal readJournal) {
return Props.create(PersistencePingActor.class, persistenceActorShardRegion, pingConfig, readJournal);
}
/**
* Creates Pekko configuration object Props for this Actor.
*
* @param persistenceActorShardRegion the shard region of the target PersistenceActor.
* @param pingConfig the Configuration to apply for this ping actor.
* @param persistenceIdsSourceSupplier supplier of persistence id sources.
* @return the Pekko configuration Props object.
*/
static Props propsForTests(final ActorRef persistenceActorShardRegion, final PingConfig pingConfig,
final Supplier<Source<String, NotUsed>> persistenceIdsSourceSupplier) {
return Props.create(PersistencePingActor.class, persistenceActorShardRegion, pingConfig,
persistenceIdsSourceSupplier);
}
private Cancellable schedulePing() {
final ActorContext context = getContext();
final InternalMessages message = InternalMessages.START_PINGING;
log.info("Scheduling ping for all PersistenceActors with initial delay <{}> and interval <{}>.",
pingConfig.getInitialDelay(), pingConfig.getInterval());
return context.getSystem().scheduler()
.scheduleAtFixedRate(pingConfig.getInitialDelay(), pingConfig.getInterval(), getSelf(),
message, context.dispatcher(), ActorRef.noSender());
}
@Override
public void preStart() throws Exception {
super.preStart();
pingCheck = schedulePing();
}
@Override
public void postStop() throws Exception {
if (null != pingCheck) {
pingCheck.cancel();
}
super.postStop();
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(PingCommandResponse.class,
command -> log.debug("Received PersistencePingCommandResponse with correlation-id <{}> " +
"and payload <{}> from sender <{}>",
command.getCorrelationId(), command.getPayload(), getSender()))
.match(DittoRuntimeException.class,
exception -> log.debug("Received <{}> for correlation-id <{}>: {}",
exception.getClass().getSimpleName(),
exception.getDittoHeaders().getCorrelationId().orElse("unknown"),
exception.getMessage()))
.matchEquals(InternalMessages.START_PINGING, msg -> startPinging())
.matchEquals(InternalMessages.PINGING_FINISHED, msg -> pingingFinished())
.matchAny(m -> {
log.warning("Unknown message: {}", m);
unhandled(m);
}).build();
}
private void startPinging() {
if (pingInProgress) {
log.info("Another ping iteration is currently in progress. Next iteration will be started after <{}>.",
pingConfig.getInterval());
} else {
log.info("Sending ping for PersistenceActors. Will be sent again after the configured interval of <{}>.",
pingConfig.getInterval());
pingInProgress = true;
final Source<String, NotUsed> currentPersistenceIdsSource = persistenceIdsSourceSupplier.get();
if (currentPersistenceIdsSource != null) {
final RateConfig rateConfig = pingConfig.getRateConfig();
currentPersistenceIdsSource
.throttle(rateConfig.getEntityAmount(), rateConfig.getFrequency())
.runForeach(this::ping, materializer)
.thenRun(() -> {
log.info("Sending pings completed.");
getSelf().tell(InternalMessages.PINGING_FINISHED, getSelf());
});
} else {
log.warning("Failed to create new persistence id source for persistence actor ping.");
}
}
}
private void pingingFinished() {
log.info("Got ping completed.");
pingInProgress = false;
}
private void ping(final String persistenceId) {
final EntityId entityId = extractEntityIdFromPersistenceId(persistenceId);
final String correlationId = toCorrelationId(entityId);
final PingCommand pingMessage = PingCommand.of(entityId,
correlationId,
JsonValue.of(pingConfig.getJournalTag()));
log.debug("Sending a 'ping' message for persistenceId <{}>: <{}>", persistenceId, pingMessage);
persistenceActorShardRegion.tell(pingMessage, getSelf());
}
private EntityId extractEntityIdFromPersistenceId(final String persistenceId) {
final int indexOfSeparator = persistenceId.indexOf(':');
if (indexOfSeparator < 0) {
final String message =
String.format("Persistence ID <%s> wasn't prefixed with an entity type.", persistenceId);
log.error(message);
throw new IllegalArgumentException(message);
}
final String id = persistenceId.substring(indexOfSeparator + 1);
final EntityType type = EntityType.of(persistenceId.substring(0, indexOfSeparator));
return EntityId.of(type, id);
}
static String toCorrelationId(final EntityId persistenceId) {
return CORRELATION_ID_PREFIX + persistenceId;
}
static Optional<String> toPersistenceId(final String correlationId) {
if (correlationId.startsWith(CORRELATION_ID_PREFIX)) {
return Optional.of(correlationId.replace(CORRELATION_ID_PREFIX, ""));
}
return Optional.empty();
}
enum InternalMessages {
START_PINGING,
PINGING_FINISHED
}
}