Red Hat Training

A Red Hat training course is available for Red Hat JBoss Operations Network

4. Running the JBoss ON CLI

The JBoss ON CLI is a shell and interpreter so that commands and statements can be executed interactively against the JBoss ON server. Scripts stored in files can also be executed, so it is possible to automate operations for the JBoss ON server.
The CLI script, rhq-cli.sh|bat, is run directly from its cli-install-dirbin directory and used to log into the server. There are two files associated with launching the JBoss ON CLI:
  • A script
  • A file of environment variables
These are listed in Table 1, “JBoss ON CLI Files”.

Table 1. JBoss ON CLI Files

Operating System CLI Script Environment Variables File
Red Hat Enterprise Linux rhq-cli.sh rhq-cli-env.sh
Microsoft Windows rhq-cli.bat rhq-cli-env.bat
The environment variables in the rhq-cli-env.sh|bat file use defaults that are reasonable for most deployments, so this file usually does not need to be edited. It is possible to reset variables to point a server that doesn't follow the default installation, such as a virtual machine or a JVM that isn't the default. If any variables need to be edited, always set them in this file. The comments at the top of the rhq-cli-env.|bat file contain a detailed list of available environment variables.

Important

Do not edit the rhq-cli.sh|bat file. Only set environment variables through the terminal or in the rhq-cli-env.sh|bat file, not the script itself.

Note

Be sure to set the correct path to the Java 6 installation in the RHQ_CLI_JAVA_HOME or the RHQ_CLI_JAVA_EXE_FILE_PATH variable.
The rhq-cli.sh|bat script has the following general syntax:
rhq-cli.sh|bat options commands
It is possible to launch the CLI script without any arguments. This opens the CLI client without connecting to the server.
cliRoot/rhq-remoting-cli-3.0.0.GA1/bin/rhq-cli.sh
RHQ - RHQ Enterprise Remote CLI 
unconnected$
While scripts can be executed without logging in, most of the functionality of the CLI is unavailable. To truly use the JBoss ON CLI, log into the server as a JBoss ON user.
rhq-cli -u rhqadmin -p rhqadmin
The CLI provides two modes of operation: interactive and non-interactive. Interactive mode executes an individual statement. In non-interactive mode, multiple commands can be executed in sequence, in the form of a script. Non-interactive mode provides the capability to automate tasks such as collecting metrics on managed resources or executing a scheduled operation. (Interactive mode provides a simple environment for prototyping, testing, learning and discovering features of the CLI, and these examples are given in interactive mode, though they are also available in non-interactive mode.)

Important

These native commands, like quit, are available only in interactive mode. They cannot be used in a script when the CLI is used in non-interactive mode, such as when running a script from file. In these instances, you must use the Java method.
For more information about integration with the underlying Java platform, look at the Rhino documentation at http://www.mozilla.org/rhino/doc.html.
After logging in, any commands (covered in Section 4.2, “JBoss ON CLI Commands”) can be passed to the server.

4.1. JBoss ON CLI Options

Both rhq-cli.bat and rhq-cli.sh scripts accept the options listed in Table 2, “Command-Line Options”.

Table 2. Command-Line Options

Short Option Long Option Description
-h --help Displays the help text of the command line options of the CLI.
-u --user The username used to log into the JBoss ON server.
-p --password The password used to log into the JBoss ON server.
-P Displays a password prompt where input is not echoed backed to the screen.
-s --host The JBoss ON server against which the CLI executes commands. Defaults to localhost.
-t --port The port on which the JBoss ON server is accepting HTTP requests. The default is 7080.
-c --command A command to be executed. The command must be encased in double quotes. The CLI will exit after the command has finished executing.
-f --file The full path and filename of a script to execute.
-v --version Displays CLI and JBoss ON server version information once connected to the the CLI.
--transport Determines whether or not SSL will be used for the communication layer protocol between the CLI and the JBoss ON server. If not specified the value is determined from the {port} option. If you use a port that ends in 443, SSL will be used. You only need to explicitly specify the transport when your JBoss ON server is listening over SSL on a port that does not end with 443.
--args-style Indicates the style or format of arguments passed to the script. See the Executing Scripts below for additional information.

4.2. JBoss ON CLI Commands

Some native commands are included in the org.rhq.enterprise.client.commands inside the CLI JAR itself. These commands are part of the CLI itself. Other input in the JBoss ON CLI is passed through the JavaScript interpreter to the server; these commands are passed to the CLI module.

Important

These native commands are available only in interactive mode. They cannot be used in a script when the CLI is used in non-interactive mode, such as when running a script from file. In these instances, you must use the Java method.

