CHAPTER 3

image

Terminology and Basics

EM CLI can seem overwhelming at first, as with any command-line utility. But like anything else in technology, the more one understands how something works, the more useful and the easier it will be to work with.

There is too much information in EM CLI to memorize even a small part of it. Documention is as critical as the tool itself. Understanding the terminology that the documentation, built-in manuals, and the tool itself use will allow you to quickly find what you need by asking the right questions. For example, if you are looking for the command to create a user, you need to know you are searching for a verb, not a parameter or a variable.

Once one understands EM CLI’s terminology, a basic understanding of its functionality allows one to immediately get started with basic tasks, and that is where the real learning begins. This chapter introduces the basics of EM CLI first by explaining how it works with Enterprise Manager and then by providing a number of detailed examples.

Terminology: Verbs

EM CLI functionality uses verbs to perform actions. A verb is a task or action in the form of a user command that exposes Enterprise Manager functionality. Understanding verbs and how they are used to accomplish tasks is essential to fully utilizing EM CLI.

Verbs can include one or more parameters. The mode being used determines what those parameters look like. For example, when using EM CLI in command-line mode, the parameters are positional arguments that follow the verb. Each argument is preceded by a dash and followed by an equal sign. The argument may then be assigned a value, which is usually enclosed with quotation marks.

Some of the parameters are required and some are optional. The documentation identifies optional arguments by enclosing them in brackets. For example, the clear_privilege_delegation_setting verb has one required argument and two optional arguments (Listing 3-1).

Listing 3-1. Required and optional parameters for the clear_privilege_delegation_setting verb

emcli clear_privilege_delegation_setting
        -host_names="name1;name2;..."
        [-input_file="FILE:file_path"]
        [-force="yes/no"]

As of version 12.1.0.3, there are 362 verbs. To more easily help you find and manage verbs, they are grouped into 58 categories. The categories represent logical functionality. For example, if you were looking for verbs related to patching, you would find them in the Patch Verbs category. If you were looking for verbs related to blackouts, you would look in the Blackout Verbs category.

The verbs are named in a way that leaves little doubt as to what they do. Some of the names are short, such as login and start_agent, and some very long, such as update_monitoring_creds_from_agent and list_target_privilege_delegation_settings. This nomenclature has the benefit of making it relatively easy to remember verbs as well as making it easy to look up a verb based on its functionality.

Modes

EM CLI is invoked in one of three different modes. The mode is the method of using EM CLI. The decision to use one mode over another depends on the purpose and scope of the task.

Command-line

Prior to version 12.1.0.3, EM CLI operated in just one mode—command-line. In command-line mode, EM CLI executes one verb per invocation of the emcli executable. There is no subshell or programming interface for EM CLI in command-line mode. Any scripting of EM CLI needs to be done with a shell that can call individual EM CLI commands and process the output.

Interactive

With the release of version 12.1.0.3, EM CLI now includes the classic command-line mode as well as interactive and scripting modes. Interactive mode allows EM CLI to be invoked as a subshell of whatever terminal is being used. When EM CLI is running in interactive mode, the prompt changes to a custom Python prompt:

cd $OMS_HOME/bin
./emcli
emcli>

Scripting

Scripting mode does not have a subshell or a prompt. In fact, it is very similar to command-line mode, except that its invocation allows as its first parameter a script written in the Python-compatible programming language. This script is then executed as if the commands were typed into interactive mode. EM CLI in scripting mode is invoked one time but unlike while in command-line mode, the full functionality of the Python programming language can be used to do everything for which a shell is required in command-line mode. In addition, scripting mode invokes EM CLI in its native form, which makes things like parsing the output of commands much easier and more efficient, especially with the use of JSON.

Help!

EM CLI has built-in help functionality. Getting a general list of available verbs for command-line mode is as simple as executing EM CLI with the verb help. Be prepared for a large amount of data if you are not qualifying the command with additional parameters. If you need additional information on a particular verb, add the verb as the second parameter.

To use help in interactive mode, the help functionality is called by using a Python function called help(). The help() function requires only one parameter—the help topic. The help topic can be a verb function as well as certain verb function parameters. Be aware that there are help topics included in interactive mode that don’t exist in command-line mode. For example, the command-line mode uses setup files to hold EM CLI properties, but interactive and scripting modes do not. The properties are set each time interactive or scripting modes are invoked. We can use the help() function to view which parameters to use to set properties, as shown in Listing 3-2.

Listing 3-2. Client properties help page

