Search in sources :

Example 6 with QmfConsoleData

use of org.apache.qpid.qmf2.console.QmfConsoleData in project qpid by apache.

the class QpidConfig method queueList.

/**
     * For every queue list detailed info (equivalent of qpid-config queues).
     *
     * More or less a direct Java port of QueueList in qpid-config, which handles qpid-config queues.
     *
     * @param filter specifies the queue name to display info for, if set to "" displays info for every queue.
     */
private void queueList(final String filter) {
    List<QmfConsoleData> queues = _console.getObjects("org.apache.qpid.broker", "queue");
    String caption = "Queue Name";
    int maxNameLen = caption.length();
    for (QmfConsoleData queue : queues) {
        String name = queue.getStringValue("name");
        if (filter.equals("") || filter.equals(name)) {
            if (name.length() > maxNameLen) {
                maxNameLen = name.length();
            }
        }
    }
    System.out.printf("%-" + maxNameLen + "s Attributes\n", caption);
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < ((maxNameLen / 5) + 5); i++) {
        buf.append("=====");
    }
    String line = buf.toString();
    System.out.println(line);
    for (QmfConsoleData queue : queues) {
        String name = queue.getStringValue("name");
        if (filter.equals("") || filter.equals(name)) {
            System.out.printf("%-" + maxNameLen + "s ", name);
            Map<String, Object> args = queue.<Map<String, Object>>getValue("arguments");
            args = (args == null) ? Collections.EMPTY_MAP : args;
            /*System.out.println(args);
for (Map.Entry<String, Object> entry  : args.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue().getClass().getCanonicalName());
}*/
            if (queue.getBooleanValue("durable")) {
                System.out.printf("--durable ");
            }
            if (queue.getBooleanValue("autoDelete")) {
                System.out.printf("auto-del ");
            }
            if (queue.getBooleanValue("exclusive")) {
                System.out.printf("excl ");
            }
            if (args.containsKey(FILESIZE)) {
                System.out.printf("--file-size=%d ", QmfData.getLong(args.get(FILESIZE)));
            }
            if (args.containsKey(FILECOUNT)) {
                System.out.printf("--file-count=%d ", QmfData.getLong(args.get(FILECOUNT)));
            }
            if (args.containsKey(MAX_QUEUE_SIZE)) {
                System.out.printf("--max-queue-size=%d ", QmfData.getLong(args.get(MAX_QUEUE_SIZE)));
            }
            if (args.containsKey(MAX_QUEUE_COUNT)) {
                System.out.printf("--max-queue-count=%d ", QmfData.getLong(args.get(MAX_QUEUE_COUNT)));
            }
            if (args.containsKey(POLICY_TYPE)) {
                System.out.printf("--limit-policy=%s ", (QmfData.getString(args.get(POLICY_TYPE))).replace("_", "-"));
            }
            if (args.containsKey(LVQ) && QmfData.getLong(args.get(LVQ)) == 1) {
                System.out.printf("--order lvq ");
            }
            if (args.containsKey(LVQNB) && QmfData.getLong(args.get(LVQNB)) == 1) {
                System.out.printf("--order lvq-no-browse ");
            }
            if (queue.hasValue("altExchange")) {
                ObjectId altExchangeRef = queue.getRefValue("altExchange");
                List<QmfConsoleData> altExchanges = _console.getObjects(altExchangeRef);
                if (altExchanges.size() == 1) {
                    QmfConsoleData altExchange = altExchanges.get(0);
                    System.out.printf("--alternate-exchange=%s", altExchange.getStringValue("name"));
                }
            }
            if (args.containsKey(FLOW_STOP_SIZE)) {
                System.out.printf("--flow-stop-size=%d ", QmfData.getLong(args.get(FLOW_STOP_SIZE)));
            }
            if (args.containsKey(FLOW_RESUME_SIZE)) {
                System.out.printf("--flow-resume-size=%d ", QmfData.getLong(args.get(FLOW_RESUME_SIZE)));
            }
            if (args.containsKey(FLOW_STOP_COUNT)) {
                System.out.printf("--flow-stop-count=%d ", QmfData.getLong(args.get(FLOW_STOP_COUNT)));
            }
            if (args.containsKey(FLOW_RESUME_COUNT)) {
                System.out.printf("--flow-resume-count=%d ", QmfData.getLong(args.get(FLOW_RESUME_COUNT)));
            }
            for (Map.Entry<String, Object> entry : args.entrySet()) {
                // Display generic queue arguments
                if (!SPECIAL_ARGS.contains(entry.getKey())) {
                    System.out.printf("--argument %s=%s ", entry.getKey(), entry.getValue());
                }
            }
            System.out.println();
        }
    }
}
Also used : ObjectId(org.apache.qpid.qmf2.common.ObjectId) QmfConsoleData(org.apache.qpid.qmf2.console.QmfConsoleData) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with QmfConsoleData