4.2.1. login

Logs into a JBoss ON server with the specified username and password. The host name (or IP address) and port can be specified. The host name defaults to localhost and the port defaults to 7080. The transport argument is optional. It determines whether or not SSL will be used for the communication layer protocol between the CLI and the JBoss ON server. If not specified, the value is determined from the port argument. If you use a port that ends in 443, SSL will be used. You only need to explicitly specify the transport when your JBoss ON server is listening over SSL on a port that does not end in 443.
login username password [host] [port]

4.2.2. logout

Logs off of the JBoss ON server but does not exit from the CLI.
logout

4.2.3. quit

Exits the CLI.
quit
This only works when the CLI is running interactively. In a script, you must use java.lang.System.exit.

4.2.4. exec

Executes a statement or a script with the specified file name. A statement wraps onto multiple lines using backslashes.
exec statement | [-s indexed|named] -f /path/to/file [args]
Option Description
-f, --file
The full path filename of the script to execute. The full path must be given, or the CLI cannot locate the script.
-s, --style
Indicates the style or format of arguments passed to the script. It must have a value of either indexed or named.

Example 1. Executing a Single Statement

localhost:7080> exec var x = 1

Example 2. Executing a Multi-Line Statement

localhost:7080(rhqadmin)> exec for (i = 1; i < 3; ++i) { \
localhost:7080(rhqadmin)>    println(i); \
localhost:7080(rhqadmin)> }
1
2
		
localhost:7080(rhqadmin)>

Example 3. Executing a Named Script without Arguments

localhost:7080(rhqadmin)> exec -f myscript.js

Example 4. Executing a Named Script with Arguments

localhost:7080(rhqadmin)> exec -f myscript.js 1 2 3

Example 5. Executing a Named Script with Named Arguments

localhost:7080(rhqadmin)> exec --style=named -f myscript.js x=1 y=2 y=3

4.2.5. record

Records user input commands to a file.
record [-b | -e] [-a] -f
Option Description
-b, --start
Specify this option to start recording.
-e, --end
Specify this option to stop recording.
-a, --append
Appends output to the end of a file. If not specified, output will be written starting at the beginning of the file.
-f, --file
The file where output will be written.

4.3. Available Implicit Variables in the JBoss ON API

The JBoss ON API makes a number of variables available to interfaces. These variables are bound to the CLI script context.
In the Java programming language, classes in the java.lang package do not have to be imported; they are automatically made available. Classes in other packages, however, have to be explicitly imported.
In the JBoss ON CLI, there are a number of classes from various packages that likely to be used on a routine basis. To simplify using the JBoss ON CLI and remote clients, certain classes are also imported. Everything under the org.rhq.core.domain class is automatically imported, which makes it easier to use the CLI for managing resources, alerts, and other aspects of JBoss ON.
For example, the class org.rhq.core.domain.criteria.ResourceCriteria is commonly used to query resources. The entire class path can be given when calling that class:
var criteria = new org.rhq.core.domain.criteria.ResourceCriteria();
var resource = new org.rhq.core.domain.resource.Resource();
Because the domain class is already imported, this can be more succinctly written as:
var criteria = new ResourceCriteria();
var resource = new Resource();
Common variables used with the CLI scripts are listed in Table 3, “Variables Available by Default to the JBoss ON CLI”. Methods and other information about these variables are in Section 9, “Reference: Methods Specific to the JBoss ON CLI”.

Table 3. Variables Available by Default to the JBoss ON CLI

