Introducing iRules

An iRule is a powerful and flexible feature within the BIG-IP® local traffic management (LTM) system that you can use to manage your network traffic. The iRulesTM feature not only allows you to select pools based on header data, but also allows you to direct traffic by searching on any type of content data that you define. Thus, the iRules feature significantly enhances your ability to customize your content switching to suit your exact needs.

The remainder of this introduction presents an overview of iRules, lists the basic elements that make up an iRule, and shows some examples of how to use iRules to direct traffic to a specific destination such as a pool or a particular node.

What is an iRule?

An iRule is a script that you write if you want individual connections to target a pool other than the default pool defined for a virtual server. iRules allow you to more directly specify the pools to which you want traffic to be directed. Using iRules, you can send traffic not only to pools, but also to individual pool members, ports, or URIs.

The iRules you create can be simple or sophisticated, depending on your content-switching needs. Figure 13.1 shows an example of a simple iRule.

Figure 13.1 Example of an iRule

when CLIENT_ACCEPTED {

if { [IP::addr [IP::client_addr] equals 10.10.10.10] } {

pool my_pool

}

}

This iRule is triggered when a client-side connection has been accepted, causing the LTM system to send the packet to the pool my_pool, if the client's address matches 10.10.10.10.

Using a feature called the Universal Inspection Engine (UIE), you can write an iRule that searches either a header of a packet, or actual packet content, and then directs the packet based on the result of that search. iRules can also direct packets based on the result of a client authentication attempt.

iRules can direct traffic not only to specific pools, but also to individual pool members, including port numbers and URI paths, either to implement persistence or to meet specific load balancing requirements.

The syntax that you use to write iRules is based on the Tool Command Language (Tcl) programming standard. Thus, you can use many of the standard Tcl commands, plus a robust set of extensions that the LTM system provides to help you further increase load balancing efficiency.

For information about standard Tcl syntax, see http://tmml.sourceforge.net/doc/tcl/index.html. For a list of Tcl commands that have been disabled within the LTM system and therefore cannot be used when writing iRules, see Appendix B, Disabled Tcl Commands.

Basic iRule elements

iRules are made up of these basic elements:

Event declarations

Operators

iRule commands

Event declarations

iRules are event-driven, which means that the LTM system triggers an iRule based on an event that you specify in the iRule. An event declaration is the specification of an event within an iRule that causes the LTM system to trigger that iRule whenever that event occurs. Examples of event declarations that can trigger an iRule are HTTP_REQUEST, which triggers an iRule whenever the system receives an HTTP request, and CLIENT_ACCCEPTED, which triggers an iRule when a client has established a connection.

Operators

An iRule operator compares two operands in an expression. In addition to using the Tcl standard operators, you can use the operators listed in Table 13.1 .

Table 13.1 iRule operators

Operator

Syntax

Relational operators

containsmatchesequalsstarts_withends_withmatches_regex

Logical operators

not

and

or

For example, you can use the contains operator to compare a variable operand to a constant. You do this by creating an if statement that represents the following: "If the HTTP URI contains aol, send to pool aol_pool." Figure 13.2 shows an iRule that performs this action.

Figure 13.2 An iRule based on the contains operator

when HTTP_REQUEST {

if { [HTTP::uri] contains "aol" } {

pool aol_pool

} else {

pool all_pool

}

}

iRule commands

An iRule command within an iRule causes the LTM system to take some action, such as querying for data, manipulating data, or specifying a traffic destination. The types of commands that you can include within iRules are:

Statement commandsThese commands cause actions such as selecting a traffic destination or assigning a SNAT translation address. An example of a statement command is pool <name>, which directs traffic to the named load balancing pool. For more information, see Using statement commands.

Query commandsThese commands search for header and content data. An example of a query command is IP::remote_addr, which searches for and returns the remote IP address of a connection. For more information on query commands, see Querying header or content data.

Data manipulation commandsThese commands perform data manipulation such as inserting headers into HTTP requests. An example of a data manipulation command is HTTP::header remove <name>, which removes the last occurrence of the named header from a request or response. For more information on data manipulation commands, see Manipulating header or content data.

Utility commandsThese commands are functions that are useful for parsing and manipulating content. An example of a utility command is decode_uri <string>, which decodes the named string using HTTP URI encoding and returns the result. For more information on using utility commands, see Using utility commands.

Specifying traffic destinations and address translations

As described in the previous section, iRule commands instruct the LTM system to take direct action in some way. The following sections show examples of iRule commands that either direct traffic to a specific destination or assign translation addresses for SNAT implementation.

Selecting a load balancing pool

Once you have specified a query within your iRule, you can use the pool command to select a load balancing pool to which you want the LTM system to send a request. Figure 13.3 shows an example of this command.

Figure 13.3 Example of the pool command within an iRule

when HTTP_REQUEST {

set uri [HTTP::uri]

if { $uri ends_with ".gif" } {

pool my_pool

} elseif { $uri ends_with ".jpg" } {

pool your_pool

}

}

Selecting a specific server

As an alternative to the pool command, you can also write an iRule that directs traffic to a specific server. To do this, you use the node command. Figure 13.4 shows an example of this command.

Figure 13.4 Example of the node command within an iRule

when HTTP_REQUEST {

if { [HTTP::uri] ends_with ".gif" } {

node 10.1.2.200 80

}

}

Redirecting HTTP requests

In addition to configuring an iRule to select a specific pool, you can also configure an iRule to redirect an HTTP request to a specific location, using the HTTP::redirect iRule command. The location can be either a host name or a URI.

For example, Figure 13.5 shows an iRule that is configured to redirect an HTTP response.

Figure 13.5 An iRule based on HTTP redirection

when HTTP_RESPONSE {

if { [HTTP::status] contains "404"} {

HTTP::redirect "http://www.siterequest.com/"

}

}

Figure 13.6 shows an example of an iRule that redirects an HTTP request.

Figure 13.6 Another iRule based on HTTP redirection

when HTTP_REQUEST {

if { [HTTP::uri] contains "secure"} {

HTTP::redirect "https://[HTTP::host][HTTP::uri]"

}

}

Assigning translation addresses for SNAT connections

The iRules feature includes the two statement commands snat and snatpool. Using the snat command, you can assign a specified translation address to an original IP address from within the iRule, instead of using the SNAT screens within the Configuration utility.

Using the snatpool command also assigns a translation address to an original IP address, although unlike the snat command, the snatpool command causes the LTM system to select the translation address from a specified SNAT pool that you previously created.

For detailed syntax information on writing iRules, see the remainder of this chapter.

ImportantOnce you have created an iRule, you need to configure a virtual server to reference the iRule. For information on configuring a virtual server to reference an iRule, see Chapter 2, Configuring Virtual Servers.

Controlling iRule evaluation

In a basic system configuration where no iRule exists, the LTM system directs incoming traffic to the default pool assigned to the virtual server that receives that traffic. However, you might want the LTM system to direct certain kinds of connections to other destinations. The way to do this is to write an iRule that directs traffic to that other destination, contingent on a certain type of event occurring. Otherwise, traffic continues to go to the default pool assigned to the virtual server.

