-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
EntryOperator.java
373 lines (321 loc) · 13.5 KB
/
EntryOperator.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
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* 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.
*/
package com.hazelcast.map.impl.operation;
import com.hazelcast.cluster.Address;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.core.EntryEventType;
import com.hazelcast.core.ReadOnly;
import com.hazelcast.internal.monitor.impl.LocalMapStatsImpl;
import com.hazelcast.internal.partition.IPartitionService;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.ExtendedMapEntry;
import com.hazelcast.map.impl.LazyMapEntry;
import com.hazelcast.map.impl.LocalMapStatsProvider;
import com.hazelcast.map.impl.LockAwareLazyMapEntry;
import com.hazelcast.map.impl.MapContainer;
import com.hazelcast.map.impl.MapServiceContext;
import com.hazelcast.map.impl.event.MapEventPublisher;
import com.hazelcast.map.impl.record.Record;
import com.hazelcast.map.impl.recordstore.RecordStore;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.impl.QueryableEntry;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.eventservice.EventService;
import com.hazelcast.spi.impl.operationservice.BackupOperation;
import java.util.Map.Entry;
import static com.hazelcast.config.InMemoryFormat.OBJECT;
import static com.hazelcast.core.EntryEventType.ADDED;
import static com.hazelcast.core.EntryEventType.REMOVED;
import static com.hazelcast.core.EntryEventType.UPDATED;
import static com.hazelcast.internal.util.ToHeapDataConverter.toHeapData;
import static com.hazelcast.map.impl.MapService.SERVICE_NAME;
import static com.hazelcast.map.impl.record.Record.UNSET;
import static com.hazelcast.wan.impl.CallerProvenance.NOT_WAN;
/**
* Operator for single key processing logic of {@link
* EntryProcessor} and backup entry processor related operations.
*/
public final class EntryOperator {
private final boolean shouldClone;
private final boolean backup;
private final boolean readOnly;
private final boolean wanReplicationEnabled;
private final boolean hasEventRegistration;
private final int partitionId;
private final long startTimeNanos = System.nanoTime();
private final String mapName;
private final RecordStore recordStore;
private final InternalSerializationService ss;
private final MapContainer mapContainer;
private final MapEventPublisher mapEventPublisher;
private final LocalMapStatsImpl stats;
private final IPartitionService partitionService;
private final Predicate predicate;
private final MapServiceContext mapServiceContext;
private final MapOperation mapOperation;
private final Address callerAddress;
private final InMemoryFormat inMemoryFormat;
private EntryProcessor entryProcessor;
private EntryProcessor backupProcessor;
// these fields can be used to reset this operator
private boolean didMatchPredicate;
private Data dataKey;
private Object oldValue;
private EntryEventType eventType;
private Data result;
private LockAwareLazyMapEntry entry;
@SuppressWarnings("checkstyle:executablestatementcount")
private EntryOperator(MapOperation mapOperation, Object processor, Predicate predicate, boolean collectWanEvents) {
this.backup = mapOperation instanceof BackupOperation;
setProcessor(processor);
this.mapOperation = mapOperation;
this.predicate = predicate;
this.recordStore = mapOperation.recordStore;
this.readOnly = entryProcessor instanceof ReadOnly;
this.mapContainer = recordStore.getMapContainer();
this.inMemoryFormat = mapContainer.getMapConfig().getInMemoryFormat();
this.mapName = mapContainer.getName();
this.wanReplicationEnabled = mapContainer.isWanReplicationEnabled();
this.shouldClone = mapContainer.shouldCloneOnEntryProcessing(mapOperation.getPartitionId());
this.mapServiceContext = mapContainer.getMapServiceContext();
LocalMapStatsProvider localMapStatsProvider = mapServiceContext.getLocalMapStatsProvider();
this.stats = localMapStatsProvider.getLocalMapStatsImpl(mapName);
NodeEngine nodeEngine = mapServiceContext.getNodeEngine();
this.ss = ((InternalSerializationService) nodeEngine.getSerializationService());
this.partitionService = nodeEngine.getPartitionService();
EventService eventService = nodeEngine.getEventService();
this.hasEventRegistration = eventService.hasEventRegistration(SERVICE_NAME, mapName);
this.mapEventPublisher = mapServiceContext.getMapEventPublisher();
this.partitionId = recordStore.getPartitionId();
this.callerAddress = mapOperation.getCallerAddress();
this.entry = new LockAwareLazyMapEntry();
}
private void setProcessor(Object processor) {
if (backup) {
backupProcessor = ((EntryProcessor) processor);
entryProcessor = null;
} else {
entryProcessor = ((EntryProcessor) processor);
backupProcessor = null;
}
}
public static EntryOperator operator(MapOperation mapOperation) {
return new EntryOperator(mapOperation, null, null, false);
}
public static EntryOperator operator(MapOperation mapOperation, Object processor) {
return new EntryOperator(mapOperation, processor, null, false);
}
public static EntryOperator operator(MapOperation mapOperation, Object processor, Predicate predicate) {
return new EntryOperator(mapOperation, processor, predicate, false);
}
public EntryOperator init(Data dataKey, Object oldValue, Object newValue, Data result,
EntryEventType eventType, Boolean locked) {
this.dataKey = dataKey;
this.oldValue = oldValue;
this.eventType = eventType;
this.result = result;
this.didMatchPredicate = true;
this.entry.init(ss, dataKey, newValue != null ? newValue : oldValue,
mapContainer.getExtractors(), locked);
return this;
}
public EntryOperator operateOnKey(Data dataKey) {
init(dataKey, null, null, null, null, null);
if (belongsAnotherPartition(dataKey)) {
return this;
}
oldValue = recordStore.get(dataKey, backup, callerAddress, false);
// predicated entry processors can only be applied to existing entries
// so if we have a predicate and somehow(due to expiration or split-brain healing)
// we found value null, we should skip that entry.
if (predicate != null && oldValue == null) {
return this;
}
Boolean locked = recordStore.isLocked(dataKey);
return operateOnKeyValueInternal(dataKey, clonedOrRawOldValue(), locked);
}
public EntryOperator operateOnKeyValue(Data dataKey, Object oldValue) {
return operateOnKeyValueInternal(dataKey, oldValue, null);
}
private EntryOperator operateOnKeyValueInternal(Data dataKey, Object oldValue, Boolean locked) {
init(dataKey, oldValue, null, null, null, locked);
if (outOfPredicateScope(entry)) {
this.didMatchPredicate = false;
return this;
}
process(entry);
findModificationType(entry);
if (readOnly && entryWasModified()) {
throwModificationInReadOnlyException();
}
return this;
}
private boolean entryWasModified() {
return eventType != null;
}
public EntryEventType getEventType() {
return eventType;
}
public Object getByPreferringDataNewValue() {
return entry.getByPrioritizingDataValue();
}
public Object getOldValue() {
return oldValue;
}
public Data getResult() {
return result;
}
public EntryOperator doPostOperateOps() {
if (!didMatchPredicate) {
return this;
}
if (eventType == null) {
// when event type is null, it means this is a
// read-only entry processor and not modified entry.
onTouched();
return this;
}
switch (eventType) {
case UPDATED:
onTouched();
onAddedOrUpdated();
break;
case ADDED:
onAddedOrUpdated();
break;
case REMOVED:
onRemove();
break;
default:
throw new IllegalArgumentException("Unexpected event found:" + eventType);
}
if (wanReplicationEnabled) {
publishWanReplicationEvent();
}
if (!backup) {
if (hasEventRegistration) {
publishEntryEvent();
}
mapOperation.invalidateNearCache(dataKey);
}
mapOperation.evict(dataKey);
return this;
}
private void onAddedOrUpdated() {
Object newValue = inMemoryFormat == OBJECT
? entry.getValue() : entry.getByPrioritizingDataValue();
if (backup) {
recordStore.putBackup(dataKey, newValue, entry.getNewTtl(), UNSET, NOT_WAN);
} else {
recordStore.setWithUncountedAccess(dataKey, newValue, entry.getNewTtl(), UNSET);
if (mapOperation.isPostProcessing(recordStore)) {
Record record = recordStore.getRecord(dataKey);
newValue = record == null ? null : record.getValue();
entry.setValueByInMemoryFormat(inMemoryFormat, newValue);
}
mapServiceContext.interceptAfterPut(mapContainer.getInterceptorRegistry(), newValue);
stats.incrementPutLatencyNanos(getLatencyNanos(startTimeNanos));
}
}
private void onRemove() {
if (backup) {
recordStore.removeBackup(dataKey, NOT_WAN);
} else {
recordStore.delete(dataKey, NOT_WAN);
mapServiceContext.interceptAfterRemove(mapContainer.getInterceptorRegistry(), oldValue);
stats.incrementRemoveLatencyNanos(getLatencyNanos(startTimeNanos));
}
}
private Object clonedOrRawOldValue() {
return shouldClone ? ss.toObject(ss.toData(oldValue)) : oldValue;
}
// Needed for MultipleEntryOperation.
private boolean belongsAnotherPartition(Data key) {
return partitionService.getPartitionId(key) != partitionId;
}
private boolean outOfPredicateScope(Entry entry) {
assert entry instanceof QueryableEntry;
if (predicate == null || predicate == Predicates.alwaysTrue()) {
return false;
}
return predicate == Predicates.alwaysFalse() || !predicate.apply(entry);
}
private void findModificationType(LazyMapEntry mapEntry) {
if (!mapEntry.isModified()
|| (oldValue == null && mapEntry.hasNullValue())) {
// read only
eventType = null;
return;
}
if (mapEntry.hasNullValue()) {
eventType = REMOVED;
return;
}
eventType = oldValue == null ? ADDED : UPDATED;
}
private void onTouched() {
// updates access time if record exists
Record record = recordStore.getRecord(dataKey);
if (record != null) {
recordStore.accessRecord(record, Clock.currentTimeMillis());
}
}
private static long getLatencyNanos(long beginTimeNanos) {
return System.nanoTime() - beginTimeNanos;
}
private void process(ExtendedMapEntry entry) {
if (backup) {
backupProcessor.process(entry);
return;
}
result = ss.toData(entryProcessor.process(entry));
}
private void throwModificationInReadOnlyException() {
throw new UnsupportedOperationException("Entry Processor " + entryProcessor.getClass().getName()
+ " marked as ReadOnly tried to modify map " + mapName + ". This is not supported. Remove "
+ "the ReadOnly marker from the Entry Processor or do not modify the entry in the process "
+ "method.");
}
private void publishWanReplicationEvent() {
assert entryWasModified();
if (eventType == REMOVED) {
mapOperation.publishWanRemove(dataKey);
} else {
mapOperation.publishWanUpdate(dataKey, entry.getByPrioritizingDataValue());
}
}
private void publishEntryEvent() {
Object oldValue = getOrNullOldValue();
mapEventPublisher.publishEvent(callerAddress, mapName, eventType,
toHeapData(dataKey), oldValue, entry.getByPrioritizingDataValue());
}
/**
* Nullify old value if in memory format is object and operation is not removal
* since old and new value in fired event {@link com.hazelcast.core.EntryEvent}
* may be same due to the object in memory format.
*/
private Object getOrNullOldValue() {
if (inMemoryFormat == OBJECT && eventType != REMOVED) {
return null;
} else {
return oldValue;
}
}
}