-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
FileIdempotentRepository.java
533 lines (477 loc) · 18.2 KB
/
FileIdempotentRepository.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
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.processor.idempotent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedOperation;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.spi.IdempotentRepository;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.LRUCache;
import org.apache.camel.util.LRUCacheFactory;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A file based implementation of {@link org.apache.camel.spi.IdempotentRepository}.
* <p/>
* This implementation provides a 1st-level in-memory {@link LRUCache} for fast check of the most
* frequently used keys. When {@link #add(String)} or {@link #contains(String)} methods are being used
* then in case of 1st-level cache miss, the underlying file is scanned which may cost additional performance.
* So try to find the right balance of the size of the 1st-level cache, the default size is 1000.
* The file store has a maximum capacity of 32mb by default. If the file store grows bigger, then
* the {@link #getDropOldestFileStore()} number of entries from the file store is dropped to reduce
* the file store and make room for newer entries.
*
* @version
*/
@ManagedResource(description = "File based idempotent repository")
public class FileIdempotentRepository extends ServiceSupport implements IdempotentRepository<String> {
private static final Logger LOG = LoggerFactory.getLogger(FileIdempotentRepository.class);
private static final String STORE_DELIMITER = "\n";
private final AtomicBoolean init = new AtomicBoolean();
private Map<String, Object> cache;
private File fileStore;
private long maxFileStoreSize = 32 * 1024 * 1000L; // 32mb store file
private long dropOldestFileStore = 1000;
public FileIdempotentRepository() {
}
public FileIdempotentRepository(File fileStore, Map<String, Object> set) {
this.fileStore = fileStore;
this.cache = set;
}
/**
* Creates a new file based repository using a {@link org.apache.camel.util.LRUCache}
* as 1st level cache with a default of 1000 entries in the cache.
*
* @param fileStore the file store
*/
public static IdempotentRepository<String> fileIdempotentRepository(File fileStore) {
return fileIdempotentRepository(fileStore, 1000);
}
/**
* Creates a new file based repository using a {@link org.apache.camel.util.LRUCache}
* as 1st level cache.
*
* @param fileStore the file store
* @param cacheSize the cache size
*/
@SuppressWarnings("unchecked")
public static IdempotentRepository<String> fileIdempotentRepository(File fileStore, int cacheSize) {
return fileIdempotentRepository(fileStore, LRUCacheFactory.newLRUCache(cacheSize));
}
/**
* Creates a new file based repository using a {@link org.apache.camel.util.LRUCache}
* as 1st level cache.
*
* @param fileStore the file store
* @param cacheSize the cache size
* @param maxFileStoreSize the max size in bytes for the filestore file
*/
@SuppressWarnings("unchecked")
public static IdempotentRepository<String> fileIdempotentRepository(File fileStore, int cacheSize, long maxFileStoreSize) {
FileIdempotentRepository repository = new FileIdempotentRepository(fileStore, LRUCacheFactory.newLRUCache(cacheSize));
repository.setMaxFileStoreSize(maxFileStoreSize);
return repository;
}
/**
* Creates a new file based repository using the given {@link java.util.Map}
* as 1st level cache.
* <p/>
* Care should be taken to use a suitable underlying {@link java.util.Map} to avoid this class being a
* memory leak.
*
* @param store the file store
* @param cache the cache to use as 1st level cache
*/
public static IdempotentRepository<String> fileIdempotentRepository(File store, Map<String, Object> cache) {
return new FileIdempotentRepository(store, cache);
}
@ManagedOperation(description = "Adds the key to the store")
public boolean add(String key) {
synchronized (cache) {
if (cache.containsKey(key)) {
return false;
} else {
// always register the most used keys in the LRUCache
cache.put(key, key);
// now check the file store
boolean containsInFile = containsStore(key);
if (containsInFile) {
return false;
}
// its a new key so append to file store
appendToStore(key);
// check if we hit maximum capacity and report a warning about this
if (fileStore.length() > maxFileStoreSize) {
LOG.warn("Maximum capacity of file store: {} hit at {} bytes. Dropping {} oldest entries from the file store", fileStore, maxFileStoreSize, dropOldestFileStore);
trunkStore();
}
return true;
}
}
}
@ManagedOperation(description = "Does the store contain the given key")
public boolean contains(String key) {
synchronized (cache) {
// check 1st-level first and then fallback to check the actual file
return cache.containsKey(key) || containsStore(key);
}
}
@ManagedOperation(description = "Remove the key from the store")
public boolean remove(String key) {
boolean answer;
synchronized (cache) {
answer = cache.remove(key) != null;
// remove from file cache also
removeFromStore(key);
}
return answer;
}
public boolean confirm(String key) {
// noop
return true;
}
@ManagedOperation(description = "Clear the store (danger this removes all entries)")
public void clear() {
synchronized (cache) {
cache.clear();
if (cache instanceof LRUCache) {
((LRUCache) cache).cleanUp();
}
// clear file store
clearStore();
}
}
public File getFileStore() {
return fileStore;
}
public void setFileStore(File fileStore) {
this.fileStore = fileStore;
}
@ManagedAttribute(description = "The file path for the store")
public String getFilePath() {
return fileStore.getPath();
}
public Map<String, Object> getCache() {
return cache;
}
public void setCache(Map<String, Object> cache) {
this.cache = cache;
}
@ManagedAttribute(description = "The maximum file size for the file store in bytes")
public long getMaxFileStoreSize() {
return maxFileStoreSize;
}
/**
* Sets the maximum file size for the file store in bytes.
* <p/>
* The default is 32mb.
*/
@ManagedAttribute(description = "The maximum file size for the file store in bytes")
public void setMaxFileStoreSize(long maxFileStoreSize) {
this.maxFileStoreSize = maxFileStoreSize;
}
public long getDropOldestFileStore() {
return dropOldestFileStore;
}
/**
* Sets the number of oldest entries to drop from the file store when the maximum capacity is hit to reduce
* disk space to allow room for new entries.
* <p/>
* The default is 1000.
*/
@ManagedAttribute(description = "Number of oldest elements to drop from file store if maximum file size reached")
public void setDropOldestFileStore(long dropOldestFileStore) {
this.dropOldestFileStore = dropOldestFileStore;
}
/**
* Sets the 1st-level cache size.
*
* Setting cache size is only possible when using the default {@link LRUCache} cache implementation.
*/
@SuppressWarnings("unchecked")
public void setCacheSize(int size) {
if (cache != null && !(cache instanceof LRUCache)) {
throw new IllegalArgumentException("Setting cache size is only possible when using the default LRUCache cache implementation");
}
if (cache != null) {
cache.clear();
}
cache = LRUCacheFactory.newLRUCache(size);
}
@ManagedAttribute(description = "The current 1st-level cache size")
public int getCacheSize() {
if (cache != null) {
return cache.size();
}
return 0;
}
/**
* Reset and clears the 1st-level cache to force it to reload from file
*/
@ManagedOperation(description = "Reset and reloads the file store")
public synchronized void reset() throws IOException {
synchronized (cache) {
// run the cleanup task first
if (cache instanceof LRUCache) {
((LRUCache) cache).cleanUp();
}
cache.clear();
loadStore();
}
}
/**
* Checks the file store if the key exists
*
* @param key the key
* @return <tt>true</tt> if exists in the file, <tt>false</tt> otherwise
*/
protected boolean containsStore(final String key) {
if (fileStore == null || !fileStore.exists()) {
return false;
}
Scanner scanner = null;
try {
scanner = new Scanner(fileStore);
scanner.useDelimiter(STORE_DELIMITER);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals(key)) {
return true;
}
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
if (scanner != null) {
scanner.close();
}
}
return false;
}
/**
* Appends the given key to the file store
*
* @param key the key
*/
protected void appendToStore(final String key) {
LOG.debug("Appending: {} to idempotent filestore: {}", key, fileStore);
FileOutputStream fos = null;
try {
// create store parent directory if missing
File storeParentDirectory = fileStore.getParentFile();
if (storeParentDirectory != null && !storeParentDirectory.exists()) {
LOG.info("Parent directory of file store {} doesn't exist. Creating.", fileStore);
if (fileStore.getParentFile().mkdirs()) {
LOG.info("Parent directory of filestore: {} successfully created.", fileStore);
} else {
LOG.warn("Parent directory of filestore: {} cannot be created.", fileStore);
}
}
// create store if missing
if (!fileStore.exists()) {
FileUtil.createNewFile(fileStore);
}
// append to store
fos = new FileOutputStream(fileStore, true);
fos.write(key.getBytes());
fos.write(STORE_DELIMITER.getBytes());
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
IOHelper.close(fos, "Appending to file idempotent repository", LOG);
}
}
protected synchronized void removeFromStore(String key) {
LOG.debug("Removing: {} from idempotent filestore: {}", key, fileStore);
// we need to re-load the entire file and remove the key and then re-write the file
List<String> lines = new ArrayList<>();
boolean found = false;
Scanner scanner = null;
try {
scanner = new Scanner(fileStore);
scanner.useDelimiter(STORE_DELIMITER);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (key.equals(line)) {
found = true;
} else {
lines.add(line);
}
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
if (scanner != null) {
scanner.close();
}
}
if (found) {
// rewrite file
LOG.debug("Rewriting idempotent filestore: {} due to key: {} removed", fileStore, key);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileStore);
for (String line : lines) {
fos.write(line.getBytes());
fos.write(STORE_DELIMITER.getBytes());
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
IOHelper.close(fos, "Rewriting file idempotent repository", LOG);
}
}
}
/**
* Clears the file-store (danger this deletes all entries)
*/
protected void clearStore() {
try {
FileUtil.deleteFile(fileStore);
FileUtil.createNewFile(fileStore);
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
/**
* Trunks the file store when the max store size is hit by dropping the most oldest entries.
*/
protected synchronized void trunkStore() {
if (fileStore == null || !fileStore.exists()) {
return;
}
LOG.debug("Trunking: {} oldest entries from idempotent filestore: {}", dropOldestFileStore, fileStore);
// we need to re-load the entire file and remove the key and then re-write the file
List<String> lines = new ArrayList<>();
Scanner scanner = null;
int count = 0;
try {
scanner = new Scanner(fileStore);
scanner.useDelimiter(STORE_DELIMITER);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
count++;
if (count > dropOldestFileStore) {
lines.add(line);
}
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
if (scanner != null) {
scanner.close();
}
}
if (!lines.isEmpty()) {
// rewrite file
LOG.debug("Rewriting idempotent filestore: {} with {} entries:", fileStore, lines.size());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileStore);
for (String line : lines) {
fos.write(line.getBytes());
fos.write(STORE_DELIMITER.getBytes());
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
IOHelper.close(fos, "Rewriting file idempotent repository", LOG);
}
} else {
// its a small file so recreate the file
LOG.debug("Clearing idempotent filestore: {}", fileStore);
clearStore();
}
}
/**
* Cleanup the 1st-level cache.
*/
protected void cleanup() {
// run the cleanup task first
if (cache instanceof LRUCache) {
((LRUCache) cache).cleanUp();
}
}
/**
* Loads the given file store into the 1st level cache
*/
protected void loadStore() throws IOException {
// auto create starting directory if needed
if (!fileStore.exists()) {
LOG.debug("Creating filestore: {}", fileStore);
File parent = fileStore.getParentFile();
if (parent != null) {
parent.mkdirs();
}
boolean created = FileUtil.createNewFile(fileStore);
if (!created) {
throw new IOException("Cannot create filestore: " + fileStore);
}
}
LOG.trace("Loading to 1st level cache from idempotent filestore: {}", fileStore);
cache.clear();
Scanner scanner = null;
try {
scanner = new Scanner(fileStore);
scanner.useDelimiter(STORE_DELIMITER);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
cache.put(line, line);
}
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
if (scanner != null) {
scanner.close();
}
}
LOG.debug("Loaded {} to the 1st level cache from idempotent filestore: {}", cache.size(), fileStore);
}
@Override
@SuppressWarnings("unchecked")
protected void doStart() throws Exception {
ObjectHelper.notNull(fileStore, "fileStore", this);
if (this.cache == null) {
// default use a 1st level cache
this.cache = LRUCacheFactory.newLRUCache(1000);
}
// init store if not loaded before
if (init.compareAndSet(false, true)) {
loadStore();
}
}
@Override
protected void doStop() throws Exception {
// run the cleanup task first
if (cache instanceof LRUCache) {
((LRUCache) cache).cleanUp();
}
cache.clear();
init.set(false);
}
}