iRules are therefore evaluated whenever an event occurs that you have specified in the iRule. For example, if an iRule includes the event declaration CLIENT_ACCEPTED, then the iRule is triggered whenever the LTM system accepts a client connection. The LTM system then follows the directions in the remainder of the iRule to determine the destination of the packet.

Configuration prerequisites

Before the LTM system can evaluate the iRule that you have written, you must do the following:

Assign the iRule to a virtual server.When an iRule is assigned to virtual server, this means that the virtual server references the iRule, similar to the way that a virtual server references a pool or a profile.

Ensure that the virtual server references the appropriate profile.For example, if your iRule includes the event declaration HTTP_REQUEST, then the LTM system only evaluates the iRule if the virtual server references an http profile type.

NoteWhen assigning an iRule that specifies the event HTTP_REQUEST, make sure that the virtual server references the appropriate profile type.

Specifying events

The iRules feature includes several types of event declarations that you can make in an iRule. Specifying an event declaration determines when the LTM system evaluates the iRule. The following sections list and describe these event types. Also described is the concept of iRule context and the use of the when keyword.

Event types

The iRule command syntax includes several types of event declarations that you can specify within an iRule:

Global events

HTTP events

SSL events

Authentication events

Table 13.2 lists and describes the events that you can declare in an iRule for each of these event types.

Table 13.2 Event declarations for iRules

iRule Event

Description

Global Events

CLIENT_ACCEPTED

Triggered when a client establishes a connection.

CLIENT_DATA

Triggered when a client receives new data while the connection is in collect state.

LB_SELECTED

Triggered when the LTM system has selected a target node.

LB_FAILED

Triggered when a connection to the server was unable to complete. This might occur if the pool has no available members or a selected pool member is otherwise not available.

SERVER_CONNECTED

Triggered when the system establishes a connection with the target node.

SERVER_DATA

Triggered when the system has received new data from the target node while the connection is in hold state.

RULE_INIT

Triggered when you add or modify an iRule. You use this event to initialize global variables that you are using within iRules.

CLIENT_CLOSED

Triggered when the client's connection is closed.

SERVER_CLOSED

Triggered when the server's connection is closed.

HTTP Events

HTTP_CLASS_SELECTED

Triggered when an HTTP request matches an HTTP class. You can use the HTTP::class command to extract the matching class name.

HTTP_REQUEST

Triggered when the system fully parses a complete client request header (that is, the method, URI, version and all headers, not including the body).

HTTP_REQUEST_DATA

Triggered whenever an HTTP::collect command finishes running, after collecting the requested amount of request data. For more information, see Querying HTTP headers and content.

HTTP_REQUEST_SEND

Triggered just before a request is sent to a server. This is a server-side event.

HTTP_RESPONSE

Triggered when the system parses all of the response status and header lines from the server response.

HTTP_RESPONSE_DATA

Triggered whenever an HTTP::collect command finishes running on the server side of a connection, after collecting the requested amount of response data. Also triggered if the server closes the connection before the HTTP:collect command finishes running. For more information, see Querying HTTP headers and content.

HTTP_RESPONSE_CONTINUE

Triggered whenever the system receives a 100 Continue response from the server.

CACHE_REQUEST

Triggered when the system receives a request for a cached object. Used to override default behavior.

CACHE_RESPONSE

Triggered immediately prior to sending a cache response. Used to override default behavior.

SSL Events

CLIENTSSL_HANDSHAKE

Triggered when a client-side SSL handshake is completed.

CLIENTSSL_CLIENTCERT

Triggered when the system adds an SSL client certificate to the client certificate chain. The LTM system can retrieve the X509 certificate and its X509 issuer with the SSL::cert and SSL::cert issuer commands.

SERVERSSL_HANDSHAKE

Triggered when a server-side SSL handshake is completed.

Authentication Events

AUTH_FAILURE

Triggered when an unsuccessful authorization operation is completed. A default handler for this event is associated with each of the authentication profiles, and causes the system to close the connection.

AUTH_ERROR

Triggered when an error occurs during authorization. A default handler for this event is associated with each of the authentication profiles, and causes the system to close the connection. The associated authentication session ID is invalidated and the user should immediately discard the session ID upon receipt of this event.

AUTH_WANTCREDENTIAL

Triggered when an authorization operation needs an additional credential. See also the description of the AUTH::wantcredential_prompt. command in section Querying authentication data. A default handler for this event is associated with each of the authentication profiles, and causes the system to close the connection unless it can obtain the desired credential. Typically this implies that the protocol layer that provides the credential has also not yet obtained the credential, because the system did not enable the necessary authentication protocol. Each of the authentication profiles contains appropriate default handlers for its respective protocol.

AUTH_SUCCESS

Triggered when a successful authorization has completed all of the required authentication services.

iRule context

For every event that you specify within an iRule, you can also specify a context, denoted by the keywords clientside or serverside. Because each event has a default context associated with it, you need only declare a context if you want to change the context from the default.

For example, Figure 13.7 shows my_iRule1, which includes the event declaration CLIENT_ACCEPTED, as well as the iRule command IP::remote_addr. In this case, the IP address that the iRule command returns is that of the client, because the default context of the event declaration CLIENT_ACCEPTED is clientside.

Figure 13.7 An iRule that uses default clientside context

when CLIENT_ACCEPTED {

if { [IP::addr [IP::remote_addr] equals 10.1.1.80] } {

pool my_pool1

}

}

Similarly, if you include the event declaration SERVER_CONNECTED in an iRule as well as the iRule command IP::remote_addr, the IP address that the iRule command returns is that of the server, because the default context of the event declaration SERVER_CONNECTED is serverside.

Figure 13.7 shows what happens when you write an iRule that uses the default context when processing iRule commands. You can, however, explicitly specify the clientside and serverside keywords to alter the behavior of iRule commands.

Continuing with the previous example, Figure 13.8 shows the event declaration SERVER_CONNECTED and explicitly specifies the clientside keyword for the iRule command IP::remote_addr. In this case, the IP address that the iRule command returns is that of the client, despite the serverside default context of the event declaration.

Using the when keyword

You make an event declaration in an iRule by using the when keyword, followed by the event name. The previous figure shows an example of an event declaration in an iRule.

Listing iRules on a virtual server

When you assign multiple iRules as resources for a virtual server, it is important to consider the order in which you list them on the virtual server. This is because the LTM system processes duplicate iRule events in the order that the applicable iRules are listed. An iRule event can therefore terminate the triggering of events, thus preventing the LTM system from triggering subsequent events.

NoteIf an iRule references a profile, the LTM system processes this type of iRule last, regardless of its order in the list of iRules assigned to a virtual server.

Using statement commands

Some of the commands available for use within iRules are known as statement commands. Statement commands enable the LTM system to perform a variety of different actions. For example, some of these commands specify the pools or servers to which you want the LTM system to direct traffic. Other commands specify translation addresses for implementing SNAT connections. Still others specify objects such as data groups or a persistence profiles.