emcli>help('client_properties')
EMCLI_OMS_URL             : OMS URL To connect to.
EMCLI_USERNAME            : OMS Username.
EMCLI_AUTOLOGIN           : Possible values are true,false. Default is false.
EMCLI_TRUSTALL            : Possible values are true,false. Default is false.
EMCLI_VERBJAR_DIR         : Location of bindings directory.
EMCLI_CERT_LOC            : Location of a valid certificate file.
EMCLI_LOG_LOC             : Directory where log files will be stored.
EMCLI_LOG_LEVEL           : Possible values are ALL,INFO,FINE,FINER,WARN,SEVERE. Default is SEVERE.
EMCLI_OUTPUT_TYPE         : Possible values are json, JSON, text, TEXT. Default is json in script mode and text in interactive mode.

status() will list values of all the client properties. set_client_property(propertyname,value) and get_client_property(propertyname)can be used to set and get a client property.

Understanding Error Codes

There are a number of error codes that you might see when using EM CLI. The information provided in these error codes is critical to determining what caused the error. The error codes shown below are some of those that are seen most often; they almost always have an easy fix.

Command-line mode requires a login session to be established before any commands can be executed. In secure environments and by default, the login session will expire after 45 minutes. When a valid command is executed without an established login session when in command-line mode, an error is thrown with an exit code of 255. In order to proceed, a valid session will need to be established by using the login verb, as shown in Listing 3-3.

Listing 3-3. Login error message and exit code in command-line mode

[oracle oms]$ emcli get_targets
Error: Session expired. Run emcli login to establish a session.
[oracle oms]$ echo $?
255

Interactive and scripting modes require that the connection parameters be included each time a script is executed or an interactive session is established. If the connection URL has not been specified, an error will be thrown with details on how to establish the connection, as shown in Listing 3-4.

Listing 3-4. Settings error in interactive and scripting modes

emcli>get_targets()
Error: EM URL is not set. Do set_client_property('EMCLI_OMS_URL', '<value>')
Or set it as environment variable.

[oracle ~]$ emcli @test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    get_targets()
  File "<string>", line 41, in get_targets
emcli.exception.VerbExecutionError: Error: EM URL is not set. Do set_client_property('EMCLI_OMS_URL', '<value>')
Or set it as environment variable.

Errors can be caused by myriad reasons. The EM CLI developers have done an excellent job of making the error messages descriptive and useful. When you encounter errors, read the description thoroughly in order to understand what issue caused it. When in doubt, search for the error in the documentation or on the Internet. Chances are, someone else has already found and fixed the cause of the error.

Syntax

The EM CLI program can be used in three different modes. These are command-line mode, interactive mode, and scripting mode. Up until version 12.1.0.2, there was only the command-line mode. The interactive and scripting modes became available in version 12.1.0.3, along with an exposed programming interface that uses Jython.

The standard command-line mode hasn’t changed much since Grid Control 10g. With few exceptions, scripts used with previous versions of EM CLI will continue to work with the latest version or 12c. The command-line syntax is the emcli command, followed by one verb, followed by zero or more verb options or parameters, as shown in this example:

emcli create_group -name=my_group -add_targets="mymachine.example.com:hostname"

The interactive and scripting modes both use the Jython programming language. The interactive mode is a single-user interactive session created by executing the emcli command without any parameters.

Standard Linux shell commands will not work in the interactive shell. The interactive mode of EM CLI can be closed using the command exit() or by typing ctrl-d in Linux or ctrl-z in Windows.

Interactive mode syntax differs from that of the standard command-line mode. Once an interactive mode shell has been established, it is no longer necessary to use the emcli command. Executing an EM CLI command is done by putting a verb into the shell directly and enclosing the verb options within parentheses. The verb options are not preceded by a dash like they are in command-line mode, but rather are preceded by a comma when followed by other options. The following shows the create_group function in interactive mode with the name and add_targets options:

emcli> create_group(name=my_group, add_targets="mymachine.example.com:hostname")

Scripting mode uses the same command syntax as the interactive mode but does not require the Jython shell. All of the EM CLI commands to be executed would be formatted like the interactive shell command above and put into a script, along with any other Python code to be included. The script is executed non-interactively by following the emcli command with an @ symbol and the name of the script:

[oracle ~]$ emcli @my_script.py

Setup

EM CLI is included in every OMS installation and is set up to connect to that OMS automatically. The setup configuration can be confirmed with the setup verb. Running the command in command-line mode shows that EM CLI is configured to connect to https://oem.example.com:7802/em with the SYSMAN user, as shown in Listing 3-5.

Listing 3-5. Output of EM CLI setup in command-line mode

[oracle ~]$ emcli status
Oracle Enterprise Manager 12c EMCLI12.1.0.3.0.
Copyright (c) 1996, 2013 Oracle Corporation and/or its affiliates. All rights reserved.

