Search in sources :

Example 11 with Subscription

use of org.apache.qpid.qmf2.agent.Subscription in project qpid by apache.

the class AgentExternalTest method evaluateQuery.

/**
     * This method evaluates a QmfQuery over the Agent's data on behalf of a Subscription
     *
     * @param query the QmfQuery that the Subscription wants to be evaluated over the Agent's data
     * @return a List of QmfAgentData objects that match the specified QmfQuery
     */
public List<QmfAgentData> evaluateQuery(QmfQuery query) {
    List<QmfAgentData> results = new ArrayList<QmfAgentData>(_objectIndex.size());
    if (query.getTarget() == QmfQueryTarget.OBJECT) {
        if (query.getObjectId() != null) {
            // Look up a QmfAgentData object by the ObjectId obtained from the query
            ObjectId objectId = query.getObjectId();
            QmfAgentData object = _objectIndex.get(objectId);
            if (object != null && !object.isDeleted()) {
                results.add(object);
            }
        } else {
            // Look up QmfAgentData objects evaluating the query
            for (QmfAgentData object : _objectIndex.values()) {
                if (!object.isDeleted() && query.evaluate(object)) {
                    results.add(object);
                }
            }
        }
    }
    return results;
}
Also used : ObjectId(org.apache.qpid.qmf2.common.ObjectId) ArrayList(java.util.ArrayList) QmfAgentData(org.apache.qpid.qmf2.agent.QmfAgentData)

Example 12 with Subscription

use of org.apache.qpid.qmf2.agent.Subscription in project qpid by apache.

the class AgentExternalTest method onEvent.

