View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.procedure2.store.wal;
20  
21  import com.google.protobuf.InvalidProtocolBufferException;
22  
23  import java.io.IOException;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.fs.FSDataInputStream;
28  import org.apache.hadoop.hbase.ProcedureInfo;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.classification.InterfaceStability;
31  import org.apache.hadoop.hbase.procedure2.Procedure;
32  import org.apache.hadoop.hbase.procedure2.store.ProcedureStore.ProcedureIterator;
33  import org.apache.hadoop.hbase.procedure2.store.ProcedureStoreTracker;
34  import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos;
35  import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos.ProcedureWALEntry;
36  
37  /**
38   * Helper class that loads the procedures stored in a WAL
39   */
40  @InterfaceAudience.Private
41  @InterfaceStability.Evolving
42  public class ProcedureWALFormatReader {
43    private static final Log LOG = LogFactory.getLog(ProcedureWALFormatReader.class);
44  
45    // ==============================================================================================
46    //  We read the WALs in reverse order. from the newest to the oldest.
47    //  We have different entry types:
48    //   - INIT: Procedure submitted by the user (also known as 'root procedure')
49    //   - INSERT: Children added to the procedure <parentId>:[<childId>, ...]
50    //   - UPDATE: The specified procedure was updated
51    //   - DELETE: The procedure was removed (completed/rolledback and result TTL expired)
52    //
53    // In the WAL we can find multiple times the same procedure as UPDATE or INSERT.
54    // We read the WAL from top to bottom, so every time we find an entry of the
55    // same procedure, that will be the "latest" update.
56    //
57    // We keep two in-memory maps:
58    //  - localProcedureMap: is the map containing the entries in the WAL we are processing
59    //  - procedureMap: is the map containing all the procedures we found up to the WAL in process.
60    // localProcedureMap is merged with the procedureMap once we reach the WAL EOF.
61    //
62    // Since we are reading the WALs in reverse order (newest to oldest),
63    // if we find an entry related to a procedure we already have in 'procedureMap' we can discard it.
64    //
65    // The WAL is append-only so the last procedure in the WAL is the one that
66    // was in execution at the time we crashed/closed the server.
67    // given that, the procedure replay order can be inferred by the WAL order.
68    //
69    // Example:
70    //    WAL-2: [A, B, A, C, D]
71    //    WAL-1: [F, G, A, F, B]
72    //    Replay-Order: [D, C, A, B, F, G]
73    //
74    // The "localProcedureMap" keeps a "replayOrder" list. Every time we add the
75    // record to the map that record is moved to the head of the "replayOrder" list.
76    // Using the example above:
77    //    WAL-2 localProcedureMap.replayOrder is [D, C, A, B]
78    //    WAL-1 localProcedureMap.replayOrder is [F, G]
79    //
80    // each time we reach the WAL-EOF, the "replayOrder" list is merged/appended in 'procedureMap'
81    // so using the example above we end up with: [D, C, A, B] + [F, G] as replay order.
82    //
83    //  Fast Start: INIT/INSERT record and StackIDs
84    // ---------------------------------------------
85    // We have two special record, INIT and INSERT that tracks the first time
86    // the procedure was added to the WAL. We can use that information to be able
87    // to start procedures before reaching the end of the WAL, or before reading all the WALs.
88    // but in some cases the WAL with that record can be already gone.
89    // In alternative we can use the stackIds on each procedure,
90    // to identify when a procedure is ready to start.
91    // If there are gaps in the sum of the stackIds we need to read more WALs.
92    //
93    // Example (all procs child of A):
94    //   WAL-2: [A, B]                   A stackIds = [0, 4], B stackIds = [1, 5]
95    //   WAL-1: [A, B, C, D]
96    //
97    // In the case above we need to read one more WAL to be able to consider
98    // the root procedure A and all children as ready.
99    // ==============================================================================================
100   private final WalProcedureMap localProcedureMap = new WalProcedureMap(1024);
101   private final WalProcedureMap procedureMap = new WalProcedureMap(1024);
102 
103   //private long compactionLogId;
104   private long maxProcId = 0;
105 
106   private final ProcedureStoreTracker tracker;
107   private final boolean hasFastStartSupport;
108 
109   public ProcedureWALFormatReader(final ProcedureStoreTracker tracker) {
110     this.tracker = tracker;
111     // we support fast-start only if we have a clean shutdown.
112     this.hasFastStartSupport = !tracker.isEmpty();
113   }
114 
115   public void read(ProcedureWALFile log, ProcedureWALFormat.Loader loader) throws IOException {
116     FSDataInputStream stream = log.getStream();
117     try {
118       boolean hasMore = true;
119       while (hasMore) {
120         ProcedureWALEntry entry = ProcedureWALFormat.readEntry(stream);
121         if (entry == null) {
122           LOG.warn("nothing left to decode. exiting with missing EOF");
123           hasMore = false;
124           break;
125         }
126         switch (entry.getType()) {
127           case PROCEDURE_WAL_INIT:
128             readInitEntry(entry);
129             break;
130           case PROCEDURE_WAL_INSERT:
131             readInsertEntry(entry);
132             break;
133           case PROCEDURE_WAL_UPDATE:
134           case PROCEDURE_WAL_COMPACT:
135             readUpdateEntry(entry);
136             break;
137           case PROCEDURE_WAL_DELETE:
138             readDeleteEntry(entry);
139             break;
140           case PROCEDURE_WAL_EOF:
141             hasMore = false;
142             break;
143           default:
144             throw new CorruptedWALProcedureStoreException("Invalid entry: " + entry);
145         }
146       }
147     } catch (InvalidProtocolBufferException e) {
148       LOG.error("got an exception while reading the procedure WAL: " + log, e);
149       loader.markCorruptedWAL(log, e);
150     }
151 
152     if (!localProcedureMap.isEmpty()) {
153       log.setProcIds(localProcedureMap.getMinProcId(), localProcedureMap.getMaxProcId());
154       procedureMap.mergeTail(localProcedureMap);
155       //if (hasFastStartSupport) {
156         // TODO: Some procedure may be already runnables (see readInitEntry())
157         //       (we can also check the "update map" in the log trackers)
158         // --------------------------------------------------
159         //EntryIterator iter = procedureMap.fetchReady();
160         //if (iter != null) loader.load(iter);
161         // --------------------------------------------------
162       //}
163     }
164   }
165 
166   public void finalize(ProcedureWALFormat.Loader loader) throws IOException {
167     // notify the loader about the max proc ID
168     loader.setMaxProcId(maxProcId);
169 
170     // fetch the procedure ready to run.
171     ProcedureIterator procIter = procedureMap.fetchReady();
172     if (procIter != null) loader.load(procIter);
173 
174     // remaining procedures have missing link or dependencies
175     // consider them as corrupted, manual fix is probably required.
176     procIter = procedureMap.fetchAll();
177     if (procIter != null) loader.handleCorrupted(procIter);
178   }
179 
180   private void loadProcedure(final ProcedureWALEntry entry, final ProcedureProtos.Procedure proc) {
181     maxProcId = Math.max(maxProcId, proc.getProcId());
182     if (isRequired(proc.getProcId())) {
183       if (LOG.isTraceEnabled()) {
184         LOG.trace("read " + entry.getType() + " entry " + proc.getProcId());
185       }
186       localProcedureMap.add(proc);
187       tracker.setDeleted(proc.getProcId(), false);
188     }
189   }
190 
191   private void readInitEntry(final ProcedureWALEntry entry)
192       throws IOException {
193     assert entry.getProcedureCount() == 1 : "Expected only one procedure";
194     loadProcedure(entry, entry.getProcedure(0));
195   }
196 
197   private void readInsertEntry(final ProcedureWALEntry entry) throws IOException {
198     assert entry.getProcedureCount() >= 1 : "Expected one or more procedures";
199     loadProcedure(entry, entry.getProcedure(0));
200     for (int i = 1; i < entry.getProcedureCount(); ++i) {
201       loadProcedure(entry, entry.getProcedure(i));
202     }
203   }
204 
205   private void readUpdateEntry(final ProcedureWALEntry entry) throws IOException {
206     assert entry.getProcedureCount() == 1 : "Expected only one procedure";
207     loadProcedure(entry, entry.getProcedure(0));
208   }
209 
210   private void readDeleteEntry(final ProcedureWALEntry entry) throws IOException {
211     assert entry.hasProcId() : "expected ProcID";
212 
213     if (entry.getChildIdCount() > 0) {
214       assert entry.getProcedureCount() == 1 : "Expected only one procedure";
215 
216       // update the parent procedure
217       loadProcedure(entry, entry.getProcedure(0));
218 
219       // remove the child procedures of entry.getProcId()
220       for (int i = 0, count = entry.getChildIdCount(); i < count; ++i) {
221         deleteEntry(entry.getChildId(i));
222       }
223     } else {
224       assert entry.getProcedureCount() == 0 : "Expected no procedures";
225 
226       // delete the procedure
227       deleteEntry(entry.getProcId());
228     }
229   }
230 
231   private void deleteEntry(final long procId) {
232     if (LOG.isTraceEnabled()) {
233       LOG.trace("delete entry " + procId);
234     }
235     maxProcId = Math.max(maxProcId, procId);
236     localProcedureMap.remove(procId);
237     assert !procedureMap.contains(procId);
238     tracker.setDeleted(procId, true);
239   }
240 
241   private boolean isDeleted(final long procId) {
242     return tracker.isDeleted(procId) == ProcedureStoreTracker.DeleteState.YES;
243   }
244 
245   private boolean isRequired(final long procId) {
246     return !isDeleted(procId) && !procedureMap.contains(procId);
247   }
248 
249   // ==========================================================================
250   //  We keep an in-memory map of the procedures sorted by replay order.
251   //  (see the details in the beginning of the file)
252   //                      _______________________________________________
253   //      procedureMap = | A |   | E |   | C |   |   |   |   | G |   |   |
254   //                       D               B
255   //      replayOrderHead = C <-> B <-> E <-> D <-> A <-> G
256   //
257   //  We also have a lazy grouping by "root procedure", and a list of
258   //  unlinked procedure. If after reading all the WALs we have unlinked
259   //  procedures it means that we had a missing WAL or a corruption.
260   //      rootHead = A <-> D <-> G
261   //                 B     E
262   //                 C
263   //      unlinkFromLinkList = None
264   // ==========================================================================
265   private static class Entry {
266     // hash-table next
267     protected Entry hashNext;
268     // child head
269     protected Entry childHead;
270     // double-link for rootHead or childHead
271     protected Entry linkNext;
272     protected Entry linkPrev;
273     // replay double-linked-list
274     protected Entry replayNext;
275     protected Entry replayPrev;
276     // procedure-infos
277     protected Procedure procedure;
278     protected ProcedureProtos.Procedure proto;
279     protected boolean ready = false;
280 
281     public Entry(Entry hashNext) { this.hashNext = hashNext; }
282 
283     public long getProcId() { return proto.getProcId(); }
284     public long getParentId() { return proto.getParentId(); }
285     public boolean hasParent() { return proto.hasParentId(); }
286     public boolean isReady() { return ready; }
287 
288     public boolean isCompleted() {
289       if (!hasParent()) {
290         // we only consider 'root' procedures. because for the user 'completed'
291         // means when everything up to the 'root' is complete.
292         switch (proto.getState()) {
293           case ROLLEDBACK:
294             return true;
295           case FINISHED:
296             return !proto.hasException();
297           default:
298             break;
299         }
300       }
301       return false;
302     }
303 
304     public Procedure convert() throws IOException {
305       if (procedure == null) {
306         procedure = Procedure.convert(proto);
307       }
308       return procedure;
309     }
310 
311     public ProcedureInfo convertToInfo() {
312       return ProcedureInfo.convert(proto);
313     }
314 
315     @Override
316     public String toString() {
317       final StringBuilder sb = new StringBuilder();
318       sb.append("Entry(");
319       sb.append(getProcId());
320       sb.append(", parentId=");
321       sb.append(getParentId());
322       sb.append(", class=");
323       sb.append(proto.getClassName());
324       sb.append(")");
325       return sb.toString();
326     }
327   }
328 
329   private static class EntryIterator implements ProcedureIterator {
330     private final Entry replayHead;
331     private Entry current;
332 
333     public EntryIterator(Entry replayHead) {
334       this.replayHead = replayHead;
335       this.current = replayHead;
336     }
337 
338     @Override
339     public void reset() {
340       this.current = replayHead;
341     }
342 
343     @Override
344     public boolean hasNext() {
345       return current != null;
346     }
347 
348     @Override
349     public boolean isNextCompleted() {
350       return current != null && current.isCompleted();
351     }
352 
353     @Override
354     public void skipNext() {
355       current = current.replayNext;
356     }
357 
358     @Override
359     public Procedure nextAsProcedure() throws IOException {
360       try {
361         return current.convert();
362       } finally {
363         current = current.replayNext;
364       }
365     }
366 
367     @Override
368     public ProcedureInfo nextAsProcedureInfo() {
369       try {
370         return current.convertToInfo();
371       } finally {
372         current = current.replayNext;
373       }
374     }
375   }
376 
377   private static class WalProcedureMap {
378     // procedure hash table
379     private Entry[] procedureMap;
380 
381     // replay-order double-linked-list
382     private Entry replayOrderHead;
383     private Entry replayOrderTail;
384 
385     // root linked-list
386     private Entry rootHead;
387 
388     // pending unlinked children (root not present yet)
389     private Entry childUnlinkedHead;
390 
391     // Track ProcId range
392     private long minProcId = Long.MAX_VALUE;
393     private long maxProcId = Long.MIN_VALUE;
394 
395     public WalProcedureMap(int size) {
396       procedureMap = new Entry[size];
397       replayOrderHead = null;
398       replayOrderTail = null;
399       rootHead = null;
400       childUnlinkedHead = null;
401     }
402 
403     public void add(ProcedureProtos.Procedure procProto) {
404       trackProcIds(procProto.getProcId());
405       Entry entry = addToMap(procProto.getProcId(), procProto.hasParentId());
406       boolean isNew = entry.proto == null;
407       entry.proto = procProto;
408       addToReplayList(entry);
409 
410       if (isNew) {
411         if (procProto.hasParentId()) {
412           childUnlinkedHead = addToLinkList(entry, childUnlinkedHead);
413         } else {
414           rootHead = addToLinkList(entry, rootHead);
415         }
416       }
417     }
418 
419     public boolean remove(long procId) {
420       trackProcIds(procId);
421       Entry entry = removeFromMap(procId);
422       if (entry != null) {
423         unlinkFromReplayList(entry);
424         unlinkFromLinkList(entry);
425         return true;
426       }
427       return false;
428     }
429 
430     private void trackProcIds(long procId) {
431       minProcId = Math.min(minProcId, procId);
432       maxProcId = Math.max(maxProcId, procId);
433     }
434 
435     public long getMinProcId() {
436       return minProcId;
437     }
438 
439     public long getMaxProcId() {
440       return maxProcId;
441     }
442 
443     public boolean contains(long procId) {
444       return getProcedure(procId) != null;
445     }
446 
447     public boolean isEmpty() {
448       return replayOrderHead == null;
449     }
450 
451     public void clear() {
452       for (int i = 0; i < procedureMap.length; ++i) {
453         procedureMap[i] = null;
454       }
455       replayOrderHead = null;
456       replayOrderTail = null;
457       rootHead = null;
458       childUnlinkedHead = null;
459       minProcId = Long.MAX_VALUE;
460       maxProcId = Long.MIN_VALUE;
461     }
462 
463     /*
464      * Merges two WalProcedureMap,
465      * the target is the "global" map, the source is the "local" map.
466      *  - The entries in the hashtables are guaranteed to be unique.
467      *    On replay we don't load procedures that already exist in the "global"
468      *    map (the one we are merging the "local" in to).
469      *  - The replayOrderList of the "local" nao will be appended to the "global"
470      *    map replay list.
471      *  - The "local" map will be cleared at the end of the operation.
472      */
473     public void mergeTail(WalProcedureMap other) {
474       for (Entry p = other.replayOrderHead; p != null; p = p.replayNext) {
475         int slotIndex = getMapSlot(p.getProcId());
476         p.hashNext = procedureMap[slotIndex];
477         procedureMap[slotIndex] = p;
478       }
479 
480       if (replayOrderHead == null) {
481         replayOrderHead = other.replayOrderHead;
482         replayOrderTail = other.replayOrderTail;
483         rootHead = other.rootHead;
484         childUnlinkedHead = other.childUnlinkedHead;
485       } else {
486         // append replay list
487         assert replayOrderTail.replayNext == null;
488         assert other.replayOrderHead.replayPrev == null;
489         replayOrderTail.replayNext = other.replayOrderHead;
490         other.replayOrderHead.replayPrev = replayOrderTail;
491         replayOrderTail = other.replayOrderTail;
492 
493         // merge rootHead
494         if (rootHead == null) {
495           rootHead = other.rootHead;
496         } else if (other.rootHead != null) {
497           Entry otherTail = findLinkListTail(other.rootHead);
498           otherTail.linkNext = rootHead;
499           rootHead.linkPrev = otherTail;
500           rootHead = other.rootHead;
501         }
502 
503         // merge childUnlinkedHead
504         if (childUnlinkedHead == null) {
505           childUnlinkedHead = other.childUnlinkedHead;
506         } else if (other.childUnlinkedHead != null) {
507           Entry otherTail = findLinkListTail(other.childUnlinkedHead);
508           otherTail.linkNext = childUnlinkedHead;
509           childUnlinkedHead.linkPrev = otherTail;
510           childUnlinkedHead = other.childUnlinkedHead;
511         }
512       }
513 
514       other.clear();
515     }
516 
517     /*
518      * Returns an EntryIterator with the list of procedures ready
519      * to be added to the executor.
520      * A Procedure is ready if its children and parent are ready.
521      */
522     public EntryIterator fetchReady() {
523       buildGraph();
524 
525       Entry readyHead = null;
526       Entry readyTail = null;
527       Entry p = replayOrderHead;
528       while (p != null) {
529         Entry next = p.replayNext;
530         if (p.isReady()) {
531           unlinkFromReplayList(p);
532           if (readyTail != null) {
533             readyTail.replayNext = p;
534             p.replayPrev = readyTail;
535           } else {
536             p.replayPrev = null;
537             readyHead = p;
538           }
539           readyTail = p;
540           p.replayNext = null;
541         }
542         p = next;
543       }
544       // we need the hash-table lookups for parents, so this must be done
545       // out of the loop where we check isReadyToRun()
546       for (p = readyHead; p != null; p = p.replayNext) {
547         removeFromMap(p.getProcId());
548         unlinkFromLinkList(p);
549       }
550       return readyHead != null ? new EntryIterator(readyHead) : null;
551     }
552 
553     /*
554      * Drain this map and return all procedures in it.
555      */
556     public EntryIterator fetchAll() {
557       Entry head = replayOrderHead;
558       for (Entry p = head; p != null; p = p.replayNext) {
559         removeFromMap(p.getProcId());
560       }
561       for (int i = 0; i < procedureMap.length; ++i) {
562         assert procedureMap[i] == null : "map not empty i=" + i;
563       }
564       replayOrderHead = null;
565       replayOrderTail = null;
566       childUnlinkedHead = null;
567       rootHead = null;
568       return head != null ? new EntryIterator(head) : null;
569     }
570 
571     private void buildGraph() {
572       Entry p = childUnlinkedHead;
573       while (p != null) {
574         Entry next = p.linkNext;
575         Entry rootProc = getRootProcedure(p);
576         if (rootProc != null) {
577           rootProc.childHead = addToLinkList(p, rootProc.childHead);
578         }
579         p = next;
580       }
581 
582       for (p = rootHead; p != null; p = p.linkNext) {
583         checkReadyToRun(p);
584       }
585     }
586 
587     private Entry getRootProcedure(Entry entry) {
588       while (entry != null && entry.hasParent()) {
589         entry = getProcedure(entry.getParentId());
590       }
591       return entry;
592     }
593 
594     /*
595      * (see the comprehensive explaination in the beginning of the file)
596      * A Procedure is ready when parent and children are ready.
597      * "ready" means that we all the information that we need in-memory.
598      *
599      * Example-1:
600      * We have two WALs, we start reading fronm the newest (wal-2)
601      *    wal-2 | C B |
602      *    wal-1 | A B C |
603      *
604      * If C and B don't depend on A (A is not the parent), we can start them
605      * before reading wal-1. If B is the only one with parent A we can start C
606      * and read one more WAL before being able to start B.
607      *
608      * How do we know with the only information in B that we are not ready.
609      *  - easy case, the parent is missing from the global map
610      *  - more complex case we look at the Stack IDs
611      *
612      * The Stack-IDs are added to the procedure order as incremental index
613      * tracking how many times that procedure was executed, which is equivalent
614      * at the number of times we wrote the procedure to the WAL.
615      * In the example above:
616      *   wal-2: B has stackId = [1, 2]
617      *   wal-1: B has stackId = [1]
618      *   wal-1: A has stackId = [0]
619      *
620      * Since we know that the Stack-IDs are incremental for a Procedure,
621      * we notice that there is a gap in the stackIds of B, so something was
622      * executed before.
623      * To identify when a Procedure is ready we do the sum of the stackIds of
624      * the procedure and the parent. if the stackIdSum is equals to the
625      * sum of {1..maxStackId} then everything we need is avaiable.
626      *
627      * Example-2
628      *    wal-2 | A |              A stackIds = [0, 2]
629      *    wal-1 | A B |            B stackIds = [1]
630      *
631      * There is a gap between A stackIds so something was executed in between.
632      */
633     private boolean checkReadyToRun(Entry rootEntry) {
634       assert !rootEntry.hasParent() : "expected root procedure, got " + rootEntry;
635 
636       if (rootEntry.isCompleted()) {
637         // if the root procedure is completed, sub-procedures should be gone
638         if (rootEntry.childHead != null) {
639           LOG.error("unexpected active children for root-procedure: " + rootEntry);
640           for (Entry p = rootEntry.childHead; p != null; p = p.linkNext) {
641             LOG.error("unexpected active children: " + p);
642           }
643         }
644 
645         assert rootEntry.childHead == null : "unexpected children on root completion. " + rootEntry;
646         rootEntry.ready = true;
647         return true;
648       }
649 
650       int stackIdSum = 0;
651       int maxStackId = 0;
652       for (int i = 0; i < rootEntry.proto.getStackIdCount(); ++i) {
653         int stackId = 1 + rootEntry.proto.getStackId(i);
654         maxStackId  = Math.max(maxStackId, stackId);
655         stackIdSum += stackId;
656       }
657 
658       for (Entry p = rootEntry.childHead; p != null; p = p.linkNext) {
659         for (int i = 0; i < p.proto.getStackIdCount(); ++i) {
660           int stackId = 1 + p.proto.getStackId(i);
661           maxStackId  = Math.max(maxStackId, stackId);
662           stackIdSum += stackId;
663         }
664       }
665       final int cmpStackIdSum = (maxStackId * (maxStackId + 1) / 2);
666       if (cmpStackIdSum == stackIdSum) {
667         rootEntry.ready = true;
668         for (Entry p = rootEntry.childHead; p != null; p = p.linkNext) {
669           p.ready = true;
670         }
671         return true;
672       }
673       return false;
674     }
675 
676     private void unlinkFromReplayList(Entry entry) {
677       if (replayOrderHead == entry) {
678         replayOrderHead = entry.replayNext;
679       }
680       if (replayOrderTail == entry) {
681         replayOrderTail = entry.replayPrev;
682       }
683       if (entry.replayPrev != null) {
684         entry.replayPrev.replayNext = entry.replayNext;
685       }
686       if (entry.replayNext != null) {
687         entry.replayNext.replayPrev = entry.replayPrev;
688       }
689     }
690 
691     private void addToReplayList(final Entry entry) {
692       unlinkFromReplayList(entry);
693       entry.replayNext = replayOrderHead;
694       entry.replayPrev = null;
695       if (replayOrderHead != null) {
696         replayOrderHead.replayPrev = entry;
697       } else {
698         replayOrderTail = entry;
699       }
700       replayOrderHead = entry;
701     }
702 
703     private void unlinkFromLinkList(Entry entry) {
704       if (entry == rootHead) {
705         rootHead = entry.linkNext;
706       } else if (entry == childUnlinkedHead) {
707         childUnlinkedHead = entry.linkNext;
708       }
709       if (entry.linkPrev != null) {
710         entry.linkPrev.linkNext = entry.linkNext;
711       }
712       if (entry.linkNext != null) {
713         entry.linkNext.linkPrev = entry.linkPrev;
714       }
715     }
716 
717     private Entry addToLinkList(Entry entry, Entry linkHead) {
718       unlinkFromLinkList(entry);
719       entry.linkNext = linkHead;
720       entry.linkPrev = null;
721       if (linkHead != null) {
722         linkHead.linkPrev = entry;
723       }
724       return entry;
725     }
726 
727     private Entry findLinkListTail(Entry linkHead) {
728       Entry tail = linkHead;
729       while (tail.linkNext != null) {
730         tail = tail.linkNext;
731       }
732       return tail;
733     }
734 
735     private Entry addToMap(final long procId, final boolean hasParent) {
736       int slotIndex = getMapSlot(procId);
737       Entry entry = getProcedure(slotIndex, procId);
738       if (entry != null) return entry;
739 
740       entry = new Entry(procedureMap[slotIndex]);
741       procedureMap[slotIndex] = entry;
742       return entry;
743     }
744 
745     private Entry removeFromMap(final long procId) {
746       int slotIndex = getMapSlot(procId);
747       Entry prev = null;
748       Entry entry = procedureMap[slotIndex];
749       while (entry != null) {
750         if (procId == entry.getProcId()) {
751           if (prev != null) {
752             prev.hashNext = entry.hashNext;
753           } else {
754             procedureMap[slotIndex] = entry.hashNext;
755           }
756           entry.hashNext = null;
757           return entry;
758         }
759         prev = entry;
760         entry = entry.hashNext;
761       }
762       return null;
763     }
764 
765     private Entry getProcedure(final long procId) {
766       return getProcedure(getMapSlot(procId), procId);
767     }
768 
769     private Entry getProcedure(final int slotIndex, final long procId) {
770       Entry entry = procedureMap[slotIndex];
771       while (entry != null) {
772         if (procId == entry.getProcId()) {
773           return entry;
774         }
775         entry = entry.hashNext;
776       }
777       return null;
778     }
779 
780     private int getMapSlot(final long procId) {
781       return (int)(Procedure.getProcIdHashCode(procId) % procedureMap.length);
782     }
783   }
784 }