This section describes the REST API provided by the Apache Qpid Broker-J. The REST API is intended
for use by developers who wish to automate the management or monitoring of the Broker. It
is also very useful for adhoc monitoring on the command line using tools such as
curl
.
The REST API provides access to all of the Broker's entities using hierarchical paths expressed by the URI. Responses are returned in JSON format.
The GET
method request retrieves information about an object, the
DELETE
method requests the removal of one, and the PUT
or POST
methods perform updates or create new objects. The
POST
method is also used to invoke operations.
The REST API is versioned with the version number embedded within the URI. The general form
of the URI is /api/<version>
where <version> is a dot separated
major and minor model version prefixed with "v", for example, "v6.1" (without the quotation marks).
For convenience the alias latest
(/api/latest
) signifies the
latest supported version.
There are also some ancillary services under URI /service
used for
authentication and logout.
REST API documentation is available on-line from any Broker at location
/apidocs
. It is also linked from the menu of the Web Management Console.
Before you can use the REST API, you must authenticate. Authentication decisions are made by the authentication provider associated with HTTP port on which you connect.
You may authenticate using SASL
(/service/sasl
) or HTTP
Basic Authentication. The latter is convienent when using tools such as
curl
on the command line. This is illustrated in the examples
below.
For SASL authentication use a GET
request to
/service/sasl
to get a list of supported SASL mechanisms, and use
PUT
to the same URL to perform the SASL negotiation.
It is possible to end an authenticated session using
/service/logout
.
Methods PUT or POST can be used to create ConfiguredObject.
ConfiguredObject can be created by submitting PUT request against ConfiguredObject full URI (the one ending with configured object name) or by submitting PUT/POST request against parent URI. The request encoding should be json (application/json) and request body should contain attributes values in json format. On successful completion of operation a response should be returned having response status code set to 201 and response header "Location" set to ConfiguredObject full URI. If object with a such name/id already exist and POST/PUT requests is made against parent URI, an error response should be returned having response code 409 (conflict) and body containing the json with the reason of operation failure. If object with a such name/id already exist and and PUT request is made against ConfiguredObject full URI, then ConfiguredObject update should be performed and http status code 200 should be returned. If ConfiguredObject cannot be created because of validation failure(s) the response should have http status code set 422 (Unprocessible Entity) and body should contain json with the reason of operation failure. On any other failure to create ConfiguredObject the response should have status code set to 400 (Bad Request) and payload should contain a json with error explaining the exact reason of failure.
Example 6.1. Examples of REST calls for Queue creation
To create Queue with name "my-queue" on a virtual host with name "vh" (which is contained within virtual host node with name "vhn") either of the following requests should be made:
PUT /api/latest/queue/vhn/vh HTTP/1.1
POST /api/latest/queue/vhn/vh HTTP/1.1
PUT /api/latest/queue/vhn/vh/my-queue HTTP/1.1
Response code 201 should be returned on successful queue creation. Response header "Location" should be set to "/api/latest/queue/test/my-queue". If queue with name "my-queue" already exists and either of 2 first requests above were used, an error response with response code 409 (conflict) and body containing json with message that queue exists should be returned. If queue with name "my-queue" exists and last request is used, then Queue update should occur.
Methods PUT or POST can be used to update ConfiguredObject.
ConfiguredObject can be updated by submitting PUT or POST request against ConfiguredObject full URI (the one ending with configured object name). The request encoding should be json (application/json) and request body should contain a ConfiguredObject json (with all or only modified attributes). On successful completion of operation a response code 200 should be returned. If ConfiguredObject does not exists and PUT method is used, such object should be created (201 response will be returned in this case). If ConfiguredObject does not exists and POST method is used, an error response should be returned having response status code 404 and payload with json explaining the problem. If any error occur on update, a response with response code 400 or 422 or 404 should be sent back to the client containing json body with error details.
Example 6.2. Examples of REST calls for Queue update
To update Queue with name "my-queue" on a virtual host with name "vh" (contained in virtual host node with name "vhn") either of the following requests can be made:
POST /api/latest/queue/vhn/vh/my-queue HTTP/1.1
POST /api/latest/queue/vhn/vh/my-queue HTTP/1.1
Method DELETE can be used to delete ConfiguredObject. Alternatively, ConfiguredObject can be deleted with update request having desiredState attribute set to value "DELETED". POST or PUT methods can be used in this case.
On successful completion of operation a response code 200 should be returned.
With DELETE method object ConfiguredObject in following ways:
by submitting DELETE request using ConfiguredObject full URI (the one ending with configured object name)
by submitting DELETE request using parent URI and providing parameters having the same names as children attributes, for example, id, name, etc. Multiple children can be deleted in a such way. Many "id" parameters can be specified in such requests. Only children with matching attribute values will be deleted.
Example 6.3. Examples of REST calls for Queue deletion
To delete Queue with name "my-queue" on a virtual host with name "vh" (contained in virtual host node with name "vhn") either of the following requests can be made:
DELETE /api/latest/queue/vhn/vh/my-queue HTTP/1.1
DELETE /api/latest/queue/vhn/vh?name=my-queue HTTP/1.1
DELETE /api/latest/queue/vhn/vh?id=real-queue-id HTTP/1.1
Method GET is used to retrieve an object's attributes values and statistics.
To retrieve a single object, use its full URI. For instance, to retrieve a single queue:
GET /api/latest/queue/vhn/vh/my-queue
To retrieve all objects beneath a parent, pass the parent's URI. For instance, to retrieve
all queues beneath the virtualhost called vh
. A collection will be returned.
GET /api/latest/queue/vhn/vh
Request parameters (with the same name as an attribute) are used to filter the returned collection.
For instance, to filter those queues of type standard
:
GET /api/latest/queue/vhn/vh?type=standard
Additional parameters supported in GET requests:
To restrict the depth of hierarchy of configured objects to return in response
If set to "true" attribute actual values are returned instead of effective
If set to "false" the inherited context is included from the object's ancestors. Default is true.
Sets the maximum length for values of over-sized attributes to trim
If set to "true", the returned json can be used as initial configuration.
Method POST is used to invoke Configured Objects operations. Some operations support parameters. Pass parameters using a JSON request body containing a map with a map entry for each parameter.
Example 6.4. Example REST call invoking the operation clear queue
To clear the queue with name "my-queue" on a virtual host with name "vh".
POST api/latest/queue/vhn/vh/my-queue/clearQueue HTTP/1.1
Table 6.1. HTTP status codes returned by REST interfaces
Status code | Description |
---|---|
200 |
REST request is successfully completed. This status code can be returned by update, delete and get requests. |
201 |
New configured object is created. It is returned by REST PUT and POST requests for creation of configured objects. |
400 |
REST request cannot be performed due to errors in request. It can be returned from create, update and delete requests. The details of a problem are provided in the response payload in json format. |
401 |
The request requires user authentication |
403 |
Execution of request is not allowed due to failure to authorize user operation. |
404 |
The requested configured object cannot be found. This status code can be returned from POST update requests if configured object does not exist. The reason for the status code is provided in the response payload in json format. |
409 |
The request can not be performed because its execution can create conflicts in the broker. This status code can be returned from POST/PUT create requests against parent URI if configured object with requested name or id already exists. The status code 409 can also be returned if removal or update of configured object can violate system integrity. The reason for the status code is provided in the response payload in json format. |
422 |
The request can not be performed because provided information either incomplete or invalid. This status code can be returned from create or update requests. The reason for the status code is provided in the response payload in json format. |
Example 6.5. Examples of queue creation using curl (authenticating as user admin):
#create a durable queue curl --user admin -X PUT -d '{"durable":true}' http://localhost:8080/api/latest/queue/<vhostnode name>/<vhostname>/<queuename> #create a durable priority queue curl --user admin -X PUT -d '{"durable":true,"type":"priority"}' http://localhost:8080/api/latest/queue/<vhostnode name>/<vhostname>/<queuename>
NOTE: These curl examples utilise an unsecured HTTP transport. To use the examples it is first necessary enable Basic authentication for HTTP within the HTTP Management Configuration (it is off by default). For details see Section 7.17, “HTTP Plugin”
The Qpid Broker-J provides a powerful feature called the Query API. This allows the retrieval of the existing configured objects attributes satisfying user-provided queries.
Developers and operators can use this feature to monitor the Broker. For example, using Query API one can find all queues with queue depth exceeding some limit or existing connections made from a particular location(s).
When using the Query API one specifies the category of the object to query, a list of attributes to return in the result set, an optional where clause, expressed as a predicate, that determines the filtering criteria, ordering, and limit/offset. The features should be readily recognisable to anyone who has has familiarity with SQL.
Queries associate with either the broker as a whole, or an individual virtualhost. Queries associated with the Broker can query any object within the Broker. Queries associated with a virtualhost are limited to the objects of the virtualhost itself. For instance a queue query associated with a virtualhost queries only the queues belonging to that virtualhost. On the other hand, a queue query associated with the Broker sees all the queues belonging on the entire Broker.
Table 6.2. Query API URLs
Query API URL | Description |
---|---|
/api/latest/querybroker/<configured object category name> /api/<version>/querybroker/<configured object category name> |
Query API URL fragment to query the specified object type across the entire broker |
/api/latest/queryvhost/<virtual host node name>/<virtual host name>/<configured object category name> /api/<version>/queryvhost/<virtual host node name>/<virtual host name>/<configured object category name> |
Query API URL fragment to query the specified object type for a specific virtualhost |
The QueryAPI accepts select
, where
, orderBy
,
limit
and offset
request parameters.
Table 6.3. Query API request parameters
Parameter Name | Parameter Description |
---|---|
|
The Columns within the result set are named. For expressions that are simple attribute names, the column names will follow the attributes themselves. By default, other expressions will have a no name. Column names can be overridden with an |
|
The The syntax of the expression
is based on a subset of the SQL92 conditional expression syntax and is similar to selector expressions in JMS e.g.
|
|
Ordering conditions; the syntax of the expression is based on a subset of the SQL92 ordering expression syntax. Similar to ordering expressions in SQL, one can specify in ordering expression attributes names, sub-expressions or indexes (starting from 1) of attributes or expressions specified in select. |
|
The maximum number of results to provide starting from given offset. |
|
An offset in results (default is 0) to provide results from. |
Example 6.6. Example of a Query API request to retrieve queue names and depths.
GET api/latest/querybroker/queue?select=name,queueDepthBytes,queueDepthMessages&where=queueDepthBytes>0&orderBy=1 desc,2 desc&offset=0&limit=100 HTTP/1.1
The Query API returns a JSON response. The response contains the following:
headers
ordered list of result set column names derived from the select
clause. Note that anonymous expressions (that is, those expressed without an
AS
) will have empty column name.
results
two dimensional array containing the result-set
total
The total number of results matching the where criteria.
Example 6.7. Example of Query API call for queue names and depths.
GET api/latest/querybroker/queue?select=name,queueDepthBytes,queueDepthMessages&where=queueDepthBytes>0&orderBy=1 desc,2 desc&offset=0&limit=100 HTTP/1.1
{ "headers" : [ "name", "queueDepthBytes", "queueDepthMessages" ], "results" : [ [ "foo", 312, 26], [ "bar", 300, 24 ] ], "total" : 2 }
Expressions within the select
, where
and orderBy
clauses can be comprised in the following manner. Expressions can be nested to arbitary depth. Parentheses
allow for precedence to be explicitly denoted.
variable name which can be an attribute name e.g queueDepthBytes
or
a reference to a parent attribute $parent.name
literal e.g. 3
or 'foo'
functions - see below e.g. now()
or to_string(createdDate, '%tm/%td/%ty', 'EST')
arithmetic operations e.g. 3 * 4
or to_string(now()) + name
The following functions are supported:
Table 6.4. Query API functions
Function Name | Function Description |
---|---|
|
concatenates the given objects into a string |
|
returns current date and time |
|
converts the first parameter, which must be a string. into a date. The
string must be in ISO-8601 format e.g. |
|
adds the given ISO-8601 duration |
|
Converts given object into a string. If the format argument is present, it must be a Java
Formatter
compliant string e.g. The timezone argument is significant if the object is a Date. If the timezone
argument is specified it must be a valid Java timezone name. The date is converted
to the specified timezone before being formatted by the |
Broker query engine extends existing functionality of broker query API and allows executing complex SQL-like queries against the broker. It allows using predicates combining AND/OR/NOT logical operations, supports aggregation and grouping as well as numerous numeric, datetime and string functions. Currently, querying from multiple object types (domains) in a single query as well as all types of joins are not supported.
Some properties influencing the query output can be specified directly in the request, but there are also global properties, affecting the way query engine works.
Table 6.5. Query Engine Configuration
Context Property Name | Description |
---|---|
qpid.port.http.query.engine.cacheSize |
Query cache size |
qpid.port.http.query.engine.maxQueryDepth |
Maximal query depth |
qpid.port.http.query.engine.zoneId |
Timezone ID |
After query is parsed from the SQL string, it is stored into a cache. When the same query will be fired against the query engine, parsing will be omitted and the query structure will be retrieved from cache. By default, query cache size is 1000. This means, that when 1000 different queries will be fired against the query engine, the next one will override the oldest cache entry. When set to 0 or to negative value, query cache will not be used and each query will be parsed.
The longer is the query and the more conditions it contains, the bigger becomes the query depth. To limit query complexity, maximal query depth parameter can be used. By default, maximal query depth is 4096. This should suffice for most queries even complicated ones. If query depth exceeds this limit, following error will be returned:
{ "errorMessage": "Max query depth reached: 4096" }
Zone ID value should follow the rules described in javadoc. The default value for zone id is "UTC".
An authorized request should be sent to the following endpoint: POST http://<hostname>:<port>/api/latest/querybroker/broker SQL query should be supplied in the "sql" field of the JSON body:
{ "sql": "select * from broker" }
SQL keywords, operators and functions are case-insensitive, so are domain names (object types) specified in
the FROM
clause. Field names specified in the SELECT
clause are case-sensitive.
Following queries are similar:
{ "sql": "SELECT name FROM BROKER" }
{ "sql": "SELECT name FROM broker" }
{ "sql": "select name from broker" }
They will return the same output. When an entity field name is written in wrong case or misspelled, an error will be returned. For example, following query
{ "sql": "SELECT NAME FROM BROKER" }
has field NAME
written in upper case, which will result in an error:
{ "errorMessage": "Domain 'BROKER' does not contain field 'NAME'" }
In this document many SQL queries are split into several lines for better readability, but JSON format does not support
multiline string fields. Therefore, even the long SQL queries should be placed in sql
field of the JSON body as a
single line.
Aside from SQL query several configuration parameters can be provided to influence output format:
Table 6.6. Additional Request Parameters
Field Name | Description |
---|---|
dateTimeFormat |
Format of the datetime fields, possible values: LONG, STRING |
dateTimePattern |
Pattern for datetime fields formatting, e.g. yyyy-MM-dd HH:mm:ss |
decimalDigits |
Amount of decimal digits |
roundingMode |
Rounding mode for arithmetic operations, possible values UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY |
When datetime format is specified as LONG
, datetime fields will be returned as
milliseconds from UNIX epoch. So, following query
{ "sql": "select id, name, createdTime from broker", "dateTimeFormat": "LONG" }
returns following result:
{ "results": [ { "id": "ce8bbaf0-3efa-4176-889a-7987ac1988cc", "name": "broker", "createdTime": 1645195849272 } ], "total": 1 }
In opposite the query
{ "sql": "select id, name, createdTime from broker", "dateTimeFormat": "STRING" }
returns following result:
{ "results": [ { "id": "ce8bbaf0-3efa-4176-889a-7987ac1988cc", "name": "broker", "createdTime": "2022-02-18 15:50:49.272" } ], "total": 1 }
The default format of the string datetime representation is "yyyy-MM-DD HH:mm:ss.SSS".
It can be changed using the parameter dateTimePattern
.
The query
{ "sql": "select id, name, createdTime from broker", "dateTimeFormat": "STRING", "dateTimePattern": "yyyy/MM/dd HH:mm:ss.SSS" }
returns following result
{ "results": [ { "id": "ce8bbaf0-3efa-4176-889a-7987ac1988cc", "name": "broker", "createdTime": "2022/02/18 15:50:49.272" } ], "total": 1 }
By default, decimal digits value is 6, meaning there will be 6 digits after decimal point. For example, following query
{ "sql": "select avg(queueDepthMessages) from queue" }
returns following result:
{ "results": [ { "avg(queueDepthMessages)": 0.437227 } ], "total": 1 }
This behavior can be changed for each value separately using ROUND or TRUNC functions, but can also be changed for
the whole query result by supplying decimalDigits
parameter. Following query
{ "sql": "select avg(queueDepthMessages) from queue", "decimalDigits": 2 }
returns following result:
{ "results": [ { "avg(queueDepthMessages)": 0.43 } ], "total": 1 }
Rounding mode affects how results of the arithmetic operations will be rounded. The rules of applying different rounding modes can be found in appropriate javadoc. Default rounding mode is HALF_UP. Changing rounding mode will affect division operations, but will not affect results of ROUND() and TRUNC() functions (which always use rounding mode HALF_UP and HALF_DOWN appropriately). Following query
{ "sql": "select 2/3", "decimalDigits": 2, "roundingMode": "DOWN" }
uses rounding mode DOWN
and returns following result:
{ "results": [ { "2/3": 0.66 } ], "total": 1 }
When rounding mode will be changed to UP
{ "sql": "select 2/3", "decimalDigits": 2, "roundingMode": "UP" }
result will be changed as well:
{ "results": [ { "2/3": 0.67 } ], "total": 1 }
Object types or domains to query from are specified in the "FROM" clause. The broker object hierarchy can be retrieved using an endpoint http://<hostname>:<port>/service/metadata Alternatively following SQL query can be fired
{ "sql": "select * from domain" }
returning similar result:
{ "results": [ { "name": "AccessControlProvider" }, { "name": "AclRule" }, { "name": "AuthenticationProvider" }, { "name": "Binding" }, { "name": "BrokerConnectionLimitProvider" }, { "name": "BrokerLogInclusionRule" }, { "name": "BrokerLogger" }, { "name": "Certificate" }, { "name": "Connection" }, { "name": "ConnectionLimitRule" }, { "name": "Consumer" }, { "name": "Domain" }, { "name": "Exchange" }, { "name": "Group" }, { "name": "GroupMember" }, { "name": "GroupProvider" }, { "name": "KeyStore" }, { "name": "Plugin" }, { "name": "Port" }, { "name": "Queue" }, { "name": "RemoteReplicationNode" }, { "name": "Session" }, { "name": "TrustStore" }, { "name": "User" }, { "name": "VirtualHost" }, { "name": "VirtualHostAccessControlProvider" }, { "name": "VirtualHostAlias" }, { "name": "VirtualHostConnectionLimitProvider" }, { "name": "VirtualHostLogInclusionRule" }, { "name": "VirtualHostLogger" }, { "name": "VirtualHostNode" } ], "total": 31 }
In addition to the object types supported by broker query REST API, following object types (domains) can be used as well:
Those objects do not belong to the broker object hierarchy (as they don't descend from ConfiguredObject), they were added to make queries against listed domains more simple. For example, following query
SELECT * FROM AclRule WHERE identity = 'amqp_user1'
returns following result:
{ "results": [ { "identity": "amqp_user1", "attributes": {}, "action": { "objectType": "VIRTUALHOST", "properties": { "name": null, "empty": true }, "operation": "ACCESS" }, "objectType": null, "operation": null, "outcome": "ALLOW_LOG" }, { "identity": "amqp_user1", "attributes": { "NAME": "request.amqp_user1", "ROUTING_KEY": "*" }, "action": { "objectType": "EXCHANGE", "properties": { "name": "request.amqp_user1", "empty": false }, "operation": "PUBLISH" }, "objectType": null, "operation": null, "outcome": "ALLOW" }, { "identity": "amqp_user1", "attributes": { "NAME": "broadcast.amqp_user1.*" }, "action": { "objectType": "QUEUE", "properties": { "name": "broadcast.amqp_user1.*", "empty": false }, "operation": "CONSUME" }, "objectType": null, "operation": null, "outcome": "ALLOW_LOG" }, { "identity": "amqp_user1", "attributes": { "NAME": "response.amqp_user1" }, "action": { "objectType": "QUEUE", "properties": { "name": "response.amqp_user1", "empty": false }, "operation": "CONSUME" }, "objectType": null, "operation": null, "outcome": "ALLOW_LOG" } ], "total": 4 }
Please note, that keyword FROM
isn't mandatory, it is possible to execute queries without it, when the result shouldn't
retrieve any data from broker. Few examples of such queries would be:
SELECT CURRENT_TIMESTAMP()
SELECT DATE(CURRENT_TIMESTAMP())
SELECT (2 + 10) / 3
SELECT 2 * 5 > 12
Filtering is achieved by using different operators groups in a WHERE
clause. Operators
can be divided into comparison operators, conditional operators and logical operators.
Broker entities have fields belonging to different java types: primitives (boolean, int, long, double), strings, datetime Date, LocalDate, LocalDateTime, Instant. Object IDs are usually of UUID type. Many values are enums. When comparing field values, they follow some implicit casting rules: enums and UUIDs are cast to strings, datetime values are cast to Instant, numeric values are cast to BigDecimal. When casting string value to date, by default is used pattern "uuuu-MM-dd". That allows to run following queries:
SELECT * FROM certificate WHERE DATE(validUntil) = '2020-12-31'
Here string value is implicitly cast to Instant and both value are compared as Instant instances. When casting string to datetime, by default is used pattern "uuuu-MM-dd HH:mm:ss" with optional 0-6 second fractions. That allows to run following queries:
SELECT * FROM certificate WHERE DATE(validUntil) > '2020-12-31 23:59:59.999'
Here string value is implicitly cast to Instant as well and both value are compared as Instant instances. It is important to compare values of the same type, otherwise an error may be returned or query may be evaluated erroneously. For example, following query
SELECT * FROM queue WHERE durable = 'true'
will return an empty result, because field durable
is of boolean type and comparing boolean value with a string 'true'
will always return false. The correct query should be
SELECT * FROM queue WHERE durable = true
To remove duplicates from the results keyword "DISTINCT" can be used. For example, query
SELECT overflowPolicy FROM queue
will return results for all queues, but query
SELECT DISTINCT overflowPolicy FROM queue
will return only several values.
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN(expression1 AND expression2) BETWEEN(expression1, expression2) BETWEEN expression1 AND expression2 BETWEEN expression1, expression2
Equal operator is designated using "=" character. It allows comparison of boolean, datetime, numeric and string values. Both compared values must have same type.
Greater than operator is designated using ">" character. It allows comparison of datetime, numeric and string values. Both compared values must have same type.
Greater than or equal operator is designated using ">=" characters. It allows comparison of datetime, numeric and string values. Both compared values must have same type.
The IN operator allows specifying multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions. Alternatively IN operator can be used with a subquery. When a subquery is used, it should return only one value, otherwise an error will be returned.
Table 6.12. IN Parameters
Parameter | Description |
---|---|
expression |
Expression to compare to |
value_1 - value_n |
Values to compare with |
Find bindings having destination queue belonging to the list
SELECT * FROM binding WHERE destination IN ('broadcast.amqp_user1.Service1', 'broadcast.amqp_user1.Service2', 'broadcast.amqp_user1.Service3')
Find bindings having destination queue with message depth between 1000 and 2000
SELECT * FROM binding WHERE destination IN (SELECT name FROM queue WHERE queueDepthMessages BETWEEN (1000, 2000))
Less than operator is designated using "<" character. It allows comparison of datetime, numeric and string values. Both compared values must have same type.
Less than or equal operator is designated using "<=" characters. It allows comparison of datetime, numeric and string values. Both compared values must have same type.
The LIKE operator is used to search for a specified pattern in a string. There are two wildcards often used in conjunction with the LIKE operator: the percent sign "%" represents zero, one, or multiple characters; the question mark "?" represents one, single character.
expression LIKE pattern expression LIKE pattern ESCAPE escapeCharacter expression LIKE (pattern) expression LIKE (pattern ESCAPE escapeCharacter)
The CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN conditionN THEN resultN ELSE result END
Table 6.17. CASE Parameters
Parameter | Description |
---|---|
condition1 - conditionN |
Conditions to estimate |
result1 - resultN |
Results to return |
Group queues into good (< 60% of max depth), bad (60% - 90% of max depth) and critical (> 90% of max depth), count number of queues in each group. Consider queues with unlimited depth being good.
SELECT COUNT(*), CASE WHEN maximumQueueDepthMessages != -1 AND maximumQueueDepthBytes != -1 AND (queueDepthMessages > maximumQueueDepthMessages * 0.9 OR queueDepthBytes > maximumQueueDepthBytes * 0.9) THEN 'critical' WHEN maximumQueueDepthMessages != -1 AND maximumQueueDepthBytes != -1 AND queueDepthMessages BETWEEN (maximumQueueDepthMessages * 0.6 AND maximumQueueDepthMessages * 0.9) OR queueDepthBytes BETWEEN (maximumQueueDepthBytes * 0.6 AND maximumQueueDepthBytes * 0.9) THEN 'bad' ELSE 'good' END AS queueState FROM queue GROUP BY queueState
The "AND" and "OR" operators are used to filter records based on more than one condition: the "AND" operator displays a record if all the conditions separated by "AND" are TRUE. The "OR" operator displays a record if any of the conditions separated by "OR" is TRUE. The "NOT" operator displays a record if the condition(s) is NOT TRUE.
Default sorting order is ascending, default sorting field is `name` for domains having this field. Results of the following query will be sorted ascending by name:
SELECT * FROM queue
Few exceptions are following:
Table 6.18. Default sorting fields
Domain | Default sorting field |
---|---|
AclRule |
identity |
Certificate |
alias |
ConnectionLimitRule |
identity |
Results of the following query will be sorted ascending by alias:
SELECT * FROM certificate
To apply another sorting rules clause `ORDER BY` should be used. It may contain one of the fields specified in the `SELECT` clause:
SELECT id, name, state FROM queue ORDER BY name
Alternatively it may contain fields not specified in `SELECT` clause:
SELECT id, name, state FROM queue ORDER BY overflowPolicy
Instead of using field names or aliases items in the `ORDER BY` clause can also be referenced by ordinal - the numeric value of their order of appearance in the `SELECT` clause. For example, following query
SELECT name, overflowPolicy FROM queue ORDER BY 2 DESC, 1 ASC
will return results sorted in descending order by overflow policy and inside the groups with the same overflow policy name results will be sorted by queue name in ascending order.
Aggregation is achieved using functions AVG(), COUNT(), MAX(), MIN() and SUM(). It's important to remember, that aggregation functions don't consider NULL values. For example, following query
SELECT COUNT(description) FROM queue
will return count of queues having non-null value of a field `description`. To consider NULL values, they should be handled using COALESCE() function or CASE operator:
SELECT COUNT(COALESCE(description, '')) FROM queue
Alternatively
SELECT COUNT(CASE WHEN description IS NULL THEN '' ELSE description END) FROM queue
Several aggregation functions can be used together in the same query:
SELECT COUNT(*), AVG(queueDepthMessages), SUM(queueDepthMessages), SUM(queueDepthBytes), MIN(queueDepthMessages), MAX(queueDepthMessages), MIN(queueDepthBytes), MAX(queueDepthBytes) FROM queue
Grouping of the aggregated results can be achieved using the `GROUP BY` clause. For example, following query finds count of ACL rules for each user and output them in descending order:
SELECT COUNT(*) AS cnt, identity FROM aclrule GROUP BY identity ORDER BY 1 DESC
The result of the query:
{ "results": [ { "cnt": { "amqp_user1": 6, "amqp_user2": 4, "amqp_user3": 4, ... some results ommited ... "amqp_user97": 2, "amqp_user98": 1, "amqp_user99": 1 } } ], "total": 1 }
To filter the grouped result `HAVING` clause can be used:
SELECT overflowPolicy, COUNT(*) FROM queue GROUP BY overflowPolicy HAVING SUM(queueDepthMessages) > 1000
The COUNT() function returns the number of items that matches a specified criterion.
The DATEADD() function adds a time/date interval to a date and returns the date.
Table 6.25. DATEADD Parameters
Parameter | Description |
---|---|
TIMEUNIT |
The type of time unit to add. Can be one of the following values: YEAR, MONTH, WEEK, DAY, HOUR, MINUTE, SECOND, MILLISECOND |
VALUE |
The value of the time/date interval to add. Both positive and negative values are allowed |
DATE |
The date to be modified |
The DATEDIFF() function returns the number of time units between two date values.
The ROUND() function takes a numeric parameter and rounds it to the specified number of decimal places.
The CONCAT() function takes a variable number of arguments and concatenates them into a single string. It requires a minimum of one input value, otherwise CONCAT will raise an error. CONCAT implicitly converts all arguments to string types before concatenation. The implicit conversion to strings follows the existing rules for data type conversions. If any argument is NULL, CONCAT returns NULL.
The LEN() / LENGTH() function takes a string parameter and returns its length. The implicit conversion to strings follows the existing rules for data type conversions. If any argument is NULL, LEN / LENGTH returns 0.
The LOWER() function takes a string parameter and converts it to lower case. The implicit conversion to strings follows the existing rules for data type conversions. If argument is NULL, LOWER returns NULL.
The LTRIM() function removes leading spaces from a string. If argument is NULL, RTRIM returns NULL.
The POSITION() function takes a search pattern and a source string as parameters and returns the position of the first occurrence of a pattern in a source string. If the pattern is not found within the source string, this function returns 0. Optionally takes third integer parameter, defining from which position search should be started. Third parameter should be an integer greater than 0. If source string is NULL, returns zero.
The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. If source string is NULL, returns NULL.
The RTRIM() function removes trailing spaces from a string. If argument is NULL, RTRIM returns NULL.
The SUBSTRING() function takes a source parameter, a start index parameter and optional length parameter. Returns substring of a source string from the start index to the end or using the length parameter. If source string is NULL, return NULL.
Table 6.39. SUBSTRING Parameters
Parameter | Description |
---|---|
source |
The string to extract from |
startIndex |
The start position. Can be both a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, function extracts from the end of the string |
length |
The number of characters to extract. If omitted, the whole string will be returned (from the start position). If zero or negative, an empty string is returned |
The TRIM() function removes both leading and trailing spaces from a string. If argument is NULL, TRIM returns NULL.
The UPPER() function takes a string parameter and converts it to upper case. The implicit conversion to strings follows the existing rules for data type conversions. If argument is NULL, UPPER returns NULL.
UNION, MINUS and INTERSECT set operations are supported. The UNION operator is used to combine the result-set of two or more SELECT statements. Every SELECT statement within UNION must have the same number of columns. The UNION operator selects distinct values by default. To keep duplicates, UNION ALL should be used. For example, following query return certificate aliases along with the user names:
SELECT UPPER(alias) FROM certificate UNION SELECT UPPER(name) FROM user
The MINUS operator is used to remove the results of right SELECT statement from the results of left SELECT statement. Every SELECT statement within MINUS must have the same number of columns. The MINUS operator selects distinct values by default. To eliminate duplicates, MINUS ALL should be used. For example, following query finds queue names, not specified as binding destinations:
SELECT name FROM queue MINUS SELECT destination FROM binding
The INTERSECT operation is used to retain the results of right SELECT statement present in the results of left SELECT statement. Every SELECT statement within INTERSECT must have the same number of columns. The INTERSECT operator selects distinct values by default. to eliminate duplicates, INTERSECT ALL should be used. For example, following query finds certificate aliases similar with the user names:
SELECT UPPER(alias) FROM certificate INTERSECT SELECT UPPER(name) FROM user
When executing subquery parent query domain mat be passed into the subquery using alias. E.g. this query
SELECT id, name, (SELECT name FROM connection WHERE SUBSTRING(name, 1, POSITION(']' IN name)) = '[' + SUBSTRING(c.name, 1, POSITION('|' IN c.name) - 1) + ']') as connection, (SELECT id FROM connection WHERE SUBSTRING(name, 1, POSITION(']' IN name)) = '[' + SUBSTRING(c.name, 1, POSITION('|' IN c.name) - 1) + ']') as connectionId, (SELECT name FROM session WHERE id = c.session.id) as session FROM consumer c
returns following result:
{ "results": [ { "id": "7a4d7a86-652b-4112-b535-61272b936b57", "name": "1|1|qpid-jms:receiver:ID:6bd18833-3c96-4936-b9ee-9dec5f408b5c:1:1:1:broadcast.amqp_user1.public", "connection": "[1] 127.0.0.1:39134", "connectionId": "afbd0480-43b1-4b39-bc00-260c077095f3", "session": "1" } ], "total": 1 }
Query
SELECT name, destination, (SELECT id FROM queue WHERE name = b.destination) AS destinationId, exchange, (SELECT id FROM exchange WHERE name = b.exchange) AS exchangeId FROM binding b WHERE name = 'broadcast.amqp_user1.xxx.#'
returns following result:
{ "results": [ { "name": "broadcast.amqp_user1.xxx.#", "destination": "broadcast.amqp_user1.xxx", "destinationId": "d5ce9e78-8558-40db-8690-15abf69ab255", "exchange": "broadcast", "exchangeId": "470273aa-7243-4cb7-80ec-13e698c36158" }, { "name": "broadcast.amqp_user1.xxx.#", "destination": "broadcast.amqp_user2.xxx", "destinationId": "88357d15-a590-4ccf-aee8-2d5cda77752e", "exchange": "broadcast", "exchangeId": "470273aa-7243-4cb7-80ec-13e698c36158" }, { "name": "broadcast.amqp_user1.xxx.#", "destination": "broadcast.amqp_user3.xxx", "destinationId": "c8200f89-2587-4b0c-a8f6-120cda975d03", "exchange": "broadcast", "exchangeId": "470273aa-7243-4cb7-80ec-13e698c36158" } ], "total": 3 }
Query
SELECT alias, (SELECT COUNT(id) FROM queue WHERE POSITION(UPPER(c.alias) IN name) > 0) AS queueCount FROM certificate c
returns following result:
{ "results": [ { "alias": "xxx", "queueCount": 5 }, { "alias": "xxy", "queueCount": 5 }, { "alias": "xxz", "queueCount": 7 } ], "total": 3 }
Try to select entity fields by names instead of using an asterix. For example, this query
SELECT id, name, state, overflowPolicy, expiryPolicy FROM queue
will be executed faster than this one:
SELECT * FROM queue
Try to use `LIMIT` and `OFFSET` clauses where applicable to reduce the response JSON size:
SELECT id, name, state, overflowPolicy, expiryPolicy FROM queue LIMIT 10 OFFSET 0
The Broker supports Cross Origin Resource Sharing (CORS) to allow web management consoles other than the one embedded in the broker to use the REST API. This feature must be enabled by configuring the CORS Allow Origins and related attributes on the Section 7.17, “HTTP Plugin”
Apache Qpid, Messaging built on AMQP; Copyright © 2015 The Apache Software Foundation; Licensed under the Apache License, Version 2.0; Apache Qpid, Qpid, Qpid Proton, Proton, Apache, the Apache feather logo, and the Apache Qpid project logo are trademarks of The Apache Software Foundation; All other marks mentioned may be trademarks or registered trademarks of their respective owners