public void onEvent(WorkItem wi) {
    System.out.println("WorkItem type: " + wi.getType());
    if (wi.getType() == METHOD_CALL) {
        _control.incValue("methodCount", 1);
        MethodCallWorkItem item = (MethodCallWorkItem) wi;
        MethodCallParams methodCallParams = item.getMethodCallParams();
        String methodName = methodCallParams.getName();
        ObjectId objectId = methodCallParams.getObjectId();
        String userId = methodCallParams.getUserId();
        QmfData inArgs = methodCallParams.getArgs();
        ObjectId controlAddress = _control.getObjectId();
        System.out.println("Method Call User ID = " + userId);
        try {
            if (objectId == null) {
                // Method invoked directly on Agent
                if (methodName.equals("toString")) {
                    QmfData outArgs = new QmfData();
                    outArgs.setValue("string", _agent.toString());
                    _agent.methodResponse(methodName, item.getHandle(), outArgs, null);
                }
            } else if (objectId.equals(controlAddress)) {
                if (methodName.equals("stop")) {
                    System.out.println("Invoked stop method");
                    String message = inArgs.getStringValue("message");
                    System.out.println("Stopping: message = " + message);
                    _agent.methodResponse(methodName, item.getHandle(), null, null);
                    _agent.destroy();
                    System.exit(1);
                } else if (methodName.equals("echo")) {
                    System.out.println("Invoked echo method");
                    _agent.methodResponse(methodName, item.getHandle(), inArgs, null);
                } else if (methodName.equals("event")) {
                    System.out.println("Invoked event method");
                    QmfEvent event = new QmfEvent(_eventSchema);
                    event.setSeverity((int) inArgs.getLongValue("severity"));
                    event.setValue("text", inArgs.getStringValue("text"));
                    _agent.raiseEvent(event);
                    _agent.methodResponse(methodName, item.getHandle(), null, null);
                } else if (methodName.equals("fail")) {
                    System.out.println("Invoked fail method");
                    QmfData error = new QmfData();
                    if (inArgs.getBooleanValue("useString")) {
                        error.setValue("error_text", inArgs.getStringValue("stringVal"));
                    } else {
                        error.setValue("whatHappened", "It Failed");
                        error.setValue("howBad", 75);
                        error.setValue("details", inArgs.getValue("details"));
                    }
                    _agent.methodResponse(methodName, item.getHandle(), null, error);
                } else if (methodName.equals("create_child")) {
                    System.out.println("Invoked create_child method");
                    String childName = inArgs.getStringValue("name");
                    System.out.println("childName = " + childName);
                    QmfAgentData child = new QmfAgentData(_childSchema);
                    child.setValue("name", childName);
                    addObject(child);
                    QmfData outArgs = new QmfData();
                    // Set suptype just to test
                    outArgs.setRefValue("childAddr", child.getObjectId(), "reference");
                    _agent.methodResponse(methodName, item.getHandle(), outArgs, null);
                }
            }
        } catch (QmfException qmfe) {
            System.err.println("QmfException " + qmfe.getMessage() + " caught: AgentExternalTest failed");
            QmfData error = new QmfData();
            error.setValue("error_text", qmfe.getMessage());
            _agent.methodResponse(methodName, item.getHandle(), null, error);
        }
    }
    if (wi.getType() == QUERY) {
        QueryWorkItem item = (QueryWorkItem) wi;
        QmfQuery query = item.getQmfQuery();
        System.out.println("Query User ID = " + item.getUserId());
        if (query.getObjectId() != null) {
            // Look up a QmfAgentData object by the ObjectId obtained from the query
            ObjectId objectId = query.getObjectId();
            QmfAgentData object = _objectIndex.get(objectId);
            if (object != null && !object.isDeleted()) {
                _agent.queryResponse(item.getHandle(), object);
            }
            _agent.queryComplete(item.getHandle(), 0);
        } else {
            // taken by the C++ broker ManagementAgent, so if it's a problem here........
            for (QmfAgentData object : _objectIndex.values()) {
                if (!object.isDeleted() && query.evaluate(object)) {
                    _agent.queryResponse(item.getHandle(), object);
                }
            }
            _agent.queryComplete(item.getHandle(), 0);
        }
    }
    if (wi.getType() == SUBSCRIBE_REQUEST) {
        SubscribeRequestWorkItem item = (SubscribeRequestWorkItem) wi;
        SubscriptionParams params = item.getSubscriptionParams();
        Handle handle = item.getHandle();
        System.out.println("Subscribe Request User ID = " + params.getUserId());
        try {
            Subscription subscription = new Subscription(this, params);
            _subscriptions.put(subscription.getSubscriptionId(), subscription);
            _timer.schedule(subscription, 0, params.getPublishInterval());
            if (subscription == null) {
                System.out.println("Requested Subscription has already expired or been cancelled");
                QmfData error = new QmfData();
                error.setValue("error_text", "Requested Subscription has already expired or been cancelled");
                _agent.subscriptionResponse(handle, subscription.getConsoleHandle(), null, 0, 0, error);
            } else {
                _agent.subscriptionResponse(handle, subscription.getConsoleHandle(), subscription.getSubscriptionId(), subscription.getDuration(), subscription.getInterval(), null);
            }
        } catch (QmfException qmfe) {
            _agent.raiseException(handle, "Subscribe Request failed, invalid Query: " + qmfe.getMessage());
        }
    }
    if (wi.getType() == RESUBSCRIBE_REQUEST) {
        ResubscribeRequestWorkItem item = (ResubscribeRequestWorkItem) wi;
        ResubscribeParams params = item.getResubscribeParams();
        Handle handle = item.getHandle();
        System.out.println("Resubscribe Request User ID = " + params.getUserId());
        String subscriptionId = params.getSubscriptionId();
        Subscription subscription = _subscriptions.get(subscriptionId);
        if (subscription != null) {
            subscription.refresh(params);
            _agent.subscriptionResponse(handle, subscription.getConsoleHandle(), subscription.getSubscriptionId(), subscription.getDuration(), subscription.getInterval(), null);
        } else {
            System.out.println("Requested Subscription has already expired or been cancelled");
            QmfData error = new QmfData();
            error.setValue("error_text", "Requested Subscription has already expired or been cancelled");
            _agent.subscriptionResponse(handle, subscription.getConsoleHandle(), null, 0, 0, error);
        }
    }
    if (wi.getType() == UNSUBSCRIBE_REQUEST) {
        UnsubscribeRequestWorkItem item = (UnsubscribeRequestWorkItem) wi;
        String subscriptionId = item.getSubscriptionId();
        System.out.println("Received cancellation request for " + subscriptionId);
        Subscription subscription = _subscriptions.get(subscriptionId);
        if (subscription != null) {
            subscription.cancel();
        }
    }
}
Also used : MethodCallWorkItem(org.apache.qpid.qmf2.agent.MethodCallWorkItem) QmfData(org.apache.qpid.qmf2.common.QmfData) UnsubscribeRequestWorkItem(org.apache.qpid.qmf2.agent.UnsubscribeRequestWorkItem) ObjectId(org.apache.qpid.qmf2.common.ObjectId) QmfEvent(org.apache.qpid.qmf2.common.QmfEvent) SubscribeRequestWorkItem(org.apache.qpid.qmf2.agent.SubscribeRequestWorkItem) Handle(org.apache.qpid.qmf2.common.Handle) SubscriptionParams(org.apache.qpid.qmf2.agent.SubscriptionParams) ResubscribeParams(org.apache.qpid.qmf2.agent.ResubscribeParams) MethodCallParams(org.apache.qpid.qmf2.agent.MethodCallParams) QmfAgentData(org.apache.qpid.qmf2.agent.QmfAgentData) QueryWorkItem(org.apache.qpid.qmf2.agent.QueryWorkItem) Subscription(org.apache.qpid.qmf2.agent.Subscription) QmfQuery(org.apache.qpid.qmf2.common.QmfQuery) ResubscribeRequestWorkItem(org.apache.qpid.qmf2.agent.ResubscribeRequestWorkItem) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 13 with Subscription

