Writing JBoss ON Command-Line Scripts
using the JBoss ON CLI and remote API
Edition 3.1.2
Abstract
About This Guide
1. Audience and Intent
2. Document History
Revision History | |||||
---|---|---|---|---|---|
Revision 3.1.2-1.400 | 2013-10-31 | ||||
| |||||
Revision 3.1.2-1 | January 23, 2013 | ||||
| |||||
Revision 3.1.1-0 | October 3, 2012 | ||||
| |||||
Revision 3.1-3 | August 9, 2012 | ||||
| |||||
Revision 3.1-1 | June 30, 2012 | ||||
| |||||
Revision 3.1-0 | June 12, 2012 | ||||
|
Part I. Getting Started
Chapter 1. Understanding How Scripts Work with the JBoss ON Server and CLI
1.1. A Summary of JBoss ON Public APIs
API | Description |
---|---|
Remote | Resource management functions for tasks such as managing the inventory, changing configuration, uploading and managing content, initiating operations, viewing metrics and alerts, managing configuration drift, creating groups, and creating and managing users and roles.
The remote API is accessible using standard Java enterprise client mechanisms or through the servlet-based JBoss remoting endpoint.
|
Domain | Functions which parallel the server's local manager beans, particularly in how a feature area is configured.
Clients use the remote API to script actions. The remote API relies on the domain API to supply most of that functionality, such as the criteria to use for object searches or the different properties for viewing resource configuration.
|
Plug-in | Functions related to both agent (resource) plug-ins. This is not used at all for the JBoss ON CLI or server-side scripts. The APIs are used by the agent plug-ins to receive and convey information between the agent and the JBoss ON server. |
1.2. The JBoss ON Server and Its Interfaces
- The implementing class is *ManagerBean. This implements both the local API and the remote API.
- SLSBs that are used internally by the server are *ManagerLocal.
- SLSBs that define the remote API are *ManagerRemote.
*Managers
. The remote API is the compilation of the *Remote
interfaces of the server's EJBs.
Figure 1.1. The Server Interfaces and Client Interactions
1.3. JBoss ON CLI Scripts and JBoss ON Server Scripts
- The JBoss ON CLI can be run manually, execute a script file, and even be invoked automatically by a system tool like cron. The CLI can connect to to any JBoss ON server and can be run remotely.Essentially, the CLI is a script execution engine. It exposes the remote API in a scripting language, which makes it more convenient to interact dynamically the JBoss ON server.
- Server-side scripts are uploaded into a content repository, managed in the JBoss ON server database, and are then invoked in response to a fired alert. Even though the server-side scripts are located on the server, they still use the same APIs to communicate with the server as other CLI scripts.
exec
command:
$ login -u rhqadmin -p rhqadmin $ exec -f samples/util.js $ exec /opt/my-scripts/mySupportScript.js $ exec /opt/my-scripts/myScript.js
1.4. Differences Between the JBoss ON CLI and JBoss ON GUI Operations
- Alert definition configuration. This is probably the most critical difference. While fired alerts can be retrieved through the CLI and scripts, there is no way to create or edit an alert definition, to set alert notifications, or to set alert conditions.
- Manually creating child resources
- Defining failover lists for servers
- Defining affinity groups for agents
- Raw measurement data compression
- Processing, caching, and logging alert conditions
- Processing partition events
- Determining authorization to resources based on role membership
- Schedule loaders for metric collection, drift detection, and other scheduled events
1.5. Using Other Clients
- Java clients, such as a desktop application to view alerts or monitoring charts. The JBoss ON CLI itself is a Java shell that works as a script execution engine.
- Clients in JVM-compatible languages, such as Scala or Groovy
- REST clients (tech preview)
1.6. Additional Resources
Chapter 2. Installing the JBoss ON CLI
- In response to an alert
- Through the CLI utility
2.1. Installing the CLI
Note
Important
Caused by: java.lang.IllegalArgumentException: interface org.rhq.enterprise.server.auth.SubjectManagerRemote is not visible from class loader at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) at org.rhq.enterprise.client.RemoteClientProxy.getProcessor(RemoteClientProxy.java:69)
- Open the JBoss ON GUI.
http://server.example.com:7080
- Click the Administration tab in the top menu.
- Select the Downloads menu item.
- Scroll to the Command Line Client Download section, and click Download CLI 4.5.JON.3.1.2.
- Save the
.zip
file into the directory where the CLI should be installed. - Unzip the packages. For example:
[jsmith@server opt]$ unzip rhq-remoting-cli-4.5.JON.3.1.2.zip
2.2. Setting CLI Environment Variables
rhq-cli-env.sh|bat
file.
Note
rhq-cli-env.sh|bat
file is fully annotated, so all available parameters are listed with full descriptions. If you want to change some of the JVM settings or parameters, read through the rhq-cli-env.sh|bat
file to get an idea of what parameters are available.
RHQ_CLI_JAVA_HOME
or the RHQ_CLI_JAVA_EXE_FILE_PATH
variable in the rhq-cli-env.sh|bat
file. For example:
RHQ_CLI_JAVA_HOME="/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/jdk"
Important
rhq-cli.sh|bat
file or attempt to set environment variables in that file. Environment variables and Java options should only be set in the rhq-cli-env.sh|bat
file.
rhq-cli.sh|bat
file may cause unexpected behavior or prevent the utility from running.
2.3. CLI Files and Directories
File or Directory | Description | ||
---|---|---|---|
cliRoot/rhq-remoting-cli-3.1.2.GA | The installation directory. The CLI utility is simply unzipped, so the installation directory can be anywhere on a system. | ||
CLI Scripts | |||
cliRoot/rhq-remoting-cli-3.1.2.GA/bin | Contains both Linux (shell) and Windows (batch) scripts for the CLI utility. | ||
rhq-cli.sh | rhq-cli.bat | The CLI utility. | ||
rhq-cli-env.sh | rhq-cli-env.bat | Sets environment variables for the CLI utility, such as the Java home directory and Java options. | ||
Samples | |||
cliRoot/rhq-remoting-cli-3.1.2.GA/samples | Contains both sample JavaScript files and supplemental JavaScript files which can be adapted to work with other scripts. | ||
util.js | A utility script which provides additional functions for search, mapping, and listing objects. | ||
measurement_utils.js | A utility script which simplifies updating metrics schedules. Instead of having to understand the underlying measurement APIs, it provides a way to define the metrics to change based on their friendly (UI) name and then both enables/disables and sets collection intervals in simpler terms. | ||
drift.js | A sample script which contains functions to create a snapshot, search for a specific drift definition, compare snapshots, and view drift histories. | ||
bundles.js | A sample script which sets up a bundles definition. This includes generating a bundle archive, creating a destination group, and then deploying the bundle. | ||
deploy-to-and-restart-JBAS.js | A sample script which deploys a new bundle or updated bundle to a group of JBoss servers, and then restarts the servers in the destination group. | ||
Logging | |||
cliRoot/rhq-remoting-cli-3.1.2.GA/conf | Contains the XML files to configure the log4j logger for the CLI utility. | ||
| Sets the configuration for regular and debug logging for the CLI utility. | ||
cliRoot/rhq-remoting-cli-3.1.2.GA/logs | Contains the error logs for the CLI utility. This directory is created when the CLI is first run. | ||
rhq-server-cli.log | The error log for the CLI utility. | ||
Libraries | |||
cliRoot/rhq-remoting-cli-3.1.2.GA/lib | Contains all of the libraries used specifically by the CLI utility, including some libraries for proxy resources and CLI-specific commands. |
Part II. Basic Examples for Running JBoss ON Scripts Through the CLI
Commands and Options with the CLI
1. Compatible CLI and Server Versions
2. The JBoss ON CLI Command Syntax
2.1. The CLI Script
/bin
directory. There are two files associated with launching the JBoss ON CLI:
- A script (
rhq-cli.sh|bat
) - A file of environment variables (
rhq-cli-env.sh|bat
)The environment variables in therhq-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 non-default JVM. The comments at the top of therhq-cli-env.|bat
file contain a detailed list of available environment variables.Important
Do not edit therhq-cli.sh|bat
file. Only set environment variables through the terminal or in therhq-cli-env.sh|bat
file, not the script itself.
Note
RHQ_CLI_JAVA_HOME
or the RHQ_CLI_JAVA_EXE_FILE_PATH
variable.
rhq-cli.sh|bat
script has the following general syntax:
rhq-cli.sh|bat options
[jsmith@server bin]$ cliRoot/rhq-remoting-cli-3.1.2.GA/bin/rhq-cli.sh RHQ - RHQ Enterprise Remote CLI unconnected$
login
command after starting the CLI.
[jsmith@server bin]$ rhq-cli -u rhqadmin -p rhqadmin
Important
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, use the Java method.
Important
rhq-cli.sh
script — must have write access to the logs/
directory for the CLI.
2.2. CLI Script Options
rhq-cli.bat
and rhq-cli.sh
scripts accept the options listed in Table 1, “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. |
--args-style | Indicates the style or format of arguments passed to the script. This is the same as using the -s option with the exec command interactively. | |
-v | --version | Displays CLI and JBoss ON server version information once connected to 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. |
2.3. Interactive CLI Commands
Important
2.3.1. login
login username password [host] [port]
login
command can be used in a script executed using exec
or with the rhq-cli.sh --f
option.
2.3.2. logout
logout
login
command can be used in a script executed using exec
or with the rhq-cli.sh --f
option.
2.3.3. quit
quit
java.lang.System.exit
.
2.3.4. exec
exec statement | [-s indexed|named] -f /absolute/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=named|indexed
|
Indicates the style or format of arguments passed to the script. It must have a value of either
indexed or named .
|
2.3.5. record
record [-b | -e] [-a] -f filename
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.
|
3. Available Implicit Variables in the JBoss ON API
org.rhq.core.domain
class is automatically imported, which makes it easier to use the CLI for managing resources, alerts, and other configuration areas. 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();
var criteria = new ResourceCriteria(); var resource = new Resource();
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. Methods Specific to the JBoss ON CLI
4.1. Methods Available to the CLI and Server Scripts
4.1.1. Assert
Method | Signature |
---|---|
Assert.assertEquals |
assertEquals(float, float, float, String) assertEquals(short, short, String) assertEquals(double, double, double) assertEquals(long, long, String) assertEquals(byte, byte, String) assertEquals(Object, Object) assertEquals(char, char, String) assertEquals(Object, Object, String) assertEquals(double, double, double, String) assertEquals(byte[], byte[]) assertEquals(boolean, boolean) assertEquals(Object[], Object[], String) assertEquals(Collection, Collection) assertEquals(Object[], Object[]) assertEquals(byte, byte) assertEquals(float, float, float) assertEquals(char, char) assertEquals(int, int) assertEquals(long, long) assertEquals(Collection, Collection, String) assertEquals(short, short) assertEquals(String, String, String) assertEquals(byte[], byte[], String) assertEquals(boolean, boolean, String) assertEquals(String, String) assertEquals(int, int, String) |
Assert.assertEqualsNoOrder |
assertEqualsNoOrder(Object[], Object[], String) assertEqualsNoOrder(Object[], Object[]) |
Assert.assertExists |
assertExists(String) |
Assert.assertFalse |
assertFalse(boolean) assertFalse(boolean, String) |
Assert.assertNotNull |
assertNotNull(Object) assertNotNull(Object, String) |
Assert.assertNotSame |
assertNotSame(Object, Object, String) assertNotSame(Object, Object) |
Assert.assertNull |
assertNull(Object) assertNull(Object, String) |
Assert.assertNumberEqualsJS |
assertNumberEqualsJS(double, double, String) |
Assert.assertSame |
assertSame(Object, Object, String) assertSame(Object, Object) |
Assert.assertTrue |
assertTrue(boolean, String) assertTrue(boolean) |
Assert.fail |
fail() fail(String, Throwable) fail(String) |
4.1.2. Subject
Method | Signature |
---|---|
subject.addLdapRole |
addLdapRole(Role) |
subject.addRole |
addRole(Role) addRole(Role, boolean) |
subject.department | Prints the department value (if any) for the current user. |
subject.emailAddress | Prints the email address for the current user. |
subject.factive | Prints whether the user account is active. |
subject.firstName | Prints whether the first name of the user. |
subject.fsystem | |
subject.id | Prints the ID number for the user account within JBoss ON. |
subject.lastName | Prints the surname for the user. |
subject.ldapRoles | Lists any roles associated with LDAP groups to which the current user is a member. |
subject.name | Prints the JBoss ON user ID of the current user. |
subject.ownedGroups | |
subject.phoneNumber | Prints the phone number, if any exists, for the current user. |
subject.removeLdapRole |
removeLdapRole(Role) |
subject.removeRole |
removeRole(Role) |
subject.roles | Prints the role name, permissions, associated LDAP users and groups, associated resource groups, and other information about every role to which the current user belongs. |
subject.sessionId | Prints the current session ID number. |
subject.smsAddress | Returns the pager number, if it exists, for the user. |
subject.toString |
String toString() |
subject.userConfiguration | Returns all of the dashboard information, based on the configured portlets, dashboards, and settings that are specific to the logged-in user. |
4.1.3. pretty
Method | Signature |
---|---|
pretty.exportMode | Prints the current export setting for the server. |
pretty.print |
print(String[][]) print(PropertySimple, int) print(Configuration) print(PropertyMap, int) print(PropertyList, int) print(Collection) print(Map) print(Object[]) print(Object) |
pretty.width | Prints the current width settings for the console display. |
4.1.4. unlimitedPC and pageControl
Method | Signature |
---|---|
unlimitedPC.addDefaultOrderingField |
addDefaultOrderingField(String, PageOrdering) addDefaultOrderingField(String) |
unlimitedPC.clone |
clone() |
unlimitedPC.firstRecord | Returns the first record in the results page. |
unlimitedPC.getExplicitPageControl |
PageControl getExplicitPageControl(int, int) |
unlimitedPC.getSingleRowInstance |
PageControl getSingleRowInstance() |
unlimitedPC.getUnlimitedInstance |
PageControl getUnlimitedInstance() |
unlimitedPC.initDefaultOrderingField |
initDefaultOrderingField(String) initDefaultOrderingField(String, PageOrdering) |
unlimitedPC.orderingFields | |
unlimitedPC.orderingFieldsAsArray | |
unlimitedPC.pageNumber | Returns the current page number for paged results. |
unlimitedPC.pageSize | Returns the current configured page size (number of returned entries per page). |
unlimitedPC.primarySortColumn | |
unlimitedPC.primarySortOrder | |
unlimitedPC.removeOrderingField |
removeOrderingField(String) |
unlimitedPC.reset |
reset() |
unlimitedPC.setPrimarySort |
setPrimarySort(String, PageOrdering) |
unlimitedPC.setPrimarySortOrder |
setPrimarySortOrder(PageOrdering) |
unlimitedPC.sortBy |
sortBy(String) |
unlimitedPC.startRow | Returns the current starting row number. |
unlimitedPC.toString |
String toString() |
unlimitedPC.truncateOrderingFields |
truncateOrderingFields(int) |
4.1.5. exporter
Method | Signature |
---|---|
exporter.close |
close() |
exporter.file | |
exporter.format | Shows the current configured output format. |
exporter.pageWidth | Shows the configured line length for content in the output file. |
exporter.setFormat |
setFormat(String) |
exporter.setFile |
setFile(String) |
exporter.setPageWidth |
setPageWidth(int) |
exporter.setTarget |
setTarget(String, String) |
exporter.write |
write(Object) |
4.1.6. ProxyFactory
Method | Signature |
---|---|
ProxyFactory.getResource |
ResourceClientProxy getResource(int) |
ProxyFactory.outputWriter | |
ProxyFactory.remoteClient | Returns information about the managers and configuration used by the remote client. In the interactive CLI, this prints information about the manager beans used by the interactive CLI. |
ProxyFactory.resource |
4.1.7. scriptUtil
Method | Signature |
---|---|
scriptUtil.findResources |
PageList<Resource> findResources(String) |
scriptUtil.getFileBytes |
byte[] getFileBytes(String) |
scriptUtil.isDefined |
boolean isDefined(String) |
scriptUtil.saveBytesToFile |
saveBytesToFile(byte[], String) |
scriptUtil.sleep |
sleep(long) |
scriptUtil.waitForScheduledOperationToComplete |
ResourceOperationHistory waitForScheduledOperationToComplete(ResourceOperationSchedule, long, int) ResourceOperationHistory waitForScheduledOperationToComplete(ResourceOperationSchedule) |
4.2. Methods Available to Proxy Resources
Note
Information Methods | |
---|---|
measurements | Displays a pretty-print list of the available metrics, current values, and description of all measurements for the platform resource. |
operations | Lists the available operations for the resource type. |
Shortcut Metric Methods | |||
---|---|---|---|
OSName | OSVersion | architecture | createdDate |
description | distributionName | distributionVersion | freeMemory |
freeSwapSpace | hostname | idle | totalMemory |
systemLoad | totalSwapSpace | usedSwapSpace | usedMemory |
userLoad | modifiedDate | waitLoad | version |
Shortcut Resource Entry Methods | ||
---|---|---|
id (inventory ID number) | resourceType | name (inventory name) |
Shortcut Operation Methods | ||
---|---|---|
manualAutodiscovery | cleanYumMetadataCache | viewProcessList |
Shortcut Configuration Methods | |
---|---|
editPluginConfiguration() | pluginConfiguration |
pluginConfigurationDefinition |
Shortcut Content Methods |
---|
contentTypes |
Shortcut Inventory Methods |
---|
children |
Method | Signature |
---|---|
platform.getChild |
ResourceClientProxy getChild(String) |
platform.getMeasurement |
Measurement getMeasurement(String) |
platform.updatePluginConfiguration |
PluginConfigurationUpdate updatePluginConfiguration(Configuration) |
platform.toString |
String toString() |
Information Methods | |
---|---|
measurements | Displays a pretty-print list of the available metrics, current values, and description of all measurements for the JBoss resource. |
operations | Lists the available operations for the resource type. |
Shortcut Metric Methods | |||
---|---|---|---|
JVMFreeMemory | JVMMaxMemory | JVMTotalMemory | activeThreadCount |
activeThreadGroupCount | buildDate | createdDate | description |
modifiedDate | startDate | totalTransactions | totalTransactionsperMinute |
transactionsCommitted | transactionsCommittedperMinute | transactionsRolledback | transactionsRolledbackperMinute |
partitionName | versionName | version |
Shortcut Resource Entry Methods | ||
---|---|---|
id (inventory ID number) | resourceType | name (inventory name) |
Shortcut Operation Methods | ||
---|---|---|
restart | shutdown | start |
Shortcut Configuration Methods | |
---|---|
editPluginConfiguration() | pluginConfiguration |
pluginConfigurationDefinition |
Shortcut Content Methods |
---|
contentTypes |
Shortcut Inventory Methods |
---|
children |
Method | Signature |
---|---|
jbossas.getChild |
ResourceClientProxy getChild(String) |
jbossas.getMeasurement |
Measurement getMeasurement(String) |
jbossas.updatePluginConfiguration |
PluginConfigurationUpdate updatePluginConfiguration(Configuration) |
jbossas.toString |
String toString() |
Information Methods | |
---|---|
measurements | Displays a pretty-print list of the available metrics, current values, and description of all measurements for the content resource. |
operations | Lists the available operations for the resource type. |
Shortcut Metric Methods | ||
---|---|---|
createdDate | modifiedDate | description |
path | version | exploded |
Shortcut Resource Entry Methods | ||
---|---|---|
id (inventory ID number) | resourceType | name (inventory name) |
Shortcut Operation Methods |
---|
revert |
Shortcut Configuration Methods | |
---|---|
editPluginConfiguration() | pluginConfiguration |
pluginConfigurationDefinition |
Shortcut Content Methods | |
---|---|
contentTypes | backingContent |
Shortcut Inventory Methods |
---|
children |
Method | Signature |
---|---|
content.getChild |
ResourceClientProxy getChild(String) |
content.getMeasurement |
Measurement getMeasurement(String) |
content.updatePluginConfiguration |
PluginConfigurationUpdate updatePluginConfiguration(Configuration) |
content.toString |
String toString() |
content.retrieveBackingContent |
retrieveBackingContent(String fileName) |
content.updateBackingContent |
updateBackingContent(String filename, String displayVersion) |
5. Common Actions with JBoss ON CLI Scripts
Important
Caused by: java.lang.IllegalArgumentException: interface org.rhq.enterprise.server.auth.SubjectManagerRemote is not visible from class loader at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) at org.rhq.enterprise.client.RemoteClientProxy.getProcessor(RemoteClientProxy.java:69)
5.1. Logging In
- By passing user credentials when the
rhq-cli.sh
script is run. - By using the
command
in a script or after starting the CLI without connecting to the server.
Example 1. Logging in to a Specified Server
rhq-cli.sh -u rhqadmin -p rhqadmin -s 192.168.1.100 -t 70443
Example 2. Prompting for a Password
rhq-cli.sh -u rhqadmin -P
5.2. Using Resource Proxies
ProxyFactory
to interact with the remote and domain API.
Note
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.
ProxyFactory
gets information about a resource, which is identified in the getResource()
method with the resource's ID number.
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: server.example.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: server.example.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%
ProxyFactory
creates a resource proxy object.
Example 3. Defining a Platform Proxy Resource
var rhelServerOne = ProxyFactory.getResource(10001)
- 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
Note
Example 4. 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 server.example.com RHQ Server (JBossAS Server::JBossAS) [10002] RHQ Agent (RHQ Agent::RHQAgent)
Example 5. 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.
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...
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 server.example.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 6. Running Operations on a Proxy
ProxyFactory
has a shortcut method for every operation available for a resource.
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
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 7. Changing Configuration Properties
editResourceConfiguration()
and editPluginConfiguration()
, respectively — to edit those properties.
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] { }
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: ...
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 8. Managing Content on Resources
var contentResource = ProxyFactory.getResource(14932) contentResource.retrieveBackingContent("/resources/backup/original.war")
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")
5.3. Passing Command and Script Arguments
rhq-cli.sh
, commands or full scripts can be passed simultaneously. This is a non-interactive way to connect to the CLI, since the CLI runs the specified command or script and then exits, rather than staying connected in interactive mode.
Example 9. Passing Variables to the Server
-c
. In this example, the server searches for and prints all supported resource types for the server and prints the results to resource_types.txt
rhq-cli.sh -u rhqadmin -p rhqadmin -c "pretty.print(ResourceTypeManager.findResourceTypesByCriteria(new ResourceTypeCriteria()))" > resource_types.txt
ResourceTypeManager.findResourceTypesByCriteria(new ResourceTypeCriteria())
class invokes the findResourceTypesByCriteria
operation on ResourceTypeManager
. A new ResourceTypeCriteria
object is passed as the argument.
pretty
is an implicit object made available to commands and scripts by the CLI. This is useful for outputting objects in a readable, tabular format which is designed for domain objects.
Example 10. Running a Script
my_script.js
. The CLI terminates immediately after the script has finished executing.
cliRoot/rhq-remoting-cli-3.1.2.GA/bin/rhq-cli.sh -f /export/myScripts/my_script.js
Example 11. Handling Script Arguments
if (args.length > 2) { throw "Not enough arguments!"; } for (i in args) { println('args[' + i + '] = ' + args[i]); }
args
variable is only available when executing a script in non-interactive mode or with exec -f
.
rhqadmin@localhost:7080$ exec -f echo_args.js --args-style=named x=1 y=2
echo_args.js
, for example, is written to accept the two named option with the script invocation, x and y.
for (i in args) { println('args[' + i + '] = ' + args[i]); } println('named args...'); println('x = ' + x); println('y = ' + y);
args[0] = 1 args[1] = 2 named args... x = 1 y = 2
- Explicitly specify that you are using named arguments with the
--args-style
option. - The values of the named arguments are still accessible through the implicit args array.
- The named arguments, such as
x
andy
, are bound into the script context as variables.
Example 12. Executing a Single Statement
-c
option with rhq-cli.sh
. This is done using the exec
command and then the statement.
localhost:7080> exec var x = 1
Example 13. 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 14. Executing a Script
-f
option with the exec
command.
-f
option must give the absolute location of the script, even if it is in the same directory as the rhq-cli.sh
script. The CLI will not find a script with only a relative path.
localhost:7080(rhqadmin)> exec -f /absolute/path/to/myscript.js
Example 15. Executing a Script with Arguments
exec
command simply by supplying them in the proper order, as specified in the JavaScript file.
localhost:7080(rhqadmin)> exec -f /absolute/path/to/myscript.js 1 2 3
Example 16. Executing a Script with Named Arguments
exec
command which type of argument is being used, there may be instances where it is beneficial.
localhost:7080(rhqadmin)> exec --args-style=named -f /absolute/path/to/myscript.js x=1 y=2 y=3
5.4. Displaying Pretty-Print Output
TabularWriter
) is implicit for all CLI commands, so almost all output is properly formatted automatically. This class is also available as an implicit variable called pretty, which is useful when writing scripts.
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
pretty
formats any object defined in the domain (org.rhq.core.domain) package.
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], .... 8< ....
pretty
checks for the summary information (@Summary
), so that it only displays a subset of information. It then prints the summary information for the single object as a formatted list. For example:
rhqadmin@localhost:7080$ pretty.print(resources.get(0)) Resource: id: 11373 name: service-alpha-8 version: 1.0 resourceType: service-alpha
5.5. Exporting Output
export
is another implicit script variable that writes output to a specified file. exporter
uses pretty.print
to output all of the information to a plaintext file that matches the table-style formatting used in the interactive display.
rhqadmin@localhost:7080$ exporter.setTarget('raw', 'output.txt') rhqadmin@localhost:7080$ exporter.write(resources)
exporter
handles the IO operations.
exporter
can write the raw resource or other information to a CSV file:
rhqadmin@localhost:7080$ exporter.setTarget('csv', 'output.csv') rhqadmin@localhost:7080$ exporter.write(resources)
6. Tips and Tricks for Using the CLI
6.1. Using Tab Complete
[jsmith@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin RHQ Enterprise Remote CLI 3.1.2 Remote server version is: 3.1.2 (2484565) Login successful rhqadmin@localhost:7080$ Resource ResourceFactoryManager ResourceGroupManager ResourceManager ResourceTypeManager rhqadmin@localhost:7080$ ex exporter exec
rhqadmin@localhost:7080$ ResourceManager. availabilitySummary disableResources enableResources findChildResources findResourceLineage findResourcesByCriteria getAvailabilitySummary getLiveResourceAvailability getParentResource getResource getResourcesAncestry liveResourceAvailability parentResource resource toString uninventoryResources updateResource
rhqadmin@localhost:7080$ List<Integer> enableResources(GenericArrayTypeImpl[int]) Resource updateResource(Resource resource) List<Integer> uninventoryResources(GenericArrayTypeImpl[int] resourceIds) ResourceAvailabilitySummary getAvailabilitySummary(int resourceId) PageList<Resource> findChildResources(int resourceId, PageControl pageControl) Map<Integer,String> getResourcesAncestry(GenericArrayTypeImpl[Integer] resourceIds, ResourceAncestryFormat format) List<Integer> disableResources(GenericArrayTypeImpl[int]) List<Resource> findResourceLineage(int resourceId) ResourceAvailability getLiveResourceAvailability(int resourceId) PageList<Resource> findResourcesByCriteria(ResourceCriteria criteria) Resource getResource(int resourceId) String toString() Resource getParentResource(int resourceId)
6.2. Differences Between Running the CLI Interactively and with Files
-f
option or exec
command.
- quit (which exits the CLI)
- exec
- record
rhq.login('rhqadmin', 'rhqadmin'); rhq.logout();
6.3. API Differences Between Resources Types and Versions
6.4. Available Utility and Sample Scripts
Important
Script | Description | Location |
---|---|---|
Utility Scripts | ||
util.js | Defines search functions for iterating through an array of object (foreach ), to return the first matching object (find ) or to return all matching objects (findAll ). It also has functions for converting information from JavaScript hashes to JBoss ON configuration objects and back. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
measurement_utils.js | Defines functions to enable, disable, or update metric schedules. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
bundles.js | Defines functions to create and deploy a bundle, create a bundle destination, or get information on supported base directories for a resource. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
drift.js | Defines functions to create and diff snapshots, get a definition, and show the history for a resource or specific file. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
Sample Scripts | ||
add-as7-standalone-server-to-cluster.js | Defines a series of functions that add a specified AS 7 to a cluster. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
deploy-to-and-restart-JBAS.js | Defines two functions to deploy new content to EAP servers and to update existing content. With the proper variables set, this script can be run directly to deploy content and restart the given app server. | cliRoot/rhq-remoting-cli-3.1.2.GA/samples/ |
fix-bundle-deployment.js | An example server-side alert script that reverts a bundle deployment to a specified version. | serverRoot/jon-server-3.1.2.GA/jbossas/server/default/deploy/rhq.ear/rhq-downloads/cli-alert-scripts/ |
6.5. Defining Custom Functions
6.6. Script Dependencies and Loading Functions
rhq-cli.sh -f
option, there is no way to define a dependency with an external file. Any functions required by that script must be contained in the script.
exec -f
command loads whatever functions are in the file into the active CLI session. This allows utility scripts to be loaded first and then scripts to be run that take advantage of the utility functions.
util.js
contains very useful functions for iterating through an array of objects and returning some or all of the matching objects. This can be loaded first, and then a script which relies on its search functions can be executed next:
rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/util.js rhqadmin@localhost:7080$ exec -f /export/scripts/myScript.js
Important
6.7. Scheduling Script Runs with Cron
import.js
to add discovered resources to the inventory automatically and runs it daily:
vim /etc/cron.daily/rhq-cli #!/bin/sh # run JON CLI every morning to import new resources cliRoot/rhq-remoting-cli-3.1.2.GA/bin/rhq-cli.sh -u rhqadmin -p rhqadmin -f /export/scripts/import.js
6.8. Using Wrapper Scripts
6.9. Permissions and Setup for JBoss ON Users
rhq.login
method, is run on the JBoss ON server by a JBoss ON user.
Short Examples
1. Searches
find
ObjectByCriteria
, so a resource find method is findResourcesByCriteria
and a group find method is findResourceGroupsByCriteria
.
1.1. Setting Basic Search Criteria
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria() // this sets the criteria to use for the search rhqadmin@localhost:7080$ criteria.clearPaging() // this clears the 200 item page size to return all entries rhqadmin@localhost:7080$ var resources = ResourceManager.findResourcesByCriteria(criteria) // this actually runs the search rhqadmin@localhost:7080$ pretty.print(resources) // this prints the search results id name versio curren resour ------------------------------------------------------------------------------- 10001 server Linux UP Linux 10002 server AS 4.2 UP JBossA 10392 full-h UP Profil 10014 AlertH UP EJB3 S 10015 Adviso UP EJB3 S 10016 DataAc UP EJB3 S 10017 Affini UP EJB3 S 10011 Access UP Access 10391 ha UP Profil ...8<...
findResourcesByCriteria()
is what runs the search, the pretty.print
method is required to display the results.
SELECT r FROM Resource r WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED
1.2. Using Sorting
criteria.addSortPluginName()
. Sorting criteria have methods in the form addSortXXX(PageOrdering order)
.
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria() rhqadmin@localhost:7080$ criteria.addSortPluginName(PageOrdering.ASC) // adds a sort order to the results rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
SELECT r FROM Resource r WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED ) ORDER BY r.resourceType.plugin ASC
1.3. Using Filtering
addFilterXXX()
.
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria() rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server') // a search filter rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
SELECT r FROM Resource r WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED AND LOWER( r.resourceType.name ) like 'JBossAS Server' ESCAPE '\\' )
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria() rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('JBossAS Server') rhqadmin@localhost:7080$ criteria.addFilterAgentName('localhost.localdomain') rhqadmin@localhost:7080$ resources = ResourceManager.findResourcesByCriteria(criteria)
SELECT r FROM Resource r WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED AND LOWER( r.agent.name ) like 'localhost.localdomain' ESCAPE '\\' )
1.4. Fetching Associations
...8<... rhqadmin@localhost:7080$ resource = resources.get(0) rhqadmin@localhost:7080$ if (resource.childResources == null) print('no child resources')
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) 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 ...8<...
SELECT r FROM Resource r LEFT JOIN FETCH r.childResources WHERE ( r.inventoryStatus = InventoryStatus.COMMITTED AND LOWER( r.resourceType.name ) like 'JBossAS Server' ESCAPE '\\' )
1.5. Setting Page Sizes
Criteria
class defines some methods which can be used to control page sizes for search results.
Example 1. Clearing the Page Size
clearPaging
var criteria = new ResourceCriteria()
criteria.clearPaging()
var resources = ResourceManager.findResourcesByCriteria(criteria)
Example 2. Setting a Page Size
setPaging
method sets the number of pages and the page size for the given search. Generally, since there is only a single page, the page number is set to 0, and then the page size can be reset higher or lower, as desired.
rhqadmin@localhost:7080$ var criteria = new ResourceCriteria() rhqadmin@localhost:7080$ criteria.getPageSize() 200 rhqadmin@localhost:7080$ criteria.getPageNumber() 0 rhqadmin@localhost:7080$ criteria.setPaging(0,300) rhqadmin@localhost:7080$ var resources = ResourceManager.findResourcesByCriteria(criteria) id name currentAvailability resourceType ------------------------------------------------------------------------------------------------------------------ 10032 RHQDS UP Datasource 10033 ResourceFactoryManagerBean UP EJB3 Session Bean 10034 CoreTestBean UP EJB3 Session Bean 10035 rhq-postinstaller.war (//localhost/installer) UP Web Application (WAR) 10036 ResourceMetadataManagerBean UP EJB3 Session Bean 10037 SystemInfoManagerBean UP EJB3 Session Bean 10105 wstools.sh UP Script 10038 PartitionEventManagerBean UP EJB3 Session Bean 10039 CallTimeDataManagerBean UP EJB3 Session Bean 10040 AlertDefinitionManagerBean UP EJB3 Session Bean 10041 DiscoveryTestBean UP EJB3 Session Bean 10123 wsconsume.sh UP Script 10042 ROOT.war (//localhost/) UP Web Application (WAR) 10044 AlertManagerBean UP EJB3 Session Bean 10045 AgentManagerBean UP EJB3 Session Bean ... 8< ... 300 rows
2. Getting the JBoss ON ID for an Object
rhqadmin@localhost:7080$ criteria = new ResourceCriteria(); ResourceCriteria: inventoryManagerRequired: false persistentClass: class org.rhq.core.domain.resource.Resource rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('Linux') rhqadmin@localhost:7080$ ResourceManager.findResourcesByCriteria(criteria); one row Resource: id: 10001 name: gs-dl585g2-01.rhts.eng.bos.redhat.com version: Linux 2.6.32-220.el6.x86_64 currentAvailability: UP resourceType: Linux
*Criteria
search. It retrieves the ID for the object is searches for, even if that ID is not explicitly displayed.
rhqadmin@localhost:7080$ var metrics = MeasurementDataManager.findLiveData(resources.get(0).id, [mdefs.get(0).id]);
3. Getting Data for Single and Multiple Resources
exporter.write(data.get(0))
get(0)
takes the first object that was returned and uses it.
get(0)
, is to work incrementally through each object in a list. For example, this gets the data for each metric definition (i) for a resource.
Example 3. get(i)
if( mdefs != null ) { if( mdefs.size() > 1 ) { for( i =0; i < mdefs.size(); ++i) { mdef = mdefs.get(i); var data = MeasurementDataManager.findDataForResource(resources.get(0).id,[mdef.id],start,end,"") exporter.write(data.get(0)); } } ...8<...
Example 4. An Array
//find the resources //use a plugin filter to make sure they are all of the same type criteria = new ResourceCriteria(); criteria.addFilterPluginName('JBossAS5') var resources = ResourceManager.findResourcesByCriteria(criteria).toArray(); var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin('JBossAS Server', 'JBossAS5'); // go through the array var idx=0; var jbossServers = new Array(); for( i in resources ) { if( resources[i].resourceType.id == resType.id ) { jbossServers[idx] = resources[i]; idx = idx + 1; } } // restart the resources for( a in resources ) { var jboss = ProxyFactory.getResource(jbossServers[a].id); jboss.restart() }
util.js
support script has a foreach
function that also iterates cleanly through arrays, collections, and maps, as well as generic objects.
4. Setting Method Variables to String
rhqadmin@localhost:7080$ groupcriteria = new ResourceGroupCriteria(); rhqadmin@localhost:7080$ groupcriteria.addFilterGroupCategory('MIXED') Can't find method org.rhq.core.domain.criteria.ResourceGroupCriteria.addFilterGroupCategory(string). (<Unknown source>#1)
.toString
method with the remote API method.
groupcriteria.addFilterGroupCategory.toString('MIXED');
5. Resources and Groups
5.1. Creating and Updating Content-Backed Resources (Web Apps)
- Search for the resource to upload the content to. This example looks for a JBoss AS 5 server.
- Make sure the server is running. The JBoss server has to be running for content to be deployed successfully.
Example 5. Creating a Content-Backed Resource
// fill this information in before running the script var pathName = '/home/jon/myExampleApp.ear' var resTypeName = 'JBossAS Server' var pluginName = "JBossAS5" var appTypeName = "Enterprise Application (EAR)" // define a custom function to parse the filename and path info function PackageParser(pathName) { var file = new java.io.File(pathName); var fileName = file.getName(); var packageType = fileName.substring(fileName.lastIndexOf('.')+1); var tmp = fileName.substring(0, fileName.lastIndexOf('.')); var version = 1; var realName = tmp; var packageName = fileName; // parse the package version, only if version is included if(tmp.indexOf('-') != -1){ realName = tmp.substring(0, tmp.lastIndexOf('-')); version = tmp.substring(tmp.lastIndexOf('-') + 1); packageName = realName + "." + packageType; } this.packageType = packageType.toLowerCase(); this.packageName = packageName; this.version = version; this.realName = realName; this.fileName = fileName; } criteria = new ResourceCriteria(); criteria.addFilterResourceTypeName(resTypeName); criteria.addFilterPluginName(pluginName); var resources = ResourceManager.findResourcesByCriteria(criteria); // create the config options for the new EAR var deployConfig = new Configuration(); deployConfig.put( new PropertySimple("deployExploded", "false")); deployConfig.put( new PropertySimple("deployFarmed", "false")); // stream in the file bytes var file = new java.io.File(pathName); var inputStream = new java.io.FileInputStream(file); var fileLength = file.length(); var fileBytes = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, fileLength); for (numRead=0, offset=0; ((numRead >= 0) && (offset < fileBytes.length)); offset += numRead ) { numRead = inputStream.read(fileBytes, offset, fileBytes.length - offset); } // parse the filename and path info PackageParser(pathName); // identifies the type of resource being created var appType = ResourceTypeManager.getResourceTypeByNameAndPlugin(appTypeName, pluginName); // create the new EAR resource on each discovered app server if( resources != null ) { for( i =0; i < resources.size(); ++i) { var res = resources.get(i);println("res: " + res); ResourceFactoryManager.createPackageBackedResource( res.id, appType.id, packageName, null, // pluginConfiguration packageName, version, null, // architectureId deployConfig, fileBytes, null // timeout ); } }
Example 6. Updating a Content-Backed Resource
// update this var fullPathName = '/export/myfiles/updatedApp.ear' // define a custom function to parse the filename and path info function PackageParser(pathName) { var file = new java.io.File(pathName); var fileName = file.getName(); var packageType = fileName.substring(fileName.lastIndexOf('.')+1); var tmp = fileName.substring(0, fileName.lastIndexOf('.')); var version = 1; var realName = tmp; var packageName = fileName; // parse the package version, only if version is included if(tmp.indexOf('-') != -1){ realName = tmp.substring(0, tmp.lastIndexOf('-')); version = tmp.substring(tmp.lastIndexOf('-') + 1); packageName = realName + "." + packageType; } this.packageType = packageType.toLowerCase(); this.packageName = packageName; this.version = version; this.realName = realName; this.fileName = fileName; } // parse the filename and path info PackageParser(fullPathName); // search for the JBoss AS 5 server by name criteria = new ResourceCriteria(); criteria.addFilterName('My JBoss AS 5 Server'); var res = ResourceManager.findResourcesByCriteria(criteria); var jboss = ProxyFactory.getResource(res.get(0).id); var children = jboss.children; for( c in children ) { var child = children[c]; if( child.name == packageName ) { child.updateBackingContent(fullPathName,version); } }
Note
Example 7. Deleting a Content-Backed Resource
// search for the content resource by name criteria = new ResourceCriteria(); criteria.addFilterName('updatedApp.ear'); var res = ResourceManager.findResourcesByCriteria(criteria); ResourceFactoryManager.deleteResource(res.get(0).id)
5.2. Creating a Resource Group and Adding Members
- Search for the resource type.
- Create the group, based on the resource type.
- Find resources of that resource type.
- Iterate through the returned resources and add them to the group.
Example 8. Annotated Example
// search for the resource type to use for the compat group var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin("Linux","Platforms"); //create the new resource group var rg = new ResourceGroup(resType); rg.setRecursive(false); rg.setName('Linux Group - ' + java.util.Date()); rg = ResourceGroupManager.createResourceGroup(rg); //find resources to add to the group based on their resource type criteria = new ResourceCriteria(); criteria.addFilterResourceTypeId(resType.id); var resources = ResourceManager.findResourcesByCriteria(criteria); // add the found resources to the group if( resources != null ) { for( i =0; i < resources.size(); ++i) { var resource = resources.get(i); ResourceGroupManager.addResourcesToGroup(rg.id, [resource.id]); } }
6. Resource Configuration
- The plug-in configuration. In the web UI, this is called the connection setting; it is the information which the agent uses to discover and connect to the resource, such as a PID file path or a port number.Every resource has some kind of plug-in configuration.
- Resource configuration. Configuration properties are drawn from the configuration files for a resource, such as
.conf
or.xml
. The configuration files and properties that are exposed within JBoss ON are defined in the plug-in descriptor.Resource configuration is optional, and many resources do not support configuration editing or only expose a subset of possible properties.
Note
6.1. Viewing Current Configuration
get*ConfigurationDefinitionForResourceType
methods can display the descriptor-defined templates used for the resource type's configuration. These are the configuration properties available to every resource of that type.
Example 9. Viewing Plug-in Configuration for a Resource Type
rhqadmin@localhost:7080$ var res = ResourceTypeManager.getResourceTypeByNameAndPlugin('Linux','Platforms') //get the resource type ID rhqadmin@localhost:7080$ ConfigurationManager.getPluginConfigurationDefinitionForResourceType(res.id) //use the type ID to search for the resource type template ConfigurationDefinition: configurationFormat: Structured defaultTemplate: ConfigurationTemplate[id=10443, name=default, config=Linux] description: groupDefinitions: [PropertyGroupDefinition[id=10058, name=Content], PropertyGroupDefinition[id=10059, name=Event Logs]] id: 10437 name: Linux nonGroupedProperties: [] propertyDefinitions: {logs=PropertyDefinitionList[id=11792, name=logs, config=Linux, group=Event Logs], metadataCacheTimeout=SimpleProperty[metadataCacheTimeout] (Type: INTEGER)(Group: Content), enableContentDiscovery=SimpleProperty[enableContentDiscovery] (Type: BOOLEAN)(Group: Content), enableInternalYumServer=SimpleProperty[enableInternalYumServer] (Type: BOOLEAN)(Group: Content), yumPort=SimpleProperty[yumPort] (Type: INTEGER)(Group: Content)} templates: {default=ConfigurationTemplate[id=10443, name=default, config=Linux]}
propertyDefinitions
parameter contains the information about the configuration properties that can be set, including details about the configuration property setup. For example, for the event logs configuration:
logs=[id=11792, name=logs, config=Linux, group=Event Logs]
metadataCacheTimeout=SimpleProperty[metadataCacheTimeout] (Type: INTEGER)(Group: Content)
Example 10. Viewing the Configuration Properties for the Resource Type
rhqadmin@localhost:7080$ var res = ResourceTypeManager.getResourceTypeByNameAndPlugin('Samba Server', 'Samba') //get the resource type ID rhqadmin@localhost:7080$ ConfigurationManager.getResourceConfigurationDefinitionForResourceType(res.id) ConfigurationDefinition: configurationFormat: Structured defaultTemplate: ConfigurationTemplate[id=11123, name=default, config=Samba Server] description: groupDefinitions: [PropertyGroupDefinition[id=10905, name=Basic Configurations], PropertyGroupDefinition[id=10906, name=Security], PropertyGroupDefinition[id=10907, name=Printing], PropertyGroupDefinition[id=10908, name=Active Server Directory]] id: 11087 name: Samba Server nonGroupedProperties: [] propertyDefinitions: {winbind enum groups=SimpleProperty[winbind enum groups] (Type: BOOLEAN)(Group: Active Server Directory), winbind separator=SimpleProperty[winbind separator] (Type: STRING)(Group: Active Server Directory), cups options=SimpleProperty[cups options] (Type: STRING)(Group: Printing), workgroup=SimpleProperty[workgroup] (Type: STRING)(Group: Basic Configurations), encrypt passwords=SimpleProperty[encrypt passwords] (Type: BOOLEAN)(Group: Security), winbind enum users=SimpleProperty[winbind enum users] (Type: BOOLEAN)(Group: Active Server Directory), security=SimpleProperty[security] (Type: STRING)(Group: Security), template shell=SimpleProperty[template shell] (Type: STRING)(Group: Active Server Directory), password=SimpleProperty[password] (Type: PASSWORD)(Group: Active Server Directory), load printers=SimpleProperty[load printers] (Type: BOOLEAN)(Group: Printing), username=SimpleProperty[username] (Type: STRING)(Group: Active Server Directory), realm=SimpleProperty[realm] (Type: STRING)(Group: Active Server Directory), idmap gid=SimpleProperty[idmap gid] (Type: STRING)(Group: Active Server Directory), server string=SimpleProperty[server string] (Type: STRING)(Group: Basic Configurations), controller=SimpleProperty[controller] (Type: STRING)(Group: Active Server Directory), enableRecycleBin=SimpleProperty[enableRecycleBin] (Type: BOOLEAN)(Group: Basic Configurations), idmap uid=SimpleProperty[idmap uid] (Type: STRING)(Group: Active Server Directory)} templates: {default=ConfigurationTemplate[id=11123, name=default, config=Samba Server]}
get*Configuration
methods.
Note
Example 11. Viewing a Resource's Configuration Settings
rhqadmin@localhost:7080$ criteria = new ResourceCriteria(); // find the resource rhqadmin@localhost:7080$ criteria.addFilterResourceTypeName('Samba') rhqadmin@localhost:7080$ criteria.addFilterAgentName('agent1.example.com') rhqadmin@localhost:7080$ var resource = ResourceManager.findResourcesByCriteria(criteria); rhqadmin@localhost:7080$ ConfigurationManager.getResourceConfiguration(resource.get(0).id) Configuration [12082] - Loaded from Augeas at Wed May 02 12:04:24 EDT 2012 winbind separator = null winbind enum groups = null cups options = null workgroup = null winbind enum users = null encrypt passwords = null security = null template shell = null password = null load printers = null username = null realm = null idmap gid = null server string = null controller = null enableRecycleBin = false idmap uid = null
6.2. Changing Simple Configuration Properties
- Search for the resource.
- Create a configuration object.
- Set the new property value. The method to set the property value depends on the format of the property. In this case, it uses
setSimpleValue
since this is a simple property. For a simple property, the value is set by passing ('property','value'). - Run an update operation for the resource. For a resource configuration update, the method is
updateResourceConfiguration
. For a plug-in configuration update, it isupdatePluginConfiguration
.
Example 12. Changing a Simple Property
// find the resource criteria = new ResourceCriteria(); criteria.addFilterResourceTypeName('Samba') // this only updates the resource for this specific agent criteria.addFilterAgentName('agent1.example.com') var resources = ResourceManager.findResourcesByCriteria(criteria); //get current configuration var config = ConfigurationManager.getResourceConfiguration(resources.get(0).id); //set the new value in the form 'property', 'value' config.setSimpleValue("workgroup","example") // run the update operation ConfigurationManager.updateResourceConfiguration(resources.get(0).id,config)
7. Operations
7.1. Starting and Stopping a Resource
start()
function.
Example 13. Simple Start
//find the resource criteria = new ResourceCriteria(); criteria.addFilterName('My JBossAS') var servers = ResourceManager.findResourcesByCriteria(criteria); var myJBossAS = ProxyFactory.getResource(servers.get(0).id) myJBossAS.start()
operations
method to list the available operations.
rhqadmin@localhost:7080$ server.operations Array of org.rhq.bindings.client.ResourceClientProxy$Operation name description ----------------------------------------------------------------------- restart Shutdown and then start this application server. start Start this application server. shutdown Shutdown this application server via script or JMX. 3 rows
Example 14. Starting an Array 1
//find the resources //use a plugin filter to make sure they are all of the same type criteria = new ResourceCriteria(); criteria.addFilterPluginName('JBossAS5') var resources = ResourceManager.findResourcesByCriteria(criteria).toArray(); var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin('JBossAS Server', 'JBossAS5'); // go through the array var idx=0; var jbossServers = new Array(); for( i in resources ) { if( resources[i].resourceType.id == resType.id ) { jbossServers[idx] = resources[i]; idx = idx + 1; } } // restart the resources for( a in resources ) { var jboss = ProxyFactory.getResource(jbossServers[a].id); jboss.restart() }
Example 15. Starting an Array 2
//find the resources //use a plugin filter to make sure they are all of the same type criteria = new ResourceCriteria(); criteria.addFilterPluginName('JBossAS5') criteria.addFilterResourceTypeName('JBossAS Server'); var jbossServers = ResourceManager.findResourcesByCriteria(criteria).toArray(); // restart the resources for( a in jbossServers ) { var jboss = ProxyFactory.getResource(jbossServers[a].id); jboss.restart() }
7.2. Scheduling Operations
Example 16. Immediate Operation
rhqadmin@localhost:7080$ var agent = ProxyFactory.getResource(10008) rhqadmin@localhost:7080$ agent.executeAvailabilityScan(true) Invoking operation executeAvailabilityScan Configuration [13903] - null isChangesOnly = true agentName = server.example.com resourceAvailabilities [0] { }
- The resource ID
- The operation name
- A delay period, meaning when in the future to start the operation (optional)
- A repeat interval and count (optional)
- A timeout period (optional)
- Configuration parameters, if required by the operation
- A description of the scheduled operation (optional)
Example 17. Scheduled Operation Example
// find the agent var rc = ResourceCriteria(); rc.addFilterResourceTypeName("RHQ Agent"); rc.addFilterVersion("3.1.2"); var agent = ResourceManager.findResourcesByCriteria(rc); //set the config properties for the operation var config = new Configuration(); config.put(new PropertySimple("changesOnly", "true") ); //schedule the operation OperationManager.scheduleResourceOperation( agent.get(0).id, "executeAvailabilityScan", 0, // 0 means that the delay was skipped 1, 0, // this skips the repeat count 10000000, config, "test from cli" );
rhqadmin@localhost:7080$ exec -f /export/myscripts/test.js ResourceOperationSchedule: resource: Resource[id=10008, uuid=e11390ec-34c4-49df-a4b6-c37c516f545c, type={RHQAgent}RHQ Agent, key=server.example.com RHQ Agent, name=RHQ Agent, parent=server.example.com, version=3.1.2]
7.3. Retrieving the Results of an Operation
fetchResults(true)
method can be used to return the results of the operation as part of the search for the operation history.
// search for the operation var c = new ResourceOperationHistoryCriteria() c.addFilterId(schedule.id) c.fetchResults(true) var r = OperationManager.findResourceOperationHistoriesByCriteria(c) // get the operation data var h = r.get(0); // get the results var c = h.getResults(); c
Example 18. Printing the Results of a Process Scan
if (args.length != 1) { throw "we need a resource id as an argument"; } var platform = ResourceManager.getResource(args[0]);
var ros = OperationManager.scheduleResourceOperation( platform.id, "viewProcessList", 0, 1, 0, 15, null, "test operation" );
fetchResults(true)
, which is required to include the operation result data and not just the status- a sort method, in this case
addSortStartTime
var opcrit = ResourceOperationHistoryCriteria(); opcrit.addFilterResourceIds(platform.id); opcrit.fetchResults(true); // request the additional optional data in the result opcrit.addSortStartTime(PageOrdering.DESC); // sort by start time java.lang.Thread.sleep(1000); // wait a second to make sure operation is in the history // wait for up to 15 seconds for last operation to complete, then print result now=new Date().getTime(); while (new Date().getTime() - now < 15000 ) { operations = OperationManager.findResourceOperationHistoriesByCriteria(opcrit); if (operations.get(0).getResults() == null) { println("operation still pending result"); java.lang.Thread.sleep(1000); } else { pretty.print(operations.get(0).getResults()); break; } } if (operations.get(0).getErrorMessage() != null) { println("Error getting process list: "); pretty.print(operations.get(0).getErrorMessage()); }
} else { pretty.print(operations.get(0).getResults()); break; }
7.4. Checking a Resource's Operations History
Example 19. Viewing the Operation History
// find the resource var rc = ResourceCriteria(); rc.addFilterPluginName("RHQAgent"); rc.addFilterName("RHQ Agent"); rc.addFilterResourceTypeName("RHQ Agent"); rc.addFilterDescription("Agent"); var agent = ResourceManager.findResourcesByCriteria(rc); // print the operation history for the resource var opcrit = ResourceOperationHistoryCriteria() opcrit.addFilterResourceIds(agent.get(0).id) OperationManager.findResourceOperationHistoriesByCriteria(opcrit);
Configuration
objects in the results table.
rhqadmin@localhost:7080$ exec -f /export/myscripts/test.js resource results ----------------------------------------------------------------------------------------------------------------- Resource[id=10008, uuid=e11390ec-34c4-49df-a4b6-c37c516f545c, type={RHQAgent}RHQ Agent, key=server.example.com RHQ Age Configuration[id=13903] Resource[id=10008, uuid=e11390ec-34c4-49df-a4b6-c37c516f545c, type={RHQAgent}RHQ Agent, key=server.example.com RHQ Age Configuration[id=13913] 2 rows
8. Monitoring
8.1. Getting Resource Availability
- Search for the resource. In this case, the script just looks for any resource which matches the resource type (Linux platform), and uses the first match for the availability scan.
- Get the current availability status.
Example 20. Current Availability
// get the resource ID criteria = new ResourceCriteria(); criteria.addFilterResourceTypeName('Linux') var res = ResourceManager.findResourcesByCriteria(criteria); // check the current availability AvailabilityManager.getCurrentAvailabilityForResource(res.get(0).id)
rhqadmin@localhost:7080$ exec -f /export/myscripts/test.js Availability: availabilityType: UP endTime: id: 10192 resource: Resource[id=10001, uuid=null, type=<null>, key=null, name=null, parent=<null>] startTime: 1335974397214
8.2. Getting Specific Metrics
findLiveData
method is a way to pull in the current, un-average, live reading of a given metric.
- Search for the available metric definitions, based on the resource type and then filtered to a single metric. This example grabs the free memory metric for the Linux platform.
- Search for the resource.
- Get the current reading for the metric.
- Print the data to the terminal.
Example 21. Annotated Example
// search for the resource criteria = new ResourceCriteria(); criteria.addFilterResourceTypeName('Linux'); var resources = ResourceManager.findResourcesByCriteria(criteria); // search for the resource type to use in the metrics definition var rt = ResourceTypeManager.getResourceTypeByNameAndPlugin("Linux", "Platforms"); // search for the metric definition var mdc = MeasurementDefinitionCriteria(); mdc.addFilterDisplayName("Free Memory"); mdc.addFilterResourceTypeId(rt.id); var mdefs = MeasurementDefinitionManager.findMeasurementDefinitionsByCriteria(mdc); //get the data var metrics = MeasurementDataManager.findLiveData(resources.get(0).id, [mdefs.get(0).id]); // as a nice little display, print the retrieved metrics value if( metrics !=null ) { println(" Metric value for " + resources.get(0).id + " is " + metrics ); }
rhqadmin@localhost:7080$ exec -f /export/myscripts/test.js Metric value for 10001 is [MeasurementDataNumeric[value=[6.3932239872E10], MeasurementData [MeasurementDataPK: timestamp=[Tue May 08 20:10:15 EDT 2012], scheduleId=[10002]]]]
8.3. Exporting Metric Data for a Resource
- Search for the available metric definitions, based on the resource type. In this example, it is for the Linux platform.
- Search for the resource.
- Set a date range for the metric information. This is configured in seconds, relative to the time the script is run.
- Set up the file information to which to write the data.
- Iterate through all the metric definitions for the resource, and print the data to the given CSV file.
Example 22. Exporting All Metrics Definitions for a Linux Server
// search for the available metrics definitions var rt = ResourceTypeManager.getResourceTypeByNameAndPlugin("Linux","Platforms") var mdc = MeasurementDefinitionCriteria(); mdc.addFilterResourceTypeId(rt.id); var mdefs = MeasurementDefinitionManager.findMeasurementDefinitionsByCriteria(mdc); // search for the resource criteria = new ResourceCriteria(); criteria.addFilterResourceTypeName('Linux') var resources = ResourceManager.findResourcesByCriteria(criteria); // give the date range for the metrics collection // this is in seconds var start = new Date() - 8* 3600 * 1000; var end = new Date() // setup up the CSV to dump the data to exporter.file = '/opt/myfile.csv' exporter.format = 'csv' // iterate through the metrics definitions for the resource // and export all the collected metrics for all definitions // within the given date range if( mdefs != null ) { if( mdefs.size() > 1 ) { for( i =0; i < mdefs.size(); ++i) { mdef = mdefs.get(i); var data = MeasurementDataManager.findDataForResource(resources.get(0).id,[mdef.id],start,end,"") exporter.write(data.get(0)); // write the data to the CSV file } } else if( mdefs.size() == 1 ) { mdef = mdefs.get(0); var data = MeasurementDataManager.findDataForResource(resources.get(0).id,[mdef.get(0).id],start,end,60) exporter.write(data.get(0)) } }
8.4. Getting Baseline Calculations
rhqadmin@localhost:7080$ MeasurementBaselineManager.findBaselinesForResource(10001) one row MeasurementBaseline: computeTime: Tue May 08 21:28:05 EDT 2012 id: 10001 max: 6.4005419008E10 mean: 6.3933904981333336E10 min: 6.380064768E10 schedule: [MeasurementSchedule, id=10002] userEntered: true
9. Alerts
9.1. Using Alerts with Scripts
alert
method identifies the alert definition, it identifies the resource which triggered the alert. This allows you to create a reusable proxy resource definition in the script that could be applied to any resource which uses that alert script.
var myResource = ProxyFactory.getResource(alert.alertDefinition.resource.id)
Note
9.2. Acknowledging Alerts
- Search for fired alerts; in this case, the search is based on the resource type (Linux).
- Retrieve the data for the search results.
- Acknowledge all returned alerts.
Example 23. Acknowledging Alerts for Platform Resources
// set the criteria and search for the alerts var criteria = new AlertCriteria() criteria.addFilterResourceTypeName('Linux') var alerts = AlertManager.findAlertsByCriteria(criteria) // go through the results and then acknowledge the alerts if( alerts != null ) { if( alerts.size() > 1 ) { for( i =0; i < alerts.size(); ++i) { alert = alerts.get(i); AlertManager.acknowledgeAlerts([alert.id]) } } else if( alerts.size() == 1 ) { alert = alerts.get(0); AlertManager.acknowledgeAlerts([alert.id]) } }
9.3. Enabling or Disabling Alert Definitions
- Search for matching alert definitions based on priority (low, in this case).
- Retrieve the data for the search results.
- Disable all returned alert definitions, based on the IDs in the retrieved search list.
Example 24. Disabling Alerts Based on Priority
// set the search criteria for the alert definitions with a reasonable filter var criteria = new AlertDefinitionCriteria() criteria.addFilterPriority(AlertPriority.LOW) //search for the alert definitions alertdefs = AlertDefinitionManager.findAlertDefinitionsByCriteria(criteria) //get the data from the results alertdef = alertdefs.get(0); println(" alert: " + alertdef.id ); //disable the matching alerts, based on ID AlertDefinitionManager.disableAlertDefinitions([alertdef.id]);
10. Users and Roles
10.1. Creating Roles
- Create a role and assigning the appropriate permissions. In this case, the role has manage inventory and view user permissions.
- Search for the group to add as a member.
- Search for the new role entry.
- Add the group to the role.
Example 25. A New Role
// create the role var role = Role('Role Name - ' + java.util.Date()); role.description = 'This role is an example'; role.addPermission(Permission.MANAGE_INVENTORY); role.addPermission(Permission.VIEW_USERS); RoleManager.createRole(role); //search for the group to add to the role groupcriteria = new ResourceGroupCriteria(); groupcriteria.addFilterGroupCategory.toString('MIXED'); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupcriteria); //search for the new role var c = new RoleCriteria(); c.addFilterName('Role Name'); var roles = RoleManager.findRolesByCriteria( c ); RoleManager.addResourceGroupsToRole(roles.get(0).id,[groups.get(0).id]);
10.2. Creating Users
- Create a new user (subject) entry.
- Create a principal for the new user.
- Search for roles to add the user to and create an array.
- Add the user to the roles.
Example 26. Creatting a User and Adding Roles
//create the new user entry var newSubject = new Subject(); newSubject.setEmailAddress( 'admin@example.com' ); newSubject.setFirstName('John'); newSubject.setLastName('Smith' ); newSubject.setFactive(true); newSubject.setFsystem(false); newSubject.setName('jsmith'); var s = SubjectManager.createSubject(newSubject); //create the login principal for the user SubjectManager.createPrincipal( s.name, 'password' ); //search for the role and create an array var c = new RoleCriteria(); c.addFilterName('Role Name'); var roles = RoleManager.findRolesByCriteria( c ); var role = roles.get(0); var rolesArray = new Array(1); rolesArray[0] = role.getId(); //add the new user to the roles in the array RoleManager.addRolesToSubject(s.getId(), rolesArray );
Part III. Extended Examples and Use Scenarios
Example Workflows
1. Example: Scripts to Manage Inventory (All Resource Types)
1.1. Automatically Import New Resources: autoimport.js
NEW
. That's an in-between state, because JBoss ON is aware that the resource exists, but the resource has not been committed so JBoss ON can't manage it.
- It identifies new resources using the
findUncommittedResources()
method. - It gets those new resources' IDs.
- It then imports those resources by invoking the discovery system's import operation.
//Usage: autoImport.js //Description: Imports all auto-discovered inventory into JON // autoImport.js rhq.login('rhqadmin', 'rhqadmin'); println("Running autoImport.js"); var resources = findUncommittedResources(); var resourceIds = getIds(resources); DiscoveryBoss.importResources(resourceIds); rhq.logout();
importResources
. The other two functions — findUncommittedResources
and getIds
— have to be defined in the script.
ResourceCriteria
search by adding a search parameter based on the inventory status.
// returns a java.util.List of Resource objects // that have not yet been committed into inventory function findUncommittedResources() { var criteria = ResourceCriteria(); criteria.addFilterInventoryStatus(InventoryStatus.NEW); return ResourceManager.findResourcesByCriteria(criteria); }
// returns an array of ids for a given list // of Resource objects. Note the resources argument // can actually be any Collection that contains // elements having an id property. function getIds(resources) { var ids = []; if (resources.size() > 0) { println("Found resources to import: "); for (i = 0; i < resources.size(); i++) { resource = resources.get(i); ids[i] = resource.id; println(" " + resource.name); } } else { println("No resources found awaiting import..."); } return ids; }
1.2. Simple Inventory Count: inventoryCount.js
*Criteria
classes; for resources, this is ResourceCriteria
. A search can be very specific, passing criteria so that it returns only one resource or a small subset of resource. It is also possible to return everything in inventory.
ResourceCriteria()
), so that every resource matches the search. It then takes the size of the results to produce a simple inventory count.
// inventory.js rhq.login('rhqadmin', 'rhqadmin'); var resources = ResourceManager.findResourcesByCriteria(ResourceCriteria()); println('There are ' + resources.size() + ' resources in inventory'); // end script
1.3. Uninventory a Resource After an Alert: uninventory.js
uninventoryResource
method:
List<Integer> uninventoryResources(Subject subject, int[] resourceIds);
Note
2. Example: Scripts to Manage Resources of a Specific Type
- Search for new, uncommitted resources of a specific type.
- Get the resource IDs.
- Import those new resources.
- Do something with the newly-imported resources.
autoimport.js
example in Section 1.1, “Automatically Import New Resources: autoimport.js”, with one significant change. The search has an extra filter for the resource type.
ResourceCriteria
search by adding a search parameter based on the inventory status and the resource type (in this example, JBoss EAP 6 domain deployments, for new web applications). The new findUncommittedJbasApps()
function runs that search.
function findUncommittedJbasApps() { var criteria = ResourceCriteria(); criteria.addFilterInventoryStatus(InventoryStatus.NEW); criteria.addFilterResourceTypeName('DomainDeployment'); return ResourceManager.findResourcesByCriteria(criteria); }
autoimport.js
example, a getIds
function retrieves an array of the resource IDs.
function getIds(resources) { var ids = []; if (resources.size() > 0) { println("Found resources to import: "); for (i = 0; i < resources.size(); i++) { resource = resources.get(i); ids[i] = resource.id; println(" " + resource.name); } } else { println("No resources found awaiting import..."); } return ids; }
DiscoveryBoss
method to import the discovered resources.
autoimport.js
, with the slight adjustment to the new function to search for JBoss EAP 6 domain deployments.
rhq.login('rhqadmin', 'rhqadmin'); println("Running autoImport.js"); var resources = findUncommittedJbasApps(); var resourceIds = getIds(resources); DiscoveryBoss.importResources(resourceIds);
var config = new Configuration(); config.put(new PropertySimple("server-group", "Staging-Server-Group") ); OperationManager.scheduleResourceOperation( resources.get(0).id, "promote", 0, // 0 means that the delay was skipped 1, 0, // this skips the repeat count 10000000, config, "promote new app to server group" );
ResourceGroupManager.addResourcesToGroup(15001, [resourceIds]);
rhq.logout();
3. Example: Scripting Resource Deployments (JBoss EAP 5)
- Find all JBoss EAP instances for a specified JBoss ON group.
- Shut down each EAP instance.
- Update binaries for existing deployed applications or create new deployments.
- Restart the EAP instance.
- End the loop.
3.1. Declaring Custom Functions
function usage() { println("Usage: deployToGroup <fileName> <groupName>"); throw "Illegal arguments"; } function PackageParser(fullPathName) { var file = new java.io.File(fullPathName); var fileName = file.getName(); var packageType = fileName.substring(fileName.lastIndexOf('.')+1); var tmp = fileName.substring(0, fileName.lastIndexOf('.')); var realName = tmp.substring(0, tmp.lastIndexOf('-')); var version = tmp.substring(tmp.lastIndexOf('-') + 1); var packageName = realName + "." + packageType; this.packageType = packageType.toLowerCase(); this.packageName = packageName; this.version = version; this.realName = realName; }
3.2. Checking the JBoss ON Groups and Inventory
if( args.length < 2 ) usage(); var fileName = args[0]; var groupName = args[1];
// check that the file exists and that we can read it var file = new java.io.File(fileName); if( !file.exists() ) { println(fileName + " does not exist!"); usage(); } if( !file.canRead() ) { println(fileName + " can't be read!"); usage(); }
// find resource group var rgc = new ResourceGroupCriteria(); rgc.addFilterName(groupName); rgc.fetchExplicitResources(true); var groupList = ResourceGroupManager.findResourceGroupsByCriteria(rgc);
rgc.fetchExplicitResources(true);
if( groupList == null || groupList.size() != 1 ) { println("Can't find a resource group named " + groupName); usage(); } var group = groupList.get(0); println(" Found group: " + group.name ); println(" Group ID : " + group.id ); println(" Description: " + group.description);
if( group.explicitResources == null || group.explicitResources.size() == 0 ) { println(" Group does not contain explicit resources --> exiting!" ); usage(); } var resourcesArray = group.explicitResources.toArray();
resourceArray
now contains all resources which are part of the group. Next, check if there are JBoss AS 5 Server instances which need to be restarted before the application is deployed.
for( i in resourcesArray ) { var res = resourcesArray[i]; var resType = res.resourceType.name; println(" Found resource " + res.name + " of type " + resType + " and ID " + res.id); if( resType != "JBossAS5 Server") { println(" ---> Resource not of required type. Exiting!"); usage(); } // get server resource to start/stop it and to redeploy application var server = ProxyFactory.getResource(res.id); }
server
contains the JBoss AS 5 instance. This requires re-reading the server because it needs to be fully populated. Internally, the CLI is using simple JPA persistence, and it is necessary to not always fetch all dependent objects.
var children = server.children; for( c in children ) { var child = children[c]; if( child.name == packageName ) { } }
packageName
is the name of the application without version information and path as shown in the JBoss ON GUI as deployed applications.
println(" download old app to /tmp"); child.retrieveBackingContent("/tmp/" + packageName + "_" + server.name + "_old");
/tmp/
directory.
println(" stopping " + server.name + "...."); try { server.shutDown(); } catch( ex ) { println(" --> Caught " + ex ); } println(" uploading new application code"); child.updateBackingContent(fileName); println(" restarting " + server.name + "....." ); try { server.start(); } catch( ex ) { println(" --> Caught " + ex ); }
3.3. Deploying the New Resource
- The type of the application (e.g., WAR or EAR)
- The type of the container the app needs to be deployed on (such as Tomcat or JBoss AS 5)
Note
rhq-plugin.xml
descriptor. The attributes, configuration parameters, operations, and metrics for each default resource type are listed in the Resource Monitoring and Operations Reference.
var appType = ResourceTypeManager.getResourceTypeByNameAndPlugin( appTypeName, "JBossAS5" ); if( appType == null ) { println(" Could not find application type. Exit."); usage(); }
var realPackageType = ContentManager.findPackageTypes( appTypeName, "JBossAS5" ); if( realPackageType == null ) { println(" Could not find JBoss ON's packageType. Exit."); usage(); }
rhq-plugin.xml
descriptor. To be able to create a new resource, these parameters need to be filled in.
// create deployConfig var deployConfig = new Configuration(); deployConfig.put( new PropertySimple("deployExploded", "false")); deployConfig.put( new PropertySimple("deployFarmed", "false"));
var deployConfigDef = ConfigurationManager.getPackageTypeConfigurationDefinition(realPackageType.getId());
var inputStream = new java.io.FileInputStream(file); var fileLength = file.length(); var fileBytes = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, fileLength); for (numRead=0, offset=0; ((numRead >= 0) && (offset < fileBytes.length)); offset += numRead ) { numRead = inputStream.read(fileBytes, offset, fileBytes.length - offset); }
rhq-plugin.xml
descriptor. For example:
ResourceFactoryManager.createPackageBackedResource( server.id, appType.id, packageName, null, // pluginConfiguration packageName, packageVersion, null, // architectureId deployConfig, fileBytes, null // timeout );
4. Example: Deploying an Application with Bundles (JBoss EAP 4, 5, and 6)
deploy-to-and-restart-JBAS.js
script in the cliRoot/rhq-remoting-cli-3.1.2.GA/samples
directory defines a set of custom functions that quickly create a bundle version and definition and then deploy it to the given JBoss servers.
4.1. Creating a New Application
deploy-to-and-restart-JBAS.js
script requires the util.js
and bundles.js
scripts for supporting functions. This is easiest to do when running the CLI interactively, because all of the scripts can be loaded using the exec
command.
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/util.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/bundles.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/deploy-to-and-restart-JBAS.js
deploy-to-and-restart-JBAS.js
script defines a function called createAppAndRestartJBAS
that creates and then deploys a bundle. The function takes seven parameters:
- The path to the bundle archive file.
- A configuration object that contains any tokens or variables required for the bundle configuration. In this example, no properties are passed, so the value is null. Details about the configuration are in the comments in the
bundles.js
file and general configuration information is in Section 6.2, “Changing Simple Configuration Properties”. - The name of the compatible group to which to deploy the bundle.
- A name of the bundle destination.
- A description for the bundle destination.
- The base directory to which to deploy the bundle and, optionally, a subdirectory to deploy the bundle to.
rhqadmin@localhost:7080$ var bundleZipFile = /export/bundles/myBundle.zip rhqadmin@localhost:7080$ var deploymentConfiguration = null rhqadmin@localhost:7080$ var groupName = "JBoss EAP 6 Group" rhqadmin@localhost:7080$ var destinationName = "My App - JBoss EAP 6 Destination" rhqadmin@localhost:7080$ var destinationDescription = "For my application" rhqadmin@localhost:7080$ var baseDirName = "Install Directory" rhqadmin@localhost:7080$ var deployDir = "deploy" rhqadmin@localhost:7080$ createAppAndRestartJBAS(bundleZipFile, deploymentConfiguration, groupName, destinationName, destinationDescription, baseDirName, deployDir)
deploy-to-and-restart-JBAS.js
script which provide support to the createAppAndRestartJBAS
function. Those are explained in the comments in the deploy-to-and-restart-JBAS.js
file.
Note
Install Directory
or Profile Directory
. Those two locations are then identified based on the connection information for the specified JBoss EAP resource which is accessed by the script.
createAppAndRestartJBAS
function has three parts: finding the resource group, creating the bundle, and restarting the JBoss servers in the group.
function createAppAndRestartJBAS(bundleZipFile, deploymentConfiguration, groupName, destinationName, destinationDescription, baseDirName, deployDir) { var gcrit = new ResourceGroupCriteria; gcrit.addFilterName(groupName); gcrit.fetchResourceType(true); var groups = ResourceGroupManager.findResourceGroupsByCriteria(gcrit); if (groups.empty) { throw "Could not find a resource group called " + groupName; } else if (groups.size() > 1) { throw "There are more than 1 groups called " + groupName; } var group = groups.get(0); var targetResourceType = group.resourceType;
var deployFn = function(restartFn) {
var bundleVersion = createBundleVersion(bundleZipFile);
var destination = BundleManager.createBundleDestination(bundleVersion.bundle.id, destinationName, destinationDescription, baseDirName, deployDir, group.id);
var deployment = deployBundle(destination,bundleVersion, deploymentConfiguration, "Web application", false); if (deployment.status != BundleDeploymentStatus.SUCCESS) { throw "Deployment wasn't successful: " + deployment; }
deploy-to-and-restart-JBAS.js
script) and restarts each resource. It then prints the deployment information.
restartFn(group); return deployment; };
deploy-to-and-restart-JBAS.js
script can deploy content to any supported version of JBoss EAP: 4, 5, or 6. The bundle system uses the configuration defined in the resource plug-in, based on the resource type of the group. For the restart operation, different restart function are defined for each version of JBoss EAP.
if (targetResourceType.plugin == "JBossAS" && targetResourceType.name == "JBossAS Server") { return deployFn(_restartAS4); } else if (targetResourceType.plugin == "JBossAS5" && targetResourceType.name == "JBossAS Server") { return deployFn(_restartAS5); } else if (targetResourceType.plugin == "JBossAS7" && (targetResourceType.name == "JBossAS7 Standalone Server" || targetResourceType.name == "JBossAS-Managed")) { return deployFn(_restartAS7); } throw "The resource group the destination targets doesn't seem to be a JBoss AS server group."; }
4.2. Updating Applications
util.js
, bundles.js
, and deploy-to-and-restart-JBAS.js
— need to be loaded using the exec
command.
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/util.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/bundles.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/deploy-to-and-restart-JBAS.js
rhqadmin@localhost:7080$ var bundleZipFile = /export/bundles/myBundle.zip rhqadmin@localhost:7080$ var deploymentConfiguration = null rhqadmin@localhost:7080$ var jbasDestination = "My App - JBoss EAP 6 Destination" rhqadmin@localhost:7080$ updateAppAndRestartJBAS(bundleZipFile, jbasDestination, deploymentConfiguration)
bundles.js
file and general configuration information is in Section 6.2, “Changing Simple Configuration Properties”.
function updateAppAndRestartJBAS(bundleZipFile, jbasDestination, deploymentConfiguration) { // first figure out the jbas version we are deploying to var destinationId = jbasDestination; if (typeof(jbasDestination) == 'object') { destinationId = jbasDestination.id; } var destCrit = new BundleDestinationCriteria destCrit.fetchGroup(true)
get(0)
call), the destination configuration contains the resource type.
var destinations = BundleManager.findBundleDestinationsByCriteria(destCrit); if (destinations.empty) { throw "No destinations corresponding to " + jbasDestination + " found on the server."; } var destination = destinations.get(0); var targetResourceType = destination.group.resourceType; if (targetResourceType == null) { throw "This function expects a compatible group of JBoss AS (4,5,6 or 7) resources but the provided destination is connected with " + destination.group; }
createBundleVersion
method.
var deployFn = function(restartFn) { var bundleVersion = createBundleVersion(bundleZipFile);
var deployment = deployBundle(destination,bundleVersion, deploymentConfiguration, "Web application", false); if (deployment.status != BundleDeploymentStatus.SUCCESS) { throw "Deployment wasn't successful: " + deployment; } restartFn(destination.group); return deployment; };
if (targetResourceType.plugin == "JBossAS" && targetResourceType.name == "JBossAS Server") { return deployFn(_restartAS4); } else if (targetResourceType.plugin == "JBossAS5" && targetResourceType.name == "JBossAS Server") { return deployFn(_restartAS5); } else if (targetResourceType.plugin == "JBossAS7" && (targetResourceType.name == "JBossAS7 Standalone Server" || targetResourceType.name == "JBossAS-Managed")) { return deployFn(_restartAS7); } throw "The resource group the destination targets doesn't seem to be a JBoss AS server group."; }
5. Example: JNDI Lookups After an Alert (JBoss EAP 5)
Important
-f
parameter or through a server-side alert script. This cannot be run using the interactive CLI.
assertNotNull
method to get the JMX object. The script then prints the JMX information.
//This test requires a remote JBoss AS 5 server running with JNDI directory remotely accessible using JNP (without authz) //This script assumes that there is a bound object called "jmx" in the directory (which it should be) var jbossHost = 'localhost'; var jbossJnpPort = 1299; var env = new java.util.Hashtable(); env.put('java.naming.factory.initial', 'org.jboss.naming.NamingContextFactory'); env.put('java.naming.provider.url', "jnp://" + jbossHost + ":" + jbossJnpPort); var ctx = new javax.naming.InitialContext(env); var jmx = ctx.lookup('jmx'); assertNotNull(jmx); pretty.print(jmx);
6. Example: Managing Grouped Servers (JBoss EAP 5)
Note
6.1. The Plan for the Scripts
-f
parameter. The idea here is to create a series of small management scripts that perform specific tasks on a group of JBoss EAP servers. This example has seven scripts for:
- Creating a group
- Adding EAP instances to the group
- Checking EAP status
- Starting the EAP instance
- Scheduling an operation
- Deploying new content to the group
- Checking metrics
6.2. Creating the Wrapper Script and .conf File
- The wrapper script is run as a regular user, which means that any JavaScript files must be accessible to a regular user.
- The scripts are located in a
scripts/
directory that is in the same directory as the wrapper script. - A separate configuration file defines connection information for the JBoss ON server.
- Each JavaScript file is invoked by a separate CLI command invocation, defined in the wrapper.
- Any options or information required by the JBoss ON CLI command is defined in the JavaScript file and can, potentially, be passed with the wrapper script as an option.
#!/bin/bash # # groupcontrol # ------------ # This is a simple wrapper script for all the java script scripts in this folder. # Start this script with some parameters to automate group handling from within the # command line. # # With groupcontrol you can do the following: # create : Create a new group # addMember: Add a new EAP instance to the specified group # status : Print the status of all resources of a group # start : start all EAP instances specified by group name # deploy : Deploys an application to all AS instances specified by group name # avail : Runs an availability operation on all discovered agent instances # metrics : Gets the specified metric value for all AS instances specified by group name # # ## Should not be run as root. if [ "$EUID" = "0" ]; then echo " Please use a normal user account and not the root account" exit 1 fi ## Figure out script home MY_HOME=$(cd `dirname $0` && pwd) SCRIPT_HOME=$MY_HOME/scripts ## Source some defaults . $MY_HOME/groupcontrol.conf ## Check to see if we have a valid CLI home if [ ! -d ${JON_CLI_HOME} ]; then echo "JON_CLI_HOME not correctly set. Please do so in the file" echo $MY_HOME/groupcontrol.conf exit 1 fi RHQ_OPTS="-s $JON_HOST -u $JON_USER -t $JON_PORT" # If JBoss ON_PWD is given then use it as argument. Else let the user enter the password if [ "x$JON_PWD" == "x" ]; then RHQ_OPTS="$RHQ_OPTS -P" else RHQ_OPTS="$RHQ_OPTS -p $JON_PWD" fi #echo "Calling groupcontrol with $RHQ_OPTS" usage() { echo " Usage $0:" echo " Use this tool to control most group related tasks with a simple script." echo " ------------------------------------------------------------------------- " }
do
Command()
section which defines the JBoss ON CLI command to run and the JavaScript file to use.
doDeploy() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/deploy.js $2 $3 } doCreate() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/group.js $2 } doAddMember() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/addMember.js $2 $3 $4 } doStatus() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/status.js $2 } doRestart() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/restart.js $2 } doAvail() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/avail.js } doMetrics() { $JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/metrics.js $2 $3 } case "$1" in 'deploy') doDeploy $* ;; 'create') doCreate $* ;; 'addMember') doAddMember $* ;; 'status') doStatus $* ;; 'restart') doRestart $* ;; 'avail') doAvail $* ;; 'metrics') doMetrics $* ;; *) usage $* ;; esac
groupcontrol.conf
, which defines the connection information to connect to the JBoss ON server (which is required by the JBoss ON CLI).
## ## This file contains some defaults for the groupcontrol script ## JON_CLI_HOME=cliRoot/rhq-remoting-cli-3.1.2.GA JON_HOST=localhost JON_PORT=7080 # The user you want to connect with JON_USER=rhqadmin # if you omit the password here, you'll be prompted for it. JON_PWD=rhqadmin
6.3. Defining Arguments and Other Parameters for the CLI Scripts
args
methods. At a minimum, each script should accept the name of the group on which to perform the task.
usage
function, so that each command can print what options are expected. For example:
function usage() { println("Usage: deploy groupName"); throw "Illegal arguments"; } if( args.length < 1 ) usage(); var groupName = args[0];
Note
$2 $3
.
doDeploy() {
$JON_CLI_HOME/bin/rhq-cli.sh $RHQ_OPTS -f $SCRIPT_HOME/deploy.js $2 $3
}
groupcriteria = new ResourceGroupCriteria(); groupcriteria.addFilterName(groupName); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupcriteria); if( groups != null ) { if( groups.size() > 1 ) { println("Found more than one group."); } else if( groups.size() == 1 ) { group = groups.get(0); } }
6.4. Creating a Group: group.js
function usage() { println("Usage: deploy groupName"); throw "Illegal arguments"; } if( args.length < 1 ) usage(); var groupName = args[0];
var rg = new ResourceGroup(resType); rg.setRecursive(false); rg.setDescription("Created via groupcontrol scripts on " + new java.util.Date().toString()); rg.setName(groupName); rg = ResourceGroupManager.createResourceGroup(rg); var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin("JBossAS 5 Server","JBossAS5");
6.5. Adding Resources to a Group: addMember.js
- groupName for the group to add the resources to
- resourceName for the name of the resource to add; this is one of the search criteria
- resourceTypeName for the type of resource to add; this is one of the search criteria
function usage() { println("Usage: addMember groupName resourceName resourceTypeName"); throw "Illegal arguments"; } if( args.length < 3 ) usage(); var groupName = args[0]; var resourceName = args[1]; var resourceTypeName = args[2]; groupcriteria = new ResourceGroupCriteria(); groupcriteria.addFilterName(groupName); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupcriteria); if( groups != null ) { if( groups.size() > 1 ) { println("Found more than one group."); } else if( groups.size() == 1 ) { group = groups.get(0); } }
criteria = new ResourceCriteria(); criteria.addFilterName(resourceName); criteria.addFilterResourceTypeName(resourceTypeName); var resources = ResourceManager.findResourcesByCriteria(criteria); if( resources != null ) { if( resources.size() > 1 ) { println("Found more than one JBossAS Server instance. Try to specialize."); for( i =0; i < resources.size(); ++i) { var resource = resources.get(i); println(" found " + resource.name ); } } else if( resources.size() == 1 ) { resource = resources.get(0); println("Found one JBossAS Server instance. Trying to add it."); println(" " + resource.name ); ResourceGroupManager.addResourcesToGroup(group.id, [resource.id]); println(" Added to " + group.name + "!"); } else { println("Did not find any JBossAS Server instance matching your pattern. Try again."); } }
[jsmith@server cli]$ ./wrapper.sh addMember myGroup "JBossAS App 1" "JBossAS Server" Remote server version is: 3.0.1.GA (b2cb23b:859b914) Login successful Found one JBossAS Server instance. Trying to add it. AS server.example.com JBossAS App 1 Added to myGroup!
6.6. Getting Inventory and Status Information: status.js
function usage() { println("Usage: status groupName"); throw "Illegal arguments"; } if( args.length < 1 ) usage(); var groupName = args[0]; groupcriteria = new ResourceGroupCriteria(); groupcriteria.addFilterName(groupName); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupcriteria); if( groups != null ) { if( groups.size() > 1 ) { println("Found more than one group."); } else if( groups.size() == 1 ) { group = groups.get(0); } }
criteria = new ResourceCriteria(); criteria.addFilterExplicitGroupIds(group.id); var resources = ResourceManager.findResourcesByCriteria(criteria); for( i =0; i < resources.size(); ++i) { var resource = resources.get(i); println(" found " + resource.name ); }
var server = ProxyFactory.getResource(resource.id); var avail = AvailabilityManager.getCurrentAvailabilityForResource(server.id); println(" " + server.name ); println(" - Availability: " + avail.availabilityType.getName()); println(" - Started : " + avail.startTime.toGMTString()); println(""); var avail = AvailabilityManager.getCurrentAvailabilityForResource(server.id); if( avail.availabilityType.toString() == "DOWN" ) { println(" Server is DOWN. Please first start the server and run this script again!"); println(""); }
[jsmith@server cli]$ ./wrapper.sh status myGroup Remote server version is: 3.0.1.GA (b2cb23b:859b914) Login successful found AS server.example.com JBossAS App 1 AS server.example.com JBossAS App 1 - Availability: UP - Started : 11 Feb 2012 04:07:37 GMT
6.7. Starting, Stopping, and Restarting the Server: restart.js
shutdown()
for AS4 servers andshutDown()
for AS5 serversstart()
criteria = new ResourceCriteria(); criteria.addFilterExplicitGroupIds(group.id); var resources = ResourceManager.findResourcesByCriteria(criteria); for( i =0; i < resources.size(); ++i) { var resource = resources.get(i); var resType = resource.resourceType.name; println(" found " + resource.name ); if( resType != "JBossAS Server") { println(" ---> Resource not of required type. Exiting!"); usage(); } var server = ProxyFactory.getResource(resource.id); println(" stopping " + server.name + "...."); try { server.shutdown() } catch( ex ) { println(" --> Caught " + ex ); } println(" restarting " + server.name + "....." ); try { server.start(); } catch( ex ) { println(" --> Caught " + ex ); } }
6.8. Deploying Applications to the Group Members: deploy.js
// we need check to see if the given server is up and running var avail = AvailabilityManager.getCurrentAvailabilityForResource(server.id); // unfortunately, we can only proceed with deployment if the server is running. Why? if( avail.availabilityType.toString() == "DOWN" ) { println(" Server is DOWN. Please first start the server and run this script again!"); println(""); continue; }
6.9. Scheduling an Availability Operation: avail.js
println("Scanning all RHQ Agent instances"); var rc = ResourceCriteria(); var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin("RHQ Agent", "RHQAgent"); rc.addFilterPluginName("RHQAgent"); rc.addFilterResourceTypeName("RHQ Agent"); rc.addFilterParentResourceTypeId("10001"); var resources = ResourceManager.findResourcesByCriteria(rc).toArray(); var idx=0; for( i in resources ) { if( resources[i].resourceType.id == resType.id ) { resources[idx] = resources[i]; idx = idx + 1; } }
for( a in resources ) { var agent = resources[a] var resType = agent.resourceType.name; println(" Found resource " + agent.name + " of type " + resType + " and ID " + agent.id); println(" executing availability scan on agent" ); println(" -> " + agent.name + " / " + agent.id); var config = new Configuration(); config.put(new PropertySimple("changesOnly", "true") ); var ros = OperationManager.scheduleResourceOperation( agent.id, "executeAvailabilityScan", 0, 1, 0, 10000000, config, "test from cli" ); println(ros); println(""); }
6.10. Gathering Metric Data of Managed Servers: metrics.js
findLiveData
method, which returns the current active value for the resource.
function usage() { println("Usage: metrics groupName metricName"); throw "Illegal arguments"; } if( args.length < 2 ) usage(); var groupName = args[0]; var metricName = args[1]; groupcriteria = new ResourceGroupCriteria(); groupcriteria.addFilterName(groupName); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupcriteria); if( groups != null ) { if( groups.size() > 1 ) { println("Found more than one group."); } else if( groups.size() == 1 ) { group = groups.get(0); } } criteria = new ResourceCriteria(); criteria.addFilterExplicitGroupIds(group.id);
var rt = ResourceTypeManager.getResourceTypeByNameAndPlugin("JBossAS 5 Server","JBossAS5"); var mdc = MeasurementDefinitionCriteria(); mdc.addFilterDisplayName(metricName); mdc.addFilterResourceTypeId(rt.id); var mdefs = MeasurementDefinitionManager.findMeasurementDefinitionsByCriteria(mdc); var resources = ResourceManager.findResourcesByCriteria(criteria); var metrics = MeasurementDataManager.findLiveData(resources.get(0).id, [mdefs.get(0).id]); if( metrics !=null ) { println(" Metric value for " + resources.get(0).id + " is " + metrics ); }
[jsmith@server cli]$ ./wrapper.sh metrics myGroup "Active Thread Count" Remote server version is: 3.0.1.GA (b2cb23b:859b914) Login successful Metric value for 10003 is [MeasurementDataNumeric[value=[64.0], MeasurementData [MeasurementDataPK: timestamp=[Wed Feb 15 22:14:38 EST 2012], scheduleId=[1]]]]
7. Example: Deploying a Standalone Server to a Cluster (JBoss EAP 6)
/samples
directory the defines a series of functions that allow a JBoss EAP 6 standalone server to be added to an existing cluster.
add-as7-standalone-server-to-cluster.js
file defines some useful functions that simplify identifying cluster servers, deployed content, and relevant configuration settings.
add-as7-standalone-server-to-cluster.js
file, so they are out of the scope of this example. The main purpose of this is example is to review the two public functions which perform two distinct cluster management tasks:
addToCluster
copyDeployments
7.1. Adding a Standalone EAP 6 Server to a Cluster
- An identifying name for the JBoss instance to use within the cluster (the node-name)
- Multicast settings, including the multicast port, a UDP port, and multicast address
- Socket-binding group information used by mod_cluster
addToCluster
function uses to add a standalone server to a cluster. It uses the configuration properties in an existing cluster member and copies them over to the standalone server.
add-as7-standalone-server-to-cluster.js
script to load the function.
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/add-as7-standalone-server-to-cluster.js rhqadmin@localhost:7080$ var newAs7Resource = ProxyFactory.getResource(10381) rhqadmin@localhost:7080$ var existingClusterMemberResource = ProxyFactory.getResource(10577) rhqadmin@localhost:7080$ var newNodeName = jbas7-standalone1 rhqadmin@localhost:7080$ addToCluster(newAs7Resource, newNodeName, existingClusterMemberResource, true)
addToCluster
function makes some assumptions that the cache configuration between the two servers is compatible, both for concrete caches and the cache containers for individual subsystems.
- It checks the plug-in connection properties in the cluster server and compares them to the plug-in connection properties in the standalone server. If necessary, it copies over the plug-in configuration from the cluster server and restarts the standalone server, loading the new configuration.
- It checks the given node name for the standalone server. If necessary, it changes the default node name to the one passed with the function.
- It then compares the socket-binding settings for the cluster and standalone servers. If necessary, it copies over the socket-binding configuration for the jgroups, messaging, and mod_cluster bindings from the cluster server and restarts the standalone server.
- If set, then the script copies the deployments from the cluster server to the standalone server and restarts the standalone server.
_getClusterSignificantConfig
) for the cluster and then for the standalone server.
function addToCluster(newAs7Resource, newNodeName, existingClusterMemberResource, copyDeployments) { println("Reading config of the existing cluster member"); var clusterConfig = _getClusterSignificantConfig(existingClusterMemberResource); println("Reading config of the new member"); var memberConfig = _getClusterSignificantConfig(newAs7Resource); var memberResourceConfiguration = newAs7Resource.resourceConfiguration;
if (memberConfig['config'] != clusterConfig['config']) { println("The configurations of the servers differ.\n" + "The new cluster member's configuration will be changed to match the configuration of the existing member."); //switch to the same configuration var pluginConfig = newAs7Resource.pluginConfiguration; pluginConfig.getSimple('config').setValue(clusterConfig['config']); newAs7Resource.updatePluginConfiguration(pluginConfig); //we need to restart straight away so that we see the changes to the //rest of the configuration caused by the change of current config. println("Restarting the new cluster member to switch it to the new configuration."); newAs7Resource.restart(); //refresh the resource newAs7Resource = ProxyFactory.getResource(newAs7Resource.id); //refresh the cluster specific config after the restart with the new //config memberConfig = _getClusterSignificantConfig(newAs7Resource); memberResourceConfiguration = newAs7Resource.resourceConfiguration; }
//now check what's the node name we see if (memberConfig['node-name'] != newNodeName) { println("Updating the node name of the new cluster member from '" + memberConfig['node-name'] + "' to '" + newNodeName + "'"); _updateNodeName(memberResourceConfiguration, newNodeName); newAs7Resource.updateResourceConfiguration(memberResourceConfiguration); }
//now apply the socket binding changes for jgroups and other cluster //significant subsystems //first find the socket binding group config in the new member for(i in newAs7Resource.children) { var child = newAs7Resource.children[i]; if (child.resourceType.name == 'SocketBindingGroup' && child.resourceType.plugin == 'jboss-as-7') { println("Updating socket bindings of jgroups, messaging and modcluster subsystems"); var portOffset = javascriptString(child.resourceConfiguration.getSimpleValue('port-offset', '0')); var clusterMemberPortOffset = clusterConfig['port-offset']; var newConfig = child.resourceConfiguration.deepCopy(false); _updateSocketBindings(newConfig, portOffset, clusterMemberPortOffset, clusterConfig['jgroups']); _updateSocketBindings(newConfig, portOffset, clusterMemberPortOffset, clusterConfig['messaging']); _updateSocketBindings(newConfig, portOffset, clusterMemberPortOffset, clusterConfig['modcluster']); child.updateResourceConfiguration(newConfig); } } println("Restarting the new member for the new socket bindings to take effect."); newAs7Resource.restart();
if (copyDeployments) { println("Copying the deployments to the new cluster member..."); copyDeployments(existingClusterMemberResource, newAs7Resource); println("Restarting the new cluster member."); newAs7Resource.restart(); } }
7.2. Copying Deployed Applications Between Standalone Servers
addToCluster
function has this as an option when joining a standalone server to a cluster. The copyDeployments
function can copy deployments between any two standalone instances.
add-as7-standalone-server-to-cluster.js
script and then set the source and target resources. For example, in interactive mode:
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/add-as7-standalone-server-to-cluster.js rhqadmin@localhost:7080$ var source = ProxyFactory.getResource(10381) rhqadmin@localhost:7080$ var target = ProxyFactory.getResource(10577) rhqadmin@localhost:7080$ copyDeployments(source, target)
function copyDeployments(sourceAS7, targetAS7) { if (typeof sourceAS7 == 'object') { sourceAS7 = sourceAS7.id; } if (typeof targetAS7 == 'object') { targetAS7 = targetAS7.id; }
copyDeployments
function retrieves each deployment by searching for all of the children of the server that are of a deployment resource type.
var deploymentResourceType = ResourceTypeManager.getResourceTypeByNameAndPlugin('Deployment', 'jboss-as-7'); var deploymentsCrit = new ResourceCriteria; deploymentsCrit.addFilterParentResourceId(sourceAS7); deploymentsCrit.addFilterResourceTypeId(deploymentResourceType.id); var unlimitedPageControl = PageControl.unlimitedInstance; var sourceDeployments = ResourceManager.findResourcesByCriteria(deploymentsCrit); var iterator = sourceDeployments.iterator(); while (iterator.hasNext()) { var deploymentResource = iterator.next(); //get a resource proxy for easy access to configurations, etc. deploymentResource = ProxyFactory.getResource(deploymentResource.id); println("Copying deployment " + deploymentResource.name);
var installedPackage = ContentManager.getBackingPackageForResource(deploymentResource.id); var content = ContentManager.getPackageBytes(deploymentResource.id, installedPackage.id); var runtimeName = deploymentResource.resourceConfiguration.getSimpleValue('runtime-name', deploymentResource.name); var deploymentConfiguration = new Configuration; deploymentConfiguration.put(new PropertySimple('runtimeName', runtimeName)); //so now we have both metadata and the data of the deployment, let's //push a copy of it to the target server var history = ResourceFactoryManager.createPackageBackedResource(targetAS7, deploymentResourceType.id, deploymentResource.name, deploymentResource.pluginConfiguration, installedPackage.packageVersion.generalPackage.name, installedPackage.packageVersion.version, installedPackage.packageVersion.architecture.id, deploymentConfiguration, content, null); while (history.status.name() == 'IN_PROGRESS') { java.lang.Thread.sleep(1000); //the API for checking the create histories is kinda weird.. var histories = ResourceFactoryManager.findCreateChildResourceHistory(targetAS7, null, null, unlimitedPageControl); var hit = histories.iterator(); var found = false; while(hit.hasNext()) { var h = hit.next(); if (h.id == history.id) { history = h; found = true; break; } } if (!found) { throw "The history object for the deployment seems to have disappeared, this is very strange."; } } println("Deployment finished with status: " + history.status.toString() + (history.status.name() == 'SUCCESS' ? "." : (", error message: " + history.errorMessage + "."))); } }
8. Example: Deploying Applications Through Bundles (General)
8.1. Setting up Bundle Versions and Destinations
bundles.js
script in the cliRoot/rhq-remoting-cli-3.1.2.GA/samples
directory defines a set of custom functions that quickly create a bundle version and definition.
bundles.js
script also requires the util.js
script. This is easiest to do when running the CLI interactively, because all of the scripts can be loaded using the exec
command.
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/util.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/bundles.js
rhqadmin@localhost:7080$ var path = '/export/files/myApp.zip' rhqadmin@localhost:7080$ createBundleVersion(path)
createBundleVersion
function in the bundles.js
file uploads the files as a byte array.
function createBundleVersion(pathToBundleZipFile) { var bytes = getFileBytes(pathToBundleZipFile) return BundleManager.createBundleVersionViaByteArray(bytes) }
- A bundle version (which was just created with
createBundleVersion
) - A compatible group
rhqadmin@localhost:7080$ var destinationName = 'New Destination' rhqadmin@localhost:7080$ var description = 'My new example destination' rhqadmin@localhost:7080$ var bundleName = 'myApp' rhqadmin@localhost:7080$ var groupName = 'Linux Group' rhqadmin@localhost:7080$ var baseDirName = '/' rhqadmin@localhost:7080$ var deployDir = 'var/www/html/' rhqadmin@localhost:7080$ createBundleDestination(destinationName, description, bundleName, groupName, baseDirName, deployDir)
createBundleDestination
function runs the searches for the group and the bundle based on the specified names, which makes it possible to set up the destination without having to run additional searches.
function createBundleDestination(destinationName, description, bundleName, groupName, baseDirName, deployDir) { var groupCrit = new ResourceGroupCriteria; groupCrit.addFilterName(groupName); var groups = ResourceGroupManager.findResourceGroupsByCriteria(groupCrit); ... 8< ... var group = groups.get(0); var bundleCrit = new BundleCriteria; bundleCrit.addFilterName(bundleName); var bundles = BundleManager.findBundlesByCriteria(bundleCrit); ... 8< ... }
8.2. Deploying Bundles
bundles.js
file has a function, deployBundle
, which makes this pretty easy, but you need to obtain some information first.
[root@server bin]# ./rhq-cli.sh -u rhqadmin -p rhqadmin rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/util.js rhqadmin@localhost:7080$ exec -f cliRoot/rhq-remoting-cli-3.1.2.GA/samples/bundles.js
rhqadmin@localhost:7080$ var destinationName = "New Destination" rhqadmin@localhost:7080$ var destcrit = new BundleDestinationCriteria() rhqadmin@localhost:7080$ destcrit.addFilterName(destinationName) var dest = BundleManager.findBundleDestinationsByCriteria(destcrit)
rhqadmin@localhost:7080$ var crit = new BundleVersionCriteria() rhqadmin@localhost:7080$ crit.addFilterBundleName(name) rhqadmin@localhost:7080$ var vers = BundleManager.findBundleVersionsByCriteria(crit) rhqadmin@localhost:7080$ if( vers != null ) { \ rhqadmin@localhost:7080$ if( vers.size() > 1 ) { \ rhqadmin@localhost:7080$ for( i =0; i < vers.size(); ++i) { \ rhqadmin@localhost:7080$ ver = vers.get(i); \ rhqadmin@localhost:7080$ println("Version: " + ver.version + " " + "ID: " + ver.id) \ rhqadmin@localhost:7080$ } \ rhqadmin@localhost:7080$ } \ rhqadmin@localhost:7080$ else if( vers.size() == 1 ) { \ rhqadmin@localhost:7080$ ver = vers.get(0); \ rhqadmin@localhost:7080$ println("Version: " + ver.version + + " " + "ID: " + ver.id) \ rhqadmin@localhost:7080$ } \ rhqadmin@localhost:7080$ } Version: 2.0 ID: 10021 Version: 1.0 ID: 10012
bundles.js
file and general configuration information is in Section 6.2, “Changing Simple Configuration Properties”.
rhqadmin@localhost:7080$ deployBundle(dest.get(0).id,10021,null,'my description',true) BundleDeployment: bundleVersion: BundleVersion[id=10021,name=null,version=null] configuration: Configuration[id=15021] ctime: 1337286719259 description: my description destination: BundleDestination[id=10021, bundle=driftBundle, group=Linux Group - Thu May 10 15:10:28 EDT 2012, name=NewDestination] duration: 0 errorMessage: id: 10051 live: true mtime: 1337286719259 name: Deployment [1] of Version [2.0] to [NewDestination] replacedBundleDeploymentId: resourceDeployments: [BundleResourceDeployment: bdd=[BundleDeployment[id=10051, name=Deployment [1] of Version [2.0] to [new-test]]], resource=[Resource[id=10001, uuid=535b3f54-0bd8-4653-bdd3-323ea69b98fd, type={Platforms}Linux, key=gs-dl585g2-01.rhts.eng.bos.redhat.com, name=server.example.com, parent=<null>, version=Linux 2.6.32-220.el6.x86_64]]] status: Failure subjectName: rhqadmin tags:
deployBundle
function runs through a couple of steps to manage the deployment. This uses one of the functions from the util.js
file to convert the deployment configuration (if any is sent) into the proper into a hash.
... 8< ... var deploymentConfig = deploymentConfiguration; if (!(deploymentConfiguration instanceof Configuration)) { deploymentConfig = asConfiguration(deploymentConfiguration); }
... 8< ... var deployment = BundleManager.createBundleDeployment(bundleVersionId, destinationId, description, deploymentConfig); deployment = BundleManager.scheduleBundleDeployment(deployment.id, isCleanDeployment); ... 8< ...
8.3. Reverting a Bundle
bundles.js
file.
scheduleRevertBundleDeployment
. This requires two interesting pieces of information. The first is the destination ID, which can be retrieved with a simple criteria search.
rhqadmin@localhost:7080$ var destinationName = "NewDestination" rhqadmin@localhost:7080$ var destCrit = new BundleDestinationCriteria() rhqadmin@localhost:7080$ destCrit.addFilterName(destinationName) rhqadmin@localhost:7080$ var dest = BundleManager.findBundleDestinationsByCriteria(destCrit)
rhqadmin@localhost:7080$ var depCrit = new BundleDeploymentCriteria() rhqadmin@localhost:7080$ depCrit.addFilterDestinationName(destinationName) rhqadmin@localhost:7080$ var deploy = BundleManager.findBundleDeploymentsByCriteria(depCrit) rhqadmin@localhost:7080$ var dep = deploy.get(0); rhqadmin@localhost:7080$ var description = dep.description;
rhqadmin@localhost:7080$ BundleManager.scheduleRevertBundleDeployment(dest.get(0).id, description, true)
9. Example: Remedying Resource Drift
9.1. The Plan for the Scripts
- First, there is a script to set up drift for a resource. This shell script runs through a series of setup steps at once:
- It creates the drift definition for a resource (through the
driftDef.js
CLI script). - It creates a generic
deploy.xml
recipe, zips the drift directory, and creates a new bundle and bundle deployment (through thecreateBundle.js
CLI script). - After waiting for the initial snapshot, it then pins the snapshot to the definition (through the
snapshot.js
CLI script).
All of those files are generated by the shell script. - An alert definition has to be created through the UI (not the CLI), but it can be configured to use any drift detection as a condition and then to run a server-side script in response. This second script simply deploys the bundle that was made of the pristine base directory and overwrites the drift.
9.2. Setting up the Drift Definition and Preparing the Bundle
[root@server ~]# ./driftBundle.sh
Note
driftBundle.sh
script in this example defines a lot of variables in the script to account for each piece of information.
.conf
or even a set of .conf
files (cf. Section 6.2, “Creating the Wrapper Script and .conf File”), but for simplicity in this example, all of the variables are defined in the driftBundle.sh
script itself.
- The location of the
rhq-cli.sh
script - Any options, such as the username and password, to pass with the CLI command
- The directory to use both to save the generated JavaScript files and to use for the path to JavaScript files
#!/bin/bash # options for the CLI CLI='cliRoot/rhq-remoting-cli-3.1.2.GA/bin/rhq-cli.sh' OPTS=' -u rhqadmin -p rhqadmin' SCRIPTS='/opt'
# set parameters for the drift definition RESTYPE='Linux' RESPLUGIN='Platforms' RESNAME="server.example.com" NAME='example drift' DESC='drift from script' BASEDIR='/opt/drift' BASEDIRTYPE='fileSystem' EXCLUDE='./logs/' PATTERN= MODE='normal' INTERVAL='3600'
driftDef() { cat <<-EOF //set the resource type var resType = ResourceTypeManager.getResourceTypeByNameAndPlugin("$RESTYPE","$RESPLUGIN"); //get the resource to associate with the drift definition rcrit = ResourceCriteria() rcrit.addFilterResourceTypeName("$RESTYPE") rcrit.addFilterName("$RESNAME") var resources = ResourceManager.findResourcesByCriteria(rcrit) var res = resources.get(0)
Note
DriftDefinitionManager
is a wrapper for a Configuration()
object. The CLI script first calls for the default drift template for the given resource type and then creates a definition object based on that template.
//get the default template for the resource type criteria = DriftDefinitionTemplateCriteria() criteria.addFilterResourceTypeId(resType.id) templates = DriftTemplateManager.findTemplatesByCriteria(criteria) template = templates.get(0) //create a new drift definition instance, based on the template definition = template.createDefinition()
//set the drift definition configuration options definition.resource = res definition.name = '$NAME' definition.description = '$DESC' definition.setAttached(false) // this is false so that template changes don't affect the definition // this is set low to trigger an early initial detection run definition.setInterval(30) var basedir = new DriftDefinition.BaseDirectory(DriftConfigurationDefinition.BaseDirValueContext.valueOf('$BASEDIRTYPE'),'$BASEDIR') definition.basedir = basedir // there can be multiple exclude statements made, as desired var f = new Filter("$EXCLUDE", "$PATTERN") // location, pattern definition.addExclude(f) //this defaults to normal, which means that any changes will // trigger an alert. plannedChanges is the other option, which // disables alerting for drift changes. definition.setDriftHandlingMode(DriftConfigurationDefinition.DriftHandlingMode.valueOf('$MODE'))
//apply the new definition to the resource DriftManager.updateDriftDefinition(EntityContext.forResource(res.id),definition) EOF }
Note
bundles.js
sample script. Using those functions makes deploying bundles very easy.
# options for the bundle SAMPLES='cliRoot/rhq-remoting-cli-3.1.2.GA/samples' DESTNAME='drift destination' BUNDLEDESC='bundle to remediate drift' BUNDLENAME='driftBundle' GROUPNAME='Linux Group' ZIP='driftBundle.zip' BVER='1.0' BUNDLE='/opt/bundles/'$ZIP ARCHIVE='/opt/bundles/'$ZIP
deploy.xml
) which is used in the bundle archive.
deploy() { cat << _EOF_ <?xml version="1.0"?> <project name="$BUNDLENAME" default="main" xmlns:rhq="antlib:org.rhq.bundle"> <rhq:bundle name="$BUNDLENAME" version="$BVER" description="$BUNDLEDESC"> <rhq:deployment-unit name="drift" manageRootDir="true"> <rhq:archive name="$ZIP" exploded="true"> </rhq:archive> </rhq:deployment-unit> </rhq:bundle> <target name="main" /> </project> _EOF_ }
bundles.js
sample script already defines all of the functions required to deploy bundles, but it relies on the util.js
sample script. When the CLI is run non-interactively, there is no way to import an external script that another script requires.
bundles.js
and util.js
scripts together, and then appends the calls to create the bundle version and the bundle destination.
createBundle() { cat $SAMPLES/util.js $SAMPLES/bundles.js cat << _EOF_ // set the location of the bundle archive var path = '$BUNDLE' // create the bundle version in JON createBundleVersion(path) // set all of the variables for the bundle destination var destinationName = '$DESTNAME' var description = '$BUNDLEDESC' var bundleName = '$BUNDLENAME' var groupName = '$GROUPNAME' var baseDirName = '$BASEDIR' var deployDir = "." // create the new destinition in JON createBundleDestination(destinationName, description, bundleName, groupName, baseDirName, deployDir) _EOF_ }
Note
snapshot() { cat <<- _EOF_ //find the resource rcrit = ResourceCriteria() rcrit.addFilterResourceTypeName("$RESTYPE") rcrit.addFilterName("$RESNAME") var resources = ResourceManager.findResourcesByCriteria(rcrit) var res = resources.get(0) //find the new drift definition criteria = DriftDefinitionCriteria() criteria.addFilterName('$NAME') criteria.addFilterResourceIds(res.id) def = DriftManager.findDriftDefinitionsByCriteria(criteria) definition = def.get(0) definition.setInterval($INTERVAL) // it is necessary to redefine the complete configuration when you're // resetting the interval or the other values will be overwritten with default // or set to null var basedir = new DriftDefinition.BaseDirectory(DriftConfigurationDefinition.BaseDirValueContext.valueOf('$BASEDIRTYPE'),'$BASEDIR') definition.basedir = basedir definition.name = '$NAME' // there can be multiple exclude statements made, as desired var f = new Filter("$EXCLUDE", "$PATTERN") // location, pattern definition.addExclude(f) DriftManager.updateDriftDefinition(EntityContext.forResource(res.id),definition) // pin to the initial snapshot, which is version 0 // this gets the most recent snapshot if that is the better version to use // snap = DriftManager.getSnapshot(DriftSnapshotRequest(definition.id)) DriftManager.pinSnapshot(definition.id,0) _EOF_ }
zip
commands to create the bundle archive. The second is a sleep
command which pauses the script to give the JBoss ON agent time to collect the initial snapshot for drift before attempting to pin the snapshot.
# create the drift definition driftDef > $SCRIPTS/driftDef.js $CLI $OPTS -f $SCRIPTS/driftDef.js # create the recipe file and then zip up the # drift base directory to make the bundle archive deploy > /deploy.xml zip $ARCHIVE $BASEDIR zip $BUNDLE $ARCHIVE /deploy.xml # create the bundle from the recipe and archive # and then create the bundle definition createBundle > $SCRIPTS/createBundle.js $CLI $OPTS -f $SCRIPTS/createBundle.js # sleep to allow the server to get the first snapshot # this only sleeps for a minute, but it really depends on your environment # whether that is long enough sleep 1m # this pins the new snapshot to the new drift definition # and then changes the drift interval to the longer, variable-specified # value snapshot > $SCRIPTS/snapshot.js $CLI $OPTS -f $SCRIPTS/snapshot.js
9.3. Remedying Drift
// - The 'alert' variable is seeded by the alert sender // SET THESE VARIABLES var bundleDestinationName = 'drift destination' var bundleVersion = 1.0 var logFile = '/tmp/alert-cli-demo/logs/alert-' + alert.id + '.log' // Log what we're doing to a file tied to the fired alert id // var e = exporter e.setTarget( 'raw', logFile ) // Dump the alert // e.write( alert ) // get a proxy for the alerted-on Resource // var alertResource = ProxyFactory.getResource(alert.alertDefinition.resource.id) // Dump the resource // e.write( " " ) e.write( alertResource ) // Remediate file // Find the Bundle Destination // var destCrit = new BundleDestinationCriteria() destCrit.addFilterName( bundleDestinationName ) var result = BundleManager.findBundleDestinationsByCriteria( destCrit ) var dest = result.get( 0 ) // Find the Bundle Version // var versionCrit = new BundleVersionCriteria() versionCrit.addFilterVersion( bundleVersion ) result = BundleManager.findBundleVersionsByCriteria( versionCrit ) var ver = result.get( 0 ) // Create a new Deployment for the bundle version and the destination // var deployment = BundleManager.createBundleDeployment(ver.getId(), dest.getId(), 'remediate drift', new Configuration()) // Schedule a clean deploy of the deployment. This will wipe out the edited file and lay down a clean copy // BundleManager.scheduleBundleDeployment(deployment.getId(), true) e.write( " " ) e.write( "REMEDIATION COMPLETE!" )
10. Example: Managing JBoss ON Server Configuration
10.1. Simple Export/Import Synchronization
Note
//log into the first server rhq.login('rhqadmin','rhqadmin','server1.example.com','7080'); //export the settings var ex = SynchronizationManager.exportAllSubsystems(); rhqadmin@localhost:7080$ saveBytesToFile(ex.exportFile, 'export.xml.gz'); // log out of the first server rhq.logout()
// log into the second server rhq.login('rhqadmin','rhqadmin','server2.example.com','7080'); // import the settings var data = getFileBytes('export.xml.gz'); SynchronizationManager.importAllSubsystems(ex, null); // log out of the second server rhq.logout()
10.2. Changing Server Configuration Before Importing
//log into the first server rhq.login('rhqadmin','rhqadmin','server1.example.com','7080'); //export the settings var ex = SynchronizationManager.exportAllSubsystems(); rhqadmin@localhost:7080$ saveBytesToFile(ex.exportFile, 'export.xml.gz'); // log out of the first server rhq.logout()
- Get the default definition.
rhqadmin@localhost:7080$ var systemSettingsImportConfigurationDefinition = SynchronizationManager.getImportConfigurationDefinition('org.rhq.enterprise.server.sync.SystemSettingsSynchronizer')
- Create a new configuration instance.
rhqadmin@localhost:7080$ var configurationObject = systemSettingsImportConfigurationDefinition.configurationDefinition.defaultTemplate.createConfiguration() rhqadmin@localhost:7080$ var systemSettingsImportConfiguration = new ImportConfiguration(systemSettingsImportConfigurationDefinition.synchronizerClassName, configurationObject)
- Change the settings.For example, this edits the server synchronizer so that it imports only the database settings for storing monitoring data.
rhqadmin@localhost:7080$ configurationObject.getSimple('propertiesToImport').setValue('CAM_DATA_PURGE_1H, CAM_DATA_PURGE_6H, CAM_DATA_PURGE_1D, CAM_DATA_MAINTENANCE')
For the metrics template synchronizer, define which metric schedules to import per resource type, based on a properties list or a properties map. For example:rhqadmin@localhost:7080$ configurationObject.getSimple('updateAllSchedules').setBooleanValue(true) rhqadmin@localhost:7080$ var updateList = new PropertyList('metricUpdateOverrides') rhqadmin@localhost:7080$ var update = new PropertyMap('metricUpdateOverride') rhqadmin@localhost:7080$ update.put(new PropertySimple('metricName', 'MCBean|ServerInfo|*|freeMemory')) rhqadmin@localhost:7080$ update.put(new PropertySimple('resourceTypeName', 'JBossAS Server')) rhqadmin@localhost:7080$ update.put(new PropertySimple('resourceTypePlugin', 'JBossAS5')) rhqadmin@localhost:7080$ update.put(new PropertySimple('updateSchedules', 'true')) rhqadmin@localhost:7080$ updateList.add(update) rhqadmin@localhost:7080$ configurationObject.put(updateList)
rhqadmin@localhost:7080$ var configsToImport = new java.util.ArrayList()
rhqadmin@localhost:7080$ configsToImport.add(systemSettingsImportConfiguration);
rhqadmin@localhost:7080$ configsToImport.add(metricTemplatesImportConfiguration);
rhqadmin@localhost:7080$ SynchronizationManager.importAllSubsystems(ex, configToImport
);
11. Example: Writing a Custom Java Client
Note
11.1. Creating SampleLdapClientMain.class
SampleLdapClientMain.java
file requires these remote client JARs to be in its classpath:
cliRoot/rhq-remoting-cli-3.1.2.GA/lib/rhq-remoting-client-api-4.4.0-SNAPSHOT.jar
cliRoot/rhq-remoting-cli-3.1.2.GA/lib/rhq-core-domain-4.4.0-SNAPSHOT.jar
cliRoot/rhq-remoting-cli-3.1.2.GA/lib/persistence-api-1.0.jar
cliRoot/rhq-remoting-cli-3.1.2.GA/lib/rhq-enterprise-server-4.4.0-SNAPSHOT-client.jar
cliRoot/rhq-remoting-cli-3.1.2.GA/lib/hibernate-annotations-3.2.1.GA.jar
Example 1. SampleLdapClientMain.java
package org.rhq.sample.client.java.ldap; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.clientapi.RemoteClient; import org.rhq.enterprise.server.auth.SubjectManagerRemote; import org.rhq.enterprise.server.authz.RoleManagerRemote; import org.rhq.enterprise.server.resource.ResourceManagerRemote; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerRemote; /** * This sample program utilizes the RHQ Remote API via a Java Client. * * The RHQ CLI is the preferred remote client approach for script-based clients. Programmatic Java clients * can utilize the Remote API via the same mechanism used by the CLI, making use of ClientMain object, as * done in this sample. This is the recommended mechanism although a remote Java client could also use the * remote API exposed as WebServices. * * @author Jay Shaughnessy */ public class SampleLdapClientMain { // A remote session always starts with a login, define default user/password/server/port private static String username = "rhqadmin"; private static String password = "rhqadmin"; private static String host = "localhost"; private static int port = 7080; /** * This is a standalone remote client but calls to the remote API could be embedded into another application. */ public static void main(String[] args) { if (args.length > 0) { if ((args.length != 2) && (args.length != 4)) { System.out .println("\nUsage: SampleLdapClientMain [ [ username password ] | [username password host port] ]"); System.out.println("\n\nDefault credentials: rhqadmin/rhqadmin"); System.out.println("\n\nDefault host: determined from wsconsume of WSDL"); return; } else { username = args[0]; password = args[1]; if (args.length == 4) { host = args[2]; port = Integer.valueOf(args[3]); } } } LdapClient ldapClient = null; try { ldapClient = new LdapClient(); ldapClient.synchLdapJbasManagers(); } catch (Throwable t) { System.out.println("Error: " + t); t.printStackTrace(); } finally { if (null != ldapClient) { // clean up the session by logging out from the RHQ server ldapClient.logout(); } } } /** * The LdapClient interacts with the RHQ Server to help synchronize a (fake) LDAP server with RHQ. */ public static class LdapClient { // group containing all jbas resources private static final String JBAS_GROUP = "jbas-resource-group"; // role for jbas managers private static final String JBAS_MANAGER_ROLE = "jbas-manager-role"; // the users that should be assigned the JBAS_MANAGER_ROLE private static final List<String> JBAS_MANAGERS = new ArrayList<String>(); // the prmissions that should be assigned the JBAS_MANAGER_ROLE private static final Set<Permission> JBAS_MANAGER_PERMISSIONS = new HashSet<Permission>(); // jbas AS Server resource type (note, this picks up AS4 and AS5 resources as they share the same type name) private static final String JBAS_SERVER_NAME = "JBossAS Server"; /* The Remote API offers different remote "managers" roughly broken down by subsystem/function * Below are the managers needed by this client, there are several others that offer * interfaces into areas such as operations, alerting, content, etc. See the API. */ private ResourceGroupManagerRemote resourceGroupManager; private ResourceManagerRemote resourceManager; private RoleManagerRemote roleManager; private SubjectManagerRemote subjectManager; /* This represents the RHQ user that is logged in and making the remote calls. This user must * already exist. For the work being done here the user must also have SECURITY_MANAGER permissions. */ private Subject subject; /* This is the object through which we access the remote API */ private RemoteClient remoteClient; static { // add some fake users since we're not actually hooked into an ldap server JBAS_MANAGERS.add("mgr-1"); JBAS_MANAGERS.add("mgr-2"); // add some permissions since we're not actually hooked into an ldap server JBAS_MANAGER_PERMISSIONS.addAll(Permission.RESOURCE_ALL); } public LdapClient() throws Exception { this.remoteClient = new RemoteClient(null, host, port); this.subject = remoteClient.login(username, password); this.resourceGroupManager = this.remoteClient.getResourceGroupManager(); this.resourceManager = this.remoteClient.getResourceManager(); this.roleManager = this.remoteClient.getRoleManager(); this.subjectManager = this.remoteClient.getSubjectManager(); } /* * This method simulates a sync between an Ldap server that has defined a group of JBAS managers * and wants to associate them with a role allowing jbas management. Meaning, a role that * has the proper permissions and is associated with the jbas resources. */ private void synchLdapJbasManagers() throws Exception { // create the jbas manager role if necessary // use a criteria search with a name filter to look for the role RoleCriteria roleCriteria = new RoleCriteria(); roleCriteria.addFilterName(JBAS_MANAGER_ROLE); PageList<Role> jbasManagerRoles = roleManager.findRolesByCriteria(subject, roleCriteria); Role jbasManagerRole; if (1 == jbasManagerRoles.size()) { jbasManagerRole = jbasManagerRoles.get(0); } else { // if it doesn't exist, create it jbasManagerRole = new Role(JBAS_MANAGER_ROLE); jbasManagerRole = roleManager.createRole(subject, jbasManagerRole); } // ensure the proper permissions are granted to the role by using an update jbasManagerRole.setPermissions(JBAS_MANAGER_PERMISSIONS); roleManager.updateRole(subject, jbasManagerRole); // create, populate and associate the jbas group if necessary ResourceGroupCriteria resourceGroupCriteria = new ResourceGroupCriteria(); resourceGroupCriteria.addFilterName(JBAS_GROUP); PageList<ResourceGroup> jbasGroups = resourceGroupManager.findResourceGroupsByCriteria(subject, resourceGroupCriteria); ResourceGroup jbasGroup; if (1 == jbasGroups.size()) { jbasGroup = jbasGroups.get(0); } else { jbasGroup = new ResourceGroup(JBAS_GROUP); jbasGroup = resourceGroupManager.createResourceGroup(subject, jbasGroup); // Ensure the group is recursive to make all the children available. // In this case a specific method is available, so a general update call is not needed. resourceGroupManager.setRecursive(subject, jbasGroup.getId(), true); } // Now find all of the JBAS server resources by adding a criteria filter on resource type name ResourceCriteria resourceCriteria = new ResourceCriteria(); resourceCriteria.addFilterResourceTypeName(JBAS_SERVER_NAME); PageList<Resource> jbasServers = resourceManager.findResourcesByCriteria(subject, resourceCriteria); if (!jbasServers.isEmpty()) { int[] jbasServerIds = new int[jbasServers.size()]; int i = 0; for (Resource jbasServer : jbasServers) { jbasServerIds[i++] = jbasServer.getId(); } // ..and add them to the group which will be associated with the manager role resourceGroupManager.addResourcesToGroup(subject, jbasGroup.getId(), jbasServerIds); } // Now, associate the mixed group of Jbas servers to the manager role roleManager.addResourceGroupsToRole(subject, jbasManagerRole.getId(), new int[] { jbasGroup.getId() }); // sync managers with the role // 1. remove obsolete managers roleCriteria = new RoleCriteria(); roleCriteria.addFilterId(jbasManagerRole.getId()); // add a fetch criteria to the criteria object to get the optionally returned subjects for the role. roleCriteria.fetchSubjects(true); jbasManagerRole = roleManager.findRolesByCriteria(subject, roleCriteria).get(0); Set<Subject> subjects = jbasManagerRole.getSubjects(); if ((null != subjects) && !subjects.isEmpty()) { for (Subject subject : subjects) { if (!JBAS_MANAGERS.contains(subject.getName())) { roleManager.removeSubjectsFromRole(subject, jbasManagerRole.getId(), new int[] { subject .getId() }); } } } // 2. add new managers, create subjects for the managers, if necessary Subject jbasManagerSubject; for (String jbasManager : JBAS_MANAGERS) { jbasManagerSubject = subjectManager.getSubjectByName(jbasManager); // add the required fields for a subject, note that we skip credentials since this is // simulating ldap if (null == jbasManagerSubject) { jbasManagerSubject = new Subject(); jbasManagerSubject.setName(jbasManager); jbasManagerSubject.setEmailAddress("jbas.manager@sample.com"); jbasManagerSubject.setFactive(true); jbasManagerSubject.setFsystem(false); jbasManagerSubject = subjectManager.createSubject(subject, jbasManagerSubject); } // Finally, make sure my current set of jbas managers is associated with the manager role. roleManager.addSubjectsToRole(subject, jbasManagerRole.getId(), new int[] { jbasManagerSubject.getId() }); } } public void logout() { if ((null != subjectManager) && (null != subject)) { try { subjectManager.logout(subject); } catch (Exception e) { // just suppress the exception, nothing else we can do } } } } }
11.2. Sample LDAP Script
.bat
script invokes the custom Java class.
@echo off rem =========================================================================== rem RHQ Remote Client LDAP Example Startup Script rem rem The following variables must be set rem rem RHQ_CLIENT_HOME The home directory of the RHQ Client Installation. The rem RHQ Client can be downloaded from the RHQ GUI under rem the Administration->Downloads menu. rem =========================================================================== rem ---------------------------------------------------------------------- rem Set Environment Variables rem ---------------------------------------------------------------------- set RHQ_CLIENT_HOME=*MUST BE SET* rem ---------------------------------------------------------------------- rem Prepare the classpath rem Add all jar files supplied by the RHQ remote client install rem ---------------------------------------------------------------------- set CLASSPATH=. call :append_classpath "%RHQ_CLIENT_HOME%\conf" for /R "%RHQ_CLIENT_HOME%\lib" %%G in ("*.jar") do ( call :append_classpath "%%G" ) rem ---------------------------------------------------------------------- rem Prepare the VM command line options to be passed in rem ---------------------------------------------------------------------- if not defined RHQ_CLIENT_JAVA_OPTS ( set RHQ_CLIENT_JAVA_OPTS=-Xms64m -Xmx128m -Djava.net.preferIPv4Stack=true ) rem ---------------------------------------------------------------------- rem Uncomment For debugging on port 9999 rem ---------------------------------------------------------------------- rem set RHQ_CLIENT_ADDITIONAL_JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=y rem ---------------------------------------------------------------------- rem Execute the VM which starts the CLIENT rem ---------------------------------------------------------------------- set CMD="%JAVA_HOME%\bin\java.exe" %RHQ_CLIENT_JAVA_OPTS% %RHQ_CLIENT_ADDITIONAL_JAVA_OPTS% -cp "%CLASSPATH%" org.rhq.sample.client.java.ldap.SampleLdapClientMain %RHQ_CLIENT_CMDLINE_OPTS% %* cmd.exe /S /C "%CMD%" goto :done rem ---------------------------------------------------------------------- rem CALL subroutine that appends the first argument to CLASSPATH rem ---------------------------------------------------------------------- :append_classpath set _entry=%1 if not defined CLASSPATH ( set CLASSPATH=%_entry:"=% ) else ( set CLASSPATH=%CLASSPATH%;%_entry:"=% ) goto :eof rem ---------------------------------------------------------------------- rem CALL subroutine that exits this script normally rem ---------------------------------------------------------------------- :done endlocal exit /B 0