2
* JBoss, Home of Professional Open Source
3
* Copyright 2005, JBoss Inc., and individual contributors as indicated
4
* by the @authors tag. See the copyright.txt in the distribution for a
5
* full listing of individual contributors.
7
* This is free software; you can redistribute it and/or modify it
8
* under the terms of the GNU Lesser General Public License as
9
* published by the Free Software Foundation; either version 2.1 of
10
* the License, or (at your option) any later version.
12
* This software is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
* Lesser General Public License for more details.
17
* You should have received a copy of the GNU Lesser General Public
18
* License along with this software; if not, write to the Free
19
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
23
package org.jboss.remoting;
25
import java.security.AccessController;
26
import java.security.PrivilegedAction;
27
import java.security.PrivilegedActionException;
28
import java.security.PrivilegedExceptionAction;
29
import java.util.HashMap;
30
import java.util.HashSet;
31
import java.util.Iterator;
34
import java.util.Timer;
35
import java.util.TimerTask;
37
import org.jboss.logging.Logger;
38
import org.jboss.remoting.transport.ClientInvoker;
39
import org.jboss.remoting.util.StoppableTimerTask;
40
import org.jboss.remoting.util.TimerUtil;
43
* @author <a href="mailto:tom.elrod@jboss.com">Tom Elrod</a>
44
* @author <a href="mailto:ovidiu@jboss.org">Ovidiu Feodorov</a>
45
* @author <a href="mailto:tlee@redhat.com">Trustin Lee</a>
47
public class ConnectionValidator extends TimerTask implements StoppableTimerTask
49
// Constants ------------------------------------------------------------------------------------
51
private static final Logger log = Logger.getLogger(ConnectionValidator.class.getName());
53
/** Configuration map key for ping period. */
54
public static final String VALIDATOR_PING_PERIOD = "validatorPingPeriod";
56
/** Default ping period. Value is 2 seconds. */
57
public static final long DEFAULT_PING_PERIOD = 2000;
59
/** Configuration map key for ping timeout. */
60
public static final String VALIDATOR_PING_TIMEOUT = "validatorPingTimeout";
62
/** Default ping timeout period. Value is 1 second. */
63
public static final String DEFAULT_PING_TIMEOUT = "1000";
65
/** Default ping timeout period. Value is 1 second. */
66
public static final int DEFAULT_PING_TIMEOUT_INT = 1000;
69
* Default number of ping retries. Value is 1.
70
* Currently implemented only on socket transport family.
72
public static final String DEFAULT_NUMBER_OF_PING_RETRIES = "1";
75
* Key to determine if ConnectionValidator should tie failure to presence
76
* of active lease on server side. Default value is "true".
78
public static final String TIE_TO_LEASE = "tieToLease";
81
* Key to determine whether to stop ConnectionValidator when PING fails.
82
* Default value is "true".
84
public static final String STOP_LEASE_ON_FAILURE = "stopLeaseOnFailure";
87
* Key to determine value of disconnectTimeout upon connection failure.
89
public static final String FAILURE_DISCONNECT_TIMEOUT = "failureDisconnectTimeout";
91
// Static ---------------------------------------------------------------------------------------
93
private static boolean trace = log.isTraceEnabled();
96
* Will make $PING$ invocation on server. If sucessful, will return true. Otherwise, will throw
99
* @param locator - locator for the server to ping
100
* @param config - any configuration needed for server
101
* @return true if alive, false if not
103
public static boolean checkConnection(final InvokerLocator locator, Map config) throws Throwable
105
boolean pingWorked = false;
106
final Map configMap = createPingConfig(config, null);
107
int pingTimeout = Integer.parseInt((String) configMap.get(ServerInvoker.TIMEOUT));
108
ClientInvoker innerClientInvoker = null;
114
innerClientInvoker = (ClientInvoker) AccessController.doPrivileged( new PrivilegedExceptionAction()
116
public Object run() throws Exception
118
return InvokerRegistry.createClientInvoker(locator, configMap);
122
catch (PrivilegedActionException pae)
124
throw pae.getException();
127
if (!innerClientInvoker.isConnected())
129
if (trace) { log.trace("inner client invoker not connected, connecting ..."); }
130
innerClientInvoker.connect();
133
pingWorked = doCheckConnection(innerClientInvoker, pingTimeout);
135
catch (Throwable throwable)
137
log.debug("ConnectionValidator unable to connect to server " +
138
innerClientInvoker.getLocator().getProtocol() + "://" +
139
innerClientInvoker.getLocator().getHost() + ":" +
140
innerClientInvoker.getLocator().getPort(), throwable);
144
if (innerClientInvoker != null)
146
AccessController.doPrivileged( new PrivilegedAction()
150
InvokerRegistry.destroyClientInvoker(locator, configMap);
160
private static boolean doCheckConnection(ClientInvoker clientInvoker, int pingTimeout) throws Throwable
162
boolean pingWorked = false;
166
// Sending null client id as don't want to trigger lease on server side. This also means
167
// that client connection validator will NOT impact client lease, so can not depend on it
168
// to maintain client lease with the server.
169
InvocationRequest ir;
170
ir = new InvocationRequest(null, Subsystem.SELF, "$PING$", null, null, null);
171
ConnectionCheckThread t = new ConnectionCheckThread(clientInvoker, ir);
173
Thread.sleep(pingTimeout);
174
pingWorked = t.isValid();
178
log.debug("ConnectionValidator failed to ping via " + clientInvoker, t);
184
private static Map createPingConfig(Map config, Map metadata)
186
Map localConfig = new HashMap();
187
localConfig.put("connection_checker", "true");
191
Object o = config.get(VALIDATOR_PING_TIMEOUT);
192
log.trace("config timeout: " + o);
197
Integer.parseInt((String) o);
198
localConfig.put(ServerInvoker.TIMEOUT, o);
200
catch (NumberFormatException e)
202
log.warn("Need integer for value of parameter " + VALIDATOR_PING_TIMEOUT +
203
". Using default value " + DEFAULT_PING_TIMEOUT);
207
o = config.get("NumberOfCallRetries");
210
localConfig.put("NumberOfCallRetries", o);
214
if (metadata != null)
216
metadata.remove(ServerInvoker.TIMEOUT);
217
localConfig.putAll(metadata);
218
Object o = metadata.get(VALIDATOR_PING_TIMEOUT);
223
Integer.parseInt((String) o);
224
localConfig.put(ServerInvoker.TIMEOUT, o);
226
catch (NumberFormatException e)
228
log.warn("Need integer for value of parameter " + VALIDATOR_PING_TIMEOUT +
229
". Using default value " + DEFAULT_PING_TIMEOUT);
234
if (localConfig.get(ServerInvoker.TIMEOUT) == null)
236
localConfig.put(ServerInvoker.TIMEOUT, DEFAULT_PING_TIMEOUT);
239
if (localConfig.get("NumberOfCallRetries") == null)
241
localConfig.put("NumberOfCallRetries", DEFAULT_NUMBER_OF_PING_RETRIES);
247
// Attributes -----------------------------------------------------------------------------------
249
private Client client;
250
private long pingPeriod;
251
private Map metadata;
252
private InvokerLocator locator;
253
private Map configMap;
254
private Map listeners;
255
private ClientInvoker clientInvoker;
256
private Object lock = new Object();
257
private Object notificationLock = new Object();
258
private boolean started;
259
private volatile boolean stopped;
260
private volatile boolean stopping;
261
private String invokerSessionId;
262
private boolean tieToLease = true;
263
private boolean stopLeaseOnFailure = true;
264
private int pingTimeout;
265
private int failureDisconnectTimeout = -1;
266
private volatile boolean isValid;
268
private MicroRemoteClientInvoker sharedInvoker;
269
private LeasePinger leasePinger;
270
private boolean useClientConnectionIdentity;
272
// Constructors ---------------------------------------------------------------------------------
274
public ConnectionValidator(Client client)
276
this(client, DEFAULT_PING_PERIOD);
279
public ConnectionValidator(Client client, long pingPeriod)
281
this.client = client;
282
this.locator = client.getInvoker().getLocator();
283
this.pingPeriod = pingPeriod;
284
pingTimeout = DEFAULT_PING_TIMEOUT_INT;
285
listeners = new HashMap();
287
getParameters(client, new HashMap());
288
log.debug(this + " created");
291
public ConnectionValidator(Client client, Map metadata)
293
this.client = client;
294
this.locator = client.getInvoker().getLocator();
295
pingPeriod = DEFAULT_PING_PERIOD;
296
pingTimeout = DEFAULT_PING_TIMEOUT_INT;
297
listeners = new HashMap();
299
this.metadata = new HashMap(metadata);
300
getParameters(client, metadata);
301
log.debug(this + " created");
304
// StoppableTimerTask implementation ------------------------------------------------------------
316
// TimerTask overrides --------------------------------------------------------------------------
319
* The action to be performed by this timer task.
327
throw new IllegalStateException(
328
ConnectionValidator.class.getName() + ".run() should not be " +
329
"called directly; use " + ConnectionValidator.class.getName() +
330
".addConnectionListener() instead.");
338
TimerTask tt = new WaitOnConnectionCheckTimerTask();
342
timer.schedule(tt, 0);
344
catch (IllegalStateException e)
346
log.debug("Unable to schedule TimerTask on existing Timer", e);
347
timer = new Timer(true);
348
timer.schedule(tt, 0);
358
if (tieToLease && client.getLeasePeriod() > 0)
362
log.trace(this + " sending PING tied to lease");
364
isValid = doCheckConnectionWithLease();
368
if (trace) { log.trace(this + " pinging ..."); }
369
isValid = doCheckConnectionWithoutLease();
373
catch (Throwable thr)
375
log.debug(this + " got throwable while pinging", thr);
377
if (stopLeaseOnFailure)
379
log.debug(this + " detected connection failure: stopping");
385
synchronized (notificationLock)
387
notificationLock.notifyAll();
392
public boolean cancel()
397
// Public ---------------------------------------------------------------------------------------
399
public boolean addConnectionListener(Client client, ConnectionListener listener)
401
boolean doStart = false;
402
if (listener != null)
408
if (trace) log.trace(this + " is stopped. Cannot add ConnectionListener: " + listener + " for " + client);
411
if (listeners.size() == 0)
415
Set s = (Set) listeners.get(listener);
421
listeners.put(listener, s);
422
log.debug(this + " added ConnectionListener: " + listener + " for " + client);
433
public boolean removeConnectionListener(Client client, ConnectionListener listener)
435
if (listener == null)
437
if (trace) log.trace(this + " ConnectionListener is null");
444
if (trace) log.trace(this + " is stopped. It's too late to remove " + listener);
447
Set s = (Set) listeners.get(listener);
450
log.debug(this + ": " + listener + " is not registered");
453
if (s.remove(client))
455
log.debug(this + " removed ConnectionListener: " + listener + " for " + client);
459
log.debug(this + ": " + listener + " is not registered for " + client);
464
listeners.remove(listener);
466
if (listeners.size() == 0)
474
public long getPingPeriod()
484
public String toString()
486
return "ConnectionValidator[" + Integer.toHexString(System.identityHashCode(this)) + ":" + clientInvoker + ", pingPeriod=" + pingPeriod + " ms]";
489
public boolean isStopped()
494
// Package protected ----------------------------------------------------------------------------
496
void notifyListeners(Throwable thr)
498
final Throwable t = thr;
506
if (trace) log.trace(this + " is stopped. No more listeners will be accepted.");
508
Iterator itr = listeners.keySet().iterator();
509
while (itr.hasNext())
511
final ConnectionListener listener = (ConnectionListener) itr.next();
512
Set clients = (Set) listeners.get(listener);
513
Iterator itr2 = clients.iterator();
514
while (itr2.hasNext())
516
final Client client = (Client) itr2.next();
521
log.debug(ConnectionValidator.this + " calling " + listener + ".handleConnectionException() for " + client);
522
listener.handleConnectionException(t, client);
534
// Protected ------------------------------------------------------------------------------------
536
// Private --------------------------------------------------------------------------------------
538
private void getParameters(Client client, Map metadata)
540
if (checkUseParametersFromLocator(client, metadata))
542
getParametersFromMap(client.getInvoker().getLocator().getParameters());
544
getParametersFromMap(client.getConfiguration());
545
getParametersFromMap(metadata);
547
ClientInvoker clientInvoker = client.getInvoker();
548
if (clientInvoker instanceof MicroRemoteClientInvoker)
550
sharedInvoker = (MicroRemoteClientInvoker) clientInvoker;
551
invokerSessionId = sharedInvoker.getSessionId();
555
throw new RuntimeException("creating a ConnectionValidator on a local connection");
557
if (stopLeaseOnFailure)
559
if (sharedInvoker != null)
561
leasePinger = sharedInvoker.getLeasePinger();
564
if (trace) log.trace(this + ": sharedInvoker = " + sharedInvoker + ", leasePinger = " + leasePinger);
567
private boolean checkUseParametersFromLocator(Client client, Map metadata)
569
if (client.getInvoker() == null)
573
Object o = client.getInvoker().getLocator().getParameters().get(Client.USE_ALL_PARAMS);
576
if (o instanceof String)
578
return Boolean.valueOf(((String) o)).booleanValue();
582
log.warn(this + " could not convert " + Client.USE_ALL_PARAMS + " value" +
583
" in InvokerLocator to a boolean: must be a String");
586
o = client.getConfiguration().get(Client.USE_ALL_PARAMS);
589
if (o instanceof String)
591
return Boolean.valueOf(((String) o)).booleanValue();
595
log.warn(this + " could not convert " + Client.USE_ALL_PARAMS + " value" +
596
" in Client configuration map to a boolean: must be a String");
599
o = metadata.get(Client.USE_ALL_PARAMS);
602
if (o instanceof String)
604
return Boolean.valueOf(((String) o)).booleanValue();
608
log.warn(this + " could not convert " + Client.USE_ALL_PARAMS + " value" +
609
" in metadata map to a boolean: must be a String");
615
private void getParametersFromMap(Map config)
619
Object o = config.get(VALIDATOR_PING_PERIOD);
622
if (o instanceof String)
626
pingPeriod = Long.parseLong((String)o);
630
log.warn(this + " could not convert " + VALIDATOR_PING_PERIOD +
631
" value of " + o + " to a long value");
636
log.warn(this + " could not convert " + VALIDATOR_PING_PERIOD +
637
" value of " + o + " to a long value: must be a String");
641
o = config.get(VALIDATOR_PING_TIMEOUT);
644
if (o instanceof String)
648
pingTimeout = Integer.parseInt((String)o);
652
log.warn(this + " could not convert " + VALIDATOR_PING_TIMEOUT +
653
" value of " + o + " to a long value");
658
log.warn(this + " could not convert " + VALIDATOR_PING_TIMEOUT +
659
" value of " + o + " to a long value: must be a String");
663
o = config.get(TIE_TO_LEASE);
666
if (o instanceof String)
670
tieToLease = Boolean.valueOf(((String) o)).booleanValue();
674
log.warn(this + " could not convert " + TIE_TO_LEASE + " value" +
675
" to a boolean: " + o);
680
log.warn(this + " could not convert " + TIE_TO_LEASE + " value" +
681
" to a boolean: must be a String");
685
o = config.get(STOP_LEASE_ON_FAILURE);
688
if (o instanceof String)
692
stopLeaseOnFailure = Boolean.valueOf(((String) o)).booleanValue();
696
log.warn(this + " could not convert " + STOP_LEASE_ON_FAILURE + " value" +
697
" to a boolean: " + o);
702
log.warn(this + " could not convert " + STOP_LEASE_ON_FAILURE + " value" +
703
" to a boolean: must be a String");
707
o = config.get(FAILURE_DISCONNECT_TIMEOUT);
708
if (trace) log.trace(this + " \"failureDisconnectTimeout\" set to " + o);
711
if (o instanceof String)
715
failureDisconnectTimeout = Integer.valueOf(((String) o)).intValue();
716
if (trace) log.trace(this + " setting failureDisconnectTimeout to " + failureDisconnectTimeout);
720
log.warn(this + " could not convert " + FAILURE_DISCONNECT_TIMEOUT + " value" +
726
log.warn(this + " could not convert " + FAILURE_DISCONNECT_TIMEOUT + " value" +
727
" to an int: must be a String");
730
o = config.get(Remoting.USE_CLIENT_CONNECTION_IDENTITY);
733
if (o instanceof String)
737
useClientConnectionIdentity = Boolean.valueOf(((String) o)).booleanValue();
741
log.warn(this + " could not convert " + Remoting.USE_CLIENT_CONNECTION_IDENTITY + " value" +
742
" to a boolean: " + o);
747
log.warn(this + " could not convert " + Remoting.USE_CLIENT_CONNECTION_IDENTITY + " value" +
748
" to a boolean: must be a String");
756
metadata.put(ServerInvoker.TIMEOUT, Integer.toString(pingTimeout));
757
configMap = createPingConfig(client.getConfiguration(), metadata);
758
log.debug(this + ": pingPeriod: " + this.pingPeriod);
759
log.debug(this + ": pingTimeout: " + this.pingTimeout);
760
log.debug(this + ": ping retries: " + configMap.get("NumberOfCallRetries"));
766
clientInvoker = (ClientInvoker) AccessController.doPrivileged( new PrivilegedExceptionAction()
768
public Object run() throws Exception
770
return InvokerRegistry.createClientInvoker(locator, configMap);
774
catch (PrivilegedActionException pae)
776
throw pae.getException();
781
log.debug("Unable to create client invoker for locator: " + locator);
782
throw new RuntimeException("Unable to create client invoker for locator: " + locator, e);
785
if (!clientInvoker.isConnected())
787
if (trace) { log.trace("inner client invoker not connected, connecting ..."); }
788
clientInvoker.connect();
792
timer = new Timer(true);
796
TimerUtil.schedule(this, pingPeriod);
800
log.error(this + " unable to schedule on TimerUtil", e);
805
log.debug(this + " started");
808
private boolean doCheckConnectionWithLease() throws Throwable
810
boolean pingWorked = false;
814
Map metadata = new HashMap();
815
metadata.put(ServerInvoker.INVOKER_SESSION_ID, invokerSessionId);
816
InvocationRequest ir =
817
new InvocationRequest(null, Subsystem.SELF, "$PING$", metadata, null, null);
819
if (trace) { log.trace("pinging, sending " + ir + " over " + clientInvoker); }
821
Object o = clientInvoker.invoke(ir);
822
if (o instanceof Boolean && !((Boolean) o).booleanValue())
824
// Server indicates lease has stopped.
825
throw new Exception();
828
if (trace) { log.trace("ConnectionValidator got successful ping using " + clientInvoker);}
834
log.debug("ConnectionValidator failed to ping via " + clientInvoker, t);
840
private boolean doCheckConnectionWithoutLease() throws Throwable
842
boolean pingWorked = false;
846
// Sending null client id as don't want to trigger lease on server side. This also means
847
// that client connection validator will NOT impact client lease, so can not depend on it
848
// to maintain client lease with the server.
849
InvocationRequest ir =
850
new InvocationRequest(null, Subsystem.SELF, "$PING$", null, null, null);
852
if (trace) { log.trace("pinging, sending " + ir + " over " + clientInvoker); }
854
clientInvoker.invoke(ir);
856
if (trace) { log.trace("ConnectionValidator got successful ping using " + clientInvoker);}
862
log.debug("ConnectionValidator failed to ping via " + clientInvoker, t);
868
private boolean doStop()
870
if (trace) log.trace("entering doStop()");
878
if (!listeners.isEmpty())
887
if (clientInvoker != null)
889
AccessController.doPrivileged( new PrivilegedAction()
893
InvokerRegistry.destroyClientInvoker(locator, configMap);
899
TimerUtil.unschedule(this);
901
boolean result = super.cancel();
902
log.debug(this + " stopped, returning " + result);
906
// Inner classes --------------------------------------------------------------------------------
908
private class WaitOnConnectionCheckTimerTask extends TimerTask
912
long start = System.currentTimeMillis();
913
synchronized (notificationLock)
917
int elapsed = (int) (System.currentTimeMillis() - start);
918
int wait = pingTimeout - elapsed;
926
notificationLock.wait(wait);
929
catch (InterruptedException e)
938
log.debug(ConnectionValidator.this + "'s connection is invalid");
939
ConnectionValidator.super.cancel();
941
if (stopLeaseOnFailure)
943
if (trace) log.trace(ConnectionValidator.this + " detected connection failure: stopping LeasePinger");
944
if (leasePinger != null)
946
log.debug(ConnectionValidator.this + " shutting down lease pinger: " + leasePinger);
947
int disconnectTimeout = (failureDisconnectTimeout == -1) ? client.getDisconnectTimeout() : failureDisconnectTimeout;
948
if (trace) log.trace(ConnectionValidator.this + " disconnectTimeout: " + disconnectTimeout);
949
sharedInvoker.terminateLease(null, disconnectTimeout, leasePinger);
953
if (trace) log.trace(ConnectionValidator.this + ": lease pinger == null: perhaps leasing is not enabled for this connection");
954
notifyListeners(new Exception("Could not connect to server!"));
959
if (!useClientConnectionIdentity)
961
notifyListeners(new Exception("Could not connect to server!"));
967
private static class ConnectionCheckThread extends Thread
969
private InvocationRequest ir;
970
private ClientInvoker clientInvoker;
971
private boolean isValid;
973
public ConnectionCheckThread(ClientInvoker clientInvoker, InvocationRequest ir)
975
this.clientInvoker = clientInvoker;
984
if (trace) { log.trace("pinging, sending " + ir + " over " + clientInvoker); }
985
clientInvoker.invoke(ir);
987
if (trace) { log.trace("ConnectionValidator got successful ping using " + clientInvoker);}
991
log.debug("ConnectionValidator failed to ping via " + clientInvoker, t);
995
public boolean isValid()
b'\\ No newline at end of file'