Variable Type Description Access Requires Login
rhq org.rhq.enterprise.client.Controller Provides built-in commands to the interactive CLI: login, logout, quit, exec, and version. Two of these methods, login and logout, can be called in server script files, such as rhq.login('rhqadmin', 'rhqadmin'). YES
subject org.rhq.core.domain.auth.Subject Represents the current, logged in user. For security purposes, all remote service invocations require the subject to be passed; however, the CLI will implicitly pass the subject for you. YES
Assert org.rhq.bindings.util.ScriptAssert Provides assertion utilities for CLI scripts. NO
pretty
org.rhq.enterprise.client.TabularWriter
Provides for tabular-formatted printed and handles converting objects, particularly domain objects in the packages under org.rhq.core.domain, into a format suitable for display in the console. NO
unlimitedPC org.rhq.core.domain.util.PageControl NO
pageControl org.rhq.core.domain.util.PageControl Used to specify paging and sorting on data retrieval operations NO
exporter
org.rhq.enterprise.client.Exporter
Used to export output to a file. Supported formats are plain text in tabular format and CSV. NO
ProxyFactory
org.rhq.enterprise.client.utility.ResourceClientProxy.Factory
NO
scriptUtil
org.rhq.enterprise.client.utility.ScriptUtil
Provides methods that can be useful when writing scripts. NO
AlertManager org.rhq.enterprise.server.alert.AlertManagerRemote Provides an interface into the alerts subsystem. YES
AlertDefinitionManager org.rhq.enterprise.server.alert.AlertDefinitionManagerRemote Provides an interface into the alerts definition subsystem. YES
AvailabilityManager org.rhq.enterprise.server.measurement.AvailabilityManagerRemote Provides an interface into the measurement subsystem that can be used to determine resources' availability. YES
CallTimeDataManager org.rhq.enterprise.server.measurement.CallTimeDataManagerRemote Provides an interface into the measurement subsystem for retrieving call-time metric data. YES
RepoManager org.rhq.enterprise.server.content.RepoManagerRemote Provides an interface into the content subsystem for working with repositories. YES
ConfigurationManager org.rhq.enterprise.server.configuration.ConfigurationManagerRemote Provides an interface into the configuration subsystem. YES
DataAccessManager org.rhq.enterprise.server.report.DataAccessRemote Provides an interface for executing user-defined queries. YES
EventManager org.rhq.enterprise.server.event.EventManagerRemote Provides an interface into the events subsystem. YES
MeasurementBaselineManager org.rhq.enterprise.server.measurement.MeasurementBaselineManagerRemote Provides an interface into the measurement subsystem for working with measurement baselines. YES
MeasurementDataManager org.rhq.enterprise.server.measurement.MeasurementDataManagerRemote Provides an interface into the measurement subsystem for working with measurement data. YES
MeasurementDefinitionManager org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerRemote Provides an interface into the measurement subsystem for working with measurement definitions. YES
MeasurementScheduleManager org.rhq.enterprise.server.measurement.MeasurementScheduleManagerRemote Provides an interface into the measurement subsystem for working with measurement schedules. YES
OperationManager org.rhq.enterprise.server.operation.OperationManagerRemote Provides an interface into the operation subsystem. YES
ResourceManager org.rhq.enterprise.server.resource.ResourceManagerRemote Provides an interface into the resource subsystem. YES
ResourceGroupManager org.rhq.enterprise.server.resource.group.ResourceGroupManagerRemote Provides an interface into the resource group subsystem. YES
ResourceTypeManager org.rhq.enterprise.server.resource.ResourceTypeManagerRemote Provides an interface into the resource subsystem for working with resource types. YES
RoleManager org.rhq.enterprise.server.authz.RoleManagerRemote Provides an interface into the security subsystem for working with security rules and roles. YES
SubjectManager org.rhq.enterprise.server.auth.SubjectManagerRemote Provides an interface into the security subsystem for working with users. YES
SupportManager org.rhq.enterprise.server.support.SupportManagerRemote Provides an interface into the reporting subsystem for getting reports of managed resources. YES

4.4. Passing Script Arguments in the JBoss ON CLI

A feature common to most programming languages is the ability to pass arguments to the program to be executed. In Java, the entry point into a program is a class's main method, and it takes a String array as an argument. That array holds any arguments passed to the program. Similarly, arguments can be passed to CLI scripts. Arguments passed to a script can be accessed in the implicit args array:

Example 6. Handling Script Arguments

if (args.length > 2) {
    throw "Not enough arguments!";
}
		
for (i in args) {
     println('args[' + i + '] = ' + args[i]);
}

Important

The args variable is only available when executing a script in non-interactive mode or with exec -f.
In addition to the traditional style of indexed-based arguments, named arguments can also be passed to a script:
rhqadmin@localhost:7080$ exec -f echo_args.js --args-style=named x=1, y=2

Example 7. echo_args.js

for (i in args) {
     println('args[' + i + '] = ' + args[i]);
}
println('named args...');
println('x = ' + x);
println('y = ' + y);

This produces the following output:

Example 8. echo_args.js

args[0] = 1
args[1] = 2
named args...
		
x = 1
y = 2

Be aware of the following:
  • You have to explicitly specify that you are using named arguments via the --args-style option
  • The values of the named arguments are still accessible via the implicit args array
  • The named arguments, x and y, are bound into the script context as variables
The CLI is built using the Java Scripting API that was introduced in Java 6. The majority of commands and scripts used with the JBoss ON CLI are executed by the underlying script engine. Built-in commands, however, are native Java code and are not executed by the underlying script engine. This is similar to other interpreters like Python where some modules are implemented in C and built into the interpreter. This distinction is important because built-in commands cannot be processed by the script engine. Objects, however, that provide hooks into the built-in commands, are exposed to the scripting environment.

