org/sonews/daemon/ChannelReader.java
author cli
Mon Aug 24 13:00:05 2009 +0200 (2009-08-24)
changeset 20 6ae5e4f8329b
parent 3 2fdc9cc89502
permissions -rw-r--r--
Add stubs for org.sonews.acl and add method "impliedCapability" for org.sonews.command.Command interface.
chris@1
     1
/*
chris@1
     2
 *   SONEWS News Server
chris@1
     3
 *   see AUTHORS for the list of contributors
chris@1
     4
 *
chris@1
     5
 *   This program is free software: you can redistribute it and/or modify
chris@1
     6
 *   it under the terms of the GNU General Public License as published by
chris@1
     7
 *   the Free Software Foundation, either version 3 of the License, or
chris@1
     8
 *   (at your option) any later version.
chris@1
     9
 *
chris@1
    10
 *   This program is distributed in the hope that it will be useful,
chris@1
    11
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
chris@1
    12
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
chris@1
    13
 *   GNU General Public License for more details.
chris@1
    14
 *
chris@1
    15
 *   You should have received a copy of the GNU General Public License
chris@1
    16
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
chris@1
    17
 */
chris@1
    18
chris@1
    19
package org.sonews.daemon;
chris@1
    20
chris@1
    21
import java.io.IOException;
chris@1
    22
import java.nio.ByteBuffer;
chris@1
    23
import java.nio.channels.CancelledKeyException;
chris@1
    24
import java.nio.channels.SelectionKey;
chris@1
    25
import java.nio.channels.Selector;
chris@1
    26
import java.nio.channels.SocketChannel;
chris@1
    27
import java.util.Iterator;
chris@1
    28
import java.util.Set;
cli@15
    29
import java.util.logging.Level;
chris@3
    30
import org.sonews.util.Log;
chris@1
    31
chris@1
    32
/**
chris@1
    33
 * A Thread task listening for OP_READ events from SocketChannels.
chris@1
    34
 * @author Christian Lins
chris@1
    35
 * @since sonews/0.5.0
chris@1
    36
 */
chris@1
    37