Table 13.3 lists and describes statement commands that you can use within iRules.

Table 13.3 iRule statement commands

Statement Command

Description

clientside {<iRule commands>}

Causes the specified iRule commands to be evaluated under the client-side context. This command has no effect if the iRule is already being evaluated under the client-side context.

discard

Causes the current packet or connection (depending on the context of the event) to be discarded. This statement must be conditionally associated with an if statement.

drop

Same as the discard command.

event [<name>] disable | disable all

Discontinues evaluating the specified iRule event, or all iRule events, on this connection. However, the iRule continues to run.

forward

Sets the connection to forward IP packets.

if { <expression> } {<statement_command>}

elseif { <expression> } {<statement_command>}

Asks a true or false question and, depending on the answer, takes some action.

Note that the maximum number of if statements that you can nest in an iRule is 100.

log [<facility>.<level>] <message>

Generates and logs the specified message to the Syslog facility. The statement does this by performing variable expansion on the message as defined for the Header Insert HTTP profile attribute.

If not used appropriately, a log statement can produce large amounts of output.

matchclass <data-group operator name>

Specifies a data group. Often used within an if statement and in conjunction with the contains operator.

[use] node <addr> [<port>]

Causes the identified server node to be used directly, thus bypassing any load-balancing.

peer { <iRule commands> }

Causes the specified iRule commands to be evaluated under the peer's (opposite) context.

persist <persistence_type>

Causes the LTM system to use the named persistence profile to persist the connection. For more information on using iRules to enable persistence, see Working with profiles.

[use] pool <pool_name> [member <addr> [<port>]]

Causes the LTM system to load balance traffic to the named pool. This statement must be conditionally associated with an if statement. Optionally, you can specify a specific pool member to which you want to direct the traffic.

[use] rateclass <rate_class>

Causes the LTM system to select the specified rate class to use when transmitting packets.

reject

Causes the connection to be rejected, returning a reset as appropriate for the protocol.

return

Terminates execution of the iRule event .

serverside { <iRule commands> }

Causes the specified iRule commands to be evaluated under the server-side context. This command has no effect if the iRule is already being evaluated under the server-side context.

[use] snat <addr> [<port>] | none

Causes the LTM system to assign the specified translation address to one or more origin IP addresses specified in the iRule.

[use] snatpool <snatpool_name> | none

Causes the pool of addresses identified by <snatpool_name> to be used as translation addresses to create a SNAT.

Querying header or content data

The iRules feature includes several commands that are specifically designed to allow you to run queries on the following:

Node status

Link Layer headers

IP headers

TCP headers and content

UDP headers and content

SSL headers in HTTP requests

Authentication data

Statistics data

Querying for node status

You can query for the status of a node by using the LB::status command. Table 13.4 describes this command.

Table 13.4 iRule commands for querying node status

iRule command

Description

LB::status

LB::status node <address>

LB::status pool <pool name> member <IP address> <port>

Returns the status of a node. Possible values are up, down, session_enabled, and session_disabled. If you supply no arguments, returns the status of the currently-selected node.

Querying Link Layer headers

You can select a pool by specifying Link Layer header information. Table 13.5 lists and describes these commands.

Table 13.5 iRule commands for querying Link Layer headers headers

iRule Command

Description

LINK::vlan_id

Returns the VLAN tag of the packet.

LINK::vlan_qos

Returns the VLAN Quality of Service (QoS) value of the packet.

LINK::lasthop

Returns the last hop MAC address.

LINK::nexthop

Returns the next hop MAC accress.

Quality of Service (QoS) level

The Quality of Service (QoS) standard is a means by which network equipment can identify and treat traffic differently based on an identifier. As traffic enters the site, the LTM system can apply an iRule that sends the traffic to different pools of servers based on the QoS level within a packet.

To configure an iRule to select a pool based on the QoS level of a packet, you can use the LINK::vlan_qos iRule command, as you can see in the example in Figure 13.9 .

Querying IP packet headers

You can select a pool by querying for IP packet header information. Table 13.6 lists and describes these commands.

Table 13.6 iRule commands for querying IP packet headers

iRule Command

Description

IP::remote_addr

Returns the remote IP address of a connection.

IP::local_addr

Returns the local IP address of a connection.

IP::client_addr

Returns the client IP address of a connection. This command is equivalent to the command clientside { IP::remote_addr }.

IP::server_addr

Returns the server's IP address. This command is equivalent to the command serverside { IP::remote_addr }. Will return 0 if the load-balancing decision has not occurred.

IP::protocol

Returns the IP protocol value.

IP::tos

Returns the value of the IP protocol's Type of Service (ToS) field.

IP::ttl

Returns the TTL for an inbound IPv4 or IPv6 packet from the peer.

IP::idle_timeout

Returns or sets the idle timeout value.

IP::ttl

Returns the time-to-live (TTL) value for an inbound IPv4 or IPv6 packet.

As you can see by the preceding table, the specific types of IP packet header data that you can query for within an iRule are:

IP addresses

Protocol numbers

ToS levels

Idle timeout values

TTL values

Specifying an IP address

You can specify the IP::remote_addr or IP::local_addr command within an iRule to select a pool. For example, you can load balance traffic based on part of the client's IP address. You can also specify the IP::client_addr and IP::server_addr commands.

Figure 13.10 shows an iRule that implements the preceding statements. In this example, all client requests with the first byte of their source address equal to 206 are directed to a pool named clients_from_206 pool. All other requests are directed to a pool named other_clients_pool.

when CLIENT_ACCEPTED {

if { [IP::addr [IP::remote_addr] equals 206.0.0.0/255.0.0.0] } {

pool clients_from_206

} else {

pool other_clients_pool

}

}

Figure 13.10 An iRule based on the IP::remote_addr command

Specifying an IP protocol number

The LTM system includes an iRule command, IP::protocol, that you can use to select a pool based on an IP protocol number.

To configure an iRule to select a pool based on an IP protocol number, use the syntax shown in the example in Figure 13.11 .

Figure 13.11 An iRule based on an IP protocol number

when CLIENT_ACCEPTED {

if { [IP::protocol] == 6 } {

pool tcp_pool

} else {

pool slow_pool

}

}

Specifying a Type of Service (ToS) level

The Type of Service (ToS) standard is a means by which network equipment can identify and treat traffic differently based on an identifier. As traffic enters the site, the LTM system can apply an iRule that sends the traffic to different pools of servers based on the ToS level within a packet.

The command that you use to set the ToS level on a packet is IP::tos.

To configure an iRule to select a pool based on the ToS level of a packet, you can use the IP::tos iRule command, as shown in the example in Figure 13.12 .

Returns an unused TCP port for the specified IP tuple, using the value of <hint_port> as a starting point.

TCP::offset

Returns the position in the TCP data stream in which the collected TCP data starts.

For example, you might want an iRule that logically states: "If the packet data contains a TCP request containing the string XYZ, then load balance using the pool xyz_servers. If the string is not found, search for the string ABC at the specified offset and load balance using the pool abc_servers. If the string ABC is not found, load balance using the pool web_servers".