4.5. Configuring Criteria-Based Searching

All of the managers define operations for retrieving data. Most of the managers define criteria-based operations for data retrieval. The criteria API provides a flexible framework for fine-tuned query operations.
The criteria classes reside in the org.rhq.core.domain.criteria package. Criteria-based searches can be implemented in several different ways.

4.5.1. Setting Basic Search Criteria

The simplest criteria is to define results based on what they are, such as resource type.
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria()
rhqadmin@localhost:7080$ var resources = ResourceManager.findResourcesByCriteria(criteria)
It isn't necessary to import the ResourceCriteria class because the org.rhq.core.domain.criteria package is automatically imported.
The method, findResourcesByCriteria follows the naming format of all criteria-based query operations, findXXXByCriteria. This basic criteria search is translated into the following JPA-QL query:
SELECT r
FROM Resource r
WHERE ( r.inventoryStatus = InvetoryStatus.COMMITTED
This fetches all committed resources in the inventory.

4.5.2. Using Sorting

The basic search criteria can be refined so that the resource results are sorted by plug-in.
rhqadmin@localhost:7080$ criteria.addSortPluginName(PageOrdering.ASC)
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
This criteria is translated into the following JPA-QL query:
SELECT r
FROM Resource r
WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED )
ORDER BY r.resourceType.plugin ASC
To add sorting, call criteria.addSortPluginName(). Sorting criteria have methods in the form addSortXXX(PageOrdering order).

4.5.3. Using Filtering

Adding additional matching criteria, like resource name in this example, further narrows the search results.
rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server')
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
To add filtering to any criteria, use methods of the form addFilterXXX(). The resulting JPA-QL query will appear as follows:
SELECT r
FROM Resource r
WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED
AND LOWER( r.resourceType.name )  like 'JBossAS Server' ESCAPE '\\' )
This code is all that is required to retrieve all JBoss servers in your inventory. You can further refine your criteria to find JBoss servers that have been registered by a particular agent:
rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server')
rhqadmin@localhost:7080$ criteria.addFilterAgentName('localhost.localdomain')
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
This generates the following JPA-QL query:
SELECT r
FROM Resource r
WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED
AND LOWER( r.agent.name )  like 'localhost.localdomain' ESCAPE '\\' )

4.5.4. Fetching Associations

After retrieving the resources, it is possible to view child resources. For example:
rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server')
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
rhqadmin@localhost:7080$ resource = resources.get(0)
rhqadmin@localhost:7080$ if (resource.childResources == null) print('no child resources')
This code will print the string no child resources, even if the JBoss server has child resources. The reason for this is that lazy loading is used throughout the domain layer for one-to-many and many-to-many associations. Since child resources are lazily loaded, specify the criteria for the fetch order.
rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server')
rhqadmin@localhost:7080$ criteria.fetchChildResources(true)
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
rhqadmin@localhost:7080$ resource = resources.get(0)
rhqadmin@localhost:7080$ if (resource.childResources == null) print('no child resources'); else pretty.print(resource.childResources)
As with the call criteria.fetchChildResources(true), all criteria methods that specify that a particular lazy association should be fetched are of the form, fetchXXX().
rhqadmin@localhost:7080$ if (resource.childResources == null) print('no child resources'); else pretty.print(resource.childResources)
id  name                                                 versio resourceType
----------------------------------------------------------------------------------------------------------------------
222 AlertManagerBean                                            EJB3 Session Bean
222 SchedulerBean                                               EJB3 Session Bean
222 AlertDefinitionManagerBean                                  EJB3 Session Bean
222 AlertConditionConsumerBean                                  EJB3 Session Bean
222 PartitionEventManagerBean                                   EJB3 Session Bean
222 AlertTemplateManagerBean                                    EJB3 Session Bean
223 RHQ Server Group Definition / DynaGroups Subsystem          RHQ Server Group Definition / DynaGrou
222 DiscoveryTestBean                                           EJB3 Session Bean
222 PerspectiveManagerBean                                      EJB3 Session Bean
222 ResourceAvailabilityManagerBean                             EJB3 Session Bean
222 AlertDampeningManagerBean                                   EJB3 Session Bean
218 localhost.localdomain  Embedded JBossWeb Server 2.0. 2.0.1. Embedded Tomcat Server
222 ResourceGroupManagerBean                                    EJB3 Session Bean
222 FailoverListManagerBean                                     EJB3 Session Bean
222 ResourceFactoryManagerBean                                  EJB3 Session Bean
222 AccessBean                                                  EJB3 Session Bean
222 MeasurementTestBean                                         EJB3 Session Bean
223 wstools.sh                                                  Script
222 EventManagerBean                                            EJB3 Session Bean
222 ContentSourceManagerBean                                    EJB3 Session Bean
223 RHQ Server Alerts Engine Subsystem                          RHQ Server Alerts Engine Subsystem
222 AlertConditionManagerBean                                   EJB3 Session Bean
222 ResourceMetadataManagerBean                                 EJB3 Session Bean
222 ResourceManagerBean                                         EJB3 Session Bean
222 GroupDefinitionExpressionBuilderManagerBean                 EJB3 Session Bean
222 MeasurementViewManagerBean                                  EJB3 Session Bean
218 JmsXA Connection Factory                                    ConnectionFactory
222 ResourceTypeManagerBean                                     EJB3 Session Bean
223 JBoss Cache subsystem                                1.0    JBossCacheSubsystem
218 NoTxRHQDS Datasource                                        Datasource
222 DataAccessBean                                              EJB3 Session Bean
222 AlertConditionCacheManagerBean                              EJB3 Session Bean
222 MeasurementProblemManagerBean                               EJB3 Session Bean
222 ServerManagerBean                                           EJB3 Session Bean
222 OperationHistorySubsystemManagerBean                        EJB3 Session Bean
222 ClusterManagerBean                                          EJB3 Session Bean
222 run.sh                                                      Script
...
The output will vary depending on what you have inventoried. These are the child resources of the JBoss ON server we have used in these examples. The JPA-QL query that is generated appears as follows:
SELECT r
FROM Resource r
LEFT JOIN FETCH r.childResources
WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED
AND LOWER( r.resourceType.name )  like 'JBossAS Server' ESCAPE '\\' )