class ChannelReader extends AbstractDaemon
chris@1
    38
{
chris@1
    39
chris@1
    40
  private static ChannelReader instance = new ChannelReader();
chris@1
    41
chris@1
    42
  /**
chris@1
    43
   * @return Active ChannelReader instance.
chris@1
    44
   */
chris@1
    45
  public static ChannelReader getInstance()
chris@1
    46
  {
chris@1
    47
    return instance;
chris@1
    48
  }
chris@1
    49
  
chris@1
    50
  private Selector selector = null;
chris@1
    51
  
chris@1
    52
  protected ChannelReader()
chris@1
    53
  {
chris@1
    54
  }
chris@1
    55
  
chris@1
    56
  /**
chris@1
    57
   * Sets the selector which is used by this reader to determine the channel
chris@1
    58
   * to read from.
chris@1
    59
   * @param selector
chris@1
    60
   */
chris@1
    61
  public void setSelector(final Selector selector)
chris@1
    62
  {
chris@1
    63
    this.selector = selector;
chris@1
    64
  }
chris@1
    65
  
chris@1
    66
  /**
chris@1
    67
   * Run loop. Blocks until some data is available in a channel.
chris@1
    68
   */
chris@1
    69
  @Override
chris@1
    70
  public void run()
chris@1
    71
  {
chris@1
    72
    assert selector != null;
chris@1
    73
chris@1
    74
    while(isRunning())
chris@1
    75
    {
chris@1
    76
      try
chris@1
    77
      {
chris@1
    78
        // select() blocks until some SelectableChannels are ready for
chris@1
    79
        // processing. There is no need to lock the selector as we have only
chris@1
    80
        // one thread per selector.
chris@1
    81
        selector.select();
chris@1
    82
chris@1
    83
        // Get list of selection keys with pending events.
chris@1
    84
        // Note: the selected key set is not thread-safe
chris@1
    85
        SocketChannel channel = null;
chris@1
    86
        NNTPConnection conn = null;
chris@1
    87
        final Set<SelectionKey> selKeys = selector.selectedKeys();
chris@1
    88
        SelectionKey selKey = null;
chris@1
    89
chris@1
    90
        synchronized (selKeys)
chris@1
    91
        {
chris@1
    92
          Iterator it = selKeys.iterator();
chris@1
    93
chris@1
    94
          // Process the first pending event
chris@1
    95
          while (it.hasNext())
chris@1
    96
          {
chris@1
    97
            selKey = (SelectionKey) it.next();
chris@1
    98
            channel = (SocketChannel) selKey.channel();
chris@1
    99
            conn = Connections.getInstance().get(channel);
chris@1
   100
chris@1
   101
            // Because we cannot lock the selKey as that would cause a deadlock
chris@1
   102
            // we lock the connection. To preserve the order of the received
chris@1
   103
            // byte blocks a selection key for a connection that has pending
chris@1
   104
            // read events is skipped.
chris@1
   105
            if (conn == null || conn.tryReadLock())
chris@1
   106
            {
chris@1
   107
              // Remove from set to indicate that it's being processed
chris@1
   108
              it.remove();
chris@1
   109
              if (conn != null)
chris@1
   110
              {
chris@1
   111
                break; // End while loop
chris@1
   112
              }
chris@1
   113
            }
chris@1
   114
            else
chris@1
   115
            {
chris@1
   116
              selKey = null;
chris@1
   117
              channel = null;
chris@1
   118
              conn = null;
chris@1
   119
            }
chris@1
   120
          }
chris@1
   121
        }
chris@1
   122
chris@1
   123
        // Do not lock the selKeys while processing because this causes
chris@1
   124
        // a deadlock in sun.nio.ch.SelectorImpl.lockAndDoSelect()
chris@1
   125
        if (selKey != null && channel != null && conn != null)
chris@1
   126
        {
chris@1
   127
          processSelectionKey(conn, channel, selKey);
chris@1
   128
          conn.unlockReadLock();
chris@1
   129
        }
chris@1
   130
chris@1
   131
      }
chris@1
   132
      catch(CancelledKeyException ex)
chris@1
   133
      {
cli@15
   134
        Log.get().warning("ChannelReader.run(): " + ex);
cli@15
   135
        Log.get().log(Level.INFO, "", ex);
chris@1
   136
      }
chris@1
   137
      catch(Exception ex)
chris@1
   138
      {
chris@1
   139
        ex.printStackTrace();
chris@1
   140
      }
chris@1
   141
      
chris@1
   142
      // Eventually wait for a register operation
chris@1
   143
      synchronized (NNTPDaemon.RegisterGate)
chris@1
   144
      {
chris@1
   145
      // Do nothing; FindBugs may warn about an empty synchronized 
chris@1
   146
      // statement, but we cannot use a wait()/notify() mechanism here.
chris@1
   147
      // If we used something like RegisterGate.wait() we block here
chris@1
   148
      // until the NNTPDaemon calls notify(). But the daemon only
chris@1
   149
      // calls notify() if itself is NOT blocked in the listening socket.
chris@1
   150
      }
chris@1
   151
    } // while(isRunning())
chris@1
   152
  }
chris@1
   153
  
chris@1
   154
  private void processSelectionKey(final NNTPConnection connection,
chris@1
   155
    final SocketChannel socketChannel, final SelectionKey selKey)
chris@1
   156
    throws InterruptedException, IOException
chris@1
   157
  {
chris@1
   158
    assert selKey != null;
chris@1
   159
    assert selKey.isReadable();
chris@1
   160
    
chris@1
   161
    // Some bytes are available for reading
chris@1
   162
    if(selKey.isValid())
chris@3
   163
    {   
chris@1
   164
      // Lock the channel
chris@1
   165
      //synchronized(socketChannel)
chris@1
   166
      {
chris@1
   167
        // Read the data into the appropriate buffer
chris@1
   168
        ByteBuffer buf = connection.getInputBuffer();
chris@1
   169
        int read = -1;
chris@1
   170
        try 
chris@1
   171
        {
chris@1
   172
          read = socketChannel.read(buf);
chris@3
   173
        }
chris@3
   174
        catch(IOException ex)
chris@3
   175
        {
chris@3
   176
          // The connection was probably closed by the remote host
chris@3
   177
          // in a non-clean fashion
cli@15
   178
          Log.get().info("ChannelReader.processSelectionKey(): " + ex);
chris@3
   179
        }
chris@1
   180
        catch(Exception ex) 
chris@1
   181
        {
cli@15
   182
          Log.get().warning("ChannelReader.processSelectionKey(): " + ex);
chris@1
   183
        }
chris@1
   184
        
chris@1
   185
        if(read == -1) // End of stream
chris@1
   186
        {
chris@1
   187
          selKey.cancel();
chris@1
   188
        }
chris@1
   189
        else if(read > 0) // If some data was read
chris@1
   190
        {
chris@1
   191
          ConnectionWorker.addChannel(socketChannel);
chris@1
   192
        }
chris@1
   193
      }
chris@1
   194
    }
chris@1
   195
    else
chris@1
   196
    {
chris@1
   197
      // Should not happen
cli@15
   198
      Log.get().severe("Should not happen: " + selKey.toString());
chris@1
   199
    }
chris@1
   200
  }
chris@1
   201
  
chris@1
   202
}