Instance Home          : /u01/app/oracle/product/12.1.0/gc_inst/em/EMGC_OMS1/sysman/emcli/setup/.emcli
Verb Jars Home         : null
Status                 : Configured
EMCLI Home             : /u01/app/oracle/product/12.1.0/mw_1/oms/bin
EMCLI Version          : 12.1.0.3.0
Java Home              : /u01/app/oracle/product/12.1.0/mw_1/jdk16/jdk/jre
Java Version           : 1.6.0_43
Log file               : /u01/app/oracle/product/12.1.0/gc_inst/em/EMGC_OMS1/sysman/emcli/setup/.emcli/.emcli.log
EM URL                 : https://oem.example.com:7802/em
EM user                : SYSMAN
Auto login             : false
Trust all certificates : true

After installing EM CLI on a system other than the OMS server, it must be explicitly configured before it will function with an Enterprise Manager installation. Executing the setup command against an EM CLI installation that has not yet been configured returns an error, as shown in Listing 3-6.

Listing 3-6. An EM CLI installation that has not yet been set up

[oracle ~]$ emcli setup
Oracle Enterprise Manager 12c 3.
Copyright (c) 1996, 2013 Oracle Corporation and/or its affiliates. All rights reserved.

No current OMS

The configuration is done with the setup verb followed by a number of parameters. The url parameter is the same as the address used in the browser to login to Enterprise Manager. The dir parameter specifies the directory in which to install the client. The username parameter indicates which username the client will use for connecting. This noautologin parameter determines that a user name and password will need to be provided in order to gain access to the OMS before an EM CLI session can be established. The trustall parameter indicates that certificates on the OMS will be trusted automatically. The following dir parameter in the EM CLI setup command is using shell expansion to indicate that the installation directory is the current working directory:

[oracle ~]$ emcli -url=https://<hostname of grid server>:1159/em -dir=$(pwd) 
-username=<username> -noautologin -trustall

Running the setup command in interactive mode reveals that neither the URL nor the user has been defined. This is because these parameters must be set each time for both interactive and scripting modes, as shown in Listing 3-7.

Listing 3-7. Executing the setup function in interactive mode

emcli>status()
Oracle Enterprise Manager 12c EMCLI with Scripting option Version 12.1.0.3.0.
Copyright (c) 1996, 2013 Oracle Corporation and/or its affiliates. All rights reserved.

Verb Jars Home (EMCLI_VERBJAR_DIR)      : /u01/app/oracle/product/12.1.0/mw_1/oms/bin/bindings/default/.emcli
EMCLI Home (EMCLI_INSTALL_HOME)         : /u01/app/oracle/product/12.1.0/mw_1/oms/bin
EMCLI Version                           : 12.1.0.3.0
Java Home                               : /u01/app/oracle/product/12.1.0/mw_1/jdk16/jdk/jre
Java Version                            : 1.6.0_43
Log file (EMCLI_LOG_LOC)                : CONSOLE
Log level (EMCLI_LOG_LEVEL)             : SEVERE
EM URL (EMCLI_OMS_URL)                  : NOT SET
EM user (EMCLI_USERNAME)                : NOT SET
Auto login (EMCLI_AUTOLOGIN)            : false
Trust all certificates (EMCLI_TRUSTALL) : false

Once the setup is complete and a valid Enterprise Manager has been authenticated, EM CLI will be ready to carry out tasks against EM. Setup is often where problems can be found, especially during the initial setup. For example, you may not know that the port used by EM is blocked between the server on which EM CLI was installed and the OMS. The setup process will reveal this fact. Once a connection has been established with a successful login, the EM CLI setup process is complete.

Communication

A number of tasks can be accomplished with either EM CLI or EMCTL. The choice of which tool to use will depend on a number of factors, such as which tool is available to use or which is more efficient for a particular task. The method in which the tool will interface with Enterprise Manager may be an additional factor to consider.

EM CLI

EM CLI is a client of the Oracle Management Server (OMS) just as SQL*plus is a client of the database. The Enterprise Manager OMS installation includes an installation of EM CLI. The EM CLI executable is located in the OMS home directory, <OMS_HOME>/bin/emctl. EM CLI communicates with the OMS using HTML through the same port and URL that is used to access the Enterprise Manager graphical interface.

A network trace run on the port used for HTTP communication between EM CLI and Enterprise Manager would show that all of the requests from EM CLI are GET and POST requests via HTTP. These are the same requests that come from the GUI console when establishing a logon.

The way EM CLI interfaces with Enterprise Manager allows it to connect from any location where a network connection can be established to the IP and port of the OMS, which gives EM CLI a distinct advantage over EMCTL in cases where the commands need to be run from a server other than the one hosting the OMS agent.

EMCTL

EMCTL communicates directly with the agent with which it is installed. EMCTL will only communicate with its own agent, even when other agents are running on the same server.

Image Note  There is also an EMCTL interface that controls and communicates directly with the OMS and it has a completely different set of commands.

