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.net.unix;
019
020import java.io.Closeable;
021import java.io.EOFException;
022
023import org.apache.hadoop.classification.InterfaceAudience;
024import org.apache.hadoop.io.IOUtils;
025
026import java.io.IOException;
027import java.nio.channels.ClosedChannelException;
028import java.util.Iterator;
029import java.util.LinkedList;
030import java.util.TreeMap;
031import java.util.Map;
032import java.util.concurrent.locks.Condition;
033import java.util.concurrent.locks.ReentrantLock;
034
035import org.apache.commons.lang.SystemUtils;
036import org.apache.commons.logging.Log;
037import org.apache.commons.logging.LogFactory;
038import org.apache.hadoop.util.NativeCodeLoader;
039
040import com.google.common.annotations.VisibleForTesting;
041import com.google.common.base.Preconditions;
042import com.google.common.util.concurrent.Uninterruptibles;
043
044/**
045 * The DomainSocketWatcher watches a set of domain sockets to see when they
046 * become readable, or closed.  When one of those events happens, it makes a
047 * callback.
048 *
049 * See {@link DomainSocket} for more information about UNIX domain sockets.
050 */
051@InterfaceAudience.LimitedPrivate("HDFS")
052public final class DomainSocketWatcher implements Closeable {
053  static {
054    if (SystemUtils.IS_OS_WINDOWS) {
055      loadingFailureReason = "UNIX Domain sockets are not available on Windows.";
056    } else if (!NativeCodeLoader.isNativeCodeLoaded()) {
057      loadingFailureReason = "libhadoop cannot be loaded.";
058    } else {
059      String problem;
060      try {
061        anchorNative();
062        problem = null;
063      } catch (Throwable t) {
064        problem = "DomainSocketWatcher#anchorNative got error: " +
065          t.getMessage();
066      }
067      loadingFailureReason = problem;
068    }
069  }
070
071  static Log LOG = LogFactory.getLog(DomainSocketWatcher.class);
072
073  /**
074   * The reason why DomainSocketWatcher is not available, or null if it is
075   * available.
076   */
077  private final static String loadingFailureReason;
078
079  /**
080   * Initializes the native library code.
081   */
082  private static native void anchorNative();
083
084  public static String getLoadingFailureReason() {
085    return loadingFailureReason;
086  }
087
088  public interface Handler {
089    /**
090     * Handles an event on a socket.  An event may be the socket becoming
091     * readable, or the remote end being closed.
092     *
093     * @param sock    The socket that the event occurred on.
094     * @return        Whether we should close the socket.
095     */
096    boolean handle(DomainSocket sock);
097  }
098
099  /**
100   * Handler for {DomainSocketWatcher#notificationSockets[1]}
101   */
102  private class NotificationHandler implements Handler {
103    public boolean handle(DomainSocket sock) {
104      assert(lock.isHeldByCurrentThread());
105      try {
106        kicked = false;
107        if (LOG.isTraceEnabled()) {
108          LOG.trace(this + ": NotificationHandler: doing a read on " +
109            sock.fd);
110        }
111        if (sock.getInputStream().read() == -1) {
112          if (LOG.isTraceEnabled()) {
113            LOG.trace(this + ": NotificationHandler: got EOF on " + sock.fd);
114          }
115          throw new EOFException();
116        }
117        if (LOG.isTraceEnabled()) {
118          LOG.trace(this + ": NotificationHandler: read succeeded on " +
119            sock.fd);
120        }
121        return false;
122      } catch (IOException e) {
123        if (LOG.isTraceEnabled()) {
124          LOG.trace(this + ": NotificationHandler: setting closed to " +
125              "true for " + sock.fd);
126        }
127        closed = true;
128        return true;
129      }
130    }
131  }
132
133  private static class Entry {
134    final DomainSocket socket;
135    final Handler handler;
136
137    Entry(DomainSocket socket, Handler handler) {
138      this.socket = socket;
139      this.handler = handler;
140    }
141
142    DomainSocket getDomainSocket() {
143      return socket;
144    }
145
146    Handler getHandler() {
147      return handler;
148    }
149  }
150
151  /**
152   * The FdSet is a set of file descriptors that gets passed to poll(2).
153   * It contains a native memory segment, so that we don't have to copy
154   * in the poll0 function.
155   */
156  private static class FdSet {
157    private long data;
158
159    private native static long alloc0();
160
161    FdSet() {
162      data = alloc0();
163    }
164
165    /**
166     * Add a file descriptor to the set.
167     *
168     * @param fd   The file descriptor to add.
169     */
170    native void add(int fd);
171
172    /**
173     * Remove a file descriptor from the set.
174     *
175     * @param fd   The file descriptor to remove.
176     */
177    native void remove(int fd);
178
179    /**
180     * Get an array containing all the FDs marked as readable.
181     * Also clear the state of all FDs.
182     *
183     * @return     An array containing all of the currently readable file
184     *             descriptors.
185     */
186    native int[] getAndClearReadableFds();
187
188    /**
189     * Close the object and de-allocate the memory used.
190     */
191    native void close();
192  }
193
194  /**
195   * Lock which protects toAdd, toRemove, and closed.
196   */
197  private final ReentrantLock lock = new ReentrantLock();
198
199  /**
200   * Condition variable which indicates that toAdd and toRemove have been
201   * processed.
202   */
203  private final Condition processedCond = lock.newCondition();
204
205  /**
206   * Entries to add.
207   */
208  private final LinkedList<Entry> toAdd =
209      new LinkedList<Entry>();
210
211  /**
212   * Entries to remove.
213   */
214  private final TreeMap<Integer, DomainSocket> toRemove =
215      new TreeMap<Integer, DomainSocket>();
216
217  /**
218   * Maximum length of time to go between checking whether the interrupted
219   * bit has been set for this thread.
220   */
221  private final int interruptCheckPeriodMs;
222
223  /**
224   * A pair of sockets used to wake up the thread after it has called poll(2).
225   */
226  private final DomainSocket notificationSockets[];
227
228  /**
229   * Whether or not this DomainSocketWatcher is closed.
230   */
231  private boolean closed = false;
232  
233  /**
234   * True if we have written a byte to the notification socket. We should not
235   * write anything else to the socket until the notification handler has had a
236   * chance to run. Otherwise, our thread might block, causing deadlock. 
237   * See HADOOP-11333 for details.
238   */
239  private boolean kicked = false;
240
241  public DomainSocketWatcher(int interruptCheckPeriodMs) throws IOException {
242    if (loadingFailureReason != null) {
243      throw new UnsupportedOperationException(loadingFailureReason);
244    }
245    Preconditions.checkArgument(interruptCheckPeriodMs > 0);
246    this.interruptCheckPeriodMs = interruptCheckPeriodMs;
247    notificationSockets = DomainSocket.socketpair();
248    watcherThread.setDaemon(true);
249    watcherThread.start();
250  }
251
252  /**
253   * Close the DomainSocketWatcher and wait for its thread to terminate.
254   *
255   * If there is more than one close, all but the first will be ignored.
256   */
257  @Override
258  public void close() throws IOException {
259    lock.lock();
260    try {
261      if (closed) return;
262      if (LOG.isDebugEnabled()) {
263        LOG.debug(this + ": closing");
264      }
265      closed = true;
266    } finally {
267      lock.unlock();
268    }
269    // Close notificationSockets[0], so that notificationSockets[1] gets an EOF
270    // event.  This will wake up the thread immediately if it is blocked inside
271    // the select() system call.
272    notificationSockets[0].close();
273    // Wait for the select thread to terminate.
274    Uninterruptibles.joinUninterruptibly(watcherThread);
275  }
276
277  @VisibleForTesting
278  public boolean isClosed() {
279    lock.lock();
280    try {
281      return closed;
282    } finally {
283      lock.unlock();
284    }
285  }
286
287  /**
288   * Add a socket.
289   *
290   * @param sock     The socket to add.  It is an error to re-add a socket that
291   *                   we are already watching.
292   * @param handler  The handler to associate with this socket.  This may be
293   *                   called any time after this function is called.
294   */
295  public void add(DomainSocket sock, Handler handler) {
296    lock.lock();
297    try {
298      if (closed) {
299        handler.handle(sock);
300        IOUtils.cleanup(LOG, sock);
301        return;
302      }
303      Entry entry = new Entry(sock, handler);
304      try {
305        sock.refCount.reference();
306      } catch (ClosedChannelException e1) {
307        // If the socket is already closed before we add it, invoke the
308        // handler immediately.  Then we're done.
309        handler.handle(sock);
310        return;
311      }
312      toAdd.add(entry);
313      kick();
314      while (true) {
315        try {
316          processedCond.await();
317        } catch (InterruptedException e) {
318          Thread.currentThread().interrupt();
319        }
320        if (!toAdd.contains(entry)) {
321          break;
322        }
323      }
324    } finally {
325      lock.unlock();
326    }
327  }
328
329  /**
330   * Remove a socket.  Its handler will be called.
331   *
332   * @param sock     The socket to remove.
333   */
334  public void remove(DomainSocket sock) {
335    lock.lock();
336    try {
337      if (closed) return;
338      toRemove.put(sock.fd, sock);
339      kick();
340      while (true) {
341        try {
342          processedCond.await();
343        } catch (InterruptedException e) {
344          Thread.currentThread().interrupt();
345        }
346        if (!toRemove.containsKey(sock.fd)) {
347          break;
348        }
349      }
350    } finally {
351      lock.unlock();
352    }
353  }
354
355  /**
356   * Wake up the DomainSocketWatcher thread.
357   */
358  private void kick() {
359    assert(lock.isHeldByCurrentThread());
360    
361    if (kicked) {
362      return;
363    }
364    
365    try {
366      notificationSockets[0].getOutputStream().write(0);
367      kicked = true;
368    } catch (IOException e) {
369      if (!closed) {
370        LOG.error(this + ": error writing to notificationSockets[0]", e);
371      }
372    }
373  }
374
375  private void sendCallback(String caller, TreeMap<Integer, Entry> entries,
376      FdSet fdSet, int fd) {
377    if (LOG.isTraceEnabled()) {
378      LOG.trace(this + ": " + caller + " starting sendCallback for fd " + fd);
379    }
380    Entry entry = entries.get(fd);
381    Preconditions.checkNotNull(entry,
382        this + ": fdSet contained " + fd + ", which we were " +
383        "not tracking.");
384    DomainSocket sock = entry.getDomainSocket();
385    if (entry.getHandler().handle(sock)) {
386      if (LOG.isTraceEnabled()) {
387        LOG.trace(this + ": " + caller + ": closing fd " + fd +
388            " at the request of the handler.");
389      }
390      if (toRemove.remove(fd) != null) {
391        if (LOG.isTraceEnabled()) {
392          LOG.trace(this + ": " + caller + " : sendCallback processed fd " +
393            fd  + " in toRemove.");
394        }
395      }
396      try {
397        sock.refCount.unreferenceCheckClosed();
398      } catch (IOException e) {
399        Preconditions.checkArgument(false,
400            this + ": file descriptor " + sock.fd + " was closed while " +
401            "still in the poll(2) loop.");
402      }
403      IOUtils.cleanup(LOG, sock);
404      entries.remove(fd);
405      fdSet.remove(fd);
406    } else {
407      if (LOG.isTraceEnabled()) {
408        LOG.trace(this + ": " + caller + ": sendCallback not " +
409            "closing fd " + fd);
410      }
411    }
412  }
413
414  @VisibleForTesting
415  final Thread watcherThread = new Thread(new Runnable() {
416    @Override
417    public void run() {
418      if (LOG.isDebugEnabled()) {
419        LOG.debug(this + ": starting with interruptCheckPeriodMs = " +
420            interruptCheckPeriodMs);
421      }
422      final TreeMap<Integer, Entry> entries = new TreeMap<Integer, Entry>();
423      FdSet fdSet = new FdSet();
424      addNotificationSocket(entries, fdSet);
425      try {
426        while (true) {
427          lock.lock();
428          try {
429            for (int fd : fdSet.getAndClearReadableFds()) {
430              sendCallback("getAndClearReadableFds", entries, fdSet, fd);
431            }
432            if (!(toAdd.isEmpty() && toRemove.isEmpty())) {
433              // Handle pending additions (before pending removes).
434              for (Iterator<Entry> iter = toAdd.iterator(); iter.hasNext(); ) {
435                Entry entry = iter.next();
436                DomainSocket sock = entry.getDomainSocket();
437                Entry prevEntry = entries.put(sock.fd, entry);
438                Preconditions.checkState(prevEntry == null,
439                    this + ": tried to watch a file descriptor that we " +
440                    "were already watching: " + sock);
441                if (LOG.isTraceEnabled()) {
442                  LOG.trace(this + ": adding fd " + sock.fd);
443                }
444                fdSet.add(sock.fd);
445                iter.remove();
446              }
447              // Handle pending removals
448              while (true) {
449                Map.Entry<Integer, DomainSocket> entry = toRemove.firstEntry();
450                if (entry == null) break;
451                sendCallback("handlePendingRemovals",
452                    entries, fdSet, entry.getValue().fd);
453              }
454              processedCond.signalAll();
455            }
456            // Check if the thread should terminate.  Doing this check now is
457            // easier than at the beginning of the loop, since we know toAdd and
458            // toRemove are now empty and processedCond has been notified if it
459            // needed to be.
460            if (closed) {
461              if (LOG.isDebugEnabled()) {
462                LOG.debug(toString() + " thread terminating.");
463              }
464              return;
465            }
466            // Check if someone sent our thread an InterruptedException while we
467            // were waiting in poll().
468            if (Thread.interrupted()) {
469              throw new InterruptedException();
470            }
471          } finally {
472            lock.unlock();
473          }
474          doPoll0(interruptCheckPeriodMs, fdSet);
475        }
476      } catch (InterruptedException e) {
477        LOG.info(toString() + " terminating on InterruptedException");
478      } catch (Throwable e) {
479        LOG.error(toString() + " terminating on exception", e);
480      } finally {
481        lock.lock();
482        try {
483          kick(); // allow the handler for notificationSockets[0] to read a byte
484          for (Entry entry : entries.values()) {
485            sendCallback("close", entries, fdSet, entry.getDomainSocket().fd);
486          }
487          entries.clear();
488          fdSet.close();
489        } finally {
490          lock.unlock();
491        }
492      }
493    }
494  });
495
496  private void addNotificationSocket(final TreeMap<Integer, Entry> entries,
497      FdSet fdSet) {
498    entries.put(notificationSockets[1].fd, 
499        new Entry(notificationSockets[1], new NotificationHandler()));
500    try {
501      notificationSockets[1].refCount.reference();
502    } catch (IOException e) {
503      throw new RuntimeException(e);
504    }
505    fdSet.add(notificationSockets[1].fd);
506    if (LOG.isTraceEnabled()) {
507      LOG.trace(this + ": adding notificationSocket " +
508          notificationSockets[1].fd + ", connected to " +
509          notificationSockets[0].fd);
510    }
511  }
512
513  public String toString() {
514    return "DomainSocketWatcher(" + System.identityHashCode(this) + ")"; 
515  }
516
517  private static native int doPoll0(int maxWaitMs, FdSet readFds)
518      throws IOException;
519}