use of org.apache.qpid.qmf2.console.QmfConsoleData in project qpid by apache.

the class QpidServer method doGet.

/**
     * Called by the Web Server to allow a Server to handle a GET request.
     * The HTTP GET URL structure for the REST API is specified above in the overall class documentation.
     *
     * @param tx the HttpTransaction containing the request from the client and used to send the response.
     */
public void doGet(final HttpTransaction tx) throws IOException {
    String path = tx.getRequestURI();
    if (path.startsWith("/qpid/connection/")) {
        path = path.substring(17);
        // Using the principal lets different users use the default connection.
        String user = tx.getPrincipal();
        if (path.length() == 0) {
            // handle "/qpid/connection/" request with unspecified connection (returns list of available connections).
            tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(_connections.getAll(user)));
        } else {
            // if path.length() > 0 we're dealing with a specified Connection so extract the name and look it up.
            String connectionName = path;
            int i = path.indexOf("/");
            if (// Can use > rather than >= as we've already tested for "/qpid/connection/" above.
            i > 0) {
                connectionName = path.substring(0, i);
                path = path.substring(i + 1);
            } else {
                path = "";
            }
            connectionName = user + "." + connectionName;
            // attempts to connect to a broker specified in the QpidRestAPI config (or default 0.0.0.0:5672).
            if (connectionName.equals(user + ".default")) {
                ConnectionProxy defaultConnection = _connections.get(connectionName);
                if (defaultConnection == null) {
                    defaultConnection = _connections.create(connectionName, _defaultBroker, "", false);
                    // Wait a maximum of 1000ms for the underlying Qpid Connection to become available. If we
                    // don't do this the first call using the default will return 404 Not Found.
                    defaultConnection.waitForConnection(1000);
                }
            }
            // Find the Connection with the name extracted from the URI.
            ConnectionProxy connection = _connections.get(connectionName);
            if (connection == null) {
                tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
            } else if (!connection.isConnected()) {
                tx.sendResponse(HTTP_INTERNAL_ERROR, "text/plain", "500 Broker Disconnected.");
            } else {
                if (path.length() == 0) {
                    // handle request for information about a specified Console
                    tx.sendResponse(HTTP_OK, "application/json", connection.toString());
                } else {
                    // In this block we are dealing with resources associated with a specified connectionName.
                    // path describes the resources specifically related to "/qpid/connection/<connectionName>"
                    Console console = connection.getConsole();
                    if (path.startsWith("console/objects/")) {
                        // Get information about specified objects.
                        path = path.substring(16);
                        sendGetObjectsResponse(tx, console, path);
                    } else if (path.startsWith("console/objects") && path.length() == 15) {
                        // If objects is unspecified treat as a synonym for classes.
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getClasses()));
                    } else if (path.startsWith("console/address/")) {
                        // Get the Console AMQP Address
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getAddress()));
                    } else if (path.startsWith("console/address") && path.length() == 15) {
                        // Get the Console AMQP Address
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getAddress()));
                    } else if (path.startsWith("console/workItemCount/")) {
                        // Returns the count of pending WorkItems that can be retrieved.
                        tx.sendResponse(HTTP_OK, "text/plain", "" + console.getWorkitemCount());
                    } else if (path.startsWith("console/workItemCount") && path.length() == 21) {
                        // Returns the count of pending WorkItems that can be retrieved.
                        tx.sendResponse(HTTP_OK, "text/plain", "" + console.getWorkitemCount());
                    } else if (path.startsWith("console/nextWorkItem/")) {
                        // Obtains the next pending work item, or null if none available.
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getNextWorkitem()));
                    } else if (path.startsWith("console/nextWorkItem") && path.length() == 20) {
                        // Obtains the next pending work item, or null if none available.
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getNextWorkitem()));
                    } else if (path.startsWith("console/agents") && path.length() == 14) {
                        // Get information about all available Agents.
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getAgents()));
                    } else if (path.startsWith("console/agent/")) {
                        // Get information about a specified Agent.
                        Agent agent = console.getAgent(path.substring(14));
                        if (agent == null) {
                            tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
                        } else {
                            tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(agent));
                        }
                    } else if (path.startsWith("console/agent") && path.length() == 13) {
                        // If agent is unspecified treat as a synonym for agents.
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getAgents()));
                    } else if (path.startsWith("console/classes/")) {
                        // Get information about the classes for a specified Agent
                        // Get Agent name
                        path = path.substring(16);
                        // TODO handle getClasses() for specified Agent
                        tx.sendResponse(HTTP_NOT_IMPLEMENTED, "text/plain", "501 getClasses() for specified Agent not yet implemented.");
                    } else if (path.startsWith("console/classes") && path.length() == 15) {
                        // Get information about all the classes for all Agents
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getClasses()));
                    } else if (path.startsWith("console/packages/")) {
                        // Get information about the packages for a specified Agent
                        // Get Agent name
                        path = path.substring(17);
                        // TODO handle getPackages() for specified Agent.
                        tx.sendResponse(HTTP_NOT_IMPLEMENTED, "text/plain", "501 getPackages() for specified Agent not yet implemented.");
                    } else if (path.startsWith("object/")) {
                        /**
                             * This is the REST implementation of getObjects(oid) it is also the equivalent of
                             * the QmfConsoleData refresh() method where an object can update its state.
                             * N.B. that the ManagementAgent on the broker appears not to set the timestamp properties
                             * in the response to this call, which means that they get set to current time in the
                             * QmfConsoleData, this is OK for _update_ts but not for _create_ts and _delete_ts
                             * users of this call should be aware of that in their own code.
                             */
                        path = path.substring(7);
                        // The ObjectId has been passed in the URI, create a real ObjectId
                        ObjectId oid = new ObjectId(path);
                        List<QmfConsoleData> objects = console.getObjects(oid);
                        if (objects.size() == 0) {
                            tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
                        } else {
                            // Not that in a departure from the QMF2 API this returns the QmfConsoleData object
                            // rather than a list of size one. Perhaps the APIs should be completely consistent
                            // but this response seems more convenient.
                            tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(objects.get(0)));
                        }
                    } else if (path.startsWith("console/packages") && path.length() == 16) {
                        // Get information about all the packages for all Agents
                        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(console.getPackages()));
                    } else {
                        tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
                    }
                }
            }
        }
    } else if (path.startsWith("/qpid/connection")) {
        // handle "/qpid/connection" request with unspecified connection (returns list of available connections).
        // Using the principal lets different users use the default connection.
        String user = tx.getPrincipal();
        tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(_connections.getAll(user)));
    } else {
        tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
    }
}
Also used : Agent(org.apache.qpid.qmf2.console.Agent) ObjectId(org.apache.qpid.qmf2.common.ObjectId) Console(org.apache.qpid.qmf2.console.Console) List(java.util.List)