The emctl command located in <AGENT_BASE>/agent_inst/bin is a shell or batch script that sets environment variables and executes the <AGENT_HOME>/bin/emctl command with the parameters fed to the first command. The <AGENT_HOME>/bin/emctl is also a shell or batch script that sets environment variables as well as sources a number of other files. It then executes a perl script with the parameters fed to the first command. This perl script sources a number of other perl scripts and either reads existing state files or interacts directly with the java agent process for a result.

Because EMCTL interacts directly with the java agent process, it is not considered a client. This also means that the agent cannot be remotely controlled using EMCTL.

EMCTL versus EM CLI

When to use EMCTL versus EM CLI is largely based on preference and environment limitations. For example, both commands can control blackouts in Enterprise Manager. In one environment, there may be a limitation on installing the EM CLI remotely or locally because of the Java version it requires or the port access it needs, making EMCTL the better option. In another environment, there may be a restriction on shell access on an agent server, making EM CLI the better option. Understanding the architecture differences between EMCTL and EM CLI will help with the decision of using one versus the other in different circumstances.

The syntax of EM CLI is relatively straightforward; emcli followed by a verb, followed by mandatory and optional parameters. The syntax of EMCTL is not as easy to understand and does not follow a strict format.

For most commands the format is as follows: emctl followed by a verb, followed by agent. For some configuration commands the format is: emctl followed by config agent, followed by a verb such as listtargets or secure. Generally, the easiest way to figure out the syntax of the EMCTL command you want to execute is to look up the documentation online or to print out the help text by executing the emctl command without any arguments. The help text will print to the screen.

This help text can be made searchable by redirecting it to a file that can be opened and searched or by piping the output to a searchable line reader such as less:

emctl > help.txt; vim help.txt
emctl | less

Now that we’ve reviewed a number of important concepts and definitions, let’s look at some real-world examples that can be used to accomplish many of the most common tasks for which one might use EM CLI.

The first task, Login, is one that must be done for each session of EM CLI, regardless of which mode is used. The other tasks are examples of using EM CLI when the GUI is not a suitable option, such as within scheduled scripts or when working with large numbers of targets.

Task: Establish a Login

There is little useful functionality of EM CLI without having a connection to an OMS. Creating that connection is usually the first step of using the interface. How to establish a connection depends on the mode being used.

When using command-line mode, a login will not need to be established if the -autologin parameter was specified during setup, since this parameter indicates that the credentials used during the install of EM CLI are stored in the installation files and are used for every command automatically. A login is established using the login verb. The login verb must be followed by the -username parameter and can optionally be followed by the -password parameter.

It is inadvisable to include the password on the command line because of the security implications of exposed passwords. If the password is not included as a parameter, EM CLI will prompt the user for a password, and the characters entered will not be echoed to the screen, nor will the password be exposed when looking at the running processes using the ps command. If the -autologin parameter was not specified during setup, a login session will prompt for a password:

[oracle ~]$ emcli login -username=sysman
Enter password :

Login successful

In the case of running EM CLI in scripting or interactive mode, the login information must be explicitly given for each script execution and at the beginning of each interactive session. These two modes do not use the credentials established during setup, even if the -autologin parameter was used.

A simple script can be created to establish a connection and can be used in both interactive and scripting modes. The login script needs to specify the URL by which to connect, the SSL authentication method, and a login credential. Both of these modes expect a Python script (Listing 3-8).

Listing 3-8. Login script to be used in interactive and scripting modes

from emcli import *

set_client_property('EMCLI_OMS_URL', 'https://oem.example.com:7802/em')
set_client_property('EMCLI_TRUSTALL', 'true')

myLogin(username='sysman')

myLogin()

Placing this text in a file with an extension of .py makes it a module that can be imported into EM CLI. For example, the script can be called login.py and placed in the /home/oracle/scripts directory. However, EM CLI will not necessarily be able to find the script, because this path is not in the default Jython path. Explicitly defining the Jython search path will guarantee that any scripts within that search path can be imported by EM CLI. The JYTHONPATH variable can be supplemented with the additional directory:

export JYTHONPATH=$JYTHONPATH:/home/oracle/scripts

Similar to how the EM CLI Jython module was imported into the script with the command from emcli import *, the login script can be imported into either the interactive or scripting modes. To establish a login in interactive mode, we can simply import the module. We will then be prompted to enter the password for the user specified in the script. Listing 3-9 shows an example of using the login script in interactive mode.

Listing 3-9. Establishing a logon in interactive mode using the login module

[oracle ~]$ emcli
Oracle Enterprise Manager 12c EMCLI with Scripting option Version 12.1.0.3.0.
Copyright (c) 1996, 2013 Oracle Corporation and/or its affiliates. All rights reserved.

Type help() for help and exit() to get out.

emcli>import login
Enter password :  *********

emcli>

To establish a login in scripting mode, import the module from within the script being executed. For example, the following script prints the total count of Enterprise Manager targets using an EM CLI function. But first it needs to establish a login by importing the login module, as shown in Listing 3-10:

Listing 3-10. Establishing a login in scripting mode using the login module

import emcli
import login

mytargets = str(len(emcli.get_targets().out()['data']))

print(mytargets)

Task: Get a List of Targets

Viewing and manipulating Enterprise Manager targets are the most common uses of EM CLI. Regardless of which you are doing, the first step is to retrieve the target information.

The get_targets verb or function retrieves a target list along with a number of other columns of information. Neither the verb nor function requires parameters to retrieve the full list of information, as shown in Listing 3-11.

Listing 3-11. Retrieve the target information using command-line mode

[oracle ~]$ emcli login -username=sysman
Enter password :

Login successful

[oracle ~]$ emcli get_targets
Status  Status     Target Type     Target Name            ID
1       Up         host            oem.example.com
1       Up         oracle_emd      oem.example.com:3872
-9      n/a        oracle_home     common12c1_20_oem

The targets that are retrieved can be filtered by specifying a semi-colon-delimited list of target names and target types, which should be separated by a colon. There should be no white space anywhere within the target list filter. Listing 3-12 shows an example of creating a filter with two targets.

Listing 3-12. Limit the targets retrieved by get_targets using the targets parameter

[oracle ~]$ emcli get_targets 
   -targets='oem.example.com:host;oms12c1_3_oem:oracle_home'
Status  Status     Target Type     Target Name            ID
1       Up         host            oem.example.com
-9      n/a        oracle_home     oms12c1_3_oem

The targets parameter can use wild cards anywhere within the target name or target type values, and multiple wild cards can be used for either value, as shown in Listing 3-13.

Listing 3-13. Use wildcards in the targets parameter

[oracle ~]$ emcli get_targets 
   -targets='oem%:host;oms12c1_%_oem:%oracle%'
Status  Status     Target Type      Target Name           ID
1       Up         host             oem.example.com
-9      n/a        oracle_home      oms12c1_3_oem

Python functions require a specific format: function name, followed by an opening parenthesis, followed by a comma-delimited list of parameters and their values, followed by a closing parenthesis.

Following is an example of a typical python function:

function_name(parameter1=value1, parameter2=value2)

Since the EM CLI verbs in interactive and scripting modes are actually Python functions, they will need to follow this format as well.

Calling a function without additional parameters only requires the verb and a pair of parentheses. Listing 3-14 shows the results of using the get_targets function in interactive mode without parameters while Listing 3-15 shows the same function in scripting mode with the targets parameter.

Listing 3-14. Call the get_targets() function in interactive mode without parameters

[oracle ~]$ emcli
Oracle Enterprise Manager 12c EMCLI with Scripting option Version 12.1.0.3.0.
Copyright (c) 1996, 2013 Oracle Corporation and/or its affiliates. All rights reserved.

Type help() for help and exit() to get out.

emcli>import login
Enter password :  *********

emcli>get_targets()
Status  Status     Target Type      Target Name
          ID
1       Up         host             oem.example.com
1       Up         oracle_emd       oem.example.com:3872
-9      n/a        oracle_home      common12c1_20_oem

Listing 3-15. Call the get_targets() function in scripting mode with the targets parameter

[oracle ~]$ cat targets2.py
import emcli
import login

mytargets = emcli.get_targets
    (targets='oraoem1%:%;oms12c1_%_oraoem1:%oracle%')
    .out()['data']

for targ in mytargets:
    print('Target: ' + targ['Target Name'])

[oracle ~]$ emcli @targets2.py
Target: oraoem1.example.com
Target: oraoem1.example.com:3872
Target: oms12c1_3_oraoem1

Task: Using Blackouts

Attempting to schedule blackouts to coincide with maintenance tasks on a target host can produce false-positive alerts. This can happen when a blackout finishes prior to a maintenance activity or when a maintenance activity starts prior to a blackout. Both of these scenarios can be avoided by having the maintenance job itself start and stop the blackout.

Both EMCTL and EM CLI are capable of creating, deleting, starting, and stopping blackouts. However, EMCTL is only capable of managing blackouts for the targets local to the agent host from which it is executed, and EMCTL commands will only work if the agent is running. The limitations of setting blackouts with EMCTL are restrictive and prone to error. It is recommended to use EM CLI to set blackouts from maintenance jobs.

It is usually not necessary to use scripting mode for blackout activities since most maintenance scripts run in a shell script. The create_blackout verb requires four arguments: name, add_targets, schedule and reason. The job is identified by the name parameter, which means it must be unique to all other jobs in EM. Listing 3-16 shows an example of using EM CLI in command-line mode to set a blackout called “Blackout1” for the “ em12cr3.example.com” host. This blackout will not repeat and will last for three hours or until it is stopped. The reason the blackout has been set is for “Testing.”

Listing 3-16. Set a blackout called “Blackout1” for the “em12cr3.example.com” host