To accomplish this, you can write an iRule using the TCP::payload command. Figure 13.13 shows an iRule that illustrates this example.

when CLIENT_ACCEPTED {

TCP::collect 15

}

when CLIENT_DATA {

if { [TCP::payload 15] contains "XYZ" } {

pool xyz_servers

} else {

pool web_servers

}

}

Figure 13.13 Sample iRule using a TCP request string command

Querying HTTP headers and content

You can select a destination by specifying HTTP header or content information. Table 13.9 lists and describes these commands. Note that this list does not include commands for querying SSL-related headers in HTTP requests. For information on querying SSL headers, see Querying SSL headers of HTTP requests.

Table 13.9 iRule commands for querying HTTP headers and content

iRule Command

Description

HTTP::request

Returns the raw request header string. You can access the request payload using the HTTP::collect command.

HTTP::retry <request>

Resends a request to a server. This command applies to server-side iRules.Must be a well-formed and complete request header. Behaves like other requests and generates all client-side events such as HTTP_REQUEST

HTTP::class

Returns the HTTP class selected by the HTTP selector.

HTTP::header [value] <name>

Returns value of the HTTP header named <name>. You can omit the <value> argument if the header name does not collide with any of the subcommands.

HTTP::header names

Returns a list of all the headers present on the request or response.

HTTP::header count

Returns the number of HTTP headers present on the request or response.

HTTP::header at <index>

Returns the HTTP header that the system finds at the zero-based index value.

HTTP::header exists <name>

Returns true if the named header is present on the request or response.

HTTP::method

Returns the type of HTTP request method.

HTTP::status

Returns the response status code.

HTTP::version ["0.9" | "1.0" | "1.1"]

Returns or sets the HTTP version of the request or response.

HTTP::username

Returns the user name part of the HTTP basic authorization.

HTTP::password

Returns the password part of the HTTP basic authorization.

HTTP::path [<string>]

Returns the path part of the HTTP request.

HTTP::uri [<string>]

Returns the complete URI of the request.

HTTP::query [<string>]

Returns the query part of the HTTP request.

HTTP::is_redirect

Returns a true value if the response is a certain type of redirect.

HTTP::is_keepalive

Returns a true value if this is a Keep-Alive connection.

HTTP::collect [<length>]

Collects the amount of data that you specify with the [length] argument. When the system collects the specified amount of data, it calls the Tcl event HTTP_REQUEST_DATA or HTTP_RESPONSE_DATA. Use great caution when omitting the value of the content length. Even though this is allowed in certain cases; doing so or using a value larger than the size of the actual length can stall the connection.

HTTP::release

Releases the collected data. Unless a subsequent HTTP ::collect command was issued, there is no need to use the HTTP::release command inside of the HTTP_REQUEST_DATA and HTTP_RESPONSE_DATA events, since in these cases, the data is implicitly released.

HTTP::payload [<size>]

Returns the content that the HTTP::collect command has collected thus far. If you do not specify a size, the system returns the collected content.

HTTP::payload length

Returns the size of the content that the command has collected thus far, not including the HTTP headers.

HTTP::payload replace <offset> <length> <string>

Replaces the amount of content that you specified with the <length> argument, starting at <offset> with <string>.

CACHE::hits

Returns the document cache hits.

CACHE::age

Returns the age of the document in the cache, in seconds.

CACHE::headers

Returns the HTTP headers of the cache response. This command can only be used with the CACHE_RESPONSE event.

CACHE::payload

Returns the HTTP payload of the cache response. This command can only be used with the CACHE_RESPONSE event.

URI::protocol <string>

Extracts the protocol part from the URI string that you specify.

URI::basename <string>

Extracts the basename part from the URI string that you specify.

URI::path <string>

Extracts the path from the URI string that you specify.

URI::query <string>

Extracts the query part from the URI string that you specify.

URI::host <string>

Extracts the host part from the URI string that you specify.

URI::compare <uri1> <uri2>

Compares URIs as recommended by RFC 2616 section 3.2.3.

URI::decode <string>

Returns the decoded URI string.

URI::encode <string>

Returns the encoded URI string

URI::port <string>

Extracts the port part from the URI string that you specify.

For example, you may want an iRule that logically states: "If the packet data contains an HTTP request with a URI ending in cgi, then load balance using the pool cgi_pool. Otherwise, if the packet data contains an HTTP request with a URI starting with /abc, then load balance using the pool abc_servers. Otherwise, load balance using the virtual server's default pool."

Querying SSL headers of HTTP requests

You can select a destination based on data that resides in the SSL headers of an HTTP request. Table 13.10 lists and describes these commands.

Table 13.10 iRule commands for querying SSL headers in HTTP requests

iRule Command

Description

SSL::mode

In a client-side context, returns one of require, request, ignore, or auto. In a server-side context, returns one of require or ignore.

SSL::cert <index>

Returns the index of the X509 SSL certificate in the peer certificate chain, where index is a value greater than or equal to zero. A value of zero denotes the first certificate in the chain, a value of one is the next, and so on. This command is currently applicable only under a client-side context and returns an error within a server-side context.

SSL::cert issuer <index>

Returns the issuer certificate of the index of the X509 SSL certificate in the peer certificate chain, where index is a value greater than or equal to zero. A value of zero denotes the first certificate in the chain, a value of one is the next, and so on. This command is currently applicable only under a client-side context and returns an error within a server-side context.

SSL::cert count

Returns the total number of certificates that the peer has offered.

SSL::verify_result

Returns the result code from peer certificate verification using the same values as the OpenSSL SSL_get_verify_result() function.

SSL::cipher name

Returns the current SSL cipher version using the format of the OpenSSL SSL_CIPHER_get_version() function.

SSL::cipher version

Returns the current SSL cipher version using the format of the OpenSSL SSL_CIPHER_get_version() function.

SSL::cipher bits

Returns the number of secret bits that the current SSL cipher used, using the format of the OpenSSL SSL_CIPHER_get_bits() function

SSL::current_sessionid

Returns the SSL session ID currently negotiated, or a value of -1, if no session ID exists.

SSL::modssl_sessionid_headers [<option>+]

Returns a list of fields that the system is to add to the HTTP headers in order to emulate modssl behavior. The return type is a Tcl list that the system then interprets as a header name/header value pair. The options that you can specify with this command are initial and current. For information on ModSSL emulation, see Chapter 7, Managing SSL Traffic.

Querying authentication data

You can select a destination based on authentication data. Table 13.11 lists and describes these commands.

Table 13.11 iRule commands for querying authentication data

iRule Command

Description

AUTH::wantcredential_prompt <authid>

Returns the authorization session authid's credential prompt string that the system last requested (when the system generated an AUTH_WANTCREDENTIAL event), for example, Username:. This command is especially helpful in providing authentication services to interactive protocols (for example, telnet and ftp), where the actual text prompts and responses may be directly communicated with the remote user.