Example 8 with QmfConsoleData

use of org.apache.qpid.qmf2.console.QmfConsoleData in project qpid by apache.

the class QpidServer method doPost.

/**
     * Called by the Web Server to allow a Server to handle a POST request.
     * <pre>
     * POST: &lt;host&gt;:&lt;port&gt;/qpid/connection/&lt;name&gt;/object/&lt;ObjectId&gt;
     *      HTTP body: {"_method_name":&lt;method&gt;,"_arguments":&lt;inArgs&gt;}
     *      &lt;method&gt;: A string containing the QMF2 method name e.g. "getLogLevel", "setLogLevel", "create", "delete".
     *      &lt;inArgs&gt;: A JSON string containing the method arguments e.g. {"level":"debug+:Broker"} for setLogLevel.
     *      HTTP response: A JSON string containing the response e.g. {"level":"notice+"} for getLogLevel (may be empty).
     *
     *      This method invokes the QMF2 method &lt;method&gt; with arguments &lt;inArgs&gt; on the object &lt;ObjectId&gt;
     * </pre>
     * @param tx the HttpTransaction containing the request from the client and used to send the response.
     */
@SuppressWarnings("unchecked")
public void doPost(final HttpTransaction tx) throws IOException {
    String path = tx.getRequestURI();
    if (path.startsWith("/qpid/connection/")) {
        path = path.substring(17);
        String user = tx.getPrincipal();
        String connectionName = path;
        int i = path.indexOf("/");
        if (// Can use > rather than >= as we've already tested for "/qpid/connection/" above.
        i > 0) {
            connectionName = user + "." + path.substring(0, i);
            path = path.substring(i + 1);
            // Find the Connection with the name extracted from the URI.
            ConnectionProxy connection = _connections.get(connectionName);
            if (connection == null) {
                _log.info("QpidServer.doPost path: {} Connection not found.", tx.getRequestURI());
                tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
            } else if (!connection.isConnected()) {
                tx.sendResponse(HTTP_INTERNAL_ERROR, "text/plain", "500 Broker Disconnected.");
            } else {
                // If we get this far we should have found a Qpid Connection so retrieve the QMF2 Console Object.
                Console console = connection.getConsole();
                if (path.startsWith("object/")) {
                    path = path.substring(7);
                    // The ObjectId has been passed in the URI create an ObjectId and retrieve the Agent Name.
                    ObjectId oid = new ObjectId(path);
                    String agentName = oid.getAgentName();
                    // The qpidd ManagementAgent doesn't populate AgentName, if it's empty assume it's the broker.
                    agentName = agentName.equals("") ? "broker" : agentName;
                    // Find the Agent we got the QmfData from.
                    Agent agent = console.getAgent(agentName);
                    if (agent == null) {
                        _log.info("QpidServer.doPost path: {} Agent: {} not found.", tx.getRequestURI(), agentName);
                        tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
                    } else {
                        // If we get this far we can create the Object and invoke the method.
                        // We can create a QmfConsoleData with nothing but an ObjectId and the agent.
                        QmfConsoleData object = new QmfConsoleData(Collections.EMPTY_MAP, agent);
                        object.setObjectId(oid);
                        String request = tx.getRequestString();
                        _log.info("QpidServer.doPost path: {} body: {}", tx.getRequestURI(), request);
                        //System.out.println(request);
                        String method = "";
                        try {
                            Map<String, Object> reqMap = JSON.toMap(request);
                            method = (String) reqMap.get("_method_name");
                            Object arguments = reqMap.get("_arguments");
                            Map args = (arguments instanceof Map) ? (Map) arguments : null;
                            //System.out.println("method: " + method + ", args: " + args);
                            // Parse the args if present into a QmfData (needed by invokeMethod).
                            QmfData inArgs = (args == null) ? new QmfData() : new QmfData(args);
                            // Invoke the specified method on the QmfConsoleData we've created.
                            MethodResult results = null;
                            _log.info("invokeMethod: {}", request);
                            results = object.invokeMethod(method, inArgs);
                            tx.sendResponse(HTTP_OK, "application/json", JSON.fromObject(results));
                        } catch (QmfException qmfe) {
                            _log.info("QpidServer.doPost() caught Exception {}", qmfe.getMessage());
                            tx.sendResponse(HTTP_INTERNAL_ERROR, "text/plain", "invokeMethod(" + method + ") -> " + qmfe.getMessage());
                        } catch (Exception e) {
                            _log.info("QpidServer.doPost() caught Exception {}", e.getMessage());
                            tx.sendResponse(HTTP_INTERNAL_ERROR, "text/plain", "500 " + e.getMessage());
                        }
                    }
                } else {
                    tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
                }
            }
        } else {
            tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
        }
    } else {
        tx.sendResponse(HTTP_NOT_FOUND, "text/plain", "404 Not Found.");
    }
}
Also used : Agent(org.apache.qpid.qmf2.console.Agent) QmfData(org.apache.qpid.qmf2.common.QmfData) ObjectId(org.apache.qpid.qmf2.common.ObjectId) QmfException(org.apache.qpid.qmf2.common.QmfException) IOException(java.io.IOException) Console(org.apache.qpid.qmf2.console.Console) QmfConsoleData(org.apache.qpid.qmf2.console.QmfConsoleData) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) MethodResult(org.apache.qpid.qmf2.console.MethodResult) QmfException(org.apache.qpid.qmf2.common.QmfException)