[oracle ~]$ emcli create_blackout -name='Blackout1'  -add_targets='em12cr3.example.com:host' 
-schedule='frequency:once;duration:3'
-reason='Testing'

The get_blackouts verb will show the details of all of the blackouts that are currently defined, as shown in Listing 3-17.

Listing 3-17. List all blackouts

[oracle ~]$ emcli get_blackouts
Name       Created By  Status     Status ID  Next Start            Duration  Reason   Frequency  
Blackout1  SYSMAN      Scheduled  0          2435-07-24  17:17:56  03:00     Testing  once  
Repeat Start Time            End Time             Previous  End  TZ Region        TZ Offset
none   2000-07-24  17:17:56  2000-07-24  20:17:56  none          America/Chicago  +00:00

The following example uses the noheader and script parameters to change the output of get_blackouts to be easily parsed. Piping the output to the cut command displays only the first field, which is the blackout name field.

[oracle ~]$ emcli get_blackouts -noheader -script | cut -f1
Blackout1

The blackout job details can be queried with the get_blackout_details verb. The output includes a header and is tab delimited. If the output lines are longer than the screen width, they are wrapped to the next line, as shown in Listing 3-18.

Listing 3-18. List the details of the “Blackout1” blackout

[oracle ~]$ emcli get_blackout_details -name='Blackout1'
Status   Status ID  Run Jobs  Next Start            Duration  Reason   Frequency  Repeat  Days
Started  4          no        2014-04-12  13:37:28  03:00     Testing  once       none    none
Months Start Time            End Time              TZ Region        TZ Offset
none   2014-04-12  13:37:28  2014-04-12  16:37:28  America/Chicago  +00:00

The format above is hard to read and even harder to parse. Instead, the output could be changed to a comma-delimited format, the header removed, and the output limited only to the columns we need, as shown in Listing 3-19.

Listing 3-19. List the details of the “Blackout1” blackout in a format that is easier to parse

[oracle ~]$ emcli get_blackout_details 
-name='Blackout1' -noheader -format="name:csv"
 Started,4,no,2014-04-12 13:37:28,03:00,Testing,once,none,none,none,2014-04-12 13:37:28,
2014-04-12 16:37:28,America/Chicago,+00:00

Once the output can be parsed, we can just test for the value we are looking for by adding the commands to a shell script, creating the “Blackout1” target, as shown in Listing 3-20.

Listing 3-20. Create a blackout in a script and test the exit value

emcli create_blackout -name='Blackout1' -add_targets='em12cr3.example.com:host' -schedule='frequency:once;duration:3' -reason='Testing'

MYSTATUS=$(emcli get_blackout_details -name='Blackout1'
-noheader -format='name:csv' | cut -d ',' -f 1)

if [ "$MYSTATUS" <> "Started" ]; then
echo 'Blackout not started'
        exit 1
fi

<Maintenance Script>

By using the above in your scripts, you would notice that after multiple runs it would sometimes fail and sometimes succeed. This behavior happens because the create_blackout EM CLI verb creates but does not start the job. The job is started by another process, so there is a chance that the blackout has not started by the time the if statement that checks the status of the job has executed, and thus the script will fail. A solution is to use additional shell scripting, which will either wait for the job to start before proceeding to the rest of the script or will fail because the job stayed in “Scheduled” mode for too long, as shown in Listing 3-21.

Listing 3-21. Additional shell scripting added to make events sequential

MYSTATUS='Scheduled'
STATCOUNT=6

while [ "$MYSTATUS" == "Scheduled" ]; do
        if [ $STATCOUNT -lt 1 ]; then
            echo "Blackout1 stuck in scheduled status"
                exit 1
        fi

        let STATCOUNT-=1
        sleep 5
        MYSTATUS=$(emcli get_blackout_details -name='Blackout1'
                -noheader -format='name:csv' | cut -d ',' -f 1)
done

if [ "$MYSTATUS" != "Started" ]; then
        echo 'Blackout Blackout1 not started'
        exit 1
fi

<Maintenance Script>

When maintenance is completed, the same script can use EM CLI commands to both close and delete the blackout:

emcli stop_blackout -name='Blackout1'
emcli delete_blackout -name='Blackout1'

Task: Create Targets

Adding targets can be painful if EM doesn’t auto-discover them. This is especially true if the targets are using non-default settings, which sometimes make them hard for the agent to detect. Fortunately, EM CLI is able to add targets with much more flexibility than EM.

Which parameters need to be specified greatly depends on the target type being added. For example, when adding a database, the properties parameter needs to include:

  • SID
  • Port
  • OracleHome
  • MachineName

The credentials for a database are almost always going to be for the “dbsnmp” user unless they are for a standby database that is not open and therefore requires a privileged password file account. Listing 3-22 shows an example of adding a target through EM CLI command-line mode.