AUTH::wantcredential_prompt_style <authid>

Returns the authorization session authid's credential prompt style that the system last requested (when the system generated an AUTH_WANTCREDENTIAL event). This value is either echo_on,echo_off, or unknown. This command is especially helpful in providing authentication services to interactive protocols (or example, telnet and ftp), where the actual text prompts and responses may be directly communicated with the remote user.

AUTH::wantcredential_type <authid>

Returns the authorization session authid's credential type that the system last requested (when the system generated an AUTH_WANTCREDENTIAL event ). This value is either username, password, x509, x509_issuer, or unknown, based upon the system's assessment of the credential prompt string and style.

AUTH::status <authid>

Returns a value of success, failure, error, or not-authed, based on the result of the most recent authorization that the system performed for the authorization session authid.

AUTH::ssl_cc_ldap_username <authid>

Returns the user name that the system retrieved from the LDAP database from the last successful client certificate-based LDAP query for the authorization session authid. The system returns an empty string if the last successful query did not perform a successful client certificate-based LDAP query, or if no query has yet been performed.

AUTH::ssl_cc_ldap_status <authid>

Returns the status from the last successful client certificate-based LDAP query for the authorization session authid. The system returns an empty string if the last successful query did not perform a client certificate-based LDAP query, or if no query has yet been performed.

Querying for statistics data

The iRule command STATS::get retrieves a value of a field that is named in a Statistics profile. Table 13.12 describes this command.

Table 13.12 iRule command for querying Statistics data

iRule Command

Description

STATS::get <profile> <field>

Retrives the value of the named field in the named Statistics profile.

Manipulating header or content data

The iRules feature includes several commands that are specifically designed to manipulate certain types of data. Data manipulation in this case refers to inserting, replacing, and removing data, as well as setting certain values found in headers and cookies.

The types of headers and content that you can manipulate with iRules are:

Link Layer data

IP headers

TCP headers

HTTP headers and cookies

SSL headers

Statistical data

Manipulating Link Layer data

Using the command described in Table 13.13 , you can set the QoS level for transmitting a packet.

Table 13.13 iRule command for manipulating Link Layer data

iRule Command

Description

LINK::vlan_qos

Set the VLAN QoS level that you want the system to use when transmitting the packet.

Manipulating IP headers

Using the command described in Table 13.14 , you can set the ToS level for transmitting the packet.

Table 13.14 iRule command for manipulating IP header data

iRule Command

Description

IP::hops

Finds the nearest, next-highest power of two in the range (such as 64, 128, 255) and subtracts the value retrieved by the IP:ttl command. With the IP::hops command, you can passively estimate the number of hops between a system and its peer. A hop of 0 indicates that the client is on the local network. For example, if the TTL value equals 55, the number of estimated hops is 9 (64 minus 55). If the TTL value equals 127, the number of estimated hops is 1 (128 minus 127).

IP::tos

Sets the IP ToS level that you want the system to use when transmitting the packet.

Manipulating TCP headers and content

Using the commands described in Table 13.15 , you can manipulate TCP headers and content data.

Table 13.15 iRule command for manipulating TCP content data

iRule Command

Description

TCP::collect <length>

Causes TCP to start collecting the specified amount of content data.

TCP::release

Causes TCP to resume processing the connection and to flush collected data.

TCP::payload replace <offset> <length> <data>

Replaces collected payload with the given data.

TCP::respond <data>

Sends the named data directly to the peer. This command is used to complete a protocol handshake with an iRule.

TCP::close

Closes the connection.

Manipulating HTTP headers, content, and cookies

There are several iRule commands that you can use in your iRules to manipulate HTTP header data, content data, and cookies.

Manipulating HTTP headers and content

Table 13.16 lists the iRule commands that you can use to manipulate headers in HTTP requests and responses.

Inserts the named HTTP header and its value into the end of the HTTP request or response. If you specify "lws", the system adds linear white space to long header values.

HTTP::header insert ["lws"] {n1, v1, n2, v2, n3, v3, ...}

Passes a Tcl list to insert into a header. In such cases, the system treats the list as a list of name/value pairs. If you specify "lws", the system adds linear white space to long header values.

HTTP::header [value] <name> <string>

Sets the value of the named header. If the header is present, the command replaces the header; otherwise, the command adds the header. You can omit the <value> argument if the header name does not collide with any other values.

HTTP::header replace <name> [<string>]

Replaces the last occurrence of the named header with the string <string>. This command performs a header insertion if the header was not present.

HTTP::header remove <name>

Removes the last occurrence of the named header from the request or response.

HTTP::close

Inserts a Connection: Close header and close the HTTP connection.

HTTP::redirect <url>

Redirects a HTTP request or response to the specified URL. Note that this command sends the response to the client immediately. Therefore, you cannot specify this command multiple times in an iRule, nor can you specify any other commands that modify header or content, after you specify this command.

This is a powerful API that allows users to generate or rewrite a client request or a server response. When the system runs the command on the client side, it sends the response to the client without any load balancing taking place. If the system runs the command on the server side, the content from the actual server is discarded and replaced with the information provided to this API. Note that because the system sends the response data immediately after this iRule runs, we recommend that you not run any more iRules after this API.

HTTP::header insert_modssl_fields {options}

Inserts a header into an HTTP request. This command name is a misnomer because it does not insert a ModSSLheader. Instead, the command inserts a header that specifies, for a client connection, either the source IP address, the port number, or both.

If no options are specified, the command inserts the header ClientIPAddress: <addr>:<service>. If the optional argument addr or service is specified, the command inserts either the header ClientIPAddress: <addr> or the header ClientTCPService: <service>, respectively..

HTTP::header sanitize <header name>+

Removes all but the headers you specify. The exception to this is some essential HTTP headers.

HTTP::request_num

Returns the number of HTTP requests that a client made on the connection.

CACHE::disable

Disables the caching for this request. You can use this command with the HTTP_RESPONSE and HTTP_REQUEST events.

CACHE::enable

Forces the document to be cached. You can use his command with the HTTP_RESPONSE and HTTP_REQUEST events. You can also use this command to cache non-GET requests.

CACHE::expire

Forces the document to be revalidated from the server.

CACHE::userkey <key string>

Allows users to add user defined values to the key. For example you can use this rule to store different cached content for dialup and broad band by using the MTU as a user defined key string.

CACHE::useragent <string>

Overrides the useragent <string> value used by the cache to store the cached content. This can be used to group various user agent values into a single group to minimize duplicated cached content. This value must be specified in an HTTP_REQUEST event.

CACHE::uri <string>

Overrides the URI value used by the cache to store the cached content. This can be used to group various URIs with parameters that point to the same document. This value must be specified in an HTTP_REQUEST event.

CACHE::accept_encoding <string>

Overrides the accept_encoding value used by the cache to store the cached content. This can be used to group various user encoding values into a single group to minimize duplicated cached content. This value must be specified in an HTTP_REQUEST event.

CACHE::priority <1 .. 10>

