-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
JobSchedulerStoreImpl.java
1018 lines (902 loc) · 41.5 KB
/
JobSchedulerStoreImpl.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.activemq.store.kahadb.scheduler;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import org.apache.activemq.broker.scheduler.JobScheduler;
import org.apache.activemq.broker.scheduler.JobSchedulerStore;
import org.apache.activemq.protobuf.Buffer;
import org.apache.activemq.store.kahadb.AbstractKahaDBStore;
import org.apache.activemq.store.kahadb.JournalCommand;
import org.apache.activemq.store.kahadb.KahaDBMetaData;
import org.apache.activemq.store.kahadb.Visitor;
import org.apache.activemq.store.kahadb.data.KahaAddScheduledJobCommand;
import org.apache.activemq.store.kahadb.data.KahaDestroySchedulerCommand;
import org.apache.activemq.store.kahadb.data.KahaRemoveScheduledJobCommand;
import org.apache.activemq.store.kahadb.data.KahaRemoveScheduledJobsCommand;
import org.apache.activemq.store.kahadb.data.KahaRescheduleJobCommand;
import org.apache.activemq.store.kahadb.data.KahaTraceCommand;
import org.apache.activemq.store.kahadb.disk.index.BTreeVisitor;
import org.apache.activemq.store.kahadb.disk.journal.DataFile;
import org.apache.activemq.store.kahadb.disk.journal.Location;
import org.apache.activemq.store.kahadb.disk.page.Page;
import org.apache.activemq.store.kahadb.disk.page.PageFile;
import org.apache.activemq.store.kahadb.disk.page.Transaction;
import org.apache.activemq.store.kahadb.disk.util.VariableMarshaller;
import org.apache.activemq.store.kahadb.scheduler.legacy.LegacyStoreReplayer;
import org.apache.activemq.util.ByteSequence;
import org.apache.activemq.util.IOHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* @org.apache.xbean.XBean element="kahaDBJobScheduler"
*/
public class JobSchedulerStoreImpl extends AbstractKahaDBStore implements JobSchedulerStore {
private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreImpl.class);
private JobSchedulerKahaDBMetaData metaData = new JobSchedulerKahaDBMetaData(this);
private final MetaDataMarshaller metaDataMarshaller = new MetaDataMarshaller(this);
private final Map<String, JobSchedulerImpl> schedulers = new HashMap<String, JobSchedulerImpl>();
private File legacyStoreArchiveDirectory;
/**
* The Scheduler Token is used to identify base revisions of the Scheduler store. A store
* based on the initial scheduler design will not have this tag in it's meta-data and will
* indicate an update is needed. Later versions of the scheduler can also change this value
* to indicate incompatible store bases which require complete meta-data and journal rewrites
* instead of simpler meta-data updates.
*/
static final UUID SCHEDULER_STORE_TOKEN = UUID.fromString("57ed642b-1ee3-47b3-be6d-b7297d500409");
/**
* The default scheduler store version. All new store instance will be given this version and
* earlier versions will be updated to this version.
*/
static final int CURRENT_VERSION = 1;
@Override
public JobScheduler getJobScheduler(final String name) throws Exception {
this.indexLock.writeLock().lock();
try {
JobSchedulerImpl result = this.schedulers.get(name);
if (result == null) {
final JobSchedulerImpl js = new JobSchedulerImpl(this);
js.setName(name);
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
js.createIndexes(tx);
js.load(tx);
metaData.getJobSchedulers().put(tx, name, js);
}
});
result = js;
this.schedulers.put(name, js);
if (isStarted()) {
result.start();
}
this.pageFile.flush();
}
return result;
} finally {
this.indexLock.writeLock().unlock();
}
}
@Override
public boolean removeJobScheduler(final String name) throws Exception {
boolean result = false;
this.indexLock.writeLock().lock();
try {
final JobSchedulerImpl js = this.schedulers.remove(name);
result = js != null;
if (result) {
js.stop();
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
metaData.getJobSchedulers().remove(tx, name);
js.removeAll(tx);
}
});
}
} finally {
this.indexLock.writeLock().unlock();
}
return result;
}
/**
* Sets the directory where the legacy scheduler store files are archived before an
* update attempt is made. Both the legacy index files and the journal files are moved
* to this folder prior to an upgrade attempt.
*
* @param directory
* The directory to move the legacy Scheduler Store files to.
*/
public void setLegacyStoreArchiveDirectory(File directory) {
this.legacyStoreArchiveDirectory = directory;
}
/**
* Gets the directory where the legacy Scheduler Store files will be archived if the
* broker is started and an existing Job Scheduler Store from an old version is detected.
*
* @return the directory where scheduler store legacy files are archived on upgrade.
*/
public File getLegacyStoreArchiveDirectory() {
if (this.legacyStoreArchiveDirectory == null) {
this.legacyStoreArchiveDirectory = new File(getDirectory(), "legacySchedulerStore");
}
return this.legacyStoreArchiveDirectory.getAbsoluteFile();
}
@Override
public void load() throws IOException {
if (opened.compareAndSet(false, true)) {
getJournal().start();
try {
loadPageFile();
} catch (UnknownStoreVersionException ex) {
LOG.info("Can't start until store update is performed.");
upgradeFromLegacy();
// Restart with the updated store
getJournal().start();
loadPageFile();
LOG.info("Update from legacy Scheduler store completed successfully.");
} catch (Throwable t) {
LOG.warn("Index corrupted. Recovering the index through journal replay. Cause: {}", t.toString());
LOG.debug("Index load failure", t);
// try to recover index
try {
pageFile.unload();
} catch (Exception ignore) {
}
if (isArchiveCorruptedIndex()) {
pageFile.archive();
} else {
pageFile.delete();
}
metaData = new JobSchedulerKahaDBMetaData(this);
pageFile = null;
loadPageFile();
}
startCheckpoint();
recover();
}
LOG.info("{} started.", this);
}
@Override
public void unload() throws IOException {
if (opened.compareAndSet(true, false)) {
for (JobSchedulerImpl js : this.schedulers.values()) {
try {
js.stop();
} catch (Exception e) {
throw new IOException(e);
}
}
this.indexLock.writeLock().lock();
try {
if (pageFile != null && pageFile.isLoaded()) {
metaData.setState(KahaDBMetaData.CLOSED_STATE);
if (metaData.getPage() != null) {
pageFile.tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
tx.store(metaData.getPage(), metaDataMarshaller, true);
}
});
}
}
} finally {
this.indexLock.writeLock().unlock();
}
checkpointLock.writeLock().lock();
try {
if (metaData.getPage() != null) {
checkpointUpdate(getCleanupOnStop());
}
} finally {
checkpointLock.writeLock().unlock();
}
synchronized (checkpointThreadLock) {
if (checkpointThread != null) {
try {
checkpointThread.join();
checkpointThread = null;
} catch (InterruptedException e) {
}
}
}
if (pageFile != null) {
pageFile.unload();
pageFile = null;
}
if (this.journal != null) {
journal.close();
journal = null;
}
metaData = new JobSchedulerKahaDBMetaData(this);
}
LOG.info("{} stopped.", this);
}
private void loadPageFile() throws IOException {
this.indexLock.writeLock().lock();
try {
final PageFile pageFile = getPageFile();
pageFile.load();
pageFile.tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
if (pageFile.getPageCount() == 0) {
Page<JobSchedulerKahaDBMetaData> page = tx.allocate();
assert page.getPageId() == 0;
page.set(metaData);
metaData.setPage(page);
metaData.setState(KahaDBMetaData.CLOSED_STATE);
metaData.initialize(tx);
tx.store(metaData.getPage(), metaDataMarshaller, true);
} else {
Page<JobSchedulerKahaDBMetaData> page = null;
page = tx.load(0, metaDataMarshaller);
metaData = page.get();
metaData.setPage(page);
}
metaData.load(tx);
metaData.loadScheduler(tx, schedulers);
for (JobSchedulerImpl js : schedulers.values()) {
try {
js.start();
} catch (Exception e) {
JobSchedulerStoreImpl.LOG.error("Failed to load " + js.getName(), e);
}
}
}
});
pageFile.flush();
} finally {
this.indexLock.writeLock().unlock();
}
}
private void upgradeFromLegacy() throws IOException {
journal.close();
journal = null;
try {
pageFile.unload();
pageFile = null;
} catch (Exception ignore) {}
File storeDir = getDirectory().getAbsoluteFile();
File storeArchiveDir = getLegacyStoreArchiveDirectory();
LOG.info("Attempting to move old store files from {} to {}", storeDir, storeArchiveDir);
// Move only the known store files, locks and other items left in place.
IOHelper.moveFiles(storeDir, storeArchiveDir, new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".data") || name.endsWith(".redo") || name.endsWith(".log") || name.endsWith(".free")) {
return true;
}
return false;
}
});
// We reset everything to clean state, then we can read from the old
// scheduler store and replay the scheduled jobs into this one as adds.
getJournal().start();
metaData = new JobSchedulerKahaDBMetaData(this);
pageFile = null;
loadPageFile();
LegacyStoreReplayer replayer = new LegacyStoreReplayer(getLegacyStoreArchiveDirectory());
replayer.load();
replayer.startReplay(this);
// Cleanup after replay and store what we've done.
pageFile.tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
tx.store(metaData.getPage(), metaDataMarshaller, true);
}
});
checkpointUpdate(true);
getJournal().close();
getPageFile().unload();
}
@Override
protected void checkpointUpdate(Transaction tx, boolean cleanup) throws IOException {
LOG.debug("Job Scheduler Store Checkpoint started.");
// reflect last update exclusive of current checkpoint
Location lastUpdate = metaData.getLastUpdateLocation();
metaData.setState(KahaDBMetaData.OPEN_STATE);
tx.store(metaData.getPage(), metaDataMarshaller, true);
pageFile.flush();
if (cleanup) {
final TreeSet<Integer> completeFileSet = new TreeSet<Integer>(journal.getFileMap().keySet());
final TreeSet<Integer> gcCandidateSet = new TreeSet<Integer>(completeFileSet);
LOG.trace("Last update: {}, full gc candidates set: {}", lastUpdate, gcCandidateSet);
if (lastUpdate != null) {
gcCandidateSet.remove(lastUpdate.getDataFileId());
}
this.metaData.getJournalRC().visit(tx, new BTreeVisitor<Integer, Integer>() {
@Override
public void visit(List<Integer> keys, List<Integer> values) {
for (Integer key : keys) {
if (gcCandidateSet.remove(key)) {
LOG.trace("Removed referenced file: {} from GC set", key);
}
}
}
@Override
public boolean isInterestedInKeysBetween(Integer first, Integer second) {
return true;
}
});
LOG.trace("gc candidates after reference check: {}", gcCandidateSet);
// If there are GC candidates then check the remove command location to see
// if any of them can go or if they must stay in order to ensure proper recover.
//
// A log containing any remove commands must be kept until all the logs with the
// add commands for all the removed jobs have been dropped.
if (!gcCandidateSet.isEmpty()) {
Iterator<Entry<Integer, List<Integer>>> removals = metaData.getRemoveLocationTracker().iterator(tx);
List<Integer> orphans = new ArrayList<Integer>();
while (removals.hasNext()) {
boolean orphanedRemove = true;
Entry<Integer, List<Integer>> entry = removals.next();
// If this log is not a GC candidate then there's no need to do a check to rule it out
if (gcCandidateSet.contains(entry.getKey())) {
for (Integer addLocation : entry.getValue()) {
if (completeFileSet.contains(addLocation)) {
LOG.trace("A remove in log {} has an add still in existance in {}.", entry.getKey(), addLocation);
orphanedRemove = false;
break;
}
}
// If it's not orphaned than we can't remove it, otherwise we
// stop tracking it it's log will get deleted on the next check.
if (!orphanedRemove) {
gcCandidateSet.remove(entry.getKey());
} else {
LOG.trace("All removes in log {} are orphaned, file can be GC'd", entry.getKey());
orphans.add(entry.getKey());
}
}
}
// Drop all orphaned removes from the tracker.
for (Integer orphan : orphans) {
metaData.getRemoveLocationTracker().remove(tx, orphan);
}
}
LOG.trace("gc candidates after removals check: {}", gcCandidateSet);
if (!gcCandidateSet.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cleanup removing the data files: " + gcCandidateSet);
}
journal.removeDataFiles(gcCandidateSet);
}
}
LOG.debug("Job Scheduler Store Checkpoint complete.");
}
/**
* Adds a reference for the journal log file pointed to by the given Location value.
*
* To prevent log files in the journal that still contain valid data that needs to be
* kept in order to allow for recovery the logs must have active references. Each Job
* scheduler should ensure that the logs are accurately referenced.
*
* @param tx
* The TX under which the update is to be performed.
* @param location
* The location value to update the reference count of.
*
* @throws IOException if an error occurs while updating the journal references table.
*/
protected void incrementJournalCount(Transaction tx, Location location) throws IOException {
int logId = location.getDataFileId();
Integer val = metaData.getJournalRC().get(tx, logId);
int refCount = val != null ? val + 1 : 1;
metaData.getJournalRC().put(tx, logId, refCount);
}
/**
* Removes one reference for the Journal log file indicated in the given Location value.
*
* The references are used to track which log files cannot be GC'd. When the reference count
* on a log file reaches zero the file id is removed from the tracker and the log will be
* removed on the next check point update.
*
* @param tx
* The TX under which the update is to be performed.
* @param location
* The location value to update the reference count of.
*
* @throws IOException if an error occurs while updating the journal references table.
*/
protected void decrementJournalCount(Transaction tx, Location location) throws IOException {
int logId = location.getDataFileId();
Integer refCount = metaData.getJournalRC().get(tx, logId);
if (refCount != null) {
int refCountValue = refCount;
refCountValue--;
if (refCountValue <= 0) {
metaData.getJournalRC().remove(tx, logId);
} else {
metaData.getJournalRC().put(tx, logId, refCountValue);
}
}
}
/**
* Removes multiple references for the Journal log file indicated in the given Location map.
*
* The references are used to track which log files cannot be GC'd. When the reference count
* on a log file reaches zero the file id is removed from the tracker and the log will be
* removed on the next check point update.
*
* @param tx
* The TX under which the update is to be performed.
* @param decrementsByFileIds
* Map indicating how many decrements per fileId.
*
* @throws IOException if an error occurs while updating the journal references table.
*/
protected void decrementJournalCount(Transaction tx, HashMap<Integer, Integer> decrementsByFileIds) throws IOException {
for(Map.Entry<Integer, Integer> entry : decrementsByFileIds.entrySet()) {
int logId = entry.getKey();
Integer refCount = metaData.getJournalRC().get(tx, logId);
if (refCount != null) {
int refCountValue = refCount;
refCountValue -= entry.getValue();
if (refCountValue <= 0) {
metaData.getJournalRC().remove(tx, logId);
} else {
metaData.getJournalRC().put(tx, logId, refCountValue);
}
}
}
}
/**
* Updates the Job removal tracking index with the location of a remove command and the
* original JobLocation entry.
*
* The JobLocation holds the locations in the logs where the add and update commands for
* a job stored. The log file containing the remove command can only be discarded after
* both the add and latest update log files have also been discarded.
*
* @param tx
* The TX under which the update is to be performed.
* @param location
* The location value to reference a remove command.
* @param removedJob
* The original JobLocation instance that holds the add and update locations
*
* @throws IOException if an error occurs while updating the remove location tracker.
*/
protected void referenceRemovedLocation(Transaction tx, Location location, JobLocation removedJob) throws IOException {
int logId = location.getDataFileId();
List<Integer> removed = this.metaData.getRemoveLocationTracker().get(tx, logId);
if (removed == null) {
removed = new ArrayList<Integer>();
}
removed.add(removedJob.getLocation().getDataFileId());
this.metaData.getRemoveLocationTracker().put(tx, logId, removed);
}
/**
* Updates the Job removal tracking index with the location of a remove command and the
* original JobLocation entry.
*
* The JobLocation holds the locations in the logs where the add and update commands for
* a job stored. The log file containing the remove command can only be discarded after
* both the add and latest update log files have also been discarded.
*
* @param tx
* The TX under which the update is to be performed.
* @param location
* The location value to reference a remove command.
* @param removedJobsFileId
* List of the original JobLocation instances that holds the add and update locations
*
* @throws IOException if an error occurs while updating the remove location tracker.
*/
protected void referenceRemovedLocation(Transaction tx, Location location, List<Integer> removedJobsFileId) throws IOException {
int logId = location.getDataFileId();
List<Integer> removed = this.metaData.getRemoveLocationTracker().get(tx, logId);
if (removed == null) {
removed = new ArrayList<Integer>();
}
removed.addAll(removedJobsFileId);
this.metaData.getRemoveLocationTracker().put(tx, logId, removed);
}
/**
* Retrieve the scheduled Job's byte blob from the journal.
*
* @param location
* The location of the KahaAddScheduledJobCommand that originated the Job.
*
* @return a ByteSequence containing the payload of the scheduled Job.
*
* @throws IOException if an error occurs while reading the payload value.
*/
protected ByteSequence getPayload(Location location) throws IOException {
KahaAddScheduledJobCommand job = (KahaAddScheduledJobCommand) this.load(location);
Buffer payload = job.getPayload();
return new ByteSequence(payload.getData(), payload.getOffset(), payload.getLength());
}
public void readLockIndex() {
this.indexLock.readLock().lock();
}
public void readUnlockIndex() {
this.indexLock.readLock().unlock();
}
public void writeLockIndex() {
this.indexLock.writeLock().lock();
}
public void writeUnlockIndex() {
this.indexLock.writeLock().unlock();
}
@Override
public String toString() {
return "JobSchedulerStore: " + getDirectory();
}
@Override
protected String getPageFileName() {
return "scheduleDB";
}
@Override
protected File getDefaultDataDirectory() {
return new File(IOHelper.getDefaultDataDirectory(), "delayedDB");
}
private class MetaDataMarshaller extends VariableMarshaller<JobSchedulerKahaDBMetaData> {
private final JobSchedulerStoreImpl store;
MetaDataMarshaller(JobSchedulerStoreImpl store) {
this.store = store;
}
@Override
public JobSchedulerKahaDBMetaData readPayload(DataInput dataIn) throws IOException {
JobSchedulerKahaDBMetaData rc = new JobSchedulerKahaDBMetaData(store);
rc.read(dataIn);
return rc;
}
@Override
public void writePayload(JobSchedulerKahaDBMetaData object, DataOutput dataOut) throws IOException {
object.write(dataOut);
}
}
/**
* Called during index recovery to rebuild the index from the last known good location. For
* entries that occur before the last known good position we just ignore then and move on.
*
* @param data
* the command read from the Journal which should be used to update the index.
* @param location
* the location in the index where the command was read.
* @param inDoubtlocation
* the location in the index known to be the last time the index was valid.
*
* @throws IOException if an error occurs while recovering the index.
*/
protected void doRecover(JournalCommand<?> data, final Location location, final Location inDoubtlocation) throws IOException {
if (inDoubtlocation != null && location.compareTo(inDoubtlocation) >= 0) {
process(data, location);
}
}
/**
* Called during recovery to allow the store to rebuild from scratch.
*
* @param data
* The command to process, which was read from the Journal.
* @param location
* The location of the command in the Journal.
*
* @throws IOException if an error occurs during command processing.
*/
@Override
protected void process(JournalCommand<?> data, final Location location) throws IOException {
data.visit(new Visitor() {
@Override
public void visit(final KahaAddScheduledJobCommand command) throws IOException {
final JobSchedulerImpl scheduler;
indexLock.writeLock().lock();
try {
try {
scheduler = (JobSchedulerImpl) getJobScheduler(command.getScheduler());
} catch (Exception e) {
throw new IOException(e);
}
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
scheduler.process(tx, command, location);
}
});
processLocation(location);
} finally {
indexLock.writeLock().unlock();
}
}
@Override
public void visit(final KahaRemoveScheduledJobCommand command) throws IOException {
final JobSchedulerImpl scheduler;
indexLock.writeLock().lock();
try {
try {
scheduler = (JobSchedulerImpl) getJobScheduler(command.getScheduler());
} catch (Exception e) {
throw new IOException(e);
}
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
scheduler.process(tx, command, location);
}
});
processLocation(location);
} finally {
indexLock.writeLock().unlock();
}
}
@Override
public void visit(final KahaRemoveScheduledJobsCommand command) throws IOException {
final JobSchedulerImpl scheduler;
indexLock.writeLock().lock();
try {
try {
scheduler = (JobSchedulerImpl) getJobScheduler(command.getScheduler());
} catch (Exception e) {
throw new IOException(e);
}
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
scheduler.process(tx, command, location);
}
});
processLocation(location);
} finally {
indexLock.writeLock().unlock();
}
}
@Override
public void visit(final KahaRescheduleJobCommand command) throws IOException {
final JobSchedulerImpl scheduler;
indexLock.writeLock().lock();
try {
try {
scheduler = (JobSchedulerImpl) getJobScheduler(command.getScheduler());
} catch (Exception e) {
throw new IOException(e);
}
getPageFile().tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
scheduler.process(tx, command, location);
}
});
processLocation(location);
} finally {
indexLock.writeLock().unlock();
}
}
@Override
public void visit(final KahaDestroySchedulerCommand command) {
try {
removeJobScheduler(command.getScheduler());
} catch (Exception e) {
LOG.warn("Failed to remove scheduler: {}", command.getScheduler());
}
processLocation(location);
}
@Override
public void visit(KahaTraceCommand command) {
processLocation(location);
}
});
}
protected void processLocation(final Location location) {
indexLock.writeLock().lock();
try {
this.metaData.setLastUpdateLocation(location);
} finally {
indexLock.writeLock().unlock();
}
}
/**
* We recover from the Journal logs as needed to restore the index.
*
* @throws IllegalStateException
* @throws IOException
*/
private void recover() throws IllegalStateException, IOException {
this.indexLock.writeLock().lock();
try {
long start = System.currentTimeMillis();
Location lastIndoubtPosition = getRecoveryPosition();
Location recoveryPosition = lastIndoubtPosition;
if (recoveryPosition != null) {
int redoCounter = 0;
LOG.info("Recovering from the scheduled job journal @" + recoveryPosition);
while (recoveryPosition != null) {
try {
JournalCommand<?> message = load(recoveryPosition);
metaData.setLastUpdateLocation(recoveryPosition);
doRecover(message, recoveryPosition, lastIndoubtPosition);
redoCounter++;
} catch (IOException failedRecovery) {
if (isIgnoreMissingJournalfiles()) {
LOG.debug("Failed to recover data at position:" + recoveryPosition, failedRecovery);
// track this dud location
journal.corruptRecoveryLocation(recoveryPosition);
} else {
throw new IOException("Failed to recover data at position:" + recoveryPosition, failedRecovery);
}
}
recoveryPosition = journal.getNextLocation(recoveryPosition);
if (LOG.isInfoEnabled() && redoCounter % 100000 == 0) {
LOG.info("@ {}, {} entries recovered ..", recoveryPosition, redoCounter);
}
}
long end = System.currentTimeMillis();
LOG.info("Recovery replayed {} operations from the journal in {} seconds.",
redoCounter, ((end - start) / 1000.0f));
}
// We may have to undo some index updates.
pageFile.tx().execute(new Transaction.Closure<IOException>() {
@Override
public void execute(Transaction tx) throws IOException {
recoverIndex(tx);
}
});
} finally {
this.indexLock.writeLock().unlock();
}
}
private Location getRecoveryPosition() throws IOException {
// This loads the first position and we completely rebuild the index if we
// do not override it with some known recovery start location.
Location result = null;
if (!isForceRecoverIndex()) {
if (metaData.getLastUpdateLocation() != null) {
result = metaData.getLastUpdateLocation();
}
}
return journal.getNextLocation(result);
}
private void recoverIndex(Transaction tx) throws IOException {
long start = System.currentTimeMillis();
// It is possible index updates got applied before the journal updates..
// in that case we need to removed references to Jobs that are not in the journal
final Location lastAppendLocation = journal.getLastAppendLocation();
long undoCounter = 0;
// Go through all the jobs in each scheduler and check if any are added after
// the last appended location and remove those. For now we ignore the update
// location since the scheduled job will update itself after the next fire and
// a new update will replace any existing update.
for (Iterator<Map.Entry<String, JobSchedulerImpl>> i = metaData.getJobSchedulers().iterator(tx); i.hasNext();) {
Map.Entry<String, JobSchedulerImpl> entry = i.next();
JobSchedulerImpl scheduler = entry.getValue();
for (Iterator<JobLocation> jobLocationIterator = scheduler.getAllScheduledJobs(tx); jobLocationIterator.hasNext();) {
final JobLocation job = jobLocationIterator.next();
if (job.getLocation().compareTo(lastAppendLocation) >= 0) {
if (scheduler.removeJobAtTime(tx, job.getJobId(), job.getNextTime())) {
LOG.trace("Removed Job past last appened in the journal: {}", job.getJobId());
undoCounter++;
}
}
}
}
if (undoCounter > 0) {
// The rolled back operations are basically in flight journal writes. To avoid getting
// these the end user should do sync writes to the journal.
long end = System.currentTimeMillis();
LOG.info("Rolled back {} messages from the index in {} seconds.", undoCounter, ((end - start) / 1000.0f));
undoCounter = 0;
}
// Now we check for missing and corrupt journal files.
// 1. Collect the set of all referenced journal files based on the Location of the
// the scheduled jobs and the marked last update field.
HashSet<Integer> missingJournalFiles = new HashSet<Integer>();
for (Iterator<Map.Entry<String, JobSchedulerImpl>> i = metaData.getJobSchedulers().iterator(tx); i.hasNext();) {
Map.Entry<String, JobSchedulerImpl> entry = i.next();
JobSchedulerImpl scheduler = entry.getValue();
for (Iterator<JobLocation> jobLocationIterator = scheduler.getAllScheduledJobs(tx); jobLocationIterator.hasNext();) {
final JobLocation job = jobLocationIterator.next();
missingJournalFiles.add(job.getLocation().getDataFileId());
if (job.getLastUpdate() != null) {
missingJournalFiles.add(job.getLastUpdate().getDataFileId());
}
}
}
// 2. Remove from that set all known data file Id's in the journal and what's left
// is the missing set which will soon also contain the corrupted set.
missingJournalFiles.removeAll(journal.getFileMap().keySet());
if (!missingJournalFiles.isEmpty()) {
LOG.info("Some journal files are missing: {}", missingJournalFiles);
}
// 3. Now check all references in the journal logs for corruption and add any
// corrupt journal files to the missing set.
HashSet<Location> corruptedLocations = new HashSet<Location>();
if (isCheckForCorruptJournalFiles()) {
Collection<DataFile> dataFiles = journal.getFileMap().values();
for (DataFile dataFile : dataFiles) {
int id = dataFile.getDataFileId();
for (long offset : dataFile.getCorruptedBlocks()) {
corruptedLocations.add(new Location(id, (int) offset));
}
}
if (!corruptedLocations.isEmpty()) {
LOG.debug("Found some corrupted data blocks in the journal: {}", corruptedLocations.size());
}
}
// 4. Now we either fail or we remove all references to missing or corrupt journal
// files from the various JobSchedulerImpl instances. We only remove the Job if
// the initial Add operation is missing when the ignore option is set, the updates
// could be lost but that's price you pay when ignoring the missing logs.
if (!missingJournalFiles.isEmpty() || !corruptedLocations.isEmpty()) {
if (!isIgnoreMissingJournalfiles()) {
throw new IOException("Detected missing/corrupt journal files.");
}
// Remove all Jobs that reference an Location that is either missing or corrupt.
undoCounter = removeJobsInMissingOrCorruptJounralFiles(tx, missingJournalFiles, corruptedLocations);
// Clean up the Journal Reference count Map.
removeJournalRCForMissingFiles(tx, missingJournalFiles);
}
if (undoCounter > 0) {
long end = System.currentTimeMillis();
LOG.info("Detected missing/corrupt journal files. Dropped {} jobs from the " +
"index in {} seconds.", undoCounter, ((end - start) / 1000.0f));
}
}
private void removeJournalRCForMissingFiles(Transaction tx, Set<Integer> missing) throws IOException {
List<Integer> matches = new ArrayList<Integer>();
Iterator<Entry<Integer, Integer>> references = metaData.getJournalRC().iterator(tx);
while (references.hasNext()) {
int dataFileId = references.next().getKey();
if (missing.contains(dataFileId)) {
matches.add(dataFileId);
}
}
for (Integer match : matches) {
metaData.getJournalRC().remove(tx, match);
}
}
private int removeJobsInMissingOrCorruptJounralFiles(Transaction tx, Set<Integer> missing, Set<Location> corrupted) throws IOException {
int removed = 0;
// Remove Jobs that reference missing or corrupt files.
// Remove Reference counts to missing or corrupt files.
// Remove and remove command markers to missing or corrupt files.
for (Iterator<Map.Entry<String, JobSchedulerImpl>> i = metaData.getJobSchedulers().iterator(tx); i.hasNext();) {
Map.Entry<String, JobSchedulerImpl> entry = i.next();
JobSchedulerImpl scheduler = entry.getValue();
for (Iterator<JobLocation> jobLocationIterator = scheduler.getAllScheduledJobs(tx); jobLocationIterator.hasNext();) {
final JobLocation job = jobLocationIterator.next();