Listing 3-22. Add the “orcl” single-instance database target

[oracle ~]$ emcli add_target -name='ORCL_DB' 
-type='oracle_database' -host='oradb1.example.com'
-properties='SID:orcl;Port:1521;OracleHome:/u01/app/oracle/product/12.1.0/dbhome_1;
MachineName:oradb1-vip.example.com'
-credentials='Role:NORMAL;UserName:DBSNMP;password:<password>'
Target "ORCL_DB:oracle_database" added successfully

If we want to add an RAC database target, the individual instances of the cluster need to be added first, as shown in Listings 3-23 and 3-24.

Listing 3-23. Add RAC database node one

[oracle ~]$ emcli add_target -name='ORCL1_ORCL_RACCLUSTER'
-type='oracle_database' -host='oradb1.example.com'
-properties='SID:orclrac1;Port:1521;OracleHome:/u01/app/oracle/product/12.1.0/dbhome_1;
MachineName:oradb1-vip.example.com'
-credentials='Role:NORMAL;UserName:DBSNMP;password:<password>'
Target "ORCL1_ORCL_RACCLUSTER:oracle_database" added successfully

Listing 3-24. Add RAC database node two

[oracle ~]$ emcli add_target -name='ORCL2_ORCL_RACCLUSTER'
-type='oracle_database' -host='oradb2.example.com'
-properties='SID:orclrac2;Port:1521;OracleHome:/u01/app/oracle/product/12.1.0/dbhome_1;
MachineName:oradb2-vip.example.com'
-credentials='Role:NORMAL;UserName:DBSNMP;password:<password>'
Target "ORCL2_ORCL_RACCLUSTER:oracle_database" added successfully

Once the instances are added, the database cluster target can be added, specifying the instances as part of the properties of the EM CLI command. These instances then become associated with the database cluster target.

Image Note  Because we are adding a cluster target, a Cluster ware target must already exist before adding database cluster targets, as shown in Listing 3-25.

Listing 3-25. Add RAC database cluster, associating the two previous database instances

[oracle ~]$ emcli add_target -name='ORCL_RACCLUSTER' 
-host='oradb1.example.com' -monitor_mode='1'
-type='rac_database' -properties='ServiceName:orclrac;ClusterName:oradb-cluster'
-instances='ORCL1_ORCL_RACCLUSTER:oracle_database;ORCL2_ORCL_RACCLUSTER:oracle_database'
Target "ORCL_RACCLUSTER:rac_database" added successfully

One can use EM CLI to add almost any target type. The auto-discovery tool in EM will accurately detect most targets, making it easy to promote those targets. When an environment has customized configurations that make the auto-discovery mechanism unreliable, adding targets manually is the only option. In some environments, scripting the process of adding targets can be used to migrate between versions or to replicate an environment. In these circumestances, using EM CLI to add targets becomes a necessity.

The add_target verb accepts over a dozen parameters; use the help functionality of EM CLI for a quick reference. The online documentation provides a much more detailed description. Use the following reference if the command help isn’t enough:

http://docs.oracle.com/cd/E24628_01/em.121/e17786/cli_verb_ref.htm#CACHFHCA.

My Oracle Support (MOS) also has dozens of articles on specific use cases and examples for EM CLI. MOS notes 1448276.1 and1543773.1 offer specific information on using EM CLI to add targets.

Task: Manipulating Jobs

Jobs are very important in EM. There are a number of jobs that are already created and running in a default installation. Many administrators use EM’s robust job scheduling and execution capabilities for their critical enterprise tasks.

These capabilities can be fully exploited in both the GUI and EM CLI. For example, the GUI has a button called “Create Like” in the jobs library that allows one to replicate the settings from one job to another in order to reduce the amount of input necessary for two similar jobs. This functionality works great for a few jobs that look exactly alike except for one or two changes.

But what if you need to create dozens or hundreds of jobs that are similar? Or you need to replicate a number of jobs from one EM installation to another? EM CLI’s functionality of exporting jobs to a text file and then importing jobs from the same file or a modified version of that file makes job manipulation at any scale possible.

For example, a simple job that executes the uname -a OS command can be exported to a file. The command and job name can be changed to uname with a different flag. Then, the modified text file with the new variables can be used to create a new job, as shown in Listing 3-26.

Listing 3-26. Describe the UNAME_A_OMS job

[oracle ~]$ emcli describe_job -name='UNAME_A_OMS'

# Current status of the job is EXPIRED.
name=UNAME_A_OMS
type=OSCommand
owner=SYSMAN

target_list=oraoem1.example.com:host

# Credential Usage: defaultHostCred
# Description:
cred.defaultHostCred.<all_targets>:host=SET:HostCredsNormal

# Description: (Optional) Comma separated list of parameters to the command.
variable.args=/bin/uname -a