4.6. Displaying Output

4.6.1. TabularWriter

TabularWriter provides for tabular-formatted output. In addition to formatting, it handles converting objects, particularly domain objects in the packages under org.rhq.core.domain, into a format suitable for display in the interactive console. Let's look at an example to illustrate the utility of TabularWriter:
rhqadmin@localhost:7080$ criteria = ResourceCriteria()
rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('service-alpha')
rhqadmin@localhost:7080$ criteria.addFilterParentResourceName('server-omega-0')
rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
id    name            version resourceType
----------------------------------------------------------------------------------------------------------------------
11373 service-alpha-8 1.0     service-alpha
11374 service-alpha-1 1.0     service-alpha
11375 service-alpha-0 1.0     service-alpha
11376 service-alpha-4 1.0     service-alpha
11377 service-alpha-2 1.0     service-alpha
11378 service-alpha-3 1.0     service-alpha
11379 service-alpha-5 1.0     service-alpha
11380 service-alpha-9 1.0     service-alpha
11381 service-alpha-6 1.0     service-alpha
11382 service-alpha-7 1.0     service-alpha
10 rows
The TabularWriter instance that is bound in the script context under the name pretty is implicitly invoked to display the results of ResourceManager.findResourcesByCriteria. The returned resources are displayed in very readable, tabular format. Now let's look at the output if we do not use TabularWriter.
rhqadmin@localhost:7080$ println(resources)
PageList[Resource[id=11373, type=service-alpha, key=service-alpha-8, name=service-alpha-8, version=1.0],
Resource[id=11374, type=service-alpha, key=service-alpha-1, name=service-alpha-1, version=1.0], 
Resource[id=11375, type=service-alpha, key=service-alpha-0, name=service-alpha-0, version=1.0], 
Resource[id=11376, type=service-alpha, key=service-alpha-4, name=service-alpha-4, version=1.0], 
Resource[id=11377, type=service-alpha, key=service-alpha-2, name=service-alpha-2, version=1.0], 
Resource[id=11378, type=service-alpha, key=service-alpha-3, name=service-alpha-3, version=1.0], 
Resource[id=11379, type=service-alpha, key=service-alpha-5, name=service-alpha-5, version=1.0], 
Resource[id=11380, type=service-alpha, key=service-alpha-9, name=service-alpha-9, version=1.0], 
Resource[id=11381, type=service-alpha, key=service-alpha-6, name=service-alpha-6, version=1.0], 
Resource[id=11382, type=service-alpha, key=service-alpha-7, name=service-alpha-7, version=1.0]]
For display purposes, this output is not very usable. Let's look at one more example in which we display a single entity.
rhqadmin@localhost:7080$ pretty.print(resources.get(0))
Resource:
	          id: 11373
	        name: service-alpha-8
	     version: 1.0
	resourceType: service-alpha
