use of com.sun.messaging.jmq.jmsserver.FaultInjection in project openmq by eclipse-ee4j.
the class DBConnectionPool method getConnection.
/**
* Checks out a connection from the pool.
*/
public Connection getConnection() throws BrokerException {
if (DEBUG) {
logger.log(Logger.INFO, "[" + Thread.currentThread() + "]" + toString() + ".getConnection");
}
if (DEBUG) {
FaultInjection fi = FaultInjection.getInjection();
if (fi.FAULT_INJECTION) {
fi.checkFaultAndSleep(FaultInjection.FAULT_JDBC_GETCONN_1, null);
}
}
Connection conn = null;
boolean createdNew = false, pollWait = false;
ConnectionInfo cinfo = idleConnections.poll();
if (cinfo == null && (activeConnections.size() < maxConnections)) {
cinfo = createConnection();
try {
conn = cinfo.getConnection();
} catch (Exception e) {
destroyConnection(cinfo);
throw new BrokerException(cinfo + e.getMessage(), e);
}
if (DEBUG) {
createdNew = true;
}
} else {
// Wait until a connetion is free up
while (cinfo == null) {
try {
if (DEBUG) {
if (!pollWait) {
pollWait = true;
}
}
int pollto = pollTimeout;
if (BrokerStateHandler.isStoreShutdownStage1()) {
throw new BrokerException(br.getKString(br.W_DB_POOL_CLOSING, name));
}
if (BrokerStateHandler.getShutdownThread() == Thread.currentThread()) {
pollto = 60;
}
int slept = 0;
while (!BrokerStateHandler.isStoreShutdownStage1() && (pollto <= 0 || slept < pollto)) {
if (slept != 0 && (slept % 15 == 0)) {
logger.log(logger.INFO, br.getKString(br.I_DB_POOL_POLL_WAIT, Thread.currentThread()) + toString());
}
cinfo = idleConnections.poll(1, TimeUnit.SECONDS);
if (cinfo != null) {
break;
}
if (BrokerStateHandler.isStoreShutdownStage1()) {
throw new BrokerException(br.getKString(br.W_DB_POOL_CLOSING, name));
}
cinfo = idleConnections.poll();
if (cinfo != null) {
break;
}
if (activeConnections.size() < maxConnections) {
cinfo = createConnection();
if (DEBUG) {
createdNew = true;
}
break;
}
slept++;
if (slept % 60 == 0 || (pollto > 0 && slept == pollto)) {
StringBuilder buff = new StringBuilder(1024);
Iterator itr = activeConnections.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry) itr.next();
Thread t = (Thread) e.getValue();
buff.append('\n').append(t.getName()).append(": using connection: ").append(e.getKey());
StackTraceElement[] trace = t.getStackTrace();
for (int i = 0; i < trace.length; i++) {
buff.append("\n\tat " + trace[i]);
}
}
String emsg = br.getKTString(br.I_DB_CONN_POLL_TIMEOUT, "(" + activeConnections.size() + "," + idleConnections.size() + ")[" + minConnections + "," + maxConnections + "]", String.valueOf(slept)) + "\n" + buff.toString();
logger.log(Logger.WARNING, emsg + toString());
}
}
if (cinfo == null) {
throw new BrokerException(br.getKTString(br.W_DB_POOL_POLL_TIMEOUT));
}
} catch (Exception e) {
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
if (DEBUG) {
logger.logStack(Logger.INFO, toString() + ".getConnection: " + e.getMessage(), e);
}
}
}
boolean valid = true;
if (getInvalidateAllTimestamp(cinfo.getCreationTime()) != null) {
valid = false;
}
if (!valid || !validateConnection(cinfo, validateOnGet, true)) {
destroyConnection(cinfo);
try {
cinfo = createConnection();
conn = cinfo.getConnection();
logger.log(Logger.INFO, br.getKString(BrokerResources.I_RECONNECT_TO_DB, "" + cinfo, dbmgr.getOpenDBURL()) + toString());
} catch (Exception e) {
destroyConnection(cinfo);
String emsg = br.getString(BrokerResources.X_RECONNECT_TO_DB_FAILED, dbmgr.getOpenDBURL());
logger.logStack(Logger.ERROR, emsg + toString(), e);
throw new BrokerException(emsg, e);
}
} else {
try {
conn = cinfo.getConnection();
} catch (Exception e) {
destroyConnection(cinfo);
throw new BrokerException(cinfo + e.getMessage(), e);
}
}
}
// move the connection in the activeConnections list
Thread borrower = Thread.currentThread();
activeConnections.put(cinfo, borrower);
if (DEBUG) {
logger.log(Logger.INFO, toString() + ".getConnection[" + createdNew + "," + pollWait + "]: " + borrower.getName() + " [" + new Date() + "]: check out connection: 0x" + conn.hashCode() + cinfo);
}
return conn;
}
use of com.sun.messaging.jmq.jmsserver.FaultInjection in project openmq by eclipse-ee4j.
the class Destination method load.
public synchronized LinkedHashMap load(boolean neverExpire, Map preparedAcks, Map transactionStates, Map committingTrans, Set takeoverMsgs, boolean noerrnotfound) throws BrokerException {
if (Globals.getStore().getPartitionModeEnabled() && takeoverMsgs != null) {
String emsg = br.getKString(br.E_INTERNAL_BROKER_ERROR, ": Unexpected call:Destination.load(takeoverMsgs) for partition mode");
BrokerException ex = new BrokerException(emsg);
logger.logStack(logger.ERROR, emsg, ex);
throw ex;
}
if (loaded) {
return null;
}
logger.log(Logger.INFO, br.getKString(br.I_LOADING_DESTINATION, toString(), String.valueOf(size)) + logsuffix);
LinkedHashMap preparedTrans = null;
boolean enforceLimit = true;
Set deadMsgs = new HashSet();
int maxloadcnt = size;
int curcnt = 0;
try {
enforceLimit = destMessages.getEnforceLimits();
destMessages.enforceLimits(false);
Enumeration msgs = null;
try {
msgs = pstore.messageEnumeration(this);
} catch (DestinationNotFoundException e) {
if (noerrnotfound) {
logger.log(Logger.INFO, br.getKString(BrokerResources.I_LOAD_DST_NOTFOUND_INSTORE, getName(), e.getMessage()));
return null;
}
throw e;
}
MessageDeliveryTimeTimer dt = deliveryTimeTimer;
SortedSet s = null;
try {
// no other store access should occur in this block
HAMonitorService haMonitor = Globals.getHAMonitorService();
boolean takingoverCheck = (takeoverMsgs == null && !Globals.getStore().getPartitionModeEnabled() && Globals.getHAEnabled() && haMonitor != null && haMonitor.checkTakingoverDestination(this));
if (dt == null && !isDMQ()) {
if (!isValid()) {
String emsg = br.getKString(br.X_LOAD_MSGS_TO_DESTROYED_DST, getDestinationUID());
logger.log(logger.WARNING, emsg);
throw new BrokerException(emsg);
}
String emsg = br.getKString(br.X_LOAD_MSGS_TO_DST_NO_DELIVERY_TIMER, getDestinationUID());
logger.log(logger.WARNING, emsg);
throw new BrokerException(emsg);
}
s = new TreeSet(new RefCompare());
while (msgs.hasMoreElements()) {
Packet p = (Packet) msgs.nextElement();
PacketReference pr = PacketReference.createReference(pstore, p, uid, null);
if (isDMQ()) {
pr.clearDeliveryTimeInfo();
}
if (takeoverMsgs != null && takeoverMsgs.contains(pr)) {
pr = null;
continue;
}
if (takingoverCheck && haMonitor.checkTakingoverMessage(p)) {
pr = null;
continue;
}
MessageDeliveryTimeInfo di = pr.getDeliveryTimeInfo();
if (di != null) {
dt.removeMessage(di);
}
if (neverExpire) {
pr.overrideExpireTime(0);
}
// mark already stored and make packet a SoftReference to
// prevent running out of memory if dest has lots of msgs
pr.setLoaded();
if (getDEBUG()) {
logger.log(Logger.INFO, "Loaded Message " + p + " into destination " + this);
}
try {
if (!isDMQ && !DL.addNewMessage(false, pr).getReturn()) {
// expired
deadMsgs.add(pr);
}
} catch (Exception ex) {
String[] args = { pr.getSysMessageID().toString(), pr.getDestinationUID().toString(), ex.getMessage() };
logger.logStack(Logger.WARNING, BrokerResources.W_CAN_NOT_LOAD_MSG, args, ex);
continue;
}
s.add(pr);
DL.packetlistAdd(pr.getSysMessageID(), pr.getDestinationUID(), null);
curcnt++;
if (curcnt > 0 && (curcnt % LOAD_COUNT == 0 || (curcnt > LOAD_COUNT && curcnt == size))) {
String[] args = { toString(), String.valueOf(curcnt), String.valueOf(maxloadcnt), String.valueOf((curcnt * 100) / maxloadcnt) };
logger.log(Logger.INFO, BrokerResources.I_LOADING_DEST_IN_PROCESS, args);
}
}
} finally {
pstore.closeEnumeration(msgs);
}
if (FaultInjection.getInjection().FAULT_INJECTION) {
FaultInjection fi = FaultInjection.getInjection();
try {
fi.checkFaultAndThrowBrokerException(FaultInjection.FAULT_LOAD_DST_1_5, null);
} catch (BrokerException e) {
fi.unsetFault(fi.FAULT_LOAD_DST_1_5);
throw e;
}
}
// now we're sorted, process
Iterator itr = s.iterator();
while (itr.hasNext()) {
PacketReference pr = (PacketReference) itr.next();
// ok .. see if we need to remove the message
ConsumerUID[] consumers = pstore.getConsumerUIDs(getDestinationUID(), pr.getSysMessageID());
if (consumers == null) {
consumers = new ConsumerUID[0];
}
if (getDEBUG()) {
logger.log(Logger.INFO, consumers.length + " stored consumers for " + pr + ":" + getDestinationUID());
}
if (consumers.length == 0 && pstore.hasMessageBeenAcked(uid, pr.getSysMessageID())) {
if (getDEBUG()) {
logger.log(Logger.INFO, "Message " + pr.getSysMessageID() + "[" + this + "] has been acked, destory..");
}
decrementDestinationSize(pr);
DL.removePacketList(pr.getSysMessageID(), pr.getDestinationUID(), pr);
pr.destroy();
continue;
}
if (consumers.length > 0) {
pr.setStoredWithInterest(true);
} else {
pr.setStoredWithInterest(false);
}
// first producer side transactions
MessageDeliveryTimeInfo di = pr.getDeliveryTimeInfo();
boolean dontRoute = false;
boolean delayDelivery = false;
if (di != null && !di.isDeliveryDue()) {
dt.addMessage(di);
delayDelivery = true;
dontRoute = true;
}
TransactionUID sendtid = pr.getTransactionID();
if (sendtid != null) {
// if unrouted and not in rollback -> remove
Boolean state = (Boolean) (transactionStates == null ? null : transactionStates.get(sendtid));
// at this point, we should be down to 3 states
if (state == null) {
if (consumers.length == 0 && !delayDelivery) {
// message
try {
consumers = routeLoadedTransactionMessage(pr);
} catch (Exception ex) {
logger.logStack(Logger.WARNING, br.getKString(br.W_EXCEPTION_ROUTE_LOADED_MSG, pr.getSysMessageID(), ex.getMessage()), ex);
}
if (consumers.length > 0) {
int[] states = new int[consumers.length];
for (int i = 0; i < states.length; i++) {
states[i] = PartitionedStore.INTEREST_STATE_ROUTED;
}
try {
pstore.storeInterestStates(getDestinationUID(), pr.getSysMessageID(), consumers, states, true, null);
pr.setStoredWithInterest(true);
} catch (Exception ex) {
// ok .. maybe weve already been routed
}
} else {
if (getDEBUG()) {
logger.log(Logger.INFO, "Message " + pr.getSysMessageID() + " [TUID=" + pr.getTransactionID() + ", " + this + "] no interest" + ", destroy...");
}
decrementDestinationSize(pr);
DL.removePacketList(pr.getSysMessageID(), pr.getDestinationUID(), pr);
pr.destroy();
continue;
}
}
} else if (state.equals(Boolean.TRUE)) {
if (preparedTrans == null) {
preparedTrans = new LinkedHashMap();
}
preparedTrans.put(pr.getSysMessageID(), pr.getTransactionID());
dontRoute = true;
} else {
// rolledback
if (getDEBUG()) {
logger.log(Logger.INFO, "Message " + pr.getSysMessageID() + " [TUID=" + pr.getTransactionID() + ", " + this + "] to be rolled back" + ", destroy...");
}
decrementDestinationSize(pr);
DL.removePacketList(pr.getSysMessageID(), pr.getDestinationUID(), pr);
pr.destroy();
continue;
}
}
if (consumers.length == 0 && !dontRoute) {
if (getDEBUG()) {
logger.log(Logger.INFO, "No consumer and dontRoute: Unrouted packet " + pr + ", " + this);
}
decrementDestinationSize(pr);
DL.removePacketList(pr.getSysMessageID(), pr.getDestinationUID(), pr);
pr.destroy();
continue;
}
int[] states = new int[consumers.length];
for (int i = 0; i < consumers.length; i++) {
states[i] = pstore.getInterestState(getDestinationUID(), pr.getSysMessageID(), consumers[i]);
}
if (consumers.length > 0) {
pr.update(consumers, states);
}
try {
putMessage(pr, AddReason.LOADED);
} catch (IllegalStateException | OutOfLimitsException ex) {
String[] args = { pr.getSysMessageID().toString(), pr.getDestinationUID().toString(), ex.getMessage() };
logger.logStack(Logger.WARNING, BrokerResources.W_CAN_NOT_LOAD_MSG, args, ex);
continue;
}
ExpirationInfo ei = pr.getExpireInfo();
if (ei != null && expireReaper != null) {
expireReaper.addExpiringMessage(ei);
}
List<ConsumerUID> consumerList = Arrays.asList(consumers);
// now, deal with consumer side transactions
Map transCidToState = (Map) (preparedAcks == null ? null : preparedAcks.get(pr.getSysMessageID()));
if (transCidToState != null) {
// ok .. this isnt code focused on performance, but
// its rarely called and only once
// new a new list that allows itr.remove()
consumerList = new ArrayList<>(consumerList);
Iterator citr = consumerList.iterator();
while (citr.hasNext()) {
ConsumerUID cuid = (ConsumerUID) citr.next();
TransactionUID tid = (TransactionUID) transCidToState.get(cuid);
Boolean state = Boolean.FALSE;
if (tid != null) {
state = (Boolean) (transactionStates == null ? null : transactionStates.get(tid));
}
// OK for committed transactions, acknowledge
if (state == null) {
if (getDEBUG()) {
logger.log(Logger.INFO, "Consumed message has committed state " + pr.getSysMessageID() + " [TUID=" + tid + ", " + this + "]" + ", consumer: " + cuid);
}
// acknowledge
if (pr.acknowledged(cuid, cuid, false, true)) {
if (committingTrans != null && committingTrans.get(tid) != null) {
unputMessage(pr, RemoveReason.ACKNOWLEDGED);
}
decrementDestinationSize(pr);
DL.removePacketList(pr.getSysMessageID(), pr.getDestinationUID(), pr);
pr.destroy();
if (getDEBUG()) {
logger.log(Logger.INFO, "Remove committed consumed message " + pr.getSysMessageID() + " [TUID=" + tid + ", " + this + "]" + ", consumer: " + cuid);
}
}
citr.remove();
continue;
} else if (state.equals(Boolean.TRUE)) {
// for prepared transactions, dont route
citr.remove();
} else if (state.equals(Boolean.FALSE)) {
// for rolled back transactions, do nothing
if (getDEBUG()) {
logger.log(Logger.INFO, "Redeliver message " + pr.getSysMessageID() + " [TUID=" + tid + ", " + this + "]" + " to consumer " + cuid);
}
}
}
// done processing acks
}
// dont recurse
loaded = true;
if (!dontRoute) {
if (getDEBUG()) {
logger.log(Logger.INFO, "Route loaded message " + pr.getSysMessageID() + " [" + this + "]" + " to consumers " + consumerList);
}
if (di != null) {
forwardDeliveryDelayedMessage(new HashSet<>(consumerList), pr);
} else {
routeLoadedMessage(pr, consumerList);
}
} else if (delayDelivery) {
di.setDeliveryReady();
}
}
} catch (Throwable ex) {
String emsg = Globals.getBrokerResources().getKString(BrokerResources.W_LOAD_DST_FAIL, getName());
logger.logStack(Logger.ERROR, emsg, ex);
loaded = true;
unload(true);
throw new BrokerException(emsg, ex);
}
destMessages.enforceLimits(enforceLimit);
loaded = true;
// clean up dead messages
Iterator deaditr = deadMsgs.iterator();
while (deaditr.hasNext()) {
PacketReference pr = (PacketReference) deaditr.next();
try {
if (preparedTrans != null) {
preparedTrans.remove(pr.getSysMessageID());
}
removeMessage(pr.getSysMessageID(), RemoveReason.EXPIRED);
} catch (Exception ex) {
logger.logStack(Logger.INFO, BrokerResources.E_INTERNAL_BROKER_ERROR, "Processing " + pr + " while loading destination " + this, ex);
}
}
logger.log(Logger.INFO, br.getKString(br.I_LOADING_DEST_COMPLETE, toString(), String.valueOf(size)) + logsuffix);
return preparedTrans;
}
use of com.sun.messaging.jmq.jmsserver.FaultInjection in project openmq by eclipse-ee4j.
the class DebugHandler method handle.
/**
* Handle the incomming administration message.
*
* @param con The Connection the message came in on.
* @param cmd_msg The administration message
* @param cmd_props The properties from the administration message
*/
@Override
public boolean handle(IMQConnection con, Packet cmd_msg, Hashtable cmd_props) {
int status = Status.OK;
String msg = null;
boolean logOnly = false;
if (DEBUG) {
logger.log(Logger.DEBUG, this.getClass().getName() + ": " + cmd_props);
}
String cmd = (String) cmd_props.get(MessageType.JMQ_CMD), cmdarg = (String) cmd_props.get(MessageType.JMQ_CMDARG), target = (String) cmd_props.get(MessageType.JMQ_TARGET), targetType = (String) cmd_props.get(MessageType.JMQ_TARGET_TYPE);
// Get properties we are to update from message body
Properties p = (Properties) getBodyObject(cmd_msg);
/*
* To always see output (when debugging/developing this handler) change: if (DEBUG) to if (true)
*
* and Logger.DEBUG to Logger.INFO
*/
if (DEBUG) {
logger.log(Logger.DEBUG, "DEBUG message received:");
logger.log(Logger.DEBUG, "\t" + MessageType.JMQ_CMD + ": " + cmd);
logger.log(Logger.DEBUG, "\t" + MessageType.JMQ_CMDARG + ": " + cmdarg);
logger.log(Logger.DEBUG, "\t" + MessageType.JMQ_TARGET + ": " + target);
logger.log(Logger.DEBUG, "\tOptional Properties: " + p);
}
/*
* CHECK: Should make sure relevant values above are non null (e.g. cmd).
*/
Hashtable debugHash = null;
String fileStr = p.getProperty("file");
// Send reply
Packet reply = new Packet(con.useDirectBuffers());
reply.setPacketType(PacketType.OBJECT_MESSAGE);
if ((cmd == null) || (cmdarg == null)) {
status = Status.BAD_REQUEST;
msg = "Null/Missing values for " + MessageType.JMQ_CMD + " and/or " + MessageType.JMQ_CMDARG + " properties.";
setProperties(reply, MessageType.DEBUG_REPLY, status, msg);
parent.sendReply(con, cmd_msg, reply);
return true;
}
if (cmd.equals("update") && cmdarg.equals("bkr")) {
// Get properties we are to update from message body
// Update the broker configuration
BrokerConfig bcfg = Globals.getConfig();
try {
bcfg.updateProperties(p, true);
} catch (PropertyUpdateException e) {
status = Status.BAD_REQUEST;
msg = e.getMessage();
logger.log(Logger.WARNING, msg);
} catch (IOException e) {
status = Status.ERROR;
msg = e.toString();
logger.log(Logger.WARNING, msg);
}
// Send reply
setProperties(reply, MessageType.DEBUG_REPLY, status, msg);
parent.sendReply(con, cmd_msg, reply);
return true;
} else if (cmd.equals("dump") || cmd.equals("query")) {
if (cmd.equals("dump")) {
logOnly = true;
if (fileStr == null) {
fileStr = "dumpOutput";
}
}
try {
debugHash = getDebugInfo(cmdarg, target, targetType, p);
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error " + cmd + "ing " + cmdarg + " because " + ex.getMessage();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (cmd.equals("list")) {
debugHash = new Hashtable();
if (cmdarg.equals("dst")) {
Iterator[] itrs = DL.getAllDestinations(null);
Iterator itr = itrs[0];
while (itr.hasNext()) {
Destination d = (Destination) itr.next();
debugHash.put(d.getDestinationUID().toString(), DestType.toString(d.getType()) + ":" + (d.isStored() ? "stored" : "not stored"));
}
} else if (cmdarg.equals("con")) {
debugHash = new Hashtable();
if (target == null) {
// all
Iterator itr = Consumer.getAllConsumers();
if (!itr.hasNext()) {
status = Status.ERROR;
msg = "No consumers on the broker";
}
while (itr.hasNext()) {
Consumer c = (Consumer) itr.next();
if (c == null) {
continue;
}
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(c.getConnectionUID());
ConsumerUID cuid = c.getConsumerUID();
ConnectionUID cxuid = c.getConnectionUID();
debugHash.put(String.valueOf((cuid == null ? 0 : cuid.longValue())), (cxn == null ? "none" : cxn.getRemoteConnectionString()) + " [" + (cxuid == null ? 0 : cxuid.longValue()) + "]");
}
} else if (targetType == null) {
msg = "Please supply targetType if you are supplying a target ";
status = Status.ERROR;
} else if (targetType.equals("t") || targetType.equals("q")) {
try {
boolean isQueue = false;
if (targetType.equals("q")) {
isQueue = true;
}
DestinationUID uid = null;
Destination d = null;
if (status != Status.ERROR) {
uid = DestinationUID.getUID(target, isQueue);
Destination[] ds = DL.getDestination(null, uid);
d = ds[0];
}
if (status != Status.ERROR && d == null) {
status = Status.ERROR;
msg = "Error listing consumers on destination " + target + " unknown destination";
} else if (status != Status.ERROR) {
Iterator itr = d.getConsumers();
if (!itr.hasNext()) {
status = Status.ERROR;
msg = "No consumers on destination " + target;
}
while (itr.hasNext()) {
Consumer c = (Consumer) itr.next();
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(c.getConnectionUID());
debugHash.put(String.valueOf(c.getConsumerUID().longValue()), (cxn == null ? "" : cxn.getRemoteConnectionString()) + " [" + (c.getConnectionUID() == null ? "none" : c.getConnectionUID().longValue()) + "]");
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error listing consumers on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (targetType.equals("ses")) {
try {
SessionUID uid = new SessionUID(Long.parseLong(target));
Session ses = Session.getSession(uid);
if (ses == null) {
status = Status.ERROR;
msg = "Error listing consumers on session " + target + " unknown sessionUID";
} else {
Iterator itr = ses.getConsumers();
if (!itr.hasNext()) {
status = Status.ERROR;
msg = "No consumers on session " + target;
}
while (itr.hasNext()) {
ConsumerSpi c = (ConsumerSpi) itr.next();
if (uid.equals(c.getConnectionUID())) {
debugHash.put(String.valueOf(c.getConsumerUID().longValue()), c.getDestinationUID().toString());
}
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error listing consumers on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (targetType.equals("cxn")) {
try {
ConnectionUID uid = new ConnectionUID(Long.parseLong(target));
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(uid);
if (cxn == null) {
status = Status.ERROR;
msg = "Error listing consumers on connection " + target + " unknown connectionUID";
} else {
Iterator itr = Consumer.getAllConsumers();
while (itr.hasNext()) {
Consumer c = (Consumer) itr.next();
if (uid.equals(c.getConnectionUID())) {
debugHash.put(String.valueOf(c.getConsumerUID().longValue()), c.getDestinationUID().toString());
}
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error listing consumers on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown targetType (-t) " + target + "\n Valid formats are of the form: " + "[q|t|ses|cxn]";
}
} else if (cmdarg.equals("prd")) {
debugHash = new Hashtable();
if (target == null) {
// all
Iterator itr = Producer.getAllProducers();
while (itr.hasNext()) {
Producer c = (Producer) itr.next();
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(c.getConnectionUID());
debugHash.put(String.valueOf(c.getProducerUID().longValue()), cxn.getRemoteConnectionString() + " [" + c.getConnectionUID().longValue() + "]");
}
} else if (targetType == null) {
msg = "Please supply targetType if you are supplying a target ";
status = Status.ERROR;
} else if (targetType.equals("t") || targetType.equals("q")) {
// destination
boolean isQueue = false;
if (targetType.equals("q")) {
isQueue = true;
}
try {
DestinationUID uid = DestinationUID.getUID(target, isQueue);
Destination[] ds = DL.getDestination(null, uid);
Destination d = ds[0];
if (d == null) {
status = Status.ERROR;
msg = "Error listing producers on destination " + target + " unknown destination";
} else {
Iterator itr = d.getProducers();
while (itr.hasNext()) {
Producer c = (Producer) itr.next();
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(c.getConnectionUID());
debugHash.put(String.valueOf(c.getProducerUID().longValue()), cxn.getRemoteConnectionString() + " [" + c.getConnectionUID().longValue() + "]");
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error listing producers on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (targetType.equals("cxn")) {
try {
ConnectionUID uid = new ConnectionUID(Long.parseLong(target));
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(uid);
if (cxn == null) {
status = Status.ERROR;
msg = "Error listing producers on connection " + target + " unknown connectionUID";
} else {
Iterator itr = Producer.getAllProducers();
while (itr.hasNext()) {
Producer c = (Producer) itr.next();
if (uid.equals(c.getConnectionUID())) {
debugHash.put(String.valueOf(c.getProducerUID().longValue()), c.getDestinationUID().toString());
}
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error listing producers on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown targetType (-t) " + targetType + "\n Valid formats are of the form: " + "[t|q|cxn]";
}
} else {
status = Status.ERROR;
msg = "Unknown argument " + cmdarg;
}
} else if (cmd.equals("debug")) {
String debugStr = (String) p.get("enable");
if (debugStr != null && !debugStr.equalsIgnoreCase("true") && !debugStr.equalsIgnoreCase("false")) {
status = Status.ERROR;
msg = "bad enable flag setting " + debugStr + " defauling to false";
}
boolean debugOn = debugStr == null || Boolean.parseBoolean(debugStr);
if (cmdarg.equals("reset")) {
if (targetType == null) {
msg = "Please supply targetType (-t)\n Valid formats are of the form: [metrics|jdbcconnpool]";
status = Status.ERROR;
} else if (targetType.equalsIgnoreCase("jdbcconnpool")) {
try {
if (Globals.getStore().isJDBCStore()) {
Globals.getStore().resetConnectionPool();
} else {
status = Status.ERROR;
msg = "Operation is not applicable for a file-based data store.";
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error resetting JDBC connection pool because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (targetType.equalsIgnoreCase("metrics")) {
com.sun.messaging.jmq.jmsserver.data.handlers.admin.ResetMetricsHandler.resetAllMetrics();
}
} else if (cmdarg.equals("fault")) {
// handle fault injection
String faultName = (String) p.get("name");
if (faultName == null) {
faultName = target;
}
String faultSelector = (String) p.get("selector");
FaultInjection fi = FaultInjection.getInjection();
// ok only turn off fault injection if no name pair
if (debugStr != null && debugStr.equalsIgnoreCase("false")) {
if (faultName == null) {
fi.setFaultInjection(false);
} else {
fi.unsetFault(faultName);
}
} else {
fi.setFaultInjection(true);
if (faultName != null) {
try {
fi.setFault(faultName, faultSelector, p);
} catch (Exception ex) {
status = Status.ERROR;
msg = "Bad Selector " + faultSelector;
}
}
}
} else if (cmdarg.equals("gc")) {
logger.log(Logger.INFO, "GC'ing the system");
System.gc();
long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
msg = "Used memory is " + (usedMem / 1024l) + "k, " + " this is " + (usedMem * 100 / Runtime.getRuntime().maxMemory()) + "% of " + (Runtime.getRuntime().maxMemory() / 1024l) + "k";
logger.log(Logger.INFO, msg);
debugHash = new Hashtable();
debugHash.put("Memory", msg);
debugHash.put("Used", (usedMem / 1024l) + "k");
debugHash.put("Total", ((Runtime.getRuntime().totalMemory() / 1024l) + "k"));
debugHash.put("Free", ((Runtime.getRuntime().freeMemory() / 1024l) + "k"));
debugHash.put("Max", ((Runtime.getRuntime().maxMemory() / 1024l) + "k"));
} else if (cmdarg.equals("threads")) {
// log
try {
debugHash = new Hashtable();
debugHash.put("threads", "dumped to log");
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error " + cmd + "ing " + cmdarg + " because " + ex.getMessage() + "";
logger.logStack(Logger.INFO, msg, ex);
}
logger.log(Logger.INFO, "Dumping threads:\n" + SupportUtil.getAllStackTraces("\t"));
} else if (cmdarg.equals("pkt")) {
IMQBasicConnection.dumpPacket(debugOn);
} else if (cmdarg.equals("pktin")) {
IMQBasicConnection.dumpInPacket(debugOn);
} else if (cmdarg.equals("pktout")) {
IMQBasicConnection.dumpOutPacket(debugOn);
} else if (cmdarg.equals("class")) {
try {
Class cl = Class.forName(target);
Field[] fields = cl.getDeclaredFields();
boolean found = false;
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals(Debug.debugFieldName)) {
logger.log(Logger.INFO, "Turn " + (debugOn ? "on" : "off") + " debug for class " + target);
final Field f = fields[i];
java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Object>() {
@Override
public Object run() {
f.setAccessible(true);
return null;
}
});
fields[i].setBoolean(null, debugOn);
found = true;
break;
}
}
if (!found) {
throw new NoSuchFieldException(Debug.debugFieldName);
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Unable to set DEBUG on class " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown debug argument " + cmdarg;
}
} else if (cmd.equals("resume")) {
// session, connection, consumerUID, producer
if (cmdarg.equals("prd")) {
try {
ProducerUID pid = new ProducerUID(Long.parseLong(target));
Producer pr = (Producer) Producer.getProducer(pid);
Destination[] ds = DL.getDestination(null, pr.getDestinationUID());
Destination d = ds[0];
logger.log(Logger.INFO, "Resuming " + pr);
d.forceResumeFlow(pr);
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error resuming flow from producer " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (cmdarg.equals("cxn")) {
try {
ConnectionUID uid = new ConnectionUID(Long.parseLong(target));
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(uid);
cxn.resumeFlow(-1);
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error resuming flow on connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (cmdarg.equals("con")) {
try {
ConsumerUID cid = new ConsumerUID(Long.parseLong(target));
Consumer cxn = Consumer.getConsumer(cid);
cxn.resume("admin debug");
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error resuming flow to consumer " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (cmdarg.equals("ses")) {
try {
SessionUID sid = new SessionUID(Long.parseLong(target));
Session session = Session.getSession(sid);
session.resume("admin debug");
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error resuming flow to session " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown resume argument " + cmdarg;
}
} else if (cmd.equals("send")) {
if (cmdarg.equals("cxn")) {
try {
if (target == null) {
status = Status.ERROR;
msg = "Missing connectionUID ";
} else {
ConnectionUID uid = new ConnectionUID(Long.parseLong(target));
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(uid);
if (cxn == null) {
status = Status.ERROR;
msg = "Unknown connectionUID " + uid;
} else {
sendClientDEBUG(cxn, cmd_props, p);
}
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error notifying consumer " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else if (cmdarg.equals("bkr") || cmdarg.equals("svc")) {
Service s = null;
if (target != null) {
s = Globals.getServiceManager().getService(target);
if (s == null) {
msg = "Unknown service " + target;
status = Status.ERROR;
}
}
Iterator itr = Globals.getConnectionManager().getConnectionList(s).iterator();
try {
while (itr.hasNext()) {
IMQConnection cxn = (IMQConnection) itr.next();
Packet pkt = new Packet(false);
pkt.setPacketType(PacketType.DEBUG);
Hashtable hash = new Hashtable(cmd_props);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(p);
oos.flush();
bos.flush();
pkt.setMessageBody(bos.toByteArray());
pkt.setProperties(hash);
cxn.sendControlMessage(pkt);
}
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error notifying consumer " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown send argument " + cmdarg;
}
} else if (cmd.equals("kill")) {
if (cmdarg.equals("cxn")) {
try {
ConnectionUID uid = new ConnectionUID(Long.parseLong(target));
IMQConnection cxn = (IMQConnection) Globals.getConnectionManager().getConnection(uid);
cxn.destroyConnection(true, GoodbyeReason.ADMIN_KILLED_CON, "kill cnx");
} catch (Exception ex) {
status = Status.ERROR;
msg = "Error killing connection " + target + " because " + ex.toString();
logger.logStack(Logger.INFO, msg, ex);
}
} else {
status = Status.ERROR;
msg = "Unknown kill argument " + cmdarg;
}
}
if (fileStr != null && debugHash != null) {
DebugPrinter dbp = new DebugPrinter(2);
dbp.setHashtable(debugHash);
dbp.setFile(fileStr);
dbp.println();
dbp.close();
if (status == Status.OK) {
msg = "Data logged at file " + fileStr;
}
if (logOnly) {
debugHash = new Hashtable();
debugHash.put("logfile", fileStr);
}
}
if (msg != null) {
logger.log(Logger.INFO, msg);
}
setProperties(reply, MessageType.DEBUG_REPLY, status, msg);
if (debugHash != null) {
setBodyObject(reply, debugHash);
}
parent.sendReply(con, cmd_msg, reply);
return true;
}
use of com.sun.messaging.jmq.jmsserver.FaultInjection in project openmq by eclipse-ee4j.
the class DBConnectionPool method validateConnection.
/**
* @return true if valid connection
*/
private boolean validateConnection(ConnectionInfo cinfo, boolean ping, boolean get) {
boolean doping = ping;
Connection conn = null;
boolean destroyIdles = false;
cinfo.setValidating(true);
try {
Object o = cinfo.getKey();
if (o instanceof Connection) {
if (((Connection) o).isClosed()) {
return false;
}
if (Util.isConnectionError(cinfo.getException(), dbmgr)) {
return false;
}
} else if (cinfo.getException() != null) {
return false;
}
if (get && ((System.currentTimeMillis() - cinfo.getIdleStartTime()) >= reapInterval)) {
if (timeoutIdle) {
return false;
}
doping = true;
}
if (!doping) {
return true;
}
conn = cinfo.getConnection();
if (conn == null) {
return false;
}
Statement stmt = null;
ResultSet rs = null;
Boolean valid = null;
try {
stmt = conn.createStatement();
int queryTimeout = stmt.getQueryTimeout();
if (dbmgr.isJDBC4()) {
try {
Class cc = java.sql.Connection.class;
Method m = cc.getMethod("isValid", new Class[] { java.lang.Integer.TYPE });
long startime = System.currentTimeMillis();
boolean b = ((Boolean) m.invoke(conn, new Object[] { Integer.valueOf(queryTimeout) })).booleanValue();
if (!b) {
if (queryTimeout > 0 && (System.currentTimeMillis() < (startime + queryTimeout * 1000L))) {
valid = Boolean.FALSE;
destroyIdles = true;
setInvalidateAllTimestamp();
} else if (queryTimeout == 0) {
valid = Boolean.FALSE;
destroyIdles = true;
setInvalidateAllTimestamp();
}
} else {
valid = Boolean.valueOf(b);
if (DEBUG) {
FaultInjection fi = FaultInjection.getInjection();
if (fi.FAULT_INJECTION && fi.checkFault(FaultInjection.FAULT_JDBC_VALIDATECONN_1, null)) {
fi.unsetFault(FaultInjection.FAULT_JDBC_VALIDATECONN_1);
valid = Boolean.FALSE;
destroyIdles = true;
setInvalidateAllTimestamp();
}
}
}
} catch (NoSuchMethodException e) {
dbmgr.setJDBC4(false);
} catch (Throwable t) {
if (t instanceof InvocationTargetException) {
Throwable cause = ((InvocationTargetException) t).getTargetException();
if (cause == null) {
cause = t.getCause();
}
if (cause instanceof AbstractMethodError) {
dbmgr.setJDBC4(false);
}
}
if (dbmgr.isJDBC4() && (DEBUG)) {
logger.logStack(logger.INFO, toString() + ".validateConnection: " + "Exception in invoking Connection.isValid(" + queryTimeout + ")", t);
}
}
}
String sql = null;
if (valid == null) {
sql = validationQuery;
if (sql == null) {
valid = Boolean.TRUE;
}
}
if (valid == null) {
try {
try {
rs = dbmgr.executeQueryStatement(stmt, sql);
if (DEBUG) {
FaultInjection fi = FaultInjection.getInjection();
if (fi.FAULT_INJECTION && fi.checkFault(FaultInjection.FAULT_JDBC_VALIDATECONN_1, null)) {
fi.unsetFault(FaultInjection.FAULT_JDBC_VALIDATECONN_1);
throw new SQLException(FaultInjection.FAULT_JDBC_VALIDATECONN_1);
}
}
} catch (SQLException e) {
destroyIdles = true;
setInvalidateAllTimestamp();
throw e;
}
if (rs.next()) {
valid = Boolean.TRUE;
} else {
valid = Boolean.FALSE;
}
} finally {
try {
if (!conn.getAutoCommit()) {
conn.rollback();
}
} catch (Exception e) {
logger.log(logger.WARNING, br.getKString(br.W_DB_CONN_VALIDATION_EXCEPTION, "[" + sql + "]" + cinfo, e.toString()) + toString());
valid = Boolean.FALSE;
}
}
}
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (o instanceof PooledConnection) {
try {
conn.close();
} catch (Exception e) {
logger.log(logger.WARNING, br.getKString(br.W_DB_CONN_VALIDATION_EXCEPTION, "" + cinfo + "[0x" + conn.hashCode() + "]", e.toString()) + toString());
valid = Boolean.FALSE;
}
}
}
if (valid == null) {
valid = Boolean.FALSE;
}
return valid.booleanValue();
} catch (Exception e) {
logger.logStack(logger.WARNING, br.getKString(br.W_DB_CONN_VALIDATION_EXCEPTION, cinfo.toString(), e.getMessage()) + toString(), e);
return false;
} finally {
cinfo.setValidating(false);
cinfo.setException(null);
if (destroyIdles && invalidateAll) {
destroyIdleConnections();
}
}
}
Aggregations