# Description: (Optional) Command to run on the target.
variable.command=%job_default_shell%

schedule.frequency=IMMEDIATE

The output from this command can be used as a property file to create a new job.

  1. Copy the text into a file and modify the variables as necessary (Listing 3-27).
  2. To save a step, use the shell capabilities to redirect standard output to a file.
  3. Copy the file just created to a new file and open that new file in a standard text editor (Listing 3-27).
  4. Change the job name and command in the new file to reflect the new job (changes are shown in bold; Listing 3-28).

Listing 3-27. Create the uname_a_oms.job job properties file and make a copy

[oracle ~]$ emcli describe_job -name='UNAME_A_OMS' > uname_a_oms.job
[oracle ~]$ cp uname_a_oms.job uname_r_oms.job

Listing 3-28. Create the uname_r_oms.job job properties file

[oracle ~]$ cat uname_r_oms.job

# Current status of the job is EXPIRED.
name=UNAME_R_OMS
type=OSCommand
owner=SYSMAN

target_list=oraoem1.example.com:host

# Credential Usage: defaultHostCred
# Description:
cred.defaultHostCred.<all_targets>:host=SET:HostCredsNormal

# Description: (Optional) Comma separated list of parameters to the command.
variable.args=/bin/uname -r

# Description: (Optional) Command to run on the target.
variable.command=%job_default_shell%

schedule.frequency=IMMEDIATE

Create the new job, specifying the new properties file as the input file, as shown here:

[oracle ~]$ emcli create_job -input_file='property_file:uname_r_oms.job'
Creation of job "UNAME_R_OMS" was successful.

The UNAME_R_OMS job is now an active job. The same process can be used to create a job in the library by specifying the describe_library_job verb:

[oracle ~]$ emcli describe_library_job -name='UNAME_A'> uname_a.job
[oracle ~]$ cp uname_a.job uname_r.job

Edit the uname_r.job file. Listing 3-29 shows the contents of the script and uses the create_library_job verb to create the library job from the script.

Listing 3-29. Create the uname_a.job and uname_r.job library job properties files

[oracle ~]$ cat uname_r.job

# Current status of the job is ACTIVE.
name=UNAME_R
type=OSCommand
owner=SYSMAN
kind=library

# Credential Usage: defaultHostCred
# Description:
cred.defaultHostCred.<all_targets>:host=SET:HostCredsNormal

# Description: (Optional) Comma separated list of parameters to the command.
variable.args=/bin/uname -r

# Description: (Optional) Command to run on the target.
variable.command=%job_default_shell%

schedule.frequency=IMMEDIATE

[oracle ~]$ emcli create_library_job -input_file='property_file:uname_r.job'
Creation of library job "UNAME_R" was successful.

Exporting jobs gives one the ability to easily duplicate jobs (both active and library), as well as to keep an external backup of that job in a generic format. This backup can serve as a method of restoring the job to another system, building a duplicate or test system, and producing an audit record if necessary.

Summary

The terminology of EM CLI can be confusing for someone who is not a regular user. Verbs define the functionality of what you want to do with EM CLI. The “flavors” of how you make changes with EM CLI are known as modes. Command-line mode is also known as classic mode, where one command is executed at a time. Interactive and scripting modes use Python syntax and can additionally use the mature functionality of that powerful programming language.

Given its size and complexity, it is impossible for someone to memorize everything about EM CLI. Even the most advanced user will need the assistance of documentation on a regular basis. Fortunately, EM CLI is loaded with help. From the excellent documentation found online to the manual pages contained within the command-line and interactive modes of the tool itself, all of the information one needs is easily and readily available.

No one likes an error message, but when they pop up in EM CLI, they are descriptive and usually easy to read and interpret. The syntax of errors in many products can be tricky, especially with all of the different tools administrators have to switch between on a daily basis. The error syntax in EM CLI is intuitive and simple when compared to many of those other tools.

EM CLI will already be fully configured and ready to use on each installed OMS. It is also easy to download, install, and set up on any other machine that is capable of running Java. The method of communication between the EM CLI client and the OMS is almost identical to the communication that takes place between the browser and the OMS. Both are highly secure and use standard, mature technologies.

However, EMCTL is not going away any time soon. Despite the fact that EMCTL and EM CLI can do some of the same things, they are vastly different in their purposes and functionality. Try not to make the mistake of dismissing EMCTL as futile because of the robustness of EM CLI. You will need them both for different tasks.

The examples in this chapter show just a small sliver of what EM CLI can do, but chances are, you already have in mind a few scenarios where EM CLI can solve a problem that the GUI and other command-line tools cannot. The examples here are some of the most obvious ways to use EM CLI. There are multiple ways and tools by which to solve most problems in Enterprise Manager. The examples shown in this book will never claim to be the “right” way to do something. Use the information found here to come up with your own “right” way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.252