The formatting is different when displaying a single object.
Only a subset of the properties in the Resource class are displayed. TabularWriter determines the properties to display through the Summary annotation. If a field of an entity has the @Summary annotation, TabularWriter will include it in the output.

4.6.2. Exporter

An implicit script variable that can assist with writing output to a file is exporter. It uses TabularWriter; however, in addition to writing plain text in a tabular format, it also supports CSV-formatting. First, we will look at an example of exporting to a file as plain text:
rhqadmin@localhost:7080$ exporter.setTarget('raw', 'output.txt')
rhqadmin@localhost:7080$ exporter.write(resources)
File IO operations like opening or closing the file are not a problem because exporter handles the IO operations.
Next, export the results to a CSV file:
rhqadmin@localhost:7080$ exporter.setTarget('csv', 'output.csv')
rhqadmin@localhost:7080$ exporter.write(resources)

4.7. Simple CLI Examples

Example 9. Logging in to a Specified Server

You will be connected to the CLI and logged in with the specified credentials on the JBoss ON server running on localhost.
rhq-cli -u rhqadmin -p rhqadmin -s 192.168.1.100 -t 70443
You will be connected to the CLI and logged into the JBoss ON server on 192.168.1.100 that is listening on port 70443. Because the port number ends with 443, the CLI will attempt to communicate with the JBoss ON server over SSL using the sslservlet transport strategy.

Example 10. Prompting for a Password

rhq-cli -u rhqadmin -P
You will be connected to the CLI and prompted for a password.

Example 11. Passing Variables to the Server

rhq-cli -u rhqadmin -p rhqadmin -c "pretty.print(ResourceTypeManager.findResourceTypesByCriteria(new ResourceTypeCriteria()))" > resource_types.txt
This connects you to the CLI, logs you into the JBoss ON server running on localhost, executes the command in quotes, and redirects the output to the file resource_types.txt.
The ResourceTypeManager.findResourceTypesByCriteria(new ResourceTypeCriteria()) class invokes the findResourceTypesByCriteria operation on ResourceTypeManager. A new ResourceTypeCriteria object is passed as the argument.
Nothing has been specified on the criteria object so all resource types will be returned. The next portion is pretty.print(...). An implicit object made available to commands and scripts by the CLI, pretty is useful for outputting objects in a readable, tabular format, designed with enhanced capabilities for domain objects. This single command provides a nicely formatted, text-based report of the resource types in the inventory.

Example 12. Running a Script in the JBoss ON CLI

cliRoot/rhq-remoting-cli-3.0.0.GA1/bin/rhq-cli.sh -f my_script.js
This connects you to the CLI and executes the script file, my_script.js. The CLI will terminate immediately after the script has finished executing.

4.8. Using Resource Proxies

The JBoss ON CLI interacts directly with the JBoss ON server through remote APIs for handling resource objects and through the domain APIs for tasks like searches.
The JBoss ON CLI itself provides another API layer that can make it easier to perform common operations. The CLI can create a resource proxy object in the CLI, and then that object uses the classes available in the ProxyFactory to interact with the remote and domain API.
One thing to remember is that proxy resources still use the remote and domain API. The proxy API just provides a simpler and clearer API on top of the remote and domain APIs that can make it easier to script many operations.

Note

The ProxyFactory is available to the JBoss ON CLI in interactive mode or when using a script file. It is also available to server scripts, such as scripts used for alerting.
The ProxyFactory gets information about a resource, which is identified in the getResource() method with the resource's ID number.
At its simplest, ProxyFactory can return a complete summary of information about the specified resource, such as its current monitoring data and traits, resource name, available metrics, available operations, content information, and child inventory, all dependent on the resource type. For example:
rhqadmin@localhost:7080$ ProxyFactory.getResource(10001)
ResourceClientProxy_$$_javassist_0:
                               OSName: Linux
                            OSVersion: 2.6.32-220.4.1.el6.x86_64
                         architecture: x86_64
                             children:
                         contentTypes: {rpm=RPM File}
                          createdDate: Mon Feb 06 11:24:50 EST 2012
                          description: Linux Operating System
                     distributionName: Red Hat Enterprise Linux Server
                  distributionVersion: release 6.2 (Santiago)
                           freeMemory: 16.7GB
                        freeSwapSpace: 25.6GB
                              handler:
                             hostname: sun-x8420-01.rhts.eng.bos.redhat.com
                                   id: 10001
                                 idle: 70.8%
                         measurements: [Wait Load, Used Memory, System Load, Distribution Version, Total Memory, OS Name, Free Memory, Hostname, Architecture, Distribution Name, Idle, Total Swap Space, Used Swap Space, User Load, OS Version, Free Swap Space]
                         modifiedDate: Mon Feb 06 11:24:50 EST 2012
                                 name: sun-x8420-01.rhts.eng.bos.redhat.com
                           operations: [viewProcessList, cleanYumMetadataCache, manualAutodiscovery]
                  pluginConfiguration:
        pluginConfigurationDefinition: ConfigurationDefinition[id=10009, name=Linux]
                         resourceType: Linux
                           systemLoad: 0.0%
                          totalMemory: 23.5GB
                       totalSwapSpace: 25.6GB
                           usedMemory: 6.8GB
                        usedSwapSpace: 0.0B
                             userLoad: 15.8%
                              version: Linux 2.6.32-220.4.1.el6.x86_64
                             waitLoad: 0.0%