Adds a priority to cached documents. The priority can be between 1 and 10 inclusive. This allows users to designate documents that are costly to produce as being more important than others. An example of this is a compressed document.

ONECONNECT::detach [enable | disable ]

When enabled, detaches the client-side and server-side connection.

ONECONNECT::reuse [ enable | disable ]

When enabled, marks whether a connection can be re-used in a connection pool.

COMPRESS::enable

This command enables compression for the current HTTP response. Note that when using this command, you must set the HTTP profile setting Compression to Selective. You can only use this command in the context of the iRule events HTTP_REQUEST, HTTP_REQUEST_DATA, and HTTP_RESPONSE.

COMPRESS::disable

This command enables compression for the current HTTP response. Note that when using this command, you must set the HTTP profile setting Compression to Selective.You can only use this command in the context of the iRule events HTTP_REQUEST, HTTP_REQUEST_DATA, and HTTP_RESPONSE.

COMPRESS::buffer_size <value>

Sets the compression buffer size, described in Chapter 6, Managing HTTP and FTP Traffic. You can only use this command in the context of the iRule events HTTP_REQUEST, HTTP_REQUEST_DATA, and HTTP_RESPONSE.

COMPRESS::gzip memory_level <level>

Sets the gzip memory level, described in Chapter 6, Managing HTTP and FTP Traffic. You can only use this command in the context of the iRule events HTTP_REQUEST, HTTP_REQUEST_DATA, and HTTP_RESPONSE

COMPRESS::gzip window_size <size>

Sets the gzip window size, described in Chapter 6, Managing HTTP and FTP Traffic. You can only use this command in the context of the iRule events HTTP_REQUEST, HTTP_REQUEST_DATA, and HTTP_RESPONSE.

COMPRESS::gzip level <level>

Specifies the amount and rate of compression.

COMPRESS::method prefer [ 'gzip' | 'deflate' ]

Specifies the preferred compression algorithm.

As an option, the value of a header that you insert into an HTTP request can be the result of an SSL query command. To do this, specify an SSL query command as an argument to an HTTP::header insert command. For information on SSL query commands, see Querying SSL headers of HTTP requests.

NoteUsing HTTP::header insert or HTTP::remove commands in an iRule overrides the Header Insert and Header Erase settings in the corresponding HTTP profile.

Manipulating HTTP cookies

Table 13.17 lists the iRule commands that you can use to manipulate cookies in HTTP requests and responses.

Adds or replaces a cookie. The default value for the version is 0. cookies.

HTTP::cookie remove <name>

Removes a cookie.

HTTP::cookie maxage <name> [seconds]

Sets or gets the max-age. Applies to Version 1 cookies only.

HTTP::cookie expires <name> [seconds] [absolute | relative]

Sets or gets the expires attribute. Applies to Version 0 cookies only. If you specify the absolute argument, the seconds value represents number of seconds since the UNIX epoch (January 1, 1970). The default number of seconds is relative, which is the number of seconds from the current time.

HTTP::cookie comment <name> [comment]

Sets or gets the cookie comment. Applicable only to Version 1 cookies.

HTTP::cookie secure <name> [enable|disable]

Sets or gets the secure attribute. Applicable only to Version 1 cookies.

HTTP::cookie commenturl <name> [commenturl]

Sets or gets the comment URL. Applicable only to Version 1 cookies.

HTTP::cookie discard <name> [enable|disable]

Sets or gets the discard attribute. Applicable only to Version 1 cookies.

Decrypts the value for the given cookie using a key generated from the pass phrase. The default key length is 128.

Manipulating SSL headers and content

SSL data manipulation commands that you can use within iRules fall into two categories:

Commands to manipulate SSL query results

Commands to change settings or invoke action

The following two sections describe these commands.

Extracting X509 certificate field values

The iRules feature includes a set of X509 commands that extract X509 certificate field values. You can use these commands with the HTTP::header command when you want to insert, remove, or replace SSL-related headers for HTTP requests. The headers and values that you can query using the X509 iRule commands are listed in Table 13.18.

Table 13.18 SSL header information for use with iRules

Header Type

Header Name and Format

Description

Certificate status

Certificate status

The status of the client certificate. The value of [status] can be NoClientCert, OK, or Error. If status is NoClientCert, only this header is inserted into the request. If status is Error, the error is followed by a numeric error code.

The validity dates for the certificate. The certificate is not valid before or after the dates represented by [before] and [after], respectively.

Certificate subject

SSLClientCertSubject: [subject]

The subject of the certificate.

Public key of the subject

SSLClientCertSubjectPublicKey: [key]

The type of public key type. The allowed types are RSA ([size] bit), DSA, or Unknown public key.

The certificate itself

SSLClientCert: [cert]

The actual client certificate.

MD5 hash of the certificate

SSLClientCertHash: [hash]

The MD5 hash of the client certificate.

Table 13.19 shows the X509 commands that you can use to extract the value of a specific header. Note that the X509::cert_fields command returns a list of all name/value pairs that are suitable for use with the HTTP::header command.

Table 13.19 iRule commands for manipulating SSL query results

iRule Command

Description

X509::version <X509 certificate>

Returns the version number of the X509 certificate (an integer).

X509::serial_number <X509 certificate>

Returns the serial number of the X509 certificate (an integer).

X509::signature_algorithm <X509 certificate>

Returns the signature algorithm of the X509 certificate.

X509::issuer <X509 certificate>

Returns the issuer of the X509 certificate.

X509::not_valid_before <X509 certificate>

Returns the not-valid-before date of the X509 certificate.

X509::not_valid_after <X509 certificate>

Returns the not-valid-after date of the X509 certificate.

X509::subject <X509 certificate>

Returns the subject of the X509 certificate.

X509::subject_public_key_type <X509 certificate>

Returns the subjects public key type of the X509 certificate. The value can be either RSA, DSA, or unknown.

X509::subject_public_key <X509 certificate>

Returns the subjects public key of the X509 certificate.

X509::subject_public_key_RSA_bits <X509 certificate>

Returns the size in bits of the subjects public RSA key of the X509 certificate. This command is only applicable when the public key type is RSA, and generates an error otherwise.

X509::extensions <X509 certificate>

Returns the X509 extensions set on the certificate.

X509::whole <X509 certificate>

Returns the entire X509 certificate in PEM format.

X509::hash <X509 certificate>

Returns the MD5 hash (fingerprint) of the X509 certificate.

X509::verify_cert_error_string <X509 verify error code>

Returns the same result as the OpenSSL function X509_verify_cert_error_string(). The <X509 verify error code> argument uses the same values as those that the SSL::verify result command returns.

Returns a list of header name/value pairs suitable for use with the HTTP::header command.

Setting statistical data

You can use certain commands to set the value of counters that you define in a Statistics profile. Table 13.20 lists and describes these commands.

Table 13.20 iRule command for querying Statistics data

iRule Command

Description

STATS::set <profile> <field> [<value>]

Sets the value of the named field in the named Statistics profile to the specified value. If you do not specify a value, the BIG-IP system sets the value to 0.