use of org.apache.qpid.qmf2.agent.Subscription in project qpid by apache.

the class Console method cancelSubscription.

// end of refreshSubscription()
/**
     * Terminates the given subscription.
     *
     * @param subscriptionId the ID of the subscription to be cancelled
     */
public void cancelSubscription(final String subscriptionId) throws QmfException {
    if (subscriptionId == null) {
        throw new QmfException("Called cancelSubscription() with null subscriptionId");
    }
    SubscriptionManager subscription = _subscriptionById.get(subscriptionId);
    if (subscription == null) {
        throw new QmfException("Called cancelSubscription() with invalid subscriptionId");
    }
    String consoleHandle = subscription.getConsoleHandle();
    Agent agent = subscription.getAgent();
    if (!agent.isActive()) {
        throw new QmfException("Called cancelSubscription() with inactive agent");
    }
    String agentName = agent.getName();
    try {
        MapMessage request = _syncSession.createMapMessage();
        request.setStringProperty("x-amqp-0-10.app-id", "qmf2");
        request.setStringProperty("method", "request");
        request.setStringProperty("qmf.opcode", "_subscribe_cancel_indication");
        request.setStringProperty("qpid.subject", agentName);
        request.setObject("_subscription_id", subscriptionId);
        synchronized (this) {
            if (!_subscriptionEmulationEnabled || !agentName.equals(_brokerAgentName)) {
                _requester.send(request);
            }
        }
        subscription.cancel();
    } catch (JMSException jmse) {
        _log.info("JMSException {} caught in cancelSubscription()", jmse.getMessage());
    }
}
Also used : MapMessage(javax.jms.MapMessage) JMSException(javax.jms.JMSException) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 14 with Subscription

use of org.apache.qpid.qmf2.agent.Subscription in project qpid by apache.

the class Console method refreshSubscription.

/**
     * Renews a subscription identified by SubscriptionId.
     * <p>
     * The Console may request a new subscription duration by providing a requested lifetime. This method may be called 
     * asynchronously by providing a replyHandle argument.
     * <p>
     * When called asynchronously, the result of this method call is returned in a SUBSCRIBE_RESPONSE WorkItem.
     * <p>
     * Timeout can be used to override the console's default reply timeout.
     * <p>  
     * When called synchronously, this method returns a class SubscribeParams object containing the result of the       
     * subscription request.
     *
     * @param subscriptionId the ID of the subscription to be refreshed
     * @param options a String representation of a Map containing the options in the form
     *        <pre>"{lifetime:&lt;value&gt;, replyHandle:&lt;value&gt;, timeout:&lt;value&gt;}"</pre>
     *        they are optional and may appear in any order.
     * <pre>
     *        <b>lifetime</b> requests a new subscription duration.
     *        <b>replyHandle</b> the correlation handle used to tie asynchronous method requests with responses.
     *        <b>timeout</b> the time to wait for a reply from the Agent.
     * </pre>
     */
public SubscribeParams refreshSubscription(String subscriptionId, final String options) throws QmfException {
    if (subscriptionId == null) {
        throw new QmfException("Called refreshSubscription() with null subscriptionId");
    }
    SubscriptionManager subscription = _subscriptionById.get(subscriptionId);
    if (subscription == null) {
        throw new QmfException("Called refreshSubscription() with invalid subscriptionId");
    }
    String consoleHandle = subscription.getConsoleHandle();
    Agent agent = subscription.getAgent();
    if (!agent.isActive()) {
        throw new QmfException("Called refreshSubscription() with inactive agent");
    }
    String agentName = agent.getName();
    // Initialise optional values to defaults;
    long lifetime = 0;
    long timeout = _replyTimeout;
    String replyHandle = null;
    if (options != null) {
        // We wrap the Map in a QmfData object to avoid potential class cast issues with the parsed options
        QmfData optMap = new QmfData(new AddressParser(options).map());
        if (optMap.hasValue("lifetime")) {
            lifetime = optMap.getLongValue("lifetime");
        }
        if (optMap.hasValue("timeout")) {
            timeout = optMap.getLongValue("timeout");
        }
        if (optMap.hasValue("replyHandle")) {
            replyHandle = optMap.getStringValue("replyHandle");
        }
    }
    try {
        Destination destination = (replyHandle == null) ? _replyAddress : _asyncReplyAddress;
        MapMessage request = _syncSession.createMapMessage();
        request.setJMSReplyTo(destination);
        request.setJMSCorrelationID(replyHandle);
        request.setStringProperty("x-amqp-0-10.app-id", "qmf2");
        request.setStringProperty("method", "request");
        request.setStringProperty("qmf.opcode", "_subscribe_refresh_indication");
        request.setStringProperty("qpid.subject", agentName);
        request.setObject("_subscription_id", subscriptionId);
        if (lifetime > 0) {
            request.setObject("_duration", lifetime);
        }
        // it would be somewhat unfortunate if their response got interleaved with ours!!
        synchronized (this) {
            if (_subscriptionEmulationEnabled && agentName.equals(_brokerAgentName)) {
                // If the Agent is the broker Agent we emulate the Subscription on the Console
                subscription.refresh();
                final SubscribeParams params = new SubscribeParams(consoleHandle, subscription.mapEncode());
                if (replyHandle == null) {
                    return params;
                } else {
                    final String handle = replyHandle;
                    Thread thread = new Thread() {

                        public void run() {
                            _eventListener.onEvent(new SubscribeResponseWorkItem(new Handle(handle), params));
                        }
                    };
                    thread.start();
                }
                return null;
            }
            _requester.send(request);
            if (replyHandle == null) {
                // If this is an synchronous request get the response
                Message response = _responder.receive(timeout * 1000);
                if (response == null) {
                    subscription.cancel();
                    _log.info("No response received in refreshSubscription()");
                    throw new QmfException("No response received for Console.refreshSubscription()");
                }
                SubscribeParams result = new SubscribeParams(consoleHandle, AMQPMessage.getMap(response));
                subscriptionId = result.getSubscriptionId();
                if (subscriptionId == null) {
                    subscription.cancel();
                } else {
                    subscription.setDuration(result.getLifetime());
                    subscription.refresh();
                }
                return result;
            }
        }
        // If this is an asynchronous request return without waiting for a response
        return null;
    } catch (JMSException jmse) {
        _log.info("JMSException {} caught in refreshSubscription()", jmse.getMessage());
        throw new QmfException(jmse.getMessage());
    }
}
Also used : Destination(javax.jms.Destination) QmfData(org.apache.qpid.qmf2.common.QmfData) AddressParser(org.apache.qpid.messaging.util.AddressParser) AMQPMessage(org.apache.qpid.qmf2.common.AMQPMessage) MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) MapMessage(javax.jms.MapMessage) JMSException(javax.jms.JMSException) Handle(org.apache.qpid.qmf2.common.Handle) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 15 with Subscription

use of org.apache.qpid.qmf2.agent.Subscription in project qpid by apache.

the class QpidQueueStats method onEvent.

/**
     * Main Event handler. Checks if the WorkItem is a SubscriptionIndicationWorkItem, if it is it stores the object
     * in a Map and uses this to maintain state so we can record deltas such as enqueue and dequeue rates.
     * <p>
     * The AgentHeartbeatWorkItem is used to periodically compare the elapsed time against the Subscription duration
     * so that we can refresh the Subscription (or create a new one if necessary) in order to continue receiving
     * queue Management Object data from the broker.
     * <p>
     * When the AgentRestartedWorkItem is received we clear the state to remove any stale queue Management Objects.
     * @param wi a QMF2 WorkItem object
     */
public void onEvent(final WorkItem wi) {
    if (wi instanceof AgentHeartbeatWorkItem && _subscriptionId != null) {
        long elapsed = (long) Math.round((System.currentTimeMillis() - _startTime) / 1000.0f);
        if (elapsed > _subscriptionDuration) {
            try {
                _console.refreshSubscription(_subscriptionId);
                _startTime = System.currentTimeMillis();
            } catch (QmfException qmfe) {
                System.err.println("QmfException " + qmfe.getMessage() + " caught in QpidQueueStats onEvent");
                createQueueSubscription();
            }
        }
    } else if (wi instanceof AgentRestartedWorkItem) {
        _objects.clear();
    } else if (wi instanceof SubscriptionIndicationWorkItem) {
        SubscriptionIndicationWorkItem item = (SubscriptionIndicationWorkItem) wi;
        SubscribeIndication indication = item.getSubscribeIndication();
        String correlationId = indication.getConsoleHandle();
        if (correlationId.equals("queueStatsHandle")) {
            // If it is (and it should be!!) then it's our queue object Subscription
            List<QmfConsoleData> data = indication.getData();
            for (QmfConsoleData record : data) {
                ObjectId id = record.getObjectId();
                if (record.isDeleted()) {
                    // If the object was deleted by the Agent we remove it from out Map
                    _objects.remove(id);
                } else {
                    if (_objects.containsKey(id)) {
                        // If the object is already in the Map it's likely to be a statistics push from the broker.
                        Stats stats = _objects.get(id);
                        String name = stats.getName();
                        boolean matches = false;
                        for (Pattern x : _filter) {
                            // Check the queue name against the regexes in the filter List (if any)
                            Matcher m = x.matcher(name);
                            if (m.find()) {
                                matches = true;
                                break;
                            }
                        }
                        if (_filter.isEmpty() || matches) {
                            // If there's no filter enabled or the filter matches the queue name we display statistics.
                            QmfConsoleData lastSample = stats.getData();
                            stats.setData(record);
                            float deltaTime = record.getUpdateTime() - lastSample.getUpdateTime();
                            if (deltaTime > 1000000000.0f) {
                                float deltaEnqueues = record.getLongValue("msgTotalEnqueues") - lastSample.getLongValue("msgTotalEnqueues");
                                float deltaDequeues = record.getLongValue("msgTotalDequeues") - lastSample.getLongValue("msgTotalDequeues");
                                long msgDepth = record.getLongValue("msgDepth");
                                float enqueueRate = deltaEnqueues / (deltaTime / 1000000000.0f);
                                float dequeueRate = deltaDequeues / (deltaTime / 1000000000.0f);
                                System.out.printf("%-46s%10.2f%11d%13.2f%13.2f\n", name, deltaTime / 1000000000, msgDepth, enqueueRate, dequeueRate);
                            }
                        }
                    } else {
                        // If the object isn't in the Map it's likely to be a properties push from the broker.
                        if (!record.hasValue("name")) {
                            // This probably won't happen, but if it does we refresh the object to get its full state.
                            try {
                                record.refresh();
                            } catch (QmfException qmfe) {
                            }
                        }
                        String queueName = record.getStringValue("name");
                        _objects.put(id, new Stats(queueName, record));
                    }
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) AgentRestartedWorkItem(org.apache.qpid.qmf2.console.AgentRestartedWorkItem) SubscriptionIndicationWorkItem(org.apache.qpid.qmf2.console.SubscriptionIndicationWorkItem) ObjectId(org.apache.qpid.qmf2.common.ObjectId) Matcher(java.util.regex.Matcher) AgentHeartbeatWorkItem(org.apache.qpid.qmf2.console.AgentHeartbeatWorkItem) SubscribeIndication(org.apache.qpid.qmf2.console.SubscribeIndication) QmfConsoleData(org.apache.qpid.qmf2.console.QmfConsoleData) QmfException(org.apache.qpid.qmf2.common.QmfException)

Aggregations

QmfException (org.apache.qpid.qmf2.common.QmfException)9 ObjectId (org.apache.qpid.qmf2.common.ObjectId)8 QmfQuery (org.apache.qpid.qmf2.common.QmfQuery)6 JMSException (javax.jms.JMSException)5 Handle (org.apache.qpid.qmf2.common.Handle)5 QmfData (org.apache.qpid.qmf2.common.QmfData)4 QmfConsoleData (org.apache.qpid.qmf2.console.QmfConsoleData)4 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 MapMessage (javax.jms.MapMessage)3 QmfAgentData (org.apache.qpid.qmf2.agent.QmfAgentData)3 QmfEvent (org.apache.qpid.qmf2.common.QmfEvent)3 SchemaClassId (org.apache.qpid.qmf2.common.SchemaClassId)3 AddressParser (org.apache.qpid.messaging.util.AddressParser)2 Subscription (org.apache.qpid.qmf2.agent.Subscription)2 AgentHeartbeatWorkItem (org.apache.qpid.qmf2.console.AgentHeartbeatWorkItem)2 AgentRestartedWorkItem (org.apache.qpid.qmf2.console.AgentRestartedWorkItem)2 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1