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  
51  class SingleCoreListeningIOReactor extends AbstractSingleCoreIOReactor implements ConnectionAcceptor {
52  
53      private final IOReactorConfig reactorConfig;
54      private final Callback<SocketChannel> callback;
55      private final Queue<ListenerEndpointRequest> requestQueue;
56      private final ConcurrentMap<ListenerEndpoint, Boolean> endpoints;
57  
58      private final AtomicBoolean paused;
59  
60      SingleCoreListeningIOReactor(
61              final Queue<ExceptionEvent> auditLog,
62              final IOReactorConfig ioReactorConfig,
63              final Callback<SocketChannel> callback) {
64          super(auditLog);
65          this.reactorConfig = ioReactorConfig != null ? ioReactorConfig : IOReactorConfig.DEFAULT;
66          this.callback = callback;
67          this.requestQueue = new ConcurrentLinkedQueue<>();
68          this.endpoints = new ConcurrentHashMap<>();
69          this.paused = new AtomicBoolean(false);
70      }
71  
72      @Override
73      void doTerminate() {
74          ListenerEndpointRequest request;
75          while ((request = this.requestQueue.poll()) != null) {
76              request.cancel();
77          }
78      }
79  
80      @Override
81      protected final void doExecute() throws IOException {
82          final long selectTimeout = this.reactorConfig.getSelectInterval();
83          while (!Thread.currentThread().isInterrupted()) {
84              if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
85                  break;
86              }
87  
88              final int readyCount = this.selector.select(selectTimeout);
89  
90              if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
91                  break;
92              }
93  
94              processEvents(readyCount);
95          }
96      }
97  
98      private void processEvents(final int readyCount) throws IOException {
99          if (!this.paused.get()) {
100             processSessionRequests();
101         }
102 
103         if (readyCount > 0) {
104             final Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
105             for (final SelectionKey key : selectedKeys) {
106 
107                 processEvent(key);
108 
109             }
110             selectedKeys.clear();
111         }
112     }
113 
114     private void processEvent(final SelectionKey key) throws IOException {
115         try {
116 
117             if (key.isAcceptable()) {
118 
119                 final ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
120                 for (;;) {
121                     final SocketChannel socketChannel = serverChannel.accept();
122                     if (socketChannel == null) {
123                         break;
124                     }
125                     this.callback.execute(socketChannel);
126                 }
127             }
128 
129         } catch (final CancelledKeyException ex) {
130             final ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
131             this.endpoints.remove(endpoint);
132             key.attach(null);
133         }
134     }
135 
136     @Override
137     public Future<ListenerEndpoint> listen(final SocketAddress address, final FutureCallback<ListenerEndpoint> callback) {
138         if (getStatus().compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
139             throw new IOReactorShutdownException("I/O reactor has been shut down");
140         }
141         final BasicFuture<ListenerEndpoint> future = new BasicFuture<>(callback);
142         this.requestQueue.add(new ListenerEndpointRequest(address, future));
143         this.selector.wakeup();
144         return future;
145     }
146 
147     private void processSessionRequests() throws IOException {
148         ListenerEndpointRequest request;
149         while ((request = this.requestQueue.poll()) != null) {
150             if (request.isCancelled()) {
151                 continue;
152             }
153             final SocketAddress address = request.address;
154             final ServerSocketChannel serverChannel = ServerSocketChannel.open();
155             try {
156                 final ServerSocket socket = serverChannel.socket();
157                 socket.setReuseAddress(this.reactorConfig.isSoReuseAddress());
158                 if (this.reactorConfig.getRcvBufSize() > 0) {
159                     socket.setReceiveBufferSize(this.reactorConfig.getRcvBufSize());
160                 }
161                 serverChannel.configureBlocking(false);
162                 socket.bind(address, this.reactorConfig.getBacklogSize());
163 
164                 final SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
165                 key.attach(request);
166                 final ListenerEndpoint endpoint = new ListenerEndpointImpl(key, socket.getLocalSocketAddress());
167                 this.endpoints.put(endpoint, Boolean.TRUE);
168                 request.completed(endpoint);
169             } catch (final IOException ex) {
170                 try {
171                     serverChannel.close();
172                 } catch (final IOException ignore) {
173                 }
174                 request.failed(ex);
175             }
176         }
177     }
178 
179     @Override
180     public Set<ListenerEndpoint> getEndpoints() {
181         final Set<ListenerEndpoint> set = new HashSet<>();
182         final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
183         while (it.hasNext()) {
184             final ListenerEndpoint endpoint = it.next();
185             if (!endpoint.isClosed()) {
186                 set.add(endpoint);
187             } else {
188                 it.remove();
189             }
190         }
191         return set;
192     }
193 
194     @Override
195     public void pause() throws IOException {
196         if (paused.compareAndSet(false, true)) {
197             final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
198             while (it.hasNext()) {
199                 final ListenerEndpoint endpoint = it.next();
200                 if (!endpoint.isClosed()) {
201                     endpoint.close();
202                     this.requestQueue.add(new ListenerEndpointRequest(endpoint.getAddress(), null));
203                 }
204                 it.remove();
205             }
206         }
207     }
208 
209     @Override
210     public void resume() throws IOException {
211         if (paused.compareAndSet(true, false)) {
212             this.selector.wakeup();
213         }
214     }
215 
216 }