To truly manage resources, the ProxyFactory creates a resource proxy object.

Example 13. Creating a Platform Proxy Resource

var rhelServerOne = ProxyFactory.getResource(10001)
The methods that are available to a resource proxy depend on the resource type and the resource's own configuration. There are five major types of operations that can be performed on resource proxies:
  • Viewing basic information about the resource, such as its children
  • Getting measurement information
  • Running operations
  • Changing resource and plug-in configuration
  • Updating and retrieving content
For each resource type, methods are exposed which allow you to find and use specific information about the resource. Additionally, the proxy API includes "shortcuts" which provide one-word methods, without requiring any parameters, to perform common remoteAPI tasks, like getting monitoring information.
The proxy API for common resource types is listed in Section 9.2, “Methods Available to Proxy Resources”.

Note

Use tab-complete in the interactive CLI to find the specific methods available for a resource type or to get the method signatures for individual methods.

Example 14. Viewing a Resource's Children

ProxyFactory has a method for all proxy objects, children, which lists all of the children for the proxy resource.
var rhelServerOne = ProxyFactory.getResource(10001)

rhqadmin@localhost:7080$ platform.children
Array of org.rhq.bindings.client.ResourceClientProxy
[10027] Bundle Handler - Ant (Ant Bundle Handler::AntBundlePlugin)
[10026] CPU 6 (CPU::Platforms)
[10025] CPU 0 (CPU::Platforms)
[10024] CPU 5 (CPU::Platforms)
[10023] CPU 1 (CPU::Platforms)
[10022] CPU 4 (CPU::Platforms)
[10021] CPU 2 (CPU::Platforms)
[10020] CPU 3 (CPU::Platforms)
[10019] CPU 7 (CPU::Platforms)
[10018] /boot (File System::Platforms)
[10017] / (File System::Platforms)
[10016] /dev/shm (File System::Platforms)
[10015] /home (File System::Platforms)
[10014] eth1 (Network Adapter::Platforms)
[10013] eth2 (Network Adapter::Platforms)
[10012] eth0 (Network Adapter::Platforms)
[10011] lo (Network Adapter::Platforms)
[10004] postgres (Postgres Server::Postgres)
[10003] AS tyan-gt24-04.rhts.eng.bos.redhat.com RHQ Server (JBossAS Server::JBos                                        sAS)
[10002] RHQ Agent (RHQ Agent::RHQAgent)

Example 15. Viewing Resource Metrics

ProxyFactory provides a set of shortcut metrics for each individual measurement for a resource type. This corresponds to the findLiveData() method in the remote API, but it is much easier to get monitoring information quickly and it is simpler to identify what metrics are available.
To get a single measurement value, use the method for that resource type. (Get a list of all methods for a proxy object using tab-complete.)
var jbossas = ProxyFactory.getResource(14832)
	
rhqadmin@localhost:7080$ jbossas.JVMTotalMemory
Measurement:
                name: JVM Total Memory
        displayValue: 995.3MB
	description: The total amount of memory currently available in the app server JVM for current and fut...
Alternatively, simply get a list of metrics with their current values using the measurements method:
var rhelServerOne = ProxyFactory.getResource(10001)