STATS::incr <profile> <field> [<value>]

Increments the value of the named field in the named Statistics profile by the specified value. If you do not specify a value, the BIG-IP system sets the value to 1. Incrementing a field value by a negative number decrements the field value.

STATS::setmin <profile> <field> [<value>]

Ensures that the value of the named field in the named Statistics profile is at most value.

STATS::setmax<profile> <field> [<value>]

Ensures that the value of the named field in the named Statistics profile is at least value.

Using utility commands

The LTM system includes a number of utility commands that you can use within iRules. You can use these commands to parse and retrieve content, encode data into ASCII format, verify data integrity, and retrieve information about active pools and pool members.

Parsing and manipulating content

Table 13.21 lists and describes the commands that return a string that you specify. The pages following the table provide detail and examples of the commands.

Table 13.21 Utility commands that parse and manipulate content

Command

Description

findstr

Finds a string within another string and returns the string starting at the offset specified from the match.

substr

Finds a string within another string and returns the string starting at the offset specified from the match.

getfield

Splits a string on a character, and returns the string corresponding to the specific field

findclass

Finds the member of a data group that contains the result of the specified expression, and returns that data group member or the portion following the separator, if a separator was provided.

decode_uri

Evaluates the expression, and returns a string with any %XX escape sequences decoded as per HTTP escape sequences defined in RFC2396. Note that this command is equivalent to the command URI::decode.

domain

Parses and returns up to the specified number of trailing parts of a domain name from the specified expression.

findstr

The findstr command finds the string <search_string> within <string> and returns a sub-string based on the <skip_count> and <terminator> from the matched location.

Note the following;

<terminator> may be either a character or length.

If <skip_count> is not specified, it defaults to zero.

If <terminator> is not specified, it defaults to the end of the string.

This command (without <skip_count> or <terminator>) is equivalent to the following Tcl command: "string range <string> [string first <string> <search_string>] end".

substr

The substr command returns a sub-string <string> based on the values of <skip_count> and <terminator>.

Note the following:

The <skip_count> and <terminator> arguments are used in the same way as they are for the findstr command.

This command is equivalent to the Tcl string range command except that the value of <terminator> may be either a character or a count.

The syntax of the substr command is:

substr <string> <skip_count> [<terminator>]

getfield

The getfield command splits a string on a character, and returns the string corresponding to the specific field.

The syntax of the getfield command is:

getfield <string> <split> <field_number>

findclass

The findclass command searches a data group list for a member that starts with <string> and returns the data-group member string. This is similar to the matchclass command, except that the member is not required to be equal; instead, the member is only required to start with the string and the command returns the entire member value.

The syntax of the findclass command is:

findclass <string> <data group> [(separator)]

Note that if a separator is specified, the data group member is split on the separator, and the latter portion (that is, the portion following the separator) is returned.

decode_uri

The decode_uri command decodes the string <string> using HTTP URI encoding per RFC2616 and returns the result.

The syntax of the decode_uri command is:

decode_uri <string>

domain

The domain command parses the string <string> as a dotted domain name and return the last <count> portions of the domain name.

The syntax of the domain command is:

domain <string> <count>

Encoding data

Some of the commands available for use within iRules allow you to encode data into ASCII format. Table 13.22 lists and describes these commands.

Table 13.22 Utility commands for encoding data

Utility Command

Description

b64encode <string>

Returns a string that is base-64 encoded, or if an error occurs, an empty string.

b64decode <string>

Returns a string that is base-64 decoded, or if an error occurs, an empty string.

Ensuring data integrity

Some of the commands available for use within iRules allow you to check the integrity of data. Table 13.23 lists and describes these commands.

Table 13.23 Utility commands for ensuring data integrity

Utility Command

Description

crc32 <string>

Returns the crc32 checksum for the provided string, or if an error occurs, an empty string. Used to ensure data integrity.

md5 <string>

Returns the RSA Data Security, Inc. MD5 Message Digest Algorithm (md5) message digest of the provided string, or if an error occurs, an empty string. Used to ensure data integrity.

sha1 <string>

Returns the Secure Hash Algorithm version 1.0 (SHA1) message digest of the provided string, or if an error occurs, an empty string. Used to ensure data integrity.

Retrieving pool information

Some of the commands available for use within iRules allow you to retrieve data about pools and pool members. Table 13.24 lists and describes these commands.

Table 13.24 Utility commands for retrieving pool information

Utility Command

Description

active_members <pool name>

Returns the number of active members in the pool.

active_nodes <pool name>

Returns the alias for active pool members (for 4.X compatibility).

member_priority <pool name> member <ip> [<port>]

Returns the priority for pool member ip:port.

Working with profiles

When you are writing an iRule, you might want that iRule to know the value of a particular profile setting so that it can make a more-informed traffic management decision. Fortunately, the iRules feature includes a command that is specifically designed to read the value of profile settings that you specify within the iRule.

Not only can iRules read the values of profile settings, but they can also override values for certain settings. This means that you can apply configuration values to individual connections that differ from the values the LTM system applies to most connections passing through a virtual server.

Reading profile settings

The iRules feature includes a command called PROFILE. When you specify the PROFILE command in an iRule and name a profile type and setting, the iRule reads the value of that particular profile setting. To do this, the iRule finds the named profile type that is assigned to the virtual server and reads the value of the setting that you specified in the PROFILE command sequence. The iRule can then use this information to manage traffic.

For example, you can specify the command PROFILE::tcp idle_timeout within your iRule. The LTM system then finds the TCP profile that is assigned to the virtual server (for example, my_tcp) and queries for the value that you assigned to the Idle Timeout setting.

Overriding profile settings

Some of the iRule commands for querying and manipulating header and content data have equivalent settings within various profiles. When you use those commands in an iRule, and an event triggers that iRule, the LTM system overrides the values of those profile settings, using the value specified within the iRule instead.

For example, an HTTP profile might specify a certain buffer size to use for compressing HTTP data, but you might want to specify a different buffer size for a particular type of HTTP connection. In this case, you can include the command HTTP::compress_buffer_size in your iRule, specifying a different value than the value in the profile.

Enabling session persistence with iRules

Chapter 9, Enabling Session Persistence, describes how to enable session persistence by configuring a persistence profile and assigning it to a virtual server. As described in that chapter, the LTM system applies those persistence profile settings to every applicable session that passes through the virtual server. For example, if you have assigned the msrdp profile to the virtual server, then the LTM system applies those settings to every incoming Microsoft® Remote Desktop Protocol (RDP) connection.

There are cases, however, when you might want to enable persistence in a more granular way. For example, instead of using the ssl persistence profile, which acts on non-terminated SSL traffic only, you might want to persist sessions based on SSL certificate status that you insert into the header of an HTTP request. To do this, you write an iRule using the HTTP::header command and then assign the iRule to the virtual server. Whenever the LTM system accepts an SSL request, the iRule inserts the certificate status as a header into the request, and persists the session based on that status.

The LTM system includes a special iRule command, persist, for implementing the types of session persistence described in Chapter 9, Enabling Session Persistence. You simply type the persist command in your iRule, specifying a persistence type.

