Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPConnSetupMgr.java

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is mozilla.org code.
17 *
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 2001
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38 package org.ietf.ldap;
39
40 import java.io.IOException;
41 import java.io.Serializable;
42 import java.net.Socket;
43
44 /**
45 * Makes a connection to a server from a list using "smart" failover.
46 * Connection attempts can be made serially from the same thread, or
47 * in parallel by creating a separate thread after the specified delay.
48 * Connection setup status is preserved for later attempts, so that servers
49 * that are more likely to be available will be tried first.
50 * <P>
51 * The total time spent opening a connection can be limited with the
52 * <CODE>ConnectTimeout</CODE> property.
53 * <P>
54 * When a connection is successfully created, a socket is opened. The socket
55 * is passed to the LDAPConnThread. The LDAPConnThread must call
56 * invalidateConnection() if the connection is lost due to a network or
57 * server error, or disconnect() if the connection is deliberately terminated
58 * by the user.
59 */
60 class LDAPConnSetupMgr implements Cloneable, Serializable {
61
62 static final long serialVersionUID = 1519402748245755306L;
63 /**
64 * Policy for opening a connection when multiple servers are used
65 */
66 private static final int SERIAL = 0;
67 private static final int PARALLEL = 1;
68
69 /**
70 * ServerEntry.connSetupStatus possible value. The values also represent
71 * the likelihood that the connection will be setup to a server. Lower
72 * values have higher priority. See sortDsList() method
73 */
74 private static final int CONNECTED = 0;
75 private static final int DISCONNECTED = 1;
76 private static final int NEVER_USED = 2;
77 private static final int INTERRUPTED = 3;
78 private static final int FAILED = 4;
79
80 /**
81 * Representation for a server in the server list.
82 */
83 class ServerEntry {
84 String host;
85 int port;
86 int connSetupStatus;
87 Thread connSetupThread;
88
89 ServerEntry(String host, int port, int status) {
90 this.host = host;
91 this.port = port;
92 connSetupStatus = status;
93 connSetupThread = null;
94 }
95
96 public String toString() {
97 return "{" +host+":"+port + " status="+connSetupStatus+"}";
98 }
99 }
100
101 /**
102 * Socket to the connected server
103 */
104 private Socket _socket = null;
105
106 /**
107 * Last exception occured during connection setup
108 */
109 private LDAPException _connException = null;
110
111 /**
112 * List of server to use for the connection setup
113 */
114 ServerEntry[] _dsList;
115
116 /**
117 * Index of the last connected server
118 */
119 private int _dsIdx = -1;
120
121 /**
122 * Socket factory for SSL connections
123 */
124 LDAPSocketFactory _factory;
125
126 /**
127 * Connection setup policy (PARALLEL or SERIAL)
128 */
129 int _policy = SERIAL;
130
131 /**
132 * Delay in ms before another connection setup thread is started.
133 */
134 int _connSetupDelay = -1;
135
136 /**
137 * The maximum time to wait to established the connection
138 */
139 int _connectTimeout = 0;
140
141 /**
142 * During connection setup, the current count of servers to which
143 * connection attmpt has been made
144 */
145 private transient int _attemptCnt = 0;
146
147 /**
148 * Connection IDs for ldap trace messages
149 */
150 private static int _nextId;
151 private int _id;
152
153 /**
154 * Constructor
155 * @param host list of host names to which to connect
156 * @param port list of port numbers corresponding to the host list
157 * @param factory socket factory for SSL connections
158 */
159 LDAPConnSetupMgr(String[] hosts, int[] ports, LDAPSocketFactory factory) {
160 _dsList = new ServerEntry[hosts.length];
161 for (int i=0; i < hosts.length; i++) {
162 _dsList[i] = new ServerEntry(hosts[i], ports[i], NEVER_USED);
163 }
164 _factory = factory;
165 _id = _nextId++;
166 }
167
168 /**
169 * Try to open the connection to any of the servers in the list, limiting
170 * the time waiting for the connection to be established
171 * @return connection socket
172 */
173 synchronized Socket openConnection() throws LDAPException{
174
175 long tcur=0, tmax = Long.MAX_VALUE;
176 Thread th = null;
177
178 reset();
179
180 // If reconnecting, sort dsList so that servers more likly to
181 // be available are tried first
182 sortDsList();
183
184 if (_connectTimeout == 0) {
185 // No need for a separate thread, connect time not limited
186 connect();
187 }
188 else {
189
190 // Wait for connection at most _connectTimeout milliseconds
191 // Run connection setup in a separate thread to monitor the time
192 tmax = System.currentTimeMillis() + _connectTimeout;
193 th = new Thread (new Runnable() {
194 public void run() {
195 connect();
196 }
197 }, "ConnSetupMgr");
198 th.setDaemon(true);
199 th.start();
200
201 while (_socket==null && (_attemptCnt < _dsList.length) &&
202 (tcur = System.currentTimeMillis()) < tmax) {
203 try {
204 wait(tmax - tcur);
205 }
206 catch (InterruptedException e) {
207 th.interrupt();
208 cleanup();
209 throw new LDAPInterruptedException("Interrupted connect operation");
210 }
211 }
212 }
213
214 if (_socket != null) {
215 return _socket;
216 }
217
218 if ( th != null && (tcur = System.currentTimeMillis()) >= tmax) {
219 // We have timed out
220 th.interrupt();
221 cleanup();
222 throw new LDAPException(
223 "connect timeout, " + getServerList() + " might be unreachable",
224 LDAPException.CONNECT_ERROR);
225 }
226
227 if (_connException != null && _dsList.length == 1) {
228 throw _connException;
229 }
230
231 throw new LDAPException(
232 "failed to connect to server " + getServerList(),
233 LDAPException.CONNECT_ERROR);
234 }
235
236 private void reset() {
237 _socket = null;
238 _connException = null;
239 _attemptCnt = 0;
240
241 for (int i=0; i < _dsList.length; i++) {
242 _dsList[i].connSetupThread = null;
243 }
244 }
245
246 private String getServerList() {
247 StringBuffer sb = new StringBuffer();
248 for (int i=0; i < _dsList.length; i++) {
249 sb.append(i==0 ? "" : " ");
250 sb.append(_dsList[i].host);
251 sb.append(":");
252 sb.append(_dsList[i].port);
253 }
254 return sb.toString();
255 }
256
257 private void connect() {
258
259 if (_policy == SERIAL || _dsList.length == 1) {
260 openSerial();
261 }
262 else {
263 openParallel();
264 }
265 }
266
267 /**
268 * Called when the current connection is lost.
269 * Put the connected server at the end of the server list for
270 * the next connect attempt.
271 */
272 synchronized void invalidateConnection() {
273 if (_socket != null) {
274 _dsList[_dsIdx].connSetupStatus = FAILED;
275
276 // Move the entry to the end of the list
277 int srvCnt = _dsList.length, j=0;
278 ServerEntry[] newDsList = new ServerEntry[_dsList.length];
279 for (int i=0; i < srvCnt; i++) {
280 if (i != _dsIdx) {
281 newDsList[j++] = _dsList[i];
282 }
283 }
284 newDsList[j] = _dsList[_dsIdx];
285 _dsList = newDsList;
286 _dsIdx = j;
287 }
288
289 _socket = null;
290 }
291
292 /**
293 * Called when the current connection is terminated by the user.
294 * Mark the connected server status as DISCONNECTED. This will
295 * put it at top of the server list for the next connect attempt.
296 */
297 void disconnect() {
298 if (_socket != null) {
299 _dsList[_dsIdx].connSetupStatus = DISCONNECTED;
300 }
301
302 _socket = null;
303 }
304
305 Socket getSocket() {
306 return _socket;
307 }
308
309 String getHost() {
310 if (_dsIdx >= 0) {
311 return _dsList[_dsIdx].host;
312 }
313 return _dsList[0].host;
314 }
315
316 int getPort() {
317 if (_dsIdx >= 0) {
318 return _dsList[_dsIdx].port;
319 }
320 return _dsList[0].port;
321 }
322
323 int getConnSetupDelay() {
324 return _connSetupDelay/1000;
325 }
326
327 /**
328 * Selects the connection failover policy
329 * @param delay in seconds for the parallel connection setup policy.
330 * Possible values are: <br>(delay=-1) use serial policy,<br>
331 * (delay=0) start immediately concurrent threads to each specified server
332 * <br>(delay>0) create a new connection setup thread after delay seconds
333 */
334 void setConnSetupDelay(int delay) {
335 _policy = (delay < 0) ? SERIAL : PARALLEL;
336 _connSetupDelay = delay*1000;
337
338 }
339
340 int getConnectTimeout() {
341 return _connectTimeout/1000;
342 }
343
344 /**
345 * Sets the maximum time to spend in the openConnection() call
346 * @param timeout in seconds to wait for the connection to be established
347 */
348 void setConnectTimeout(int timeout) {
349 _connectTimeout = timeout*1000;
350 }
351
352 /**
353 * Check if the user has voluntarily closed the connection
354 */
355 boolean isUserDisconnected() {
356 return (_dsIdx >=0 &&
357 _dsList[_dsIdx].connSetupStatus == DISCONNECTED);
358 }
359
360 /**
361 * Try sequentially to open a new connection to a server.
362 */
363 private void openSerial() {
364 for (int i=0; i < _dsList.length; i++) {
365 _dsList[i].connSetupThread = Thread.currentThread();
366 connectServer(i);
367 if (_socket != null) {
368 return;
369 }
370 }
371 }
372
373 /**
374 * Try concurrently to open a new connection a server. Create a separate
375 * thread for each connection attempt.
376 */
377 private synchronized void openParallel() {
378 for (int i=0; _socket==null && i < _dsList.length; i++) {
379
380 //Create a Thread to execute connectSetver()
381 final int dsIdx = i;
382 String threadName = "ConnSetupMgr " +
383 _dsList[dsIdx].host + ":" + _dsList[dsIdx].port;
384 Thread t = new Thread(new Runnable() {
385 public void run() {
386 connectServer(dsIdx);
387 }
388 }, threadName);
389
390 _dsList[dsIdx].connSetupThread = t;
391 t.setDaemon(true);
392 t.start();
393
394 // Wait before starting another thread if the delay is not zero
395 if (_connSetupDelay != 0 && i < (_dsList.length-1)) {
396 try {
397 wait(_connSetupDelay);
398 }
399 catch (InterruptedException e) {
400 return;
401 }
402 }
403 }
404
405 // At this point all threads are started. Wait until first thread
406 // succeeds to connect or all threads terminate
407
408 while (_socket == null && (_attemptCnt < _dsList.length)) {
409
410 // Wait for a thread to terminate
411 try {
412 wait();
413 }
414 catch (InterruptedException e) {}
415 }
416 }
417
418 /**
419 * Connect to the server at the given index
420 */
421 void connectServer(int idx) {
422 ServerEntry entry = _dsList[idx];
423 Thread currThread = Thread.currentThread();
424 Socket sock = null;
425 LDAPException conex = null;
426
427 try {
428 /* If we are to create a socket ourselves, make sure it has
429 sufficient privileges to connect to the desired host */
430 if (_factory == null) {
431 sock = new Socket (entry.host, entry.port);
432 //s.setSoLinger( false, -1 );
433 } else {
434 sock = _factory.createSocket(entry.host, entry.port);
435 }
436 }
437 catch (IOException e) {
438 conex = new LDAPException("failed to connect to server "
439 + entry.host+":"+entry.port, LDAPException.CONNECT_ERROR);
440 }
441 catch (LDAPException e) {
442 conex = e;
443 }
444
445 if (currThread.isInterrupted()) {
446 return;
447 }
448
449 synchronized (this) {
450 if (_socket == null && entry.connSetupThread == currThread) {
451 entry.connSetupThread = null;
452 if (sock != null) {
453 entry.connSetupStatus = CONNECTED;
454 _socket = sock;
455 _dsIdx = idx;
456 cleanup(); // Signal other concurrent threads to terminate
457 }
458 else {
459 entry.connSetupStatus = FAILED;
460 _connException = conex;
461 }
462 _attemptCnt++;
463 notifyAll();
464 }
465 }
466 }
467
468 /**
469 * Terminate all concurrently running connection setup threads
470 */
471 private synchronized void cleanup() {
472 Thread currThread = Thread.currentThread();
473 for (int i=0; i < _dsList.length; i++) {
474 ServerEntry entry = _dsList[i];
475 if (entry.connSetupThread != null && entry.connSetupThread != currThread) {
476
477 entry.connSetupStatus = INTERRUPTED;
478 //Thread.stop() is considered to be dangerous, use Thread.interrupt().
479 //interrupt() will however not work if the thread is blocked in the
480 //socket library native connect() call, but the connect() will
481 //eventually timeout and the thread will die.
482 entry.connSetupThread.interrupt();
483
484 entry.connSetupThread = null;
485 }
486 }
487 }
488
489
490 /**
491 * Sorts Server List so that servers which are more likely to be available
492 * are tried first. The likelihood of making a successful connection
493 * is determined by the connSetupStatus. Lower values have higher
494 * likelihood. Thus, the order of server access is (1) disconnected by
495 * the user (2) never used (3) interrupted connection attempt
496 * (4) connection setup failed/connection lost
497 */
498 private void sortDsList() {
499 int srvCnt = _dsList.length;
500 for (int i=1; i < srvCnt; i++) {
501 for (int j=0; j < i; j++) {
502 if (_dsList[i].connSetupStatus < _dsList[j].connSetupStatus) {
503 // swap entries
504 ServerEntry entry = _dsList[j];
505 _dsList[j] = _dsList[i];
506 _dsList[i] = entry;
507 }
508 }
509 }
510 }
511
512 /**
513 * This is used only by the ldapjdk test libaray to simulate a
514 * server problem and to test fail-over and rebind
515 * @return A flag whether the connection was closed
516 */
517 boolean breakConnection() {
518 try {
519 _socket.close();
520 return true;
521 }
522 catch (Exception e) {
523 return false;
524 }
525 }
526
527 public String toString() {
528 String str = "dsIdx="+_dsIdx+ " dsList=";
529 for (int i=0; i < _dsList.length; i++) {
530 str += _dsList[i]+ " ";
531 }
532 return str;
533 }
534
535 int getID() {
536 return _id;
537 }
538
539 String getLDAPUrl() {
540 return ((_factory == null) ? "ldap" : "ldaps") +
541 "://" + getHost() + ":" + getPort();
542 }
543
544 public Object clone() {
545 try {
546 LDAPConnSetupMgr cloneMgr = (LDAPConnSetupMgr) super.clone();
547 cloneMgr._dsList = new ServerEntry[_dsList.length];
548 for (int i=0; i<_dsList.length; i++) {
549 ServerEntry e = _dsList[i];
550 cloneMgr._dsList[i] = new ServerEntry(e.host, e.port, e.connSetupStatus);
551 }
552 return cloneMgr;
553 }
554 catch (CloneNotSupportedException ex) {
555 return null;
556 }
557 }
558 }