001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hdfs.shortcircuit;
019
020import java.io.BufferedOutputStream;
021import java.io.Closeable;
022import java.io.DataInputStream;
023import java.io.DataOutputStream;
024import java.io.IOException;
025import java.nio.MappedByteBuffer;
026import java.util.HashMap;
027import java.util.Map;
028import java.util.Map.Entry;
029import java.util.TreeMap;
030import java.util.concurrent.ScheduledFuture;
031import java.util.concurrent.ScheduledThreadPoolExecutor;
032import java.util.concurrent.TimeUnit;
033import java.util.concurrent.locks.Condition;
034import java.util.concurrent.locks.ReentrantLock;
035
036import org.apache.commons.lang.mutable.MutableBoolean;
037import org.apache.commons.logging.Log;
038import org.apache.commons.logging.LogFactory;
039import org.apache.hadoop.classification.InterfaceAudience;
040import org.apache.hadoop.conf.Configuration;
041import org.apache.hadoop.hdfs.DFSConfigKeys;
042import org.apache.hadoop.hdfs.ExtendedBlockId;
043import org.apache.hadoop.hdfs.net.DomainPeer;
044import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
045import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
046import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ReleaseShortCircuitAccessResponseProto;
047import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
048import org.apache.hadoop.hdfs.protocolPB.PBHelper;
049import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.Slot;
050import org.apache.hadoop.io.IOUtils;
051import org.apache.hadoop.ipc.RetriableException;
052import org.apache.hadoop.net.unix.DomainSocket;
053import org.apache.hadoop.net.unix.DomainSocketWatcher;
054import org.apache.hadoop.security.token.SecretManager.InvalidToken;
055import org.apache.hadoop.util.StringUtils;
056import org.apache.hadoop.util.Time;
057import org.apache.hadoop.util.Waitable;
058
059import com.google.common.annotations.VisibleForTesting;
060import com.google.common.base.Preconditions;
061import com.google.common.util.concurrent.ThreadFactoryBuilder;
062
063/**
064 * The ShortCircuitCache tracks things which the client needs to access
065 * HDFS block files via short-circuit.
066 *
067 * These things include: memory-mapped regions, file descriptors, and shared
068 * memory areas for communicating with the DataNode.
069 */
070@InterfaceAudience.Private
071public class ShortCircuitCache implements Closeable {
072  public static final Log LOG = LogFactory.getLog(ShortCircuitCache.class);
073
074  /**
075   * Expiry thread which makes sure that the file descriptors get closed
076   * after a while.
077   */
078  private class CacheCleaner implements Runnable, Closeable {
079    private ScheduledFuture<?> future;
080
081    /**
082     * Run the CacheCleaner thread.
083     *
084     * Whenever a thread requests a ShortCircuitReplica object, we will make
085     * sure it gets one.  That ShortCircuitReplica object can then be re-used
086     * when another thread requests a ShortCircuitReplica object for the same
087     * block.  So in that sense, there is no maximum size to the cache.
088     *
089     * However, when a ShortCircuitReplica object is unreferenced by the
090     * thread(s) that are using it, it becomes evictable.  There are two
091     * separate eviction lists-- one for mmaped objects, and another for
092     * non-mmaped objects.  We do this in order to avoid having the regular
093     * files kick the mmaped files out of the cache too quickly.  Reusing
094     * an already-existing mmap gives a huge performance boost, since the
095     * page table entries don't have to be re-populated.  Both the mmap
096     * and non-mmap evictable lists have maximum sizes and maximum lifespans.
097     */
098    @Override
099    public void run() {
100      ShortCircuitCache.this.lock.lock();
101      try {
102        if (ShortCircuitCache.this.closed) return;
103        long curMs = Time.monotonicNow();
104
105        if (LOG.isDebugEnabled()) {
106          LOG.debug(this + ": cache cleaner running at " + curMs);
107        }
108
109        int numDemoted = demoteOldEvictableMmaped(curMs);
110        int numPurged = 0;
111        Long evictionTimeNs = Long.valueOf(0);
112        while (true) {
113          Entry<Long, ShortCircuitReplica> entry = 
114              evictable.ceilingEntry(evictionTimeNs);
115          if (entry == null) break;
116          evictionTimeNs = entry.getKey();
117          long evictionTimeMs = 
118              TimeUnit.MILLISECONDS.convert(evictionTimeNs, TimeUnit.NANOSECONDS);
119          if (evictionTimeMs + maxNonMmappedEvictableLifespanMs >= curMs) break;
120          ShortCircuitReplica replica = entry.getValue();
121          if (LOG.isTraceEnabled()) {
122            LOG.trace("CacheCleaner: purging " + replica + ": " + 
123                  StringUtils.getStackTrace(Thread.currentThread()));
124          }
125          purge(replica);
126          numPurged++;
127        }
128
129        if (LOG.isDebugEnabled()) {
130          LOG.debug(this + ": finishing cache cleaner run started at " +
131            curMs + ".  Demoted " + numDemoted + " mmapped replicas; " +
132            "purged " + numPurged + " replicas.");
133        }
134      } finally {
135        ShortCircuitCache.this.lock.unlock();
136      }
137    }
138
139    @Override
140    public void close() throws IOException {
141      if (future != null) {
142        future.cancel(false);
143      }
144    }
145
146    public void setFuture(ScheduledFuture<?> future) {
147      this.future = future;
148    }
149
150    /**
151     * Get the rate at which this cleaner thread should be scheduled.
152     *
153     * We do this by taking the minimum expiration time and dividing by 4.
154     *
155     * @return the rate in milliseconds at which this thread should be
156     *         scheduled.
157     */
158    public long getRateInMs() {
159      long minLifespanMs =
160          Math.min(maxNonMmappedEvictableLifespanMs,
161              maxEvictableMmapedLifespanMs);
162      long sampleTimeMs = minLifespanMs / 4;
163      return (sampleTimeMs < 1) ? 1 : sampleTimeMs;
164    }
165  }
166
167  /**
168   * A task which asks the DataNode to release a short-circuit shared memory
169   * slot.  If successful, this will tell the DataNode to stop monitoring
170   * changes to the mlock status of the replica associated with the slot.
171   * It will also allow us (the client) to re-use this slot for another
172   * replica.  If we can't communicate with the DataNode for some reason,
173   * we tear down the shared memory segment to avoid being in an inconsistent
174   * state.
175   */
176  private class SlotReleaser implements Runnable {
177    /**
178     * The slot that we need to release.
179     */
180    private final Slot slot;
181
182    SlotReleaser(Slot slot) {
183      this.slot = slot;
184    }
185
186    @Override
187    public void run() {
188      if (LOG.isTraceEnabled()) {
189        LOG.trace(ShortCircuitCache.this + ": about to release " + slot);
190      }
191      final DfsClientShm shm = (DfsClientShm)slot.getShm();
192      final DomainSocket shmSock = shm.getPeer().getDomainSocket();
193      DomainSocket sock = null;
194      DataOutputStream out = null;
195      final String path = shmSock.getPath();
196      boolean success = false;
197      try {
198        sock = DomainSocket.connect(path);
199        out = new DataOutputStream(
200            new BufferedOutputStream(sock.getOutputStream()));
201        new Sender(out).releaseShortCircuitFds(slot.getSlotId());
202        DataInputStream in = new DataInputStream(sock.getInputStream());
203        ReleaseShortCircuitAccessResponseProto resp =
204            ReleaseShortCircuitAccessResponseProto.parseFrom(
205                PBHelper.vintPrefixed(in));
206        if (resp.getStatus() != Status.SUCCESS) {
207          String error = resp.hasError() ? resp.getError() : "(unknown)";
208          throw new IOException(resp.getStatus().toString() + ": " + error);
209        }
210        if (LOG.isTraceEnabled()) {
211          LOG.trace(ShortCircuitCache.this + ": released " + slot);
212        }
213        success = true;
214      } catch (IOException e) {
215        LOG.error(ShortCircuitCache.this + ": failed to release " +
216            "short-circuit shared memory slot " + slot + " by sending " +
217            "ReleaseShortCircuitAccessRequestProto to " + path +
218            ".  Closing shared memory segment.", e);
219      } finally {
220        if (success) {
221          shmManager.freeSlot(slot);
222        } else {
223          shm.getEndpointShmManager().shutdown(shm);
224        }
225        IOUtils.cleanup(LOG, sock, out);
226      }
227    }
228  }
229
230  public interface ShortCircuitReplicaCreator {
231    /**
232     * Attempt to create a ShortCircuitReplica object.
233     *
234     * This callback will be made without holding any locks.
235     *
236     * @return a non-null ShortCircuitReplicaInfo object.
237     */
238    ShortCircuitReplicaInfo createShortCircuitReplicaInfo();
239  }
240
241  /**
242   * Lock protecting the cache.
243   */
244  private final ReentrantLock lock = new ReentrantLock();
245
246  /**
247   * The executor service that runs the cacheCleaner.
248   */
249  private final ScheduledThreadPoolExecutor cleanerExecutor
250  = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().
251          setDaemon(true).setNameFormat("ShortCircuitCache_Cleaner").
252          build());
253
254  /**
255   * The executor service that runs the cacheCleaner.
256   */
257  private final ScheduledThreadPoolExecutor releaserExecutor
258      = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().
259          setDaemon(true).setNameFormat("ShortCircuitCache_SlotReleaser").
260          build());
261
262  /**
263   * A map containing all ShortCircuitReplicaInfo objects, organized by Key.
264   * ShortCircuitReplicaInfo objects may contain a replica, or an InvalidToken
265   * exception.
266   */
267  private final HashMap<ExtendedBlockId, Waitable<ShortCircuitReplicaInfo>> 
268      replicaInfoMap = new HashMap<ExtendedBlockId,
269          Waitable<ShortCircuitReplicaInfo>>();
270
271  /**
272   * The CacheCleaner.  We don't create this and schedule it until it becomes
273   * necessary.
274   */
275  private CacheCleaner cacheCleaner;
276
277  /**
278   * Tree of evictable elements.
279   *
280   * Maps (unique) insertion time in nanoseconds to the element.
281   */
282  private final TreeMap<Long, ShortCircuitReplica> evictable =
283      new TreeMap<Long, ShortCircuitReplica>();
284
285  /**
286   * Maximum total size of the cache, including both mmapped and
287   * no$-mmapped elements.
288   */
289  private final int maxTotalSize;
290
291  /**
292   * Non-mmaped elements older than this will be closed.
293   */
294  private long maxNonMmappedEvictableLifespanMs;
295
296  /**
297   * Tree of mmaped evictable elements.
298   *
299   * Maps (unique) insertion time in nanoseconds to the element.
300   */
301  private final TreeMap<Long, ShortCircuitReplica> evictableMmapped =
302      new TreeMap<Long, ShortCircuitReplica>();
303
304  /**
305   * Maximum number of mmaped evictable elements.
306   */
307  private int maxEvictableMmapedSize;
308
309  /**
310   * Mmaped elements older than this will be closed.
311   */
312  private final long maxEvictableMmapedLifespanMs;
313
314  /**
315   * The minimum number of milliseconds we'll wait after an unsuccessful
316   * mmap attempt before trying again.
317   */
318  private final long mmapRetryTimeoutMs;
319
320  /**
321   * How long we will keep replicas in the cache before declaring them
322   * to be stale.
323   */
324  private final long staleThresholdMs;
325
326  /**
327   * True if the ShortCircuitCache is closed.
328   */
329  private boolean closed = false;
330
331  /**
332   * Number of existing mmaps associated with this cache.
333   */
334  private int outstandingMmapCount = 0;
335
336  /**
337   * Manages short-circuit shared memory segments for the client.
338   */
339  private final DfsClientShmManager shmManager;
340
341  /**
342   * Create a {@link ShortCircuitCache} object from a {@link Configuration}
343   */
344  public static ShortCircuitCache fromConf(Configuration conf) {
345    return new ShortCircuitCache(
346        conf.getInt(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_KEY,
347            DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_DEFAULT),
348        conf.getLong(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_KEY,
349            DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_DEFAULT),
350        conf.getInt(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE,
351            DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE_DEFAULT),
352        conf.getLong(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS,
353            DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS_DEFAULT),
354        conf.getLong(DFSConfigKeys.DFS_CLIENT_MMAP_RETRY_TIMEOUT_MS,
355            DFSConfigKeys.DFS_CLIENT_MMAP_RETRY_TIMEOUT_MS_DEFAULT),
356        conf.getLong(DFSConfigKeys.DFS_CLIENT_SHORT_CIRCUIT_REPLICA_STALE_THRESHOLD_MS,
357            DFSConfigKeys.DFS_CLIENT_SHORT_CIRCUIT_REPLICA_STALE_THRESHOLD_MS_DEFAULT),
358        conf.getInt(DFSConfigKeys.DFS_SHORT_CIRCUIT_SHARED_MEMORY_WATCHER_INTERRUPT_CHECK_MS,
359            DFSConfigKeys.DFS_SHORT_CIRCUIT_SHARED_MEMORY_WATCHER_INTERRUPT_CHECK_MS_DEFAULT));
360  }
361
362  public ShortCircuitCache(int maxTotalSize, long maxNonMmappedEvictableLifespanMs,
363      int maxEvictableMmapedSize, long maxEvictableMmapedLifespanMs,
364      long mmapRetryTimeoutMs, long staleThresholdMs, int shmInterruptCheckMs) {
365    Preconditions.checkArgument(maxTotalSize >= 0);
366    this.maxTotalSize = maxTotalSize;
367    Preconditions.checkArgument(maxNonMmappedEvictableLifespanMs >= 0);
368    this.maxNonMmappedEvictableLifespanMs = maxNonMmappedEvictableLifespanMs;
369    Preconditions.checkArgument(maxEvictableMmapedSize >= 0);
370    this.maxEvictableMmapedSize = maxEvictableMmapedSize;
371    Preconditions.checkArgument(maxEvictableMmapedLifespanMs >= 0);
372    this.maxEvictableMmapedLifespanMs = maxEvictableMmapedLifespanMs;
373    this.mmapRetryTimeoutMs = mmapRetryTimeoutMs;
374    this.staleThresholdMs = staleThresholdMs;
375    DfsClientShmManager shmManager = null;
376    if ((shmInterruptCheckMs > 0) &&
377        (DomainSocketWatcher.getLoadingFailureReason() == null)) {
378      try {
379        shmManager = new DfsClientShmManager(shmInterruptCheckMs);
380      } catch (IOException e) {
381        LOG.error("failed to create ShortCircuitShmManager", e);
382      }
383    }
384    this.shmManager = shmManager;
385  }
386
387  public long getStaleThresholdMs() {
388    return staleThresholdMs;
389  }
390
391  /**
392   * Increment the reference count of a replica, and remove it from any free
393   * list it may be in.
394   *
395   * You must hold the cache lock while calling this function.
396   *
397   * @param replica      The replica we're removing.
398   */
399  private void ref(ShortCircuitReplica replica) {
400    lock.lock();
401    try {
402      Preconditions.checkArgument(replica.refCount > 0,
403          "can't ref %s because its refCount reached %d", replica,
404          replica.refCount);
405      Long evictableTimeNs = replica.getEvictableTimeNs();
406      replica.refCount++;
407      if (evictableTimeNs != null) {
408        String removedFrom = removeEvictable(replica);
409        if (LOG.isTraceEnabled()) {
410          LOG.trace(this + ": " + removedFrom +
411              " no longer contains " + replica + ".  refCount " +
412              (replica.refCount - 1) + " -> " + replica.refCount +
413              StringUtils.getStackTrace(Thread.currentThread()));
414
415        }
416      } else if (LOG.isTraceEnabled()) {
417        LOG.trace(this + ": replica  refCount " +
418            (replica.refCount - 1) + " -> " + replica.refCount +
419            StringUtils.getStackTrace(Thread.currentThread()));
420      }
421    } finally {
422      lock.unlock();
423    }
424  }
425
426  /**
427   * Unreference a replica.
428   *
429   * You must hold the cache lock while calling this function.
430   *
431   * @param replica   The replica being unreferenced.
432   */
433  void unref(ShortCircuitReplica replica) {
434    lock.lock();
435    try {
436      // If the replica is stale or unusable, but we haven't purged it yet,
437      // let's do that.  It would be a shame to evict a non-stale replica so
438      // that we could put a stale or unusable one into the cache.
439      if (!replica.purged) {
440        String purgeReason = null;
441        if (!replica.getDataStream().getChannel().isOpen()) {
442          purgeReason = "purging replica because its data channel is closed.";
443        } else if (!replica.getMetaStream().getChannel().isOpen()) {
444          purgeReason = "purging replica because its meta channel is closed.";
445        } else if (replica.isStale()) {
446          purgeReason = "purging replica because it is stale.";
447        }
448        if (purgeReason != null) {
449          if (LOG.isDebugEnabled()) {
450            LOG.debug(this + ": " + purgeReason);
451          }
452          purge(replica);
453        }
454      }
455      String addedString = "";
456      boolean shouldTrimEvictionMaps = false;
457      int newRefCount = --replica.refCount;
458      if (newRefCount == 0) {
459        // Close replica, since there are no remaining references to it.
460        Preconditions.checkArgument(replica.purged,
461          "Replica %s reached a refCount of 0 without being purged", replica);
462        replica.close();
463      } else if (newRefCount == 1) {
464        Preconditions.checkState(null == replica.getEvictableTimeNs(),
465            "Replica %s had a refCount higher than 1, " +
466              "but was still evictable (evictableTimeNs = %d)",
467              replica, replica.getEvictableTimeNs());
468        if (!replica.purged) {
469          // Add the replica to the end of an eviction list.
470          // Eviction lists are sorted by time.
471          if (replica.hasMmap()) {
472            insertEvictable(System.nanoTime(), replica, evictableMmapped);
473            addedString = "added to evictableMmapped, ";
474          } else {
475            insertEvictable(System.nanoTime(), replica, evictable);
476            addedString = "added to evictable, ";
477          }
478          shouldTrimEvictionMaps = true;
479        }
480      } else {
481        Preconditions.checkArgument(replica.refCount >= 0,
482            "replica's refCount went negative (refCount = %d" +
483            " for %s)", replica.refCount, replica);
484      }
485      if (LOG.isTraceEnabled()) {
486        LOG.trace(this + ": unref replica " + replica +
487            ": " + addedString + " refCount " +
488            (newRefCount + 1) + " -> " + newRefCount +
489            StringUtils.getStackTrace(Thread.currentThread()));
490      }
491      if (shouldTrimEvictionMaps) {
492        trimEvictionMaps();
493      }
494    } finally {
495      lock.unlock();
496    }
497  }
498
499  /**
500   * Demote old evictable mmaps into the regular eviction map.
501   *
502   * You must hold the cache lock while calling this function.
503   *
504   * @param now   Current time in monotonic milliseconds.
505   * @return      Number of replicas demoted.
506   */
507  private int demoteOldEvictableMmaped(long now) {
508    int numDemoted = 0;
509    boolean needMoreSpace = false;
510    Long evictionTimeNs = Long.valueOf(0);
511
512    while (true) {
513      Entry<Long, ShortCircuitReplica> entry = 
514          evictableMmapped.ceilingEntry(evictionTimeNs);
515      if (entry == null) break;
516      evictionTimeNs = entry.getKey();
517      long evictionTimeMs = 
518          TimeUnit.MILLISECONDS.convert(evictionTimeNs, TimeUnit.NANOSECONDS);
519      if (evictionTimeMs + maxEvictableMmapedLifespanMs >= now) {
520        if (evictableMmapped.size() < maxEvictableMmapedSize) {
521          break;
522        }
523        needMoreSpace = true;
524      }
525      ShortCircuitReplica replica = entry.getValue();
526      if (LOG.isTraceEnabled()) {
527        String rationale = needMoreSpace ? "because we need more space" : 
528            "because it's too old";
529        LOG.trace("demoteOldEvictable: demoting " + replica + ": " +
530            rationale + ": " +
531            StringUtils.getStackTrace(Thread.currentThread()));
532      }
533      removeEvictable(replica, evictableMmapped);
534      munmap(replica);
535      insertEvictable(evictionTimeNs, replica, evictable);
536      numDemoted++;
537    }
538    return numDemoted;
539  }
540
541  /**
542   * Trim the eviction lists.
543   */
544  private void trimEvictionMaps() {
545    long now = Time.monotonicNow();
546    demoteOldEvictableMmaped(now);
547
548    while (true) {
549      long evictableSize = evictable.size();
550      long evictableMmappedSize = evictableMmapped.size();
551      if (evictableSize + evictableMmappedSize <= maxTotalSize) {
552        return;
553      }
554      ShortCircuitReplica replica;
555      if (evictableSize == 0) {
556       replica = evictableMmapped.firstEntry().getValue();
557      } else {
558       replica = evictable.firstEntry().getValue();
559      }
560      if (LOG.isTraceEnabled()) {
561        LOG.trace(this + ": trimEvictionMaps is purging " + replica +
562          StringUtils.getStackTrace(Thread.currentThread()));
563      }
564      purge(replica);
565    }
566  }
567
568  /**
569   * Munmap a replica, updating outstandingMmapCount.
570   *
571   * @param replica  The replica to munmap.
572   */
573  private void munmap(ShortCircuitReplica replica) {
574    replica.munmap();
575    outstandingMmapCount--;
576  }
577
578  /**
579   * Remove a replica from an evictable map.
580   *
581   * @param replica   The replica to remove.
582   * @return          The map it was removed from.
583   */
584  private String removeEvictable(ShortCircuitReplica replica) {
585    if (replica.hasMmap()) {
586      removeEvictable(replica, evictableMmapped);
587      return "evictableMmapped";
588    } else {
589      removeEvictable(replica, evictable);
590      return "evictable";
591    }
592  }
593
594  /**
595   * Remove a replica from an evictable map.
596   *
597   * @param replica   The replica to remove.
598   * @param map       The map to remove it from.
599   */
600  private void removeEvictable(ShortCircuitReplica replica,
601      TreeMap<Long, ShortCircuitReplica> map) {
602    Long evictableTimeNs = replica.getEvictableTimeNs();
603    Preconditions.checkNotNull(evictableTimeNs);
604    ShortCircuitReplica removed = map.remove(evictableTimeNs);
605    Preconditions.checkState(removed == replica,
606        "failed to make %s unevictable", replica);
607    replica.setEvictableTimeNs(null);
608  }
609
610  /**
611   * Insert a replica into an evictable map.
612   *
613   * If an element already exists with this eviction time, we add a nanosecond
614   * to it until we find an unused key.
615   *
616   * @param evictionTimeNs   The eviction time in absolute nanoseconds.
617   * @param replica          The replica to insert.
618   * @param map              The map to insert it into.
619   */
620  private void insertEvictable(Long evictionTimeNs,
621      ShortCircuitReplica replica, TreeMap<Long, ShortCircuitReplica> map) {
622    while (map.containsKey(evictionTimeNs)) {
623      evictionTimeNs++;
624    }
625    Preconditions.checkState(null == replica.getEvictableTimeNs());
626    replica.setEvictableTimeNs(evictionTimeNs);
627    map.put(evictionTimeNs, replica);
628  }
629
630  /**
631   * Purge a replica from the cache.
632   *
633   * This doesn't necessarily close the replica, since there may be
634   * outstanding references to it.  However, it does mean the cache won't
635   * hand it out to anyone after this.
636   *
637   * You must hold the cache lock while calling this function.
638   *
639   * @param replica   The replica being removed.
640   */
641  private void purge(ShortCircuitReplica replica) {
642    boolean removedFromInfoMap = false;
643    String evictionMapName = null;
644    Preconditions.checkArgument(!replica.purged);
645    replica.purged = true;
646    Waitable<ShortCircuitReplicaInfo> val = replicaInfoMap.get(replica.key);
647    if (val != null) {
648      ShortCircuitReplicaInfo info = val.getVal();
649      if ((info != null) && (info.getReplica() == replica)) {
650        replicaInfoMap.remove(replica.key);
651        removedFromInfoMap = true;
652      }
653    }
654    Long evictableTimeNs = replica.getEvictableTimeNs();
655    if (evictableTimeNs != null) {
656      evictionMapName = removeEvictable(replica);
657    }
658    if (LOG.isTraceEnabled()) {
659      StringBuilder builder = new StringBuilder();
660      builder.append(this).append(": ").append(": purged ").
661          append(replica).append(" from the cache.");
662      if (removedFromInfoMap) {
663        builder.append("  Removed from the replicaInfoMap.");
664      }
665      if (evictionMapName != null) {
666        builder.append("  Removed from ").append(evictionMapName);
667      }
668      LOG.trace(builder.toString());
669    }
670    unref(replica);
671  }
672
673  /**
674   * Fetch or create a replica.
675   *
676   * You must hold the cache lock while calling this function.
677   *
678   * @param key          Key to use for lookup.
679   * @param creator      Replica creator callback.  Will be called without
680   *                     the cache lock being held.
681   *
682   * @return             Null if no replica could be found or created.
683   *                     The replica, otherwise.
684   */
685  public ShortCircuitReplicaInfo fetchOrCreate(ExtendedBlockId key,
686      ShortCircuitReplicaCreator creator) {
687    Waitable<ShortCircuitReplicaInfo> newWaitable = null;
688    lock.lock();
689    try {
690      ShortCircuitReplicaInfo info = null;
691      do {
692        if (closed) {
693          if (LOG.isTraceEnabled()) {
694            LOG.trace(this + ": can't fetchOrCreate " + key +
695                " because the cache is closed.");
696          }
697          return null;
698        }
699        Waitable<ShortCircuitReplicaInfo> waitable = replicaInfoMap.get(key);
700        if (waitable != null) {
701          try {
702            info = fetch(key, waitable);
703          } catch (RetriableException e) {
704            if (LOG.isDebugEnabled()) {
705              LOG.debug(this + ": retrying " + e.getMessage());
706            }
707            continue;
708          }
709        }
710      } while (false);
711      if (info != null) return info;
712      // We need to load the replica ourselves.
713      newWaitable = new Waitable<ShortCircuitReplicaInfo>(lock.newCondition());
714      replicaInfoMap.put(key, newWaitable);
715    } finally {
716      lock.unlock();
717    }
718    return create(key, creator, newWaitable);
719  }
720
721  /**
722   * Fetch an existing ReplicaInfo object.
723   *
724   * @param key       The key that we're using.
725   * @param waitable  The waitable object to wait on.
726   * @return          The existing ReplicaInfo object, or null if there is
727   *                  none.
728   *
729   * @throws RetriableException   If the caller needs to retry.
730   */
731  private ShortCircuitReplicaInfo fetch(ExtendedBlockId key,
732      Waitable<ShortCircuitReplicaInfo> waitable) throws RetriableException {
733    // Another thread is already in the process of loading this
734    // ShortCircuitReplica.  So we simply wait for it to complete.
735    ShortCircuitReplicaInfo info;
736    try {
737      if (LOG.isTraceEnabled()) {
738        LOG.trace(this + ": found waitable for " + key);
739      }
740      info = waitable.await();
741    } catch (InterruptedException e) {
742      LOG.info(this + ": interrupted while waiting for " + key);
743      Thread.currentThread().interrupt();
744      throw new RetriableException("interrupted");
745    }
746    if (info.getInvalidTokenException() != null) {
747      LOG.warn(this + ": could not get " + key + " due to InvalidToken " +
748            "exception.", info.getInvalidTokenException());
749      return info;
750    }
751    ShortCircuitReplica replica = info.getReplica();
752    if (replica == null) {
753      LOG.warn(this + ": failed to get " + key);
754      return info;
755    }
756    if (replica.purged) {
757      // Ignore replicas that have already been purged from the cache.
758      throw new RetriableException("Ignoring purged replica " +
759          replica + ".  Retrying.");
760    }
761    // Check if the replica is stale before using it.
762    // If it is, purge it and retry.
763    if (replica.isStale()) {
764      LOG.info(this + ": got stale replica " + replica + ".  Removing " +
765          "this replica from the replicaInfoMap and retrying.");
766      // Remove the cache's reference to the replica.  This may or may not
767      // trigger a close.
768      purge(replica);
769      throw new RetriableException("ignoring stale replica " + replica);
770    }
771    ref(replica);
772    return info;
773  }
774
775  private ShortCircuitReplicaInfo create(ExtendedBlockId key,
776      ShortCircuitReplicaCreator creator,
777      Waitable<ShortCircuitReplicaInfo> newWaitable) {
778    // Handle loading a new replica.
779    ShortCircuitReplicaInfo info = null;
780    try {
781      if (LOG.isTraceEnabled()) {
782        LOG.trace(this + ": loading " + key);
783      }
784      info = creator.createShortCircuitReplicaInfo();
785    } catch (RuntimeException e) {
786      LOG.warn(this + ": failed to load " + key, e);
787    }
788    if (info == null) info = new ShortCircuitReplicaInfo();
789    lock.lock();
790    try {
791      if (info.getReplica() != null) {
792        // On success, make sure the cache cleaner thread is running.
793        if (LOG.isTraceEnabled()) {
794          LOG.trace(this + ": successfully loaded " + info.getReplica());
795        }
796        startCacheCleanerThreadIfNeeded();
797        // Note: new ShortCircuitReplicas start with a refCount of 2,
798        // indicating that both this cache and whoever requested the 
799        // creation of the replica hold a reference.  So we don't need
800        // to increment the reference count here.
801      } else {
802        // On failure, remove the waitable from the replicaInfoMap.
803        Waitable<ShortCircuitReplicaInfo> waitableInMap = replicaInfoMap.get(key);
804        if (waitableInMap == newWaitable) replicaInfoMap.remove(key);
805        if (info.getInvalidTokenException() != null) {
806          LOG.warn(this + ": could not load " + key + " due to InvalidToken " +
807              "exception.", info.getInvalidTokenException());
808        } else {
809          LOG.warn(this + ": failed to load " + key);
810        }
811      }
812      newWaitable.provide(info);
813    } finally {
814      lock.unlock();
815    }
816    return info;
817  }
818
819  private void startCacheCleanerThreadIfNeeded() {
820    if (cacheCleaner == null) {
821      cacheCleaner = new CacheCleaner();
822      long rateMs = cacheCleaner.getRateInMs();
823      ScheduledFuture<?> future =
824          cleanerExecutor.scheduleAtFixedRate(cacheCleaner, rateMs, rateMs,
825              TimeUnit.MILLISECONDS);
826      cacheCleaner.setFuture(future);
827      if (LOG.isDebugEnabled()) {
828        LOG.debug(this + ": starting cache cleaner thread which will run " +
829          "every " + rateMs + " ms");
830      }
831    }
832  }
833
834  ClientMmap getOrCreateClientMmap(ShortCircuitReplica replica,
835      boolean anchored) {
836    Condition newCond;
837    lock.lock();
838    try {
839      while (replica.mmapData != null) {
840        if (replica.mmapData instanceof MappedByteBuffer) {
841          ref(replica);
842          MappedByteBuffer mmap = (MappedByteBuffer)replica.mmapData;
843          return new ClientMmap(replica, mmap, anchored);
844        } else if (replica.mmapData instanceof Long) {
845          long lastAttemptTimeMs = (Long)replica.mmapData;
846          long delta = Time.monotonicNow() - lastAttemptTimeMs;
847          if (delta < mmapRetryTimeoutMs) {
848            if (LOG.isTraceEnabled()) {
849              LOG.trace(this + ": can't create client mmap for " +
850                  replica + " because we failed to " +
851                  "create one just " + delta + "ms ago.");
852            }
853            return null;
854          }
855          if (LOG.isTraceEnabled()) {
856            LOG.trace(this + ": retrying client mmap for " + replica +
857                ", " + delta + " ms after the previous failure.");
858          }
859        } else if (replica.mmapData instanceof Condition) {
860          Condition cond = (Condition)replica.mmapData;
861          cond.awaitUninterruptibly();
862        } else {
863          Preconditions.checkState(false, "invalid mmapData type %s",
864              replica.mmapData.getClass().getName());
865        }
866      }
867      newCond = lock.newCondition();
868      replica.mmapData = newCond;
869    } finally {
870      lock.unlock();
871    }
872    MappedByteBuffer map = replica.loadMmapInternal();
873    lock.lock();
874    try {
875      if (map == null) {
876        replica.mmapData = Long.valueOf(Time.monotonicNow());
877        newCond.signalAll();
878        return null;
879      } else {
880        outstandingMmapCount++;
881        replica.mmapData = map;
882        ref(replica);
883        newCond.signalAll();
884        return new ClientMmap(replica, map, anchored);
885      }
886    } finally {
887      lock.unlock();
888    }
889  }
890
891  /**
892   * Close the cache and free all associated resources.
893   */
894  @Override
895  public void close() {
896    try {
897      lock.lock();
898      if (closed) return;
899      closed = true;
900      LOG.info(this + ": closing");
901      maxNonMmappedEvictableLifespanMs = 0;
902      maxEvictableMmapedSize = 0;
903      // Close and join cacheCleaner thread.
904      IOUtils.cleanup(LOG, cacheCleaner);
905      // Purge all replicas.
906      while (true) {
907        Entry<Long, ShortCircuitReplica> entry = evictable.firstEntry();
908        if (entry == null) break;
909        purge(entry.getValue());
910      }
911      while (true) {
912        Entry<Long, ShortCircuitReplica> entry = evictableMmapped.firstEntry();
913        if (entry == null) break;
914        purge(entry.getValue());
915      }
916    } finally {
917      lock.unlock();
918    }
919    IOUtils.cleanup(LOG, shmManager);
920  }
921
922  @VisibleForTesting // ONLY for testing
923  public interface CacheVisitor {
924    void visit(int numOutstandingMmaps,
925        Map<ExtendedBlockId, ShortCircuitReplica> replicas,
926        Map<ExtendedBlockId, InvalidToken> failedLoads,
927        Map<Long, ShortCircuitReplica> evictable,
928        Map<Long, ShortCircuitReplica> evictableMmapped);
929  }
930
931  @VisibleForTesting // ONLY for testing
932  public void accept(CacheVisitor visitor) {
933    lock.lock();
934    try {
935      Map<ExtendedBlockId, ShortCircuitReplica> replicas =
936          new HashMap<ExtendedBlockId, ShortCircuitReplica>();
937      Map<ExtendedBlockId, InvalidToken> failedLoads =
938          new HashMap<ExtendedBlockId, InvalidToken>();
939      for (Entry<ExtendedBlockId, Waitable<ShortCircuitReplicaInfo>> entry :
940            replicaInfoMap.entrySet()) {
941        Waitable<ShortCircuitReplicaInfo> waitable = entry.getValue();
942        if (waitable.hasVal()) {
943          if (waitable.getVal().getReplica() != null) {
944            replicas.put(entry.getKey(), waitable.getVal().getReplica());
945          } else {
946            // The exception may be null here, indicating a failed load that
947            // isn't the result of an invalid block token.
948            failedLoads.put(entry.getKey(),
949                waitable.getVal().getInvalidTokenException());
950          }
951        }
952      }
953      if (LOG.isDebugEnabled()) {
954        StringBuilder builder = new StringBuilder();
955        builder.append("visiting ").append(visitor.getClass().getName()).
956            append("with outstandingMmapCount=").append(outstandingMmapCount).
957            append(", replicas=");
958        String prefix = "";
959        for (Entry<ExtendedBlockId, ShortCircuitReplica> entry : replicas.entrySet()) {
960          builder.append(prefix).append(entry.getValue());
961          prefix = ",";
962        }
963        prefix = "";
964        builder.append(", failedLoads=");
965        for (Entry<ExtendedBlockId, InvalidToken> entry : failedLoads.entrySet()) {
966          builder.append(prefix).append(entry.getValue());
967          prefix = ",";
968        }
969        prefix = "";
970        builder.append(", evictable=");
971        for (Entry<Long, ShortCircuitReplica> entry : evictable.entrySet()) {
972          builder.append(prefix).append(entry.getKey()).
973              append(":").append(entry.getValue());
974          prefix = ",";
975        }
976        prefix = "";
977        builder.append(", evictableMmapped=");
978        for (Entry<Long, ShortCircuitReplica> entry : evictableMmapped.entrySet()) {
979          builder.append(prefix).append(entry.getKey()).
980              append(":").append(entry.getValue());
981          prefix = ",";
982        }
983        LOG.debug(builder.toString());
984      }
985      visitor.visit(outstandingMmapCount, replicas, failedLoads,
986            evictable, evictableMmapped);
987    } finally {
988      lock.unlock();
989    }
990  }
991
992  @Override
993  public String toString() {
994    return "ShortCircuitCache(0x" +
995        Integer.toHexString(System.identityHashCode(this)) + ")";
996  }
997
998  /**
999   * Allocate a new shared memory slot.
1000   *
1001   * @param datanode       The datanode to allocate a shm slot with.
1002   * @param peer           A peer connected to the datanode.
1003   * @param usedPeer       Will be set to true if we use up the provided peer.
1004   * @param blockId        The block id and block pool id of the block we're 
1005   *                         allocating this slot for.
1006   * @param clientName     The name of the DFSClient allocating the shared
1007   *                         memory.
1008   * @return               Null if short-circuit shared memory is disabled;
1009   *                         a short-circuit memory slot otherwise.
1010   * @throws IOException   An exception if there was an error talking to 
1011   *                         the datanode.
1012   */
1013  public Slot allocShmSlot(DatanodeInfo datanode,
1014        DomainPeer peer, MutableBoolean usedPeer,
1015        ExtendedBlockId blockId, String clientName) throws IOException {
1016    if (shmManager != null) {
1017      return shmManager.allocSlot(datanode, peer, usedPeer,
1018          blockId, clientName);
1019    } else {
1020      return null;
1021    }
1022  }
1023
1024  /**
1025   * Free a slot immediately.
1026   *
1027   * ONLY use this if the DataNode is not yet aware of the slot.
1028   * 
1029   * @param slot           The slot to free.
1030   */
1031  public void freeSlot(Slot slot) {
1032    Preconditions.checkState(shmManager != null);
1033    slot.makeInvalid();
1034    shmManager.freeSlot(slot);
1035  }
1036  
1037  /**
1038   * Schedule a shared memory slot to be released.
1039   *
1040   * @param slot           The slot to release.
1041   */
1042  public void scheduleSlotReleaser(Slot slot) {
1043    Preconditions.checkState(shmManager != null);
1044    releaserExecutor.execute(new SlotReleaser(slot));
1045  }
1046
1047  @VisibleForTesting
1048  public DfsClientShmManager getDfsClientShmManager() {
1049    return shmManager;
1050  }
1051}