For example, you can write an iRule that enables persistence for SSL connections when a particular event occurs, basing the persistence on the session ID. Figure 13.16 shows an example of an iRule that you could write to do this:.

Figure 13.16 Sample iRule for SSL persistence based on session ID

when CLIENTSSL_HANDSHAKE {

persist ssl

}

The following list shows the persist command and the persistence-related keywords that you can specify when defining a persistence type within an iRule. For some persistence keywords, you must specify additional arguments.

persist cookie

persist destaddr [mask <mask>] [<timeout>]

persist hash

persist msrdp

persist sip

persist srcaddr [mask <mask>] [<timeout>]

persist ssl

persist uie <string> [<timeout>]

persist none

You can use the persist none, hash, srcaddr, destaddr, and uie commands in any circumstance, even if a corresponding persistence profile is not configured and assigned to the virtual server. However, the persist ssl, cookie, msrdp, and sip commands require that you assign a corresponding persistence profile to the virtual server. Attempts to use these commands without a corresponding profile result in a run-time iRule error. For information on assigning a persistence profile to a virtual server, see Chapter 2, Configuring Virtual Servers.

Creating, managing, and using data groups

Data groups are useful when writing iRules. A data group is simply a group of related elements, such as a set of IP addresses for AOL clients. When you specify a data group along with the matchclass command or the contains operator, you eliminate the need to list multiple values as arguments in an iRule expression

To understand the usefulness of data groups, it is helpful to first understand the matchclass command and the contains operator.

Using the matchclass command

The LTM system includes an iRule command called matchclass, which you can use to select a pool based on whether the command being used in the iRule represents a member of a specific data group. When you use the matchclass command, the LTM system knows that the string following the identifier is the name of a data group.

For example, using the matchclass command, you can cause the LTM system to load balance all incoming AOL connections to the pool aol_pool, if the value of the IP::remote_addr command is a member of the data group AOL. Figure 13.17 shows this type of iRule. In this case, the matchclass command simply indicates that the object named aol is a collection of values (that is, a data group).

Figure 13.17 An iRule based on the matchclass command

when CLIENT_ACCEPTED {

if { [matchclass [IP::remote_addr] equals $::aol] } {

pool aol_pool

} else {

pool all_pool

}

}

Note that an expression such as [IP::remote__addr] equals matchclass $::aol is true if the expression is true with at least one specific value in the data group.

Creating data groups

When using the matchclass command within an iRule, you can specify any of three types of data groups:

Addresses data group - A collection of IP addresses

String data group - A collection of strings, such as *.jpg

Integer data group - A collection of numeric values.

The following sections describe these data group types.

NoteThe size of a data group is limited by system resources only.

Address data groups

There are two types of IP address data groups, network IP address and host IP address.

The following procedure creates a network or host address data group:

To create an address data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

In the upper right corner of the screen, click Create.

In the Name box, type a unique name for the data group, such as my_address_group.

In the Type box, select Address.The screen expands to show more settings.

In the Records section, select the Type you want, Host or Network.

In the Address box, type the first IP address for the data group. If you are creating a network data group, also enter a network mask in the Mask box.

Click Add.The entry appears in the Address Records box.

Repeat steps 7 and 8 until you have entered all IP addresses.

Click Finished.

String data groups

A string data group contains a list of strings, such as *.jpg or *.gif. The following procedure creates a string data group.

Note that this example shows the use of escape characters for the quotation marks.

To create a string data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

In the upper right corner of the screen, click Create.

In the Name box, type a unique name for the data group, such as my__images.

In the Type box, select String.The screen expands to show the string-specific settings.

In the String box, type the first string for the data group.

Click Add.The entry appears in the String Records box.

Repeat steps 6 and 7 until you have entered all strings.

Click Finished.

Integer data groups

An integer data group contains a list of integers. The following procedure describes how to create an integer data group.

To create an integer data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

In the upper right corner of the screen, click Create.

In the Name box, type a unique name for the data group, such as my__integer_group.

In the Type box, select Integer.The screen expands to display the Records section.

In the Integer box, type the first integer for the data group.

Click Add.The entry appears in the Integer Records box.

Repeat steps 6 and 7 until you have added all integers.

Click Finished.

Storage options

The LTM system allows you to store data groups in two ways, either in-line or externally.

In-line storage

When you create data groups, the LTM system automatically saves them in their entirety in the bigip.conf file. This type of storage is known as in-line storage.

When any data in the data group needs to be updated, the entire data group must be reloaded. In general, in-line storage uses additional system resources due to extensive searching requirements on large data groups. Also, in-line storage requires you to reload entire data groups when incrementally updating data. For these reasons, the LTM system offers you the ability to store you data groups externally, that is, outside of the bigip.conf file.

External storage

You have the option to store data groups in another location on the LTM system, that is, outside of the bigip.conf file. Such data groups are called external data groups. The default location for storing external data groups is the /config directory. Because the data group is stored externally in another location, the bigip.conf file itself contains only meta-data for the data group. The data in an externally-stored data group file is stored as a comma-separated list of values (CSV format).

Creating external data groups is useful because data does not need to be sorted when being loaded. Instead, data is stored in a hash-table in the kernel. This storage method translates to improvements in performance when an iRule uses a large data group to direct traffic to a pool.

To store data groups externally

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

In the upper right corner of the screen, click Create.

In the Name box, type the name of the existing data group that you want to store in an external location.

If you do not want to store your data group in the default external location (/config), use the Path / Filename box to specify a path name and file name for the external location, for example, /home/my_address_group.This file name should match the name that you assigned to the data group itself.

If you want to store your data group in the default external location (/config), leave the Path / Filename box empty.

In the File Contents box, select the file type that pertains to the data group (Address, String, or Integer).

Click Finished.

The LTM system stores the data in an external data group file in comma-separated lists, and the formats of any data values, such as IP addresses, match the formats used in the bigip.conf file. Figure 13.18 shows the contents of the data group file /home/ip2.data group.

Displaying data group properties

Using the Configuration utility, you can display the properties of an existing data group.

To display the properties of an data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

Click the name of a data group.This displays the properties of that data group.

Managing data group members

Using the Configuration utility, you can add members to or delete members from an existing data group.

To add members to a data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

Click the name of a data group.This displays the properties of that data group.

Locate the records box and type an address, string, or integer in the appropriate box.

Click Add.

At the bottom of the screen, click Update.

To delete members from a data group

On the Main tab, expand Local Traffic.

Click iRules.The iRules screen opens.

On the menu bar, click Data Group List.

Click the name of a data group.This displays the properties of that data group.

Check the Select box for the member you want to delete.

Click the Delete button, and when the confirmation message appears, click Delete again.

NoteWhen you synchronize a BIG-IP system redundant-system configuration, the LTM system only includes data groups that reside in the bigip.conf file (that is, in-line stored data groups). If you want the synchronization to include externally-stored data groups, you must add an associated entry for each data group into the bigip.conf file.