rhqadmin@localhost:7080$ rhelServerOne.measurements
Array of org.rhq.bindings.client.ResourceClientProxy$Measurement
name                 displayValue                         description
-----------------------------------------------------------------------------------------------------------------------
Wait Load            0.0%                                 Percentage of all CPUs waiting on I/O
Used Memory          6.3GB                                The total used system memory
System Load          0.0%                                 Percentage of all CPUs running in system mode
Distribution Version release 6.2 (Santiago)               version of the Linux distribution
Total Memory         31.4GB                               The total system memory
OS Name              Linux                                Name that the operating system is known as
Free Memory          25.2GB                               The total free system memory
Hostname             tyan-gt24-04.rhts.eng.bos.redhat.com Name that this platform is known as
Architecture         x86_64                               Hardware architecture of the platform
Distribution Name    Red Hat Enterprise Linux Server      name of the Linux distribution
Idle                 92.6%                                Idle percentage of all CPUs
Total Swap Space     33.6GB                               The total system swap
Used Swap Space      0.0B                                 The total used system swap
User Load            16.7%                                Percentage of all CPUs running in user mode
OS Version           2.6.32-220.4.2.el6.x86_64            Version of the operating system
Free Swap Space      33.6GB                               The total free system swap
16 rows

Example 16. Running Operations on a Proxy

ProxyFactory has a shortcut method for every operation available for a resource.
First, get the list of operations available for the resource type using the operations method:
var rhelServerOne = ProxyFactory.getResource(10001)

rhqadmin@localhost:7080$ rhelServerOne.operations
Array of org.rhq.bindings.client.ResourceClientProxy$Operation
name                  description
-----------------------------------------------------------------------------------------------------------------------
viewProcessList       View running processes on this system
cleanYumMetadataCache Deletes all cached package metadata
manualAutodiscovery   Run an immediate discovery to search for resources
3 rows
Then, run the given operation method.
rhqadmin@localhost:7080$ rhelServerOne.viewProcessList();
Invoking operation viewProcessList
Configuration [11951] - null
  processList [305] {
pid   name                                        size       userTime kernelTime
------------------------------------------------------------------------------------------------------------------
1     init                                        19865600   150      10050
....
26285 httpd                                       214618112  90       80
26286 httpd                                       214618112  90       80
26288 httpd                                       214618112  110      70
26289 httpd                                       214618112  90       80
27357 java                                        4734758912 1289650  373890
30458 postgres                                    218861568  1820     27440
30460 postgres                                    180985856  1210     5330
30462 postgres                                    218984448  13080    42200
30463 postgres                                    218861568  3970     26940
30464 postgres                                    219328512  10600    15320
30465 postgres                                    181407744  18680    78760
30482 httpd                                       185905152  1660     7520
32410 bash                                        108699648  0        10
32420 java                                        6024855552 3890240  669810
305 rows
}

Example 17. Changing Configuration Properties

If the resource type supports resource configuration editing or if the resource type has plug-in connection properties, then the resource proxy has methods — editResourceConfiguration() and editPluginConfiguration(), respectively — to edit those properties.
The current configuration can be printed using the get*Configuration). For example, for the plug-in configuration:
var rhelServerOne = ProxyFactory.getResource(10001)			 
			 
rhqadmin@localhost:7080$ rhelServerOne.getPluginConfiguration()
Configuration [10793] - null
  metadataCacheTimeout = 1800
  enableContentDiscovery = false
  yumPort = 9080
  enableInternalYumServer = false
  logs [0] {
  }
The edit*Configuration() method brings up a configuration wizard that goes through all of the properties individually and prompts to keep or change each value. The properties are even grouped according to the same organization that the JBoss ON web UI uses. For example:
rhqadmin@localhost:7080$ rhelServerOne.editPluginConfiguration();
Non-Grouped Properties:
Group: Content
enableContentDiscovery[false]:
enableInternalYumServer[false]:
yumPort[9080]:
metadataCacheTimeout[1800]:
Group: Event Logs
[R]eview, [E]dit, Re[V]ert [S]ave or [C]ancel:
...
After each group, you have the option to revert or save the changes. Once the changes are saved, they are immediately updated on the JBoss ON server.
Keys Action
return Selects the default or existing value for a property.
ctrl-d The same as selecting the unset checkbox in the configuration UI.
ctrl-k Exits the configuration wizard.
ctrl-e Displays the help description for the current property.

Example 18. Managing Content on Resources

Some types of resources have content associated with them. These are typically EAR or WAR resources within an application server. The content file actually associated with that EAR/WAR resource is called backing content. These are usually JARs.
This content can be updated or downloaded from the resource.
To retrieve backing content (meaning, to download the JAR/EAR/WAR file), specify the filename and file path on the application server. For example:
var contentResource = ProxyFactory.getResource(14932)
contentResource.retrieveBackingContent("/resources/backup/original.war")
To update the content for the resource, use the updateBackingContent method and specify the filename with the path on the application server to put the content and the version number of the content. For example:
contentResource.updateBackingContent("/resources/current/new.war", "2.0")