View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.reactor;
29  
30  import java.io.IOException;
31  import java.net.ServerSocket;
32  import java.net.SocketAddress;
33  import java.nio.channels.CancelledKeyException;
34  import java.nio.channels.SelectionKey;
35  import java.nio.channels.ServerSocketChannel;
36  import java.nio.channels.SocketChannel;
37  import java.util.HashSet;
38  import java.util.Iterator;
39  import java.util.Queue;
40  import java.util.Set;
41  import java.util.concurrent.ConcurrentHashMap;
42  import java.util.concurrent.ConcurrentLinkedQueue;
43  import java.util.concurrent.ConcurrentMap;
44  import java.util.concurrent.Future;
45  import java.util.concurrent.atomic.AtomicBoolean;
46  
47  import org.apache.hc.core5.concurrent.BasicFuture;
48  import org.apache.hc.core5.concurrent.FutureCallback;
49  import org.apache.hc.core5.function.Callback;
50  import org.apache.hc.core5.io.Closer;
51  
52  class SingleCoreListeningIOReactor extends AbstractSingleCoreIOReactor implements ConnectionAcceptor {
53  
54      private final IOReactorConfig reactorConfig;
55      private final Callback<SocketChannel> callback;
56      private final Queue<ListenerEndpointRequest> requestQueue;
57      private final ConcurrentMap<ListenerEndpoint, Boolean> endpoints;
58      private final AtomicBoolean paused;
59      private final long selectTimeoutMillis;
60  
61      SingleCoreListeningIOReactor(
62              final Queue<ExceptionEvent> auditLog,
63              final IOReactorConfig ioReactorConfig,
64              final Callback<SocketChannel> callback) {
65          super(auditLog);
66          this.reactorConfig = ioReactorConfig != null ? ioReactorConfig : IOReactorConfig.DEFAULT;
67          this.callback = callback;
68          this.requestQueue = new ConcurrentLinkedQueue<>();
69          this.endpoints = new ConcurrentHashMap<>();
70          this.paused = new AtomicBoolean(false);
71          this.selectTimeoutMillis = this.reactorConfig.getSelectInterval().toMillis();
72      }
73  
74      @Override
75      void doTerminate() {
76          ListenerEndpointRequest request;
77          while ((request = this.requestQueue.poll()) != null) {
78              request.cancel();
79          }
80      }
81  
82      @Override
83      protected final void doExecute() throws IOException {
84          while (!Thread.currentThread().isInterrupted()) {
85              if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
86                  break;
87              }
88  
89              final int readyCount = this.selector.select(this.selectTimeoutMillis);
90  
91              if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
92                  break;
93              }
94  
95              processEvents(readyCount);
96          }
97      }
98  
99      private void processEvents(final int readyCount) throws IOException {
100         if (!this.paused.get()) {
101             processSessionRequests();
102         }
103 
104         if (readyCount > 0) {
105             final Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
106             for (final SelectionKey key : selectedKeys) {
107 
108                 processEvent(key);
109 
110             }
111             selectedKeys.clear();
112         }
113     }
114 
115     private void processEvent(final SelectionKey key) throws IOException {
116         try {
117 
118             if (key.isAcceptable()) {
119 
120                 final ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
121                 for (;;) {
122                     final SocketChannel socketChannel = serverChannel.accept();
123                     if (socketChannel == null) {
124                         break;
125                     }
126                     this.callback.execute(socketChannel);
127                 }
128             }
129 
130         } catch (final CancelledKeyException ex) {
131             final ListenerEndpoint../org/apache/hc/core5/reactor/ListenerEndpoint.html#ListenerEndpoint">ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
132             this.endpoints.remove(endpoint);
133             key.attach(null);
134         }
135     }
136 
137     @Override
138     public Future<ListenerEndpoint> listen(final SocketAddress address, final FutureCallback<ListenerEndpoint> callback) {
139         if (getStatus().compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
140             throw new IOReactorShutdownException("I/O reactor has been shut down");
141         }
142         final BasicFuture<ListenerEndpoint> future = new BasicFuture<>(callback);
143         this.requestQueue.add(new ListenerEndpointRequest(address, future));
144         this.selector.wakeup();
145         return future;
146     }
147 
148     private void processSessionRequests() throws IOException {
149         ListenerEndpointRequest request;
150         while ((request = this.requestQueue.poll()) != null) {
151             if (request.isCancelled()) {
152                 continue;
153             }
154             final SocketAddress address = request.address;
155             final ServerSocketChannel serverChannel = ServerSocketChannel.open();
156             try {
157                 final ServerSocket socket = serverChannel.socket();
158                 socket.setReuseAddress(this.reactorConfig.isSoReuseAddress());
159                 if (this.reactorConfig.getRcvBufSize() > 0) {
160                     socket.setReceiveBufferSize(this.reactorConfig.getRcvBufSize());
161                 }
162                 serverChannel.configureBlocking(false);
163                 socket.bind(address, this.reactorConfig.getBacklogSize());
164 
165                 final SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
166                 key.attach(request);
167                 final ListenerEndpoint endpoint = new ListenerEndpointImpl(key, socket.getLocalSocketAddress());
168                 this.endpoints.put(endpoint, Boolean.TRUE);
169                 request.completed(endpoint);
170             } catch (final IOException ex) {
171                 Closer.closeQuietly(serverChannel);
172                 request.failed(ex);
173             }
174         }
175     }
176 
177     @Override
178     public Set<ListenerEndpoint> getEndpoints() {
179         final Set<ListenerEndpoint> set = new HashSet<>();
180         final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
181         while (it.hasNext()) {
182             final ListenerEndpoint endpoint = it.next();
183             if (!endpoint.isClosed()) {
184                 set.add(endpoint);
185             } else {
186                 it.remove();
187             }
188         }
189         return set;
190     }
191 
192     @Override
193     public void pause() throws IOException {
194         if (paused.compareAndSet(false, true)) {
195             final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
196             while (it.hasNext()) {
197                 final ListenerEndpoint endpoint = it.next();
198                 if (!endpoint.isClosed()) {
199                     endpoint.close();
200                     this.requestQueue.add(new ListenerEndpointRequest(endpoint.getAddress(), null));
201                 }
202                 it.remove();
203             }
204         }
205     }
206 
207     @Override
208     public void resume() throws IOException {
209         if (paused.compareAndSet(true, false)) {
210             this.selector.wakeup();
211         }
212     }
213 
214 }