Example 9 with QmfConsoleData

use of org.apache.qpid.qmf2.console.QmfConsoleData in project qpid by apache.

the class Test4 method evaluateDataQuery.

public List<QmfConsoleData> evaluateDataQuery(QmfQuery query) {
    List<QmfConsoleData> results = new ArrayList<QmfConsoleData>();
    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(new QmfConsoleData(object.mapEncode(), null));
        }
    } else {
        for (QmfAgentData object : _objectIndex.values()) {
            if (!object.isDeleted() && query.evaluate(object)) {
                results.add(new QmfConsoleData(object.mapEncode(), null));
            }
        }
    }
    return results;
}
Also used : ObjectId(org.apache.qpid.qmf2.common.ObjectId) ArrayList(java.util.ArrayList) QmfConsoleData(org.apache.qpid.qmf2.console.QmfConsoleData) QmfAgentData(org.apache.qpid.qmf2.agent.QmfAgentData)

Example 10 with QmfConsoleData

use of org.apache.qpid.qmf2.console.QmfConsoleData in project qpid by apache.

the class ConnectionAudit method validateQueue.

/**
     * Looks up the exchange and binding information from the supplied queuename then calls the main validateQueue()
     * @param queueName the name of the queue that we want to check against the whitelists.
     * @param address the connection address information for the subscription.
     * @param timestamp the timestamp of the subscription.
     */
private void validateQueue(final String queueName, final String address, final String timestamp) {
    ObjectId queueId = null;
    List<QmfConsoleData> queues = _console.getObjects("org.apache.qpid.broker", "queue");
    for (QmfConsoleData queue : queues) {
        // We first have to find the ObjectId of the queue called queueName.
        if (queue.getStringValue("name").equals(queueName)) {
            queueId = queue.getObjectId();
            break;
        }
    }
    if (queueId == null) {
        System.out.printf("%s ERROR ConnectionAudit.validateQueue() %s reference couldn't be found\n", new Date().toString(), queueName);
    } else {
        // If we've got the queue's ObjectId we then find the binding that references it.
        List<QmfConsoleData> bindings = _console.getObjects("org.apache.qpid.broker", "binding");
        for (QmfConsoleData binding : bindings) {
            ObjectId queueRef = binding.getRefValue("queueRef");
            if (queueRef.equals(queueId)) {
                // We've found a binding that matches queue queueName so look up the associated exchange and validate.
                QmfConsoleData exchange = dereference(binding.getRefValue("exchangeRef"));
                String exchangeName = exchange.getStringValue("name");
                validateQueue(queueName, exchangeName, binding, address, timestamp);
            }
        }
    }
}
Also used : ObjectId(org.apache.qpid.qmf2.common.ObjectId) QmfConsoleData(org.apache.qpid.qmf2.console.QmfConsoleData) Date(java.util.Date)

Aggregations

QmfConsoleData (org.apache.qpid.qmf2.console.QmfConsoleData)20 ObjectId (org.apache.qpid.qmf2.common.ObjectId)16 Map (java.util.Map)11 HashMap (java.util.HashMap)10 QmfException (org.apache.qpid.qmf2.common.QmfException)5 Agent (org.apache.qpid.qmf2.console.Agent)5 Date (java.util.Date)4 QmfData (org.apache.qpid.qmf2.common.QmfData)4 QmfEvent (org.apache.qpid.qmf2.common.QmfEvent)4 SchemaClassId (org.apache.qpid.qmf2.common.SchemaClassId)4 AgentHeartbeatWorkItem (org.apache.qpid.qmf2.console.AgentHeartbeatWorkItem)4 MethodResult (org.apache.qpid.qmf2.console.MethodResult)4 ArrayList (java.util.ArrayList)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 EventReceivedWorkItem (org.apache.qpid.qmf2.console.EventReceivedWorkItem)3 MethodResponseWorkItem (org.apache.qpid.qmf2.console.MethodResponseWorkItem)3 ObjectUpdateWorkItem (org.apache.qpid.qmf2.console.ObjectUpdateWorkItem)3 SubscribeIndication (org.apache.qpid.qmf2.console.SubscribeIndication)3 SubscriptionIndicationWorkItem (org.apache.qpid.qmf2.console.SubscriptionIndicationWorkItem)3 IOException (java.io.IOException)2