Search

Administration and Configuration Guide

download PDF
Red Hat Data Grid 7.2

For use with Red Hat JBoss Data Grid 7.2

Red Hat Customer Content Services

Abstract

This guide presents information about the administration and configuration of Red Hat JBoss Data Grid 7.2

Part I. Introduction

Chapter 1. Setting up Red Hat JBoss Data Grid

1.1. Prerequisites

The only prerequisites to set up Red Hat JBoss Data Grid is a Java Virtual Machine and that the most recent supported version of the product is installed on your system.

1.2. Steps to Set up Red Hat JBoss Data Grid

The following steps outline the necessary (and optional, where stated) steps for a first time basic configuration of Red Hat JBoss Data Grid. It is recommended that the steps are followed in the order specified and not skipped unless they are identified as optional steps.

Set Up JBoss Data Grid

  1. Set Up the Cache Manager

    The foundation of a JBoss Data Grid configuration is a cache manager. Cache managers can retrieve cache instances and create cache instances quickly and easily using previously specified configuration templates. For details about setting up a cache manager, refer to the Cache Manager section in the JBoss Data Grid Getting Started Guide .

  2. Set Up JVM Memory Management

    An important step in configuring your JBoss Data Grid is to set up memory management for your Java Virtual Machine (JVM). JBoss Data Grid offers features such as eviction and expiration to help manage the JVM memory.

    1. Set Up Eviction

      Use eviction to specify the logic used to remove entries from the in-memory cache implementation based on how often they are used. JBoss Data Grid offers different eviction strategies for finer control over entry eviction in your data grid. Eviction strategies and instructions to configure them are available in Configuring Eviction.

    2. Set Up Expiration

      To set upper limits to an entry’s time in the cache, attach expiration information to each entry. Use expiration to set up the maximum period an entry is allowed to remain in the cache and how long the retrieved entry can remain idle before being removed from the cache. For details, see Configuring Expiration.

  3. Monitor Your Cache

    JBoss Data Grid uses logging via JBossLogging to help users monitor their caches.

    1. Set Up Logging

      It is not mandatory to set up logging for your JBoss Data Grid, but it is highly recommended. JBoss Data Grid uses JBossLogging, which allows the user to easily set up automated logging for operations in the data grid. Logs can subsequently be used to troubleshoot errors and identify the cause of an unexpected failure. For details, see Set Up Logging.

  4. Set Up Cache Modes

    Cache modes are used to specify whether a cache is local (simple, in-memory cache) or a clustered cache (replicates state changes over a small subset of nodes). Additionally, if a cache is clustered, either replication, distribution or invalidation mode must be applied to determine how the changes propagate across the subset of nodes. For details, see Set Up Cache Modes.

  5. Set Up Locking for the Cache

    When replication or distribution is in effect, copies of entries are accessible across multiple nodes. As a result, copies of the data can be accessed or modified concurrently by different threads. To maintain consistency for all copies across nodes, configure locking. For details, see Set Up Locking for the Cache and Set Up Isolation Levels.

  6. Set Up and Configure a Cache Store

    JBoss Data Grid offers the passivation feature (or cache writing strategies if passivation is turned off) to temporarily store entries removed from memory in a persistent, external cache store. To set up passivation or a cache writing strategy, you must first set up a cache store.

    1. Set Up a Cache Store

      The cache store serves as a connection to the persistent store. Cache stores are primarily used to fetch entries from the persistent store and to push changes back to the persistent store. For details, see Set Up and Configure a Cache Store.

    2. Set Up Passivation

      Passivation stores entries evicted from memory in a cache store. This feature allows entries to remain available despite not being present in memory and prevents potentially expensive write operations to the persistent cache. For details, see Set Up Passivation.

    3. Set Up a Cache Writing Strategy

      If passivation is disabled, every attempt to write to the cache results in writing to the cache store. This is the default Write-Through cache writing strategy. Set the cache writing strategy to determine whether these cache store writes occur synchronously or asynchronously. For details, see Set Up Cache Writing.

  7. Monitor Caches and Cache Managers

    JBoss Data Grid includes three primary tools to monitor the cache and cache managers once the data grid is up and running.

    1. Set Up JMX

      JMX is the standard statistics and management tool used for JBoss Data Grid. Depending on the use case, JMX can be configured at a cache level or a cache manager level or both. For details, see Set Up Java Management Extensions (JMX).

    2. Access the Administration Console

      Red Hat JBoss Data Grid 7.2.1 introduces an Administration Console, allowing for web-based monitoring and management of caches and cache managers. For usage details refer to Red Hat JBoss Data Grid Administration Console Getting Started.

    3. Set Up Red Hat JBoss Operations Network (JON)

      Red Hat JBoss Operations Network (JON) is the second monitoring solution available for JBoss Data Grid. JBoss Operations Network (JON) offers a graphical interface to monitor runtime parameters and statistics for caches and cache managers. For details, see Set Up Jboss Operations Network(JON).

      Note

      The JON plugin has been deprecated in JBoss Data Grid 7.2 and is expected to be removed in a subsequent version.

  8. Introduce Topology Information

    Optionally, introduce topology information to your data grid to specify where specific types of information or objects in your data grid are located. Server hinting is one of the ways to introduce topology information in JBoss Data Grid.

    1. Set Up Server Hinting

      When set up, server hinting provides high availability by ensuring that the original and backup copies of data are not stored on the same physical server, rack or data center. This is optional in cases such as a replicated cache, where all data is backed up on all servers, racks and data centers. For details, see High Availability Using Server Hinting.

The subsequent chapters detail each of these steps towards setting up a standard JBoss Data Grid configuration.

Part II. Managing JVM Memory

Chapter 2. Eviction and Expiration

Eviction and expiration are strategies for preventing OutOfMemoryError exceptions in the Java heap space. In other words, eviction and expiration ensure that Red Hat JBoss Data Grid does not run out of memory.

2.1. Overview of Eviction and Expiration

Eviction
  • Removes unused entries from memory after the number of entries in the cache reaches a maximum limit.
  • The operation is local to a single cache instance. It removes entries from memory only.
  • Executes each time an entry is added or updated in the cache.
Expiration
  • Removes entries from memory after a certain amount of time.
  • The operation is cluster-wide. It removes entries from memory across all cache instances and also removes entries from the cache store.
  • Expiration operations are processed by threads that you can configure with the ExpirationManager interface.

2.2. Configuring Eviction

You configure Red Hat JBoss Data Grid to perform eviction with the <memory /> element in your cache configuration. Alternatively, you can use the MemoryConfigurationBuilder class to configure eviction programmatically.

2.2.1. Eviction Types

Eviction types define the maximum limit for entries in the cache.

COUNT
Measures the number of entries in the cache. When the count exceeds the maximum, JBoss Data Grid evicts unused entries.
MEMORY
Measures the amount of memory that all entries in the cache take up. When the total amount of memory exceeds the maximum, JBoss Data Grid evicts unused entries.

2.2.2. Storage Types

Storage types define how JBoss Data Grid stores entries in the cache.

Storage TypeDescriptionEviction TypePolicy

OBJECT

Stores entries as objects in the Java heap. This is the default storage type.

COUNT

TinyLFU

BINARY

Stores entries as bytes[] in the Java heap.

COUNT or MEMORY

TinyLFU

OFFHEAP

Stores entries as bytes[] in native memory outside the Java.

COUNT or MEMORY

LRU

Important

The BINARY and OFF-HEAP storage types both violate object equality. This occurs because equality is determined by the equivalence of the resulting bytes[] that the storage types generate instead of the object instances.

Note

Red Hat JBoss Data Grid includes the Caffeine caching library that implements a variation of the Least Frequently Used (LFU) cache replacement algorithm known as TinyLFU. For OFFHEAP JBoss Data Grid uses a custom implementation of the Least Recently Used (LRU) algorithm.

2.2.3. Adding the Memory Element

The <memory> element controls how Red Hat JBoss Data Grid stores entries in memory.

For example, as a starting point to configure eviction for a standalone cache, add the <memory> element as follows:

<local-cache ...>
  <memory>
  </memory>
</local-cache>

2.2.4. Specifying the Storage Type

Define the storage type as a child element under <memory>, as follows:

OBJECT
<memory>
  <object/>
</memory>
BINARY
<memory>
  <binary/>
</memory>
OFFHEAP
<memory>
  <offheap/>
</memory>

2.2.5. Specifying the Eviction Type

Include the eviction attribute with the value set to COUNT or MEMORY.

OBJECT
<memory>
  <object/>
</memory>
Tip

The OBJECT storage type supports COUNT only so you do not need to explicitly set the eviction type.

BINARY
<memory>
  <binary eviction="COUNT"/>
</memory>
OFFHEAP
<memory>
  <offheap eviction="MEMORY"/>
</memory>

2.2.6. Setting the Cache Size

Include the size attribute with a value set to a number greater than zero.

  • For COUNT, the size attribute sets the maximum number of entries the cache can hold before eviction starts.
  • For MEMORY, the size attribute sets the maximum number of bytes the cache can take from memory before eviction starts. For example, a value of 10000000000 is 10 GB.
Tip

Try different cache sizes to determine the optimal setting. A cache size that is too large can cause Red Hat JBoss Data Grid to run out of memory. At the same time, a cache size that is too small wastes available memory.

OBJECT
<memory>
  <object size="100000"/>
</memory>
BINARY
<memory>
  <binary eviction="COUNT" size="100000"/>
</memory>
OFFHEAP
<memory>
  <offheap eviction="MEMORY" size="10000000000"/>
</memory>

2.2.7. Tuning the Off Heap Configuration

Include the address-count attribute when using OFFHEAP storage to prevent collisions that might decrease performance. This attribute specifies the number of pointers that are available in the hash map.

Set the value of the address-count attribute to a number that is greater than the number of cache entries. By default address-count is 2^20, or 1048576. The parameter is always rounded up to a power of 2.

<memory>
  <offheap eviction="MEMORY" size="10000000000" address-count="1048576"/>
</memory>

2.2.8. Setting the Eviction Strategy

Eviction strategies control how Red Hat JBoss Data Grid performs eviction. You set eviction strategies with the strategy attribute.

The default strategy is NONE, which disables eviction unless you explicitly configure it. For example, here are two configurations that have the same effect:

<memory/>
<memory>
  <object strategy="NONE"/>
</memory>

When you configure eviction, you implicitly use the REMOVE strategy. For example, the following two configurations have the same effect:

<memory>
  <object/>
</memory>
<memory>
  <object strategy="REMOVE"/>
</memory>
2.2.8.1. Eviction Strategies
StrategyDescription

NONE

JBoss Data Grid does not evict entries. This is the default setting unless you configure eviction.

REMOVE

JBoss Data Grid removes entries from memory so that the cache does not exceed the configured size. This is the default setting when you configure eviction.

MANUAL

JBoss Data Grid does not perform eviction. Eviction takes place manually by invoking the evict() method from the Cache API.

EXCEPTION

JBoss Data Grid does not write new entries to the cache if doing so would exceed the configured size. Instead of writing new entries to the cache, JBoss Data Grid throws a ContainerFullException.

2.2.9. Configuring Passivation

Passivation configures Red Hat JBoss Data Grid to write entries to a persistent cache store when it removes those entries from memory. In this way, passivation ensures that only a single copy of an entry is maintained, either in-memory or in a cache store but not both.

For more information, see Setting Up Passivation.

2.3. Configuring Expiration

You configure Red Hat JBoss Data Grid to perform expiration at either the entry or cache level.

If you configure expiration for the cache, all entries in that cache inherit that configuration. However, configuring expiration for specific entries takes precedence over configuration for the cache.

You configure expiration for a cache with the <expiration /> element. Alternatively, you can use the ExpirationConfigurationBuilder class to programmatically configure expiration for a cache.

You configure expiration for specific entries with the Cache API.

2.3.1. Expiration Parameters

Expiration parameters configure the amount of time entries can remain in the cache.

lifespan
Specifies how long entries can remain in the cache before they expire. The default value is -1, which is unlimited time.
max-idle
Specifies how long entries can remain idle before they expire. An entry in the cache is idle when no operation is performed with the key. The default value is -1, which is unlimited time.
interval
Specifies the amount of time between expiration operations. The default value is 60000.
Note

While expiration parameters, lifespan and max-idle, are replicated across the cluster, only the value of the lifespan parameter is replicated along with cache entries. For this reason, you should not use the max-idle parameter with clustered caches. For more information on the limitations of using max-idle in clusters, see Red Hat knowledgebase workaround.

2.3.2. Configuring Expiration

Configure Red Hat JBoss Data Grid to perform expiration for a cache as follows:

  1. Add the <expiration /> element

    <expiration />
  2. Configure the lifespan attribute.

    Specify the amount of time, in milliseconds, that an entry can remain in memory as the value, for example:

    <expiration lifespan="1000" />
  3. Configure the max-idle attribute.

    Specify the amount of time, in milliseconds, that an entry can remain idle as the value, for example:

    <expiration lifespan="1000" max-idle="1000" />
  4. Configure the interval attribute.

    Specify the amount of time, in milliseconds, that Red Hat JBoss Data Grid waits between expiration operations, for example:

    <expiration lifespan="1000" max-idle="1000" interval="120000" />
    Tip

    Set a value of -1 to disable periodic expiration.

2.3.3. Expiration Behavior

Red Hat JBoss Data Grid cannot always expire entries immediately when they reach the time limit. Instead, JBoss Data Grid marks entries as expired and removes them when:

  • Writing entries to the cache store.
  • The maintenance thread that processes expiration identifies entries as expired.

This behavior might indicate that JBoss Data Grid is not performing expiration as expected. However it is the case that the entries are marked as expired but not yet removed from either the memory or the cache store.

To ensure that users cannot receive expired entries, JBoss Data Grid returns null values for entries that are marked as expired but not yet removed.

Part III. Monitoring Your Cache

Chapter 3. Set Up Logging

3.1. About Logging

Red Hat JBoss Data Grid provides highly configurable logging facilities for both its own internal use and for use by deployed applications. The logging subsystem is based on JBossLogManager and it supports several third party application logging frameworks in addition to JBossLogging.

The logging subsystem is configured using a system of log categories and log handlers. Log categories define what messages to capture, and log handlers define how to deal with those messages (write to disk, send to console, etc).

After a JBoss Data Grid cache is configured with operations such as eviction and expiration, logging tracks relevant activity (including errors or failures).

When set up correctly, logging provides a detailed account of what occurred in the environment and when. Logging also helps track activity that occurred just before a crash or problem in the environment. This information is useful when troubleshooting or when attempting to identify the source of a crash or error.

3.2. Supported Application Logging Frameworks

3.2.1. Supported Application Logging Frameworks

Red Hat JBoss LogManager supports the following logging frameworks:

3.2.2. About JBoss Logging

JBoss Logging is the application logging framework that is included in JBoss Enterprise Application Platform 7. As a result of this inclusion, Red Hat JBoss Data Grid 7 also uses JBoss Logging.

JBoss Logging provides an easy way to add logging to an application. Add code to the application that uses the framework to send log messages in a defined format. When the application is deployed to an application server, these messages can be captured by the server and displayed and/or written to file according to the server’s configuration.

3.2.3. JBoss Logging Features

JBossLogging includes the following features:

  • Provides an innovative, easy to use typed logger.
  • Full support for internationalization and localization. Translators work with message bundles in properties files while developers can work with interfaces and annotations.
  • Build-time tooling to generate typed loggers for production, and runtime generation of typed loggers for development.

3.3. Boot Logging

3.3.1. Boot Logging

The boot log is the record of events that occur while the server is starting up (or booting). Red Hat JBoss Data Grid also includes a server log, which includes log entries generated after the server concludes the boot process.

3.3.2. Configure Boot Logging

Edit the logging.properties file to configure the boot log. This file is a standard Java properties file and can be edited in a text editor. Each line in the file has the format of property=value.

In Red Hat JBoss Data Grid, the logging.properties file is available in the $JDG_HOME/standalone/configuration folder.

3.3.3. Default Log File Locations

The following table provides a list of log files in Red Hat JBoss Data Grid and their locations:

Table 3.1. Default Log File Locations
Log FileLocationDescription

boot.log

$JDG_HOME/standalone/log/

The Server Boot Log. Contains log messages related to the start up of the server.

By default this file is prepended to the server.log . This file may be created independently of the server.log by defining the org.jboss.boot.log property in logging.properties .

server.log

$JDG_HOME/standalone/log/

The Server Log. Contains all log messages once the server has launched.

3.4. Logging Attributes

3.4.1. About Log Levels

Log levels are an ordered set of enumerated values that indicate the nature and severity of a log message. The level of a given log message is specified by the developer using the appropriate methods of their chosen logging framework to send the message.

Red Hat JBoss Data Grid supports all the log levels used by the supported application logging frameworks. The six most commonly used log levels are (ordered by lowest to highest severity):

  1. TRACE
  2. DEBUG
  3. INFO
  4. WARN
  5. ERROR
  6. FATAL

Log levels are used by log categories and handlers to limit the messages they are responsible for. Each log level has an assigned numeric value which indicates its order relative to other log levels. Log categories and handlers are assigned a log level and they only process log messages of that numeric value or higher. For example a log handler with the level of WARN will only record messages of the levels WARN, ERROR and FATAL.

3.4.2. Supported Log Levels

The following table lists log levels that are supported in Red Hat JBoss Data Grid. Each entry includes the log level, its value and description. The log level values indicate each log level’s relative value to other log levels. Additionally, log levels in different frameworks may be named differently, but have a log value consistent to the provided list.

Table 3.2. Supported Log Levels
Log LevelValueDescription

FINEST

300

-

FINER

400

-

TRACE

400

Used for messages that provide detailed information about the running state of an application. TRACE level log messages are captured when the server runs with the TRACE level enabled.

DEBUG

500

Used for messages that indicate the progress of individual requests or activities of an application. DEBUG level log messages are captured when the server runs with the DEBUG level enabled.

FINE

500

-

CONFIG

700

-

INFO

800

Used for messages that indicate the overall progress of the application. Used for application start up, shut down and other major lifecycle events.

WARN

900

Used to indicate a situation that is not in error but is not considered ideal. Indicates circumstances that can lead to errors in the future.

WARNING

900

-

ERROR

1000

Used to indicate an error that has occurred that could prevent the current activity or request from completing but will not prevent the application from running.

SEVERE

1000

-

FATAL

1100

Used to indicate events that could cause critical service failure and application shutdown and possibly cause JBoss Data Grid to shut down.

3.4.3. About Log Categories

Log categories define a set of log messages to capture and one or more log handlers which will process the messages.

The log messages to capture are defined by their Java package of origin and log level. Messages from classes in that package and of that log level or higher (with greater or equal numeric value) are captured by the log category and sent to the specified log handlers. As an example, the WARNING log level results in log values of 900, 1000 and 1100 are captured.

Log categories can optionally use the log handlers of the root logger instead of their own handlers.

3.4.4. About the Root Logger

The root logger captures all log messages sent to the server (of a specified level) that are not captured by a log category. These messages are then sent to one or more log handlers.

By default the root logger is configured to use a console and a periodic log handler. The periodic log handler is configured to write to the file server.log . This file is sometimes referred to as the server log.

3.4.5. About Log Handlers

Log handlers define how captured log messages are recorded by Red Hat JBoss Data Grid. The six types of log handlers configurable in JBoss Data Grid are:

  • Console
  • File
  • Periodic
  • Size
  • Async
  • Custom

Log handlers direct specified log objects to a variety of outputs (including the console or specified log files). Some log handlers used in JBoss Data Grid are wrapper log handlers, used to direct other log handlers' behavior.

Log handlers are used to direct log outputs to specific files for easier sorting or to write logs for specific intervals of time. They are primarily useful to specify the kind of logs required and where they are stored or displayed or the logging behavior in JBoss Data Grid.

3.4.6. Log Handler Types

The following table lists the different types of log handlers available in Red Hat JBoss Data Grid:

Table 3.3. Log Handler Types
Log Handler TypeDescriptionUse Case

Console

Console log handlers write log messages to either the host operating system’s standard out (stdout) or standard error (stderr) stream. These messages are displayed when JBoss Data Grid is run from a command line prompt.

The Console log handler is preferred when JBoss Data Grid is administered using the command line. In such a case, the messages from a Console log handler are not saved unless the operating system is configured to capture the standard out or standard error stream.

File

File log handlers are the simplest log handlers. Their primary use is to write log messages to a specified file.

File log handlers are most useful if the requirement is to store all log entries according to the time in one place.

Periodic

Periodic file handlers write log messages to a named file until a specified period of time has elapsed. Once the time period has elapsed, the specified time stamp is appended to the file name. The handler then continues to write into the newly created log file with the original name.

The Periodic file handler can be used to accumulate log messages on a weekly, daily, hourly or other basis depending on the requirements of the environment.

Size

Size log handlers write log messages to a named file until the file reaches a specified size. When the file reaches a specified size, it is renamed with a numeric prefix and the handler continues to write into a newly created log file with the original name. Each size log handler must specify the maximum number of files to be kept in this fashion.

The Size handler is best suited to an environment where the log file size must be consistent.

Async

Async log handlers are wrapper log handlers that provide asynchronous behavior for one or more other log handlers. These are useful for log handlers that have high latency or other performance problems such as writing a log file to a network file system.

The Async log handlers are best suited to an environment where high latency is a problem or when writing to a network file system.

Custom

Custom log handlers enable to you to configure new types of log handlers that have been implemented. A custom handler must be implemented as a Java class that extends java.util.logging.Handler and be contained in a module.

Custom log handlers create customized log handler types and are recommended for advanced users.

3.4.7. Selecting Log Handlers

The following are the most common uses for each of the log handler types available for Red Hat JBoss Data Grid:

  • The Console log handler is preferred when JBoss Data Grid is administered using the command line. In such a case, errors and log messages appear on the console window and are not saved unless separately configured to do so.
  • The File log handler is used to direct log entries into a specified file. This simplicity is useful if the requirement is to store all log entries according to the time in one place.
  • The Periodic log handler is similar to the File handler but creates files according to the specified period. As an example, this handler can be used to accumulate log messages on a weekly, daily, hourly or other basis depending on the requirements of the environment.
  • The Size log handler also writes log messages to a specified file, but only while the log file size is within a specified limit. Once the file size reaches the specified limit, log files are written to a new log file. This handler is best suited to an environment where the log file size must be consistent.
  • The Async log handler is a wrapper that forces other log handlers to operate asynchronously. This is best suited to an environment where high latency is a problem or when writing to a network file system.
  • The Custom log handler creates new, customized types of log handlers. This is an advanced log handler.

3.4.8. About Log Formatters

A log formatter is the configuration property of a log handler. The log formatter defines the appearance of log messages that originate from the relevant log handler. The log formatter is a string that uses the same syntax as the java.util.Formatter class.

See http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html for more information.

3.5. Logging Sample Configurations

3.5.1. Logging Sample Configuration Location

All of the sample configurations presented in this section should be placed inside the server’s configuration file, typically either standalone.xml or clustered.xml for standalone instances, or domain.xml for managed domain instances.

3.5.2. Sample XML Configuration for the Root Logger

The following procedure demonstrates a sample configuration for the root logger.

Procedure: Configure the Root Logger

  1. The level property sets the maximum level of log message that the root logger records.

    <subsystem xmlns="urn:jboss:domain:logging:3.0">
       <root-logger>
          <level name="INFO"/>
  2. handlers is a list of log handlers that are used by the root logger.

    <subsystem xmlns="urn:jboss:domain:logging:3.0">
         <root-logger>
            <level name="INFO"/>
            <handlers>
               <handler name="CONSOLE"/>
               <handler name="FILE"/>
            </handlers>
         </root-logger>
      </subsystem>

3.5.3. Sample XML Configuration for a Log Category

The following procedure demonstrates a sample configuration for a log category.

Configure a Log Category

<subsystem xmlns="urn:jboss:domain:logging:3.0">
   <logger category="com.company.accounts.rec" use-parent-handlers="true">
      <level name="WARN"/>
      <handlers>
         <handler name="accounts-rec"/>
      </handlers>
   </logger>
</subsystem>

  1. Use the category property to specify the log category from which log messages will be captured.

    The use-parent-handlers is set to "true" by default. When set to "true", this category will use the log handlers of the root logger in addition to any other assigned handlers.

  2. Use the level property to set the maximum level of log message that the log category records.
  3. The handlers element contains a list of log handlers.

3.5.4. Sample XML Configuration for a Console Log Handler

The following procedure demonstrates a sample configuration for a console log handler.

Configure the Console Log Handler

<subsystem xmlns="urn:jboss:domain:logging:3.0">
   <console-handler name="CONSOLE" autoflush="true">
      <level name="INFO"/>
      <encoding value="UTF-8"/>
      <target name="System.out"/>
      <filter-spec value="not(match(&quot;JBAS.*&quot;))"/>
      <formatter>
         <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
      </formatter>
   </console-handler>
</subsystem>

  1. Add the Log Handler Identifier Information

    The name property sets the unique identifier for this log handler.

    When autoflush is set to "true" the log messages will be sent to the handler’s target immediately upon request.

  2. Set the level Property

    The level property sets the maximum level of log messages recorded.

  3. Set the encoding Output

    Use encoding to set the character encoding scheme to be used for the output.

  4. Define the target Value

    The target property defines the system output stream where the output of the log handler goes. This can be System.err for the system error stream, or System.out for the standard out stream.

  5. Define the filter-spec Property

    The filter-spec property is an expression value that defines a filter. The example provided defines a filter that does not match a pattern: not(match("JBAS.*")).

  6. Specify the formatter

    Use formatter to list the log formatter used by the log handler.

3.5.5. Sample XML Configuration for a File Log Handler

The following procedure demonstrates a sample configuration for a file log handler.

Configure the File Log Handler

<file-handler name="accounts-rec-trail" autoflush="true">
    <level name="INFO"/>
    <encoding value="UTF-8"/>
    <file relative-to="jboss.server.log.dir" path="accounts-rec-trail.log"/>
    <formatter>
        <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
    </formatter>
    <append value="true"/>
</file-handler>

  1. Add the File Log Handler Identifier Information

    The name property sets the unique identifier for this log handler.

    When autoflush is set to "true" the log messages will be sent to the handler’s target immediately upon request.

  2. Set the level Property

    The level property sets the maximum level of log message that the root logger records.

  3. Set the encoding Output

    Use encoding to set the character encoding scheme to be used for the output.

  4. Set the file Object

    The file object represents the file where the output of this log handler is written to. It has two configuration properties: relative-to and path.

    The relative-to property is the directory where the log file is written to. JBoss Enterprise Application Platform 6 file path variables can be specified here. The jboss.server.log.dir variable points to the log/ directory of the server.

    The path property is the name of the file where the log messages will be written. It is a relative path name that is appended to the value of the relative-to property to determine the complete path.

  5. Specify the formatter

    Use formatter to list the log formatter used by the log handler.

  6. Set the append Property

    When the append property is set to "true", all messages written by this handler will be appended to an existing file. If set to "false" a new file will be created each time the application server launches. Changes to append require a server reboot to take effect.

3.5.6. Sample XML Configuration for a Periodic Log Handler

The following procedure demonstrates a sample configuration for a periodic log handler.

Configure the Periodic Log Handler

<periodic-rotating-file-handler name="FILE" autoflush="true">
   <level name="INFO"/>
   <encoding value="UTF-8"/>
   <formatter>
      <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
   </formatter>
   <file relative-to="jboss.server.log.dir" path="server.log"/>
   <suffix value=".yyyy-MM-dd"/>
   <append value="true"/>
</periodic-rotating-file-handler>

  1. Add the Periodic Log Handler Identifier Information

    The name property sets the unique identifier for this log handler.

    When autoflush is set to "true" the log messages will be sent to the handler’s target immediately upon request.

  2. Set the level Property

    The level property sets the maximum level of log message that the root logger records.

  3. Set the encoding Output

    Use encoding to set the character encoding scheme to be used for the output.

  4. Specify the formatter

    Use formatter to list the log formatter used by the log handler.

  5. Set the file Object

    The file object represents the file where the output of this log handler is written to. It has two configuration properties: relative-to and path.

    The relative-to property is the directory where the log file is written to. JBoss Enterprise Application Platform 6 file path variables can be specified here. The jboss.server.log.dir variable points to the log/ directory of the server.

    The path property is the name of the file where the log messages will be written. It is a relative path name that is appended to the value of the relative-to property to determine the complete path.

  6. Set the suffix Value

    The suffix is appended to the filename of the rotated logs and is used to determine the frequency of rotation. The format of the suffix is a dot (.) followed by a date string, which is parsable by the java.text.SimpleDateFormat class. The log is rotated on the basis of the smallest time unit defined by the suffix. For example, yyyy-MM-dd will result in daily log rotation. See http://docs.oracle.com/javase/6/docs/api/index.html?java/text/SimpleDateFormat.html

  7. Set the append Property

    When the append property is set to "true", all messages written by this handler will be appended to an existing file. If set to "false" a new file will be created each time the application server launches. Changes to append require a server reboot to take effect.

3.5.7. Sample XML Configuration for a Size Log Handler

The following procedure demonstrates a sample configuration for a size log handler.

Configure the Size Log Handler

<size-rotating-file-handler name="accounts_debug" autoflush="false">
   <level name="DEBUG"/>
   <encoding value="UTF-8"/>
   <file relative-to="jboss.server.log.dir" path="accounts-debug.log"/>
   <rotate-size value="500k"/>
   <max-backup-index value="5"/>
   <formatter>
        <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
    </formatter>
   <append value="true"/>
</size-rotating-file-handler>

  1. Add the Size Log Handler Identifier Information

    The name property sets the unique identifier for this log handler.

    When autoflush is set to "true" the log messages will be sent to the handler’s target immediately upon request.

  2. Set the level Property

    The level property sets the maximum level of log message that the root logger records.

  3. Set the encoding Object

    Use encoding to set the character encoding scheme to be used for the output.

  4. Set the file Object

    The file object represents the file where the output of this log handler is written to. It has two configuration properties: relative-to and path.

    The relative-to property is the directory where the log file is written to. JBoss Enterprise Application Platform 6 file path variables can be specified here. The jboss.server.log.dir variable points to the log/ directory of the server.

    The path property is the name of the file where the log messages will be written. It is a relative path name that is appended to the value of the relative-to property to determine the complete path.

  5. Specify the rotate-size Value

    The maximum size that the log file can reach before it is rotated. A single character appended to the number indicates the size units: b for bytes, k for kilobytes, m for megabytes, g for gigabytes. For example: 50m for 50 megabytes.

  6. Set the max-backup-index Number

    The maximum number of rotated logs that are kept. When this number is reached, the oldest log is reused.

  7. Specify the formatter

    Use formatter to list the log formatter used by the log handler.

  8. Set the append Property

    When the append property is set to "true", all messages written by this handler will be appended to an existing file. If set to "false" a new file will be created each time the application server launches. Changes to append require a server reboot to take effect.

3.5.8. Sample XML Configuration for a Async Log Handler

The following procedure demonstrates a sample configuration for an async log handler

Configure the Async Log Handler

<async-handler name="Async_NFS_handlers">
   <level name="INFO"/>
   <queue-length value="512"/>
   <overflow-action value="block"/>
   <subhandlers>
      <handler name="FILE"/>
      <handler name="accounts-record"/>
   </subhandlers>
</async-handler>

  1. The name property sets the unique identifier for this log handler.
  2. The level property sets the maximum level of log message that the root logger records.
  3. The queue-length defines the maximum number of log messages that will be held by this handler while waiting for sub-handlers to respond.
  4. The overflow-action defines how this handler responds when its queue length is exceeded. This can be set to BLOCK or DISCARD. BLOCK makes the logging application wait until there is available space in the queue. This is the same behavior as an non-async log handler. DISCARD allows the logging application to continue but the log message is deleted.
  5. The subhandlers list is the list of log handlers to which this async handler passes its log messages.

Part IV. Set Up Cache Modes

Chapter 4. Cache Modes

4.1. Cache Modes

Red Hat JBoss Data Grid provides two modes:

  • Local mode is the only non-clustered cache mode offered in JBoss Data Grid. In local mode, JBoss Data Grid operates as a simple single-node in-memory data cache. Local mode is most effective when scalability and failover are not required and provides high performance in comparison with clustered modes.
  • Clustered mode replicates state changes to a subset of nodes. The subset size should be sufficient for fault tolerance purposes, but not large enough to hinder scalability. Before attempting to use clustered mode, it is important to first configure JGroups for a clustered configuration. For details about configuring JGroups, see Configure JGroups (Library Mode)

4.2. About Cache Containers

Cache containers are used in Red Hat JBoss Data Grid’s Remote Client-Server mode as a starting point for a cache. The cache-container element acts as a parent of one or more (local or clustered) caches. To add clustered caches to the container, transport must be defined.

The following procedure demonstrates a sample cache container configuration:

How to Configure the Cache Container

<subsystem xmlns="urn:infinispan:server:core:8.5"
	   default-cache-container="local">
	<cache-container name="local"
			 default-cache="default"
			 statistics="true"
			 start="EAGER">
		<local-cache name="default"
			     statistics="false">
			     <!-- Additional configuration information here -->
		</local-cache>
	</cache-container>
</subsystem>

  1. Configure the Cache Container

    The cache-container element specifies information about the cache container using the following parameters:

    1. The name parameter defines the name of the cache container.
    2. The default-cache parameter defines the name of the default cache used with the cache container.
    3. The statistics attribute is optional and is true by default. Statistics are useful in monitoring JBoss Data Grid via JMX or JBoss Operations Network, however they adversely affect performance. Disable this attribute by setting it to false if it is not required.
    4. The start parameter indicates when the cache container starts, i.e. whether it will start lazily when requested or "eagerly" when the server starts up. Valid values for this parameter are EAGER and LAZY.
  2. Configure Per-cache Statistics

    If statistics are enabled at the container level, per-cache statistics can be selectively disabled for caches that do not require monitoring by setting the statistics attribute to false.

4.3. Local Mode

4.3.1. Local Mode

Using Red Hat JBoss Data Grid’s local mode instead of a map provides a number of benefits.

Caches offer features that are unmatched by simple maps, such as:

  • Write-through and write-behind caching to persist data.
  • Entry eviction to prevent the Java Virtual Machine (JVM) running out of memory.
  • Support for entries that expire after a defined period.

JBoss Data Grid is built around a high performance, read-based data container that uses techniques such as optimistic and pessimistic locking to manage lock acquisitions.

JBoss Data Grid also uses compare-and-swap and other lock-free algorithms, resulting in high throughput multi-CPU or multi-core environments. Additionally, JBoss Data Grid’s Cache API extends the JDK's ConcurrentMap, resulting in a simple migration process from a map to JBoss Data Grid.

4.3.2. Configure Local Mode

A local cache can be added to any cache container in both Library Mode and Remote Client-Server Mode. The following example demonstrates how to add the local-cache element.

The local-cache Element

<cache-container name="local"
                 default-cache="default"
                 statistics="true">
    <local-cache name="default"
        statistics="true">
        <!-- Additional configuration information here -->
    </local-cache>
</cache-container>

The local-cache element specifies information about the local cache used with the cache container using the following parameters: . The name parameter specifies the name of the local cache to use. . If statistics are enabled at the container level, per-cache statistics can be selectively disabled for caches that do not require monitoring by setting the statistics attribute to false.

Local and clustered caches are able to coexist in the same cache container, however where the container is without a <transport/> it can only contain local caches. The container used in the example can only contain local caches as it does not have a <transport/>.

The cache interface extends the ConcurrentMap and is compatible with multiple cache systems.

4.4. Clustered Modes

4.4.1. Clustered Modes

Red Hat JBoss Data Grid offers the following clustered modes:

  • Replication Mode replicates any entry that is added across all cache instances in the cluster.
  • Invalidation Mode does not share any data, but signals remote caches to initiate the removal of invalid entries.
  • Distribution Mode stores each entry on a subset of nodes instead of on all nodes in the cluster.

The clustered modes can be further configured to use synchronous or asynchronous transport for network communications.

4.4.2. Asynchronous and Synchronous Operations

When a clustered mode (such as invalidation, replication or distribution) is used, data is propagated to other nodes in either a synchronous or asynchronous manner.

If synchronous mode is used, the sender waits for responses from receivers before allowing the thread to continue, whereas asynchronous mode transmits data but does not wait for responses from other nodes in the cluster to continue operations.

JBoss Data Grid clusters are configured to use synchronous operations by default.

4.4.3. About Asynchronous Communications

Asynchronous mode prioritizes speed over consistency, which is ideal for use cases such as HTTP session replications with sticky sessions enabled. Such a session (or data for other use cases) is always accessed on the same cluster node, unless this node fails. If data consistency is required for your use case, you should use synchronous operations.

Additionally, it is not possible for JBoss Data Grid nodes to determine if asynchronous operations succeed because receiving nodes do not send status for operations back to the originating nodes.

In JBoss Data Grid, distributed and replicated caches are represented by the distributed-cache and replicated-cache elements.

Each of these elements contains a mode property, the value of which can be set to SYNC for synchronous, which is the default, or ASYNC for asynchronous communications.

Asynchronous Communications Example Configuration

<replicated-cache name="default"
                  statistics="true"
                  mode="ASYNC">
                 <!-- Additional configuration information here -->
</replicated-cache>

Note

The preceding configuration is valid for both JBoss Data Grid usage modes (Library mode and Remote Client-Server mode). However, this configuration does not apply to local caches local-cache because they are not clustered and do not communicate with other nodes.

4.4.4. Cache Mode Troubleshooting

4.4.4.1. Invalid Data in ReadExternal

If invalid data is passed to readExternal, it can be because when using Cache.putAsync(), starting serialization can cause your object to be modified, causing the datastream passed to readExternal to be corrupted. This can be resolved if access to the object is synchronized.

4.4.4.2. Cluster Physical Address Retrieval

How can the physical addresses of the cluster be retrieved?

The physical address can be retrieved using an instance method call. For example: AdvancedCache.getRpcManager().getTransport().getPhysicalAddresses() .

Chapter 5. Set Up Distribution Mode

5.1. About Distribution Mode

In distribution mode, Red Hat JBoss Data Grid stores cache entries across a subset of nodes in the cluster instead of replicating entries on each node. This improves JBoss Data Grid scalability.

5.2. Consistent Hashing in Distribution Mode

Red Hat JBoss Data Grid uses an algorithm based on consistent hashing to distribute cache entries on nodes across clusters. JBoss Data Grid splits keys in distributed caches into fixed numbers of hash space segments, using MurmurHash3 by default.

Segments are distributed across the cluster to nodes that act as primary and backup owners. Primary owners coordinate locking and write operations for the keys in each segment. Backup owners provide redundancy in the event the primary owner becomes unavailable.

You configure the number of owners with the owners attribute. This attribute defines how many copies of each entry are available across the cluster. The default value is 2, a primary owner and one backup owner.

You can configure the number of hash space segments with the segments attribute. This attribute defines the hash space segments for the named cache across the cluster. The cache always has the configured number of hash segments available across the JBoss Data Grid cluster, no matter how many nodes join or leave.

Additionally, the key-to-segment mapping is fixed. In other words, keys always map to the same segments, regardless of changes to the cluster topology.

The default number of segments is 256, which is suitable for JBoss Data Grid clusters of 25 nodes or less. The recommended value is 20 * the number of nodes for each cluster, which allows you to add nodes and still have capacity.

However, any value within the range of 10 * the number of nodes and 100 * the number of nodes per cluster is fine.

With a perfect segment-to-node mapping, nodes are:

  • primary owner for segments calculated as number of segments / number of nodes
  • any kind of owner for segments calculated as number of owners * number of segments / number of nodes

However, JBoss Data Grid does not always distribute segments evenly and can map more segments to some nodes than others.

Consider a scenario where a cluster has 10 nodes and there are 20 segments per node. If segments are distributed evenly across the cluster, each node is the primary owner for 2 segments. If segments are not distributed evenly, some nodes are primary owners for 3 segments, which represents an increase of 50% for the planned capacity.

Likewise, if the number of owners is 2, each node should own 4 segments. However it could be the case that some nodes are owners for 5 segments, which represents a 25% increase for the planned capacity.

Note

You must restart the JBoss Data Grid cluster for changes to the number of segments to take effect.

5.3. Locating Entries in Distribution Mode

The consistent hash algorithm used in Red Hat JBoss Data Grid’s distribution mode can locate entries deterministically, without multicasting a request or maintaining expensive metadata.

A PUT operation can result in as many remote calls as specified by the owners parameter, while a GET operation executed on any node in the cluster results in a single remote call. In the background, the GET operation results in the same number of remote calls as a PUT operation (specifically the value of the owners parameter), but these occur in parallel and the returned entry is passed to the caller as soon as one returns.

5.4. Return Values in Distribution Mode

In Red Hat JBoss Data Grid’s distribution mode, a synchronous request is used to retrieve the previous return value if it cannot be found locally. A synchronous request is used for this task irrespective of whether distribution mode is using asynchronous or synchronous processes.

5.5. Configure Distribution Mode

Distribution mode is a clustered mode in Red Hat JBoss Data Grid. Distribution mode can be added to any cache container, in both Library Mode and Remote Client-Server Mode, using the following procedure:

The distributed-cache Element

<cache-container name="clustered"
    default-cache="default"
    statistics="true">
  <!-- Additional configuration information here -->
  <distributed-cache name="default"
      statistics="true">
    <!-- Additional configuration information here -->
  </distributed-cache>
</cache-container>

The distributed-cache element configures settings for the distributed cache using the following parameters:

  1. The name parameter provides a unique identifier for the cache.
  2. If statistics are enabled at the container level, per-cache statistics can be selectively disabled for caches that do not require monitoring by setting the statistics attribute to false.
Important

JGroups must be appropriately configured for clustered mode before attempting to load this configuration.

5.6. Synchronous and Asynchronous Distribution

To elicit meaningful return values from certain public API methods, it is essential to use synchronized communication when using distribution mode.

Communication Mode example

For example, with three nodes in a cluster, node A, B and C, and a key K that maps nodes A and B. Perform an operation on node C that requires a return value, for example Cache.remove(K). To execute successfully, the operation must first synchronously forward the call to both node A and B, and then wait for a result returned from either node A or B. If asynchronous communication was used, the usefulness of the returned values cannot be guaranteed, despite the operation behaving as expected.

Chapter 6. Set Up Replication Mode

6.1. About Replication Mode

Red Hat JBoss Data Grid’s replication mode is a simple clustered mode. Cache instances automatically discover neighboring instances on other Java Virtual Machines (JVM) on the same network and subsequently form a cluster with the discovered instances. Any entry added to a cache instance is replicated across all cache instances in the cluster and can be retrieved locally from any cluster cache instance.

In JBoss Data Grid’s replication mode, return values are locally available before the replication occurs.

6.2. Optimized Replication Mode Usage

Replication mode is used for state sharing across a cluster; however, if you have a replicated cache and a large number of nodes are in use then there will be many writes to the replicated cache to keep all of the nodes synchronized. The amount of work performed will depend on many factors and on the specific use case, and for this reason it is recommended to ensure that each workload is tested thoroughly to determine if replication mode will be beneficial with the number of planned nodes. For many situations replication mode is not recommended once there are ten servers; however, in some workloads, such as if load read is important, this mode may be beneficial.

Red Hat JBoss Data Grid can be configured to use UDP multicast, which improves performance to a limited degree for larger clusters.

6.3. Configure Replication Mode

Replication mode is a clustered cache mode in Red Hat JBoss Data Grid. Replication mode can be added to any cache container, in both Library Mode and Remote Client-Server Mode, using the following procedure.

The replicated-cache Element

<cache-container name="clustered"
		 default-cache="default"
		 statistics="true">
  <!-- Additional configuration information here -->
  <replicated-cache name="default"
      statistics="true">
    <!-- Additional configuration information here -->
  </replicated-cache>
</cache-container>

Important

JGroups must be appropriately configured for clustered mode before attempting to load this configuration.

The replicated-cache element configures settings for the distributed cache using the following parameters:

  1. The name parameter provides a unique identifier for the cache.
  2. If statistics are enabled at the container level, per-cache statistics can be selectively disabled for caches that do not require monitoring by setting the statistics attribute to false.

For details about the cache-container and locking, see the appropriate chapter.

6.4. Synchronous and Asynchronous Replication

6.4.1. Synchronous and Asynchronous Replication

Replication mode can be synchronous or asynchronous depending on the problem being addressed.

  • Synchronous replication blocks a thread or caller (for example on a put() operation) until the modifications are replicated across all nodes in the cluster. By waiting for acknowledgments, synchronous replication ensures that all replications are successfully applied before the operation is concluded.
  • Asynchronous replication operates significantly faster than synchronous replication because it does not need to wait for responses from nodes. Asynchronous replication performs the replication in the background and the call returns immediately. Errors that occur during asynchronous replication are written to a log. As a result, a transaction can be successfully completed despite the fact that replication of the transaction may not have succeeded on all the cache instances in the cluster.

6.4.2. Troubleshooting Asynchronous Replication Behavior

In some instances, a cache configured for asynchronous replication or distribution may wait for responses, which is synchronous behavior. This occurs because caches behave synchronously when both state transfers and asynchronous modes are configured. This synchronous behavior is a prerequisite for state transfer to operate as expected.

Use one of the following to remedy this problem:

  • Disable state transfer and use a ClusteredCacheLoader to lazily look up remote state as and when needed.
  • Enable state transfer and REPL_SYNC. Use the Asynchronous API (for example, the cache.putAsync(k, v)) to activate 'fire-and-forget' capabilities.
  • Enable state transfer and REPL_ASYNC. All RPCs end up becoming synchronous, but client threads will not be held up if a replication queue is enabled (which is recommended for asynchronous mode).

6.5. The Replication Queue

6.5.1. The Replication Queue

In replication mode, Red Hat JBoss Data Grid uses a replication queue to replicate changes across nodes based on the following:

  • Previously set intervals.
  • The queue size exceeding the number of elements.
  • A combination of previously set intervals and the queue size exceeding the number of elements.

The replication queue ensures that during replication, cache operations are transmitted in batches instead of individually. As a result, a lower number of replication messages are transmitted and fewer envelopes are used, resulting in improved JBoss Data Grid performance.

A disadvantage of using the replication queue is that the queue is periodically flushed based on the time or the queue size. Such flushing operations delay the realization of replication, distribution, or invalidation operations across cluster nodes. When the replication queue is disabled, the data is directly transmitted and therefore the data arrives at the cluster nodes faster.

A replication queue is used in conjunction with asynchronous mode.

6.5.2. Replication Queue Usage

When using the replication queue, do one of the following:

  • Disable asynchronous marshalling.
  • Set the max-threads count value to 1 for the executor attribute of the transport element. The executor is only available in Library Mode, and is therefore defined in its configuration file as follows:

    <transport executor="infinispan-transport"/>

To implement either of these solutions, the replication queue must be in use in asynchronous mode. Asynchronous mode can be set by defining mode="ASYNC", as seen in the following example:

Replication Queue in Asynchronous Mode

<replicated-cache name="asyncCache"
                  mode="ASYNC"
                  statistics="true"
              <!-- Additional configuration information here -->
</replicated-cache>

The replication queue allows requests to return to the client faster, therefore using the replication queue together with asynchronous marshalling does not present any significant advantages.

6.6. About Replication Guarantees

In a clustered cache, the user can receive synchronous replication guarantees as well as the parallelism associated with asynchronous replication. Red Hat JBoss Data Grid provides an asynchronous API for this purpose.

The asynchronous methods used in the API return Futures, which can be queried. The queries block the thread until a confirmation is received about the success of any network calls used.

6.7. Replication Traffic on Internal Networks

Some cloud providers charge less for traffic over internal IP addresses than for traffic over public IP addresses, or do not charge at all for internal network traffic (for example, ). To take advantage of lower rates, you can configure Red Hat JBoss Data Grid to transfer replication traffic using the internal network. With such a configuration, it is difficult to know the internal IP address you are assigned. JBoss Data Grid uses JGroups interfaces to solve this problem.

Chapter 7. Set Up Invalidation Mode

7.1. About Invalidation Mode

Invalidation is a clustered mode that does not share any data, but instead removes potentially obsolete data from remote caches. Using this cache mode requires another, more permanent store for the data such as a database.

Red Hat JBoss Data Grid, in such a situation, is used as an optimization for a system that performs many read operations and prevents database usage each time a state is needed.

When invalidation mode is in use, data changes in a cache prompts other caches in the cluster to evict their outdated data from memory.

7.2. Configure Invalidation Mode

Invalidation mode is a clustered mode in Red Hat JBoss Data Grid. Invalidation mode can be added to any cache container, in both Library Mode and Remote Client-Server Mode, using the following procedure:

The invalidation-cache Element

<cache-container name="local"
     		 default-cache="default"
     		 statistics="true">
	<invalidation-cache name="default"
			    statistics="true">
			<!-- Additional configuration information here -->
	</invalidation-cache>
</cache-container>

The invalidation-cache element configures settings for the distributed cache using the following parameters:

  1. The name parameter provides a unique identifier for the cache.
  2. If statistics are enabled at the container level, per-cache statistics can be selectively disabled for caches that do not require monitoring by setting the statistics attribute to false.
Important

JGroups must be appropriately configured for clustered mode before attempting to load this configuration.

For details about the cache-container see the appropriate chapter.

7.3. Synchronous/Asynchronous Invalidation

In Red Hat JBoss Data Grid’s Library mode, invalidation operates either asynchronously or synchronously.

  • Synchronous invalidation blocks the thread until all caches in the cluster have received invalidation messages and evicted the obsolete data.
  • Asynchronous invalidation operates in a fire-and-forget mode that allows invalidation messages to be broadcast without blocking a thread to wait for responses.

7.4. The L1 Cache and Invalidation

An invalidation message is generated each time a key is updated. This message is multicast to each node that contains data that corresponds to current L1 cache entries. The invalidation message ensures that each of these nodes marks the relevant entry as invalidated.

Chapter 8. State Transfer

8.1. State Transfer

State transfer is a basic data grid or clustered cache functionality. Without state transfer, data would be lost as nodes are added to or removed from the cluster.

State transfer adjusts the cache’s internal state in response to a change in a cache membership. The change can be when a node joins or leaves, when two or more cluster partitions merge, or a combination of joins, leaves, and merges. State transfer occurs automatically in Red Hat JBoss Data Grid whenever a node joins or leaves the cluster.

In Red Hat JBoss Data Grid’s replication mode, a new node joining the cache receives the entire cache state from the existing nodes. In distribution mode, the new node receives only a part of the state from the existing nodes, and the existing nodes remove some of their state in order to keep owners copies of each key in the cache (as determined through consistent hashing). In invalidation mode the initial state transfer is similar to replication mode, the only difference being that the nodes are not guaranteed to have the same state. When a node leaves, a replicated mode or invalidation mode cache does not perform any state transfer. A distributed cache needs to make additional copies of the keys that were stored on the leaving nodes, again to keep owners copies of each key.

A State Transfer transfers both in-memory and persistent state by default, but both can be disabled in the configuration. When State Transfer is disabled a ClusterLoader must be configured, otherwise a node will become the owner or backup owner of a key without the data being loaded into its cache. In addition, if State Transfer is disabled in distributed mode then a key will occasionally have less than owners owners.

8.2. Non-Blocking State Transfer

Non-Blocking State Transfer in Red Hat JBoss Data Grid minimizes the time in which a cluster or node is unable to respond due to a state transfer in progress. Non-blocking state transfer is a core architectural improvement with the following goals:

  • Minimize the interval(s) where the entire cluster cannot respond to requests because of a state transfer in progress.
  • Minimize the interval(s) where an existing member stops responding to requests because of a state transfer in progress.
  • Allow state transfer to occur with a drop in the performance of the cluster. However, the drop in the performance during the state transfer does not throw any exception, and allows processes to continue.
  • Allows a GET operation to successfully retrieve a key from another node without returning a null value during a progressive state transfer.

For simplicity, the total order-based commit protocol uses a blocking version of the currently implemented state transfer mechanism. The main differences between the regular state transfer and the total order state transfer are:

  • The blocking protocol queues the transaction delivery during the state transfer.
  • State transfer control messages (such as CacheTopologyControlCommand) are sent according to the total order information.

The total order-based commit protocol works with the assumption that all the transactions are delivered in the same order and they see the same data set. So, no transactions are validated during the state transfer because all the nodes must have the most recent key or values in memory.

Using the state transfer and blocking protocol in this manner allows the state transfer and transaction delivery on all on the nodes to be synchronized. However, transactions that are already involved in a state transfer (sent before the state transfer began and delivered after it concludes) must be resent. When resent, these transactions are treated as new joiners and assigned a new total order value.

8.3. Suppress State Transfer via JMX

State transfer can be suppressed using JMX in order to bring down and relaunch a cluster for maintenance. This operation permits a more efficient cluster shutdown and startup, and removes the risk of Out Of Memory errors when bringing down a grid.

When a new node joins the cluster and rebalancing is suspended, the getCache() call will timeout after stateTransfer.timeout expires unless rebalancing is re-enabled or stateTransfer.awaitInitialTransferis set to false.

Disabling state transfer and rebalancing can be used for partial cluster shutdown or restart, however there is the possibility that data may be lost in a partial cluster shutdown due to state transfer being disabled.

8.4. The rebalancingEnabled Attribute

Suppressing rebalancing can only be triggered via the rebalancingEnabled JMX attribute, and requires no specific configuration.

The rebalancingEnabled attribute can be modified for the entire cluster from the LocalTopologyManager JMX Mbean on any node. This attribute is true by default, and is configurable programmatically.

Servers such as Hot Rod attempt to start all caches declared in the configuration during startup. If rebalancing is disabled, the cache will fail to start. Therefore, it is mandatory to use the following setting in a server environment:

<state-transfer enabled="true" await-initial-transfer="false"/>

Part V. Enabling APIs

Chapter 9. Enabling APIs Declaratively

9.1. Enabling APIs Declaratively

The various APIs that JBoss Data Grid provides are fully documented in the JBoss Data Grid Developer Guide ; however, Administrators can enable these declaratively by adding elements to the configuration file. The following sections discuss methods on implementing the various APIs.

9.2. Batching API

Batching allows atomicity and some characteristics of a transaction, but does not allow full-blown JTA or XA capabilities. Batching is typically lighter and cheaper than a full-blown transaction, and should be used whenever the only participant in the transaction is the JBoss Data Grid cluster. If the transaction involves multiple systems then JTA Transactions should be used. For example, consider a transaction which transfers money from one bank account to another. If both accounts are stored within the JBoss Data Grid cluster then batching could be used; however, if only one account is inside the cluster, with the second being in an external database, then distributed transactions are required.

Note

Transaction batching is only available in JBoss Data Grid’s Library Mode.

Enabling the Batching API

Batching may be enabled on a per-cache basis by defining a transaction mode of BATCH. The following example demonstrates this:

<local-cache name="batchingCache">
   <transaction mode="BATCH"/>
</local-cache>

By default invocation batching is disabled; in addition, a transaction manager is not required to use batching.

9.3. Grouping API

The grouping API allows a group of entries to be co-located on the same node, instead of the default behavior of having each entry being stored on a node corresponding to a calculated hash code of the entry. By default JBoss Data Grid will take a hash code of each key when it is stored and map that key to a hash segment; this allows an algorithm to be used to determine the node that contains the key, allowing each node in the cluster to know which node contains the key without distributing ownership information. This behavior reduces overhead and improves redundancy as the ownership information does not need to be replicated should a node fail.

By enabling the grouping API the hash of the key is ignored when deciding which node to store the entry on. Instead, a hash of the group is obtained and used in its place, while the hash of the key is used internally to prevent performance degradation. When the group API is in use every node can still determine the owners of the key, and due to this reason the group may not be manually specified. A group may either be intrinsic to the entry, generated by the key class, or extrinsic to the entry, generated by an external function.

Enabling the Grouping API

The grouping API may be enabled on a per-cache basis by adding the groups element as seen in the following example:

<distributed-cache name="groupingCache">
    <groups enabled="true"/>
</distributed-cache>

Defining an Extrinsic Group

Assuming a custom Grouper exists it may be defined by passing in the classname as seen below:

<distributed-cache name="groupingCache">
    <groups enabled="true">
        <grouper class="com.acme.KXGrouper" />
    </groups>
</distributed-cache>

9.4. Externalizable API

9.4.1. The Externalizable API

An Externalizer is a class that can:

  • Marshall a given object type to a byte array.
  • Unmarshall the contents of a byte array into an instance of the object type.

Externalizers are used by Red Hat JBoss Data Grid and allow users to specify how their object types are serialized. The marshalling infrastructure used in Red Hat JBoss Data Grid builds upon JBoss Marshalling and provides efficient payload delivery and allows the stream to be cached. The stream caching allows data to be accessed multiple times, whereas normally a stream can only be read once.

The Externalizable interface uses and extends serialization. This interface is used to control serialization and deserialization in Red Hat JBoss Data Grid.

9.4.2. Register the Advanced Externalizer (Declaratively)

After the advanced externalizer is set up, register it for use with Red Hat JBoss Data Grid. This registration is done declaratively (via XML) as follows:

Register the Advanced Externalizer

<infinispan>
    <cache-container>
        <serialization>
            <advanced-externalizer class="Book$BookExternalizer" />
        </serialization>
    </cache-container>
</infinispan>

  1. Add the serialization element to the cache-container element.
  2. Add the advanced-externalizer element, defining the custom Externalizer with the class attribute. Replace the Book$BookExternalizer values as required.

9.4.3. Configuring the Deserialization Whitelist

For security reasons, the Red Hat JBoss Data Grid server does not deserialize objects of an arbitrary class. JBoss Data Grid allows deserialization only for strings and primitives. If you want JBoss Data Grid to deserialize objects for other Java class instances, you must configure a deserialization whitelist.

Add the following system properties to the JVM at start up:

  • -Dinfinispan.deserialization.whitelist.classes Specifies the fully qualified names of one or more Java classes. JBoss Data Grid deserializes objects that belong to those classes.
  • -Dinfinispan.deserialization.whitelist.regexps Specifies one or more regular expressions. JBoss Data Grid deserializes objects that belong to any class that matches those expressions.
Note

Both system properties are optional. You can specify a combination of both properties or specify either property by itself.

For example, the following system properties enable deserialization for the com.foo.bar.spotprice.Price and com.foo.bar.spotprice.Currency classes as well as for any classes that match the .*SpotPrice.* expression:

-Dinfinispan.deserialization.whitelist.classes=com.foo.bar.spotprice.Price,com.foo.bar.spotprice.Currency
-Dinfinispan.deserialization.whitelist.regexps=.*SpotPrice.*

If you want to configure the whitelist so that JBoss Data Grid allows deserialization for any Java class, specify the following:

-Dinfinispan.deserialization.whitelist.regexps=.*

For information on configuring clients to restrict deserialization to specific Java classes, see Restricting Deserialization to Specific Java Classes in the Developer Guide.

9.4.4. Custom Externalizer ID Values

9.4.4.1. Custom Externalizer ID Values

Advanced externalizers can be assigned custom IDs if desired. Some ID ranges are reserved for other modules or frameworks and must be avoided:

Table 9.1. Reserved Externalizer ID Ranges
ID RangeReserved For

1000-1099

The Infinispan Tree Module

1100-1199

Red Hat JBoss Data Grid Server modules

1200-1299

Hibernate Infinispan Second Level Cache

1300-1399

JBoss Data Grid Lucene Directory

1400-1499

Hibernate OGM

1500-1599

Hibernate Search

1600-1699

Infinispan Query Module

1700-1799

Infinispan Remote Query Module

1800-1849

JBoss Data Grid Scripting Module

1850-1899

JBoss Data Grid Server Event Logger Module

1900-1999

JBoss Data Grid Remote Store

9.4.4.2. Customize the Externalizer ID (Declaratively)

Customize the advanced externalizer ID declaratively (via XML) as follows:

Customizing the Externalizer ID (Declaratively)

<infinispan>
    <cache-container>
        <serialization>
            <advanced-externalizer id="123"
                                   class="Book$BookExternalizer"/>
        </serialization>
    </cache-container>
</infinispan>

  1. Add the serialization element to the cache-container element.
  2. Add the advanced-externalizer element to add information about the new advanced externalizer.
  3. Define the externalizer ID using the id attribute. Ensure that the selected ID is not from the range of IDs reserved for other modules.
  4. Define the externalizer class using the class attribute. Replace the Book$BookExternalizer values as required.

Chapter 10. Set Up and Configure the Infinispan Query API

10.1. Set Up Infinispan Query

10.1.1. Infinispan Query Dependencies in Library Mode

To use the JBoss Data Grid Infinispan Query via Maven, add the following dependencies:

<dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-embedded-query</artifactId>
    <version>${infinispan.version}</version>
</dependency>

Non-Maven users must install all of the infinispan-embedded-query.jar and infinispan-embedded.jar files from the JBoss Data Grid distribution.

Warning

The Infinispan query API directly exposes the Hibernate Search and the Lucene APIs and cannot be embedded within the infinispan-embedded-query.jar file. Do not include other versions of Hibernate Search and Lucene in the same deployment as infinispan-embedded-query . This action will cause classpath conflicts and result in unexpected behavior.

10.2. Directory Providers

10.2.1. Directory Providers

The following directory providers are supported in Infinispan Query:

  • RAM Directory Provider
  • Filesystem Directory Provider
  • Infinispan Directory Provider

10.2.2. RAM Directory Provider

Storing the global index locally in Red Hat JBoss Data Grid’s Query Module allows each node to

  • maintain its own index.
  • use Lucene's in-memory or filesystem-based index directory.

The following example demonstrates an in-memory, RAM-based index store:

<local-cache name="indexesInMemory">
    <indexing index="LOCAL">
        <property name="default.directory_provider">ram</property>
    </indexing>
</local-cache>

10.2.3. Filesystem Directory Provider

To configure the storage of indexes, set the appropriate properties when enabling indexing in the JBoss Data Grid configuration.

This example shows a disk-based index store:

Disk-based Index Store

<local-cache name="indexesInInfinispan">
    <indexing index="ALL">
        <property name="default.directory_provider">filesystem</property>
        <property name="default.indexBase">/tmp/ispn_index</property>
    </indexing>
</local-cache>

10.2.4. Infinispan Directory Provider

In addition to the Lucene directory implementations, Red Hat JBoss Data Grid also ships with an infinispan-directory module.

Note

Red Hat JBoss Data Grid only supports infinispan-directory in the context of the Querying feature, not as a standalone feature.

The infinispan-directory allows Lucene to store indexes within the distributed data grid. This allows the indexes to be distributed, stored in-memory, and optionally written to disk using the cache store for durability.

Sharing the same index instance using the Infinispan Directory Provider introduces a write contention point, as only one instance can write on the same index at the same time.

Important

By default the exclusive_index_use is set to true, as this provides major performance increases; however, if external applications access the same index in use by Infinispan this property must be set to false. The default value is recommended for the majority of applications and use cases due to the performance increases, so only change this if absolutely necessary.

InfinispanIndexManager provides a default back end that sends all updates to master node which later applies the updates to the index. In case of master node failure, the update can be lost, therefore keeping the cache and index non-synchronized. Non-default back ends are not supported.

Enable Shared Indexes

<local-cache name="indexesInInfinispan">
    <indexing index="ALL">
        <property name="default.directory_provider">infinispan</property>
        <property name="default.indexmanager">org.infinispan.query.indexmanager.InfinispanIndexManager</property>
    </indexing>
</local-cache>

When using an indexed, clustered cache ensure that the caches containing the index data are also clustered, as described in Tuning Infinispan Directory.

10.3. Configure Indexing

10.3.1. Configure the Index in Remote Client-Server Mode

In Remote Client-Server Mode, index configuration depends on the provider and its configuration. The indexing mode depends on the provider and whether or not it is local or distributed.

The following indexing modes are supported:

  • NONE
  • LOCAL = indexLocalOnly="true"
  • ALL = indexLocalOnly="false"

Index configuration in Remote Client-Server Mode is as follows:

Configuration in Remote Client-Server Mode

<indexing index="LOCAL">
    <property name="default.directory_provider">ram</property>
    <!-- Additional configuration information here -->
</indexing>

Configure Lucene Caches

By default the Lucene caches will be created as local caches; however, with this configuration the Lucene search results are not shared between nodes in the cluster. To prevent this define the caches required by Lucene in a clustered mode, as seen in the following configuration snippet:

Configuring the Lucene cache in Remote Client-Server Mode

<cache-container name="clustered" default-cache="repltestcache">
    [...]
    <replicated-cache name="LuceneIndexesMetadata" />
    <distributed-cache name="LuceneIndexesData" />
    <replicated-cache name="LuceneIndexesLocking" />
    [...]
</cache-container>

These caches are discussed in further detail at in the Red Hat JBoss Data Grid Developer Guide .

10.3.2. Automatic Indexing

You can use the auto-config attribute to automatically configure indexing based on the cache type.

  • Replicated and local caches: Indexing is persisted to disk and is not shared with other processes. Indexing is also configured so that there is minimum delay between the time an object is indexed and the time it becomes available for searches.
  • Distributed caches: Indexing is handled internally to Red Hat JBoss Data Grid as a master-slave mechanism so that indexing operations are delegated to a single node that writes to the index.

The following XML snippet shows a local cache configuration with the auto-config attribute:

<local-cache name="default">
   <indexing index="LOCAL" auto-config="true">
   </indexing>
</local-cache>

The auto-config attribute adds properties to the cache. You can tune the indexing behavior by re-defining the properties or adding new properties.

Table 10.1. Properties for Replicated and Local Caches
PropertyValueDescription

default.directory_provider

filesystem

Use a filesystem to store the index.

default.exclusive_index_use

true

Perform indexing operations in exclusive mode. This mode allows Hibernate Search to optimize writes.

default.indexmanager

near-real-time

Use Lucene’s Near-Real-Time (NRT) search feature.

default.reader.strategy

shared

Reuse the index reader across several queries.

Table 10.2. Properties for Distributed Caches
PropertyValueDescription

default.directory_provider

infinispan

Store indexes interally to JBoss Data Grid.

default.exclusive_index_use

true

Perform indexing operations in exclusive mode. This mode allows Hibernate Search to optimize writes.

default.indexmanager

org.infinispan.query.indexmanager.InfinispanIndexManager

Delegate index write operations to a single node in the cluster.

default.reader.strategy

shared

Reuse the index reader across several queries.

10.3.3. Rebuilding the Index

You can manually rebuild the Lucene index if required. However, you do not usually need to rebuild the index manually because JBoss Data Grid maintains the index during normal operation.

Rebuilding the index actually reconstructs the entire index from the data store, which requires JBoss Data Grid to process all data in the grid and can take a very long time to complete. You should only need to rebuild the Lucene index if:

  • The definition of what is indexed in the types has changed.
  • A parameter affecting how the index is defined, such as the Analyser changes.
  • The index is destroyed or corrupted, possibly due to a system administration error.

Rebuilding the index may be performed by executing the Start operation on the MassIndexer MBean.

10.4. Tuning the Index

10.4.1. Near-Realtime Index Manager

By default, each update is immediately flushed into the index. In order to achieve better throughput, the updates can be batched. However, this can result in a lag between the update and query — the query can see outdated data. If this is acceptable, you can use the Near-Realtime Index Manager by setting the following.

<property name="default.indexmanager">near-real-time</property>

10.4.2. Tuning Infinispan Directory

Lucene directory uses three caches to store the index:

  • Data cache
  • Metadata cache
  • Locking cache

Configuration for these caches can be set explicitly, specifying the cache names as in the example below, and configuring those caches as usual. All of these caches must be clustered unless Infinispan Directory is used in local mode.

Tuning the Infinispan Directory

<distributed-cache name="indexedCache" >
    <indexing index="LOCAL">
        <property name="default.indexmanager">org.infinispan.query.indexmanager.InfinispanIndexManager</property>
        <property name="default.metadata_cachename">lucene_metadata_repl</property>
        <property name="default.data_cachename">lucene_data_dist</property>
        <property name="default.locking_cachename">lucene_locking_repl</property>
    </indexing>
</distributed-cache>

<replicated-cache name="lucene_metadata_repl" />

<distributed-cache name="lucene_data_dist" />

<replicated-cache name="lucene_locking_repl" />

10.4.3. Per-Index Configuration

The indexing properties in examples above apply for all indices - this is because we use the default. prefix for each property. To specify different configuration for each index, replace default with the index name. By default, this is the full class name of the indexed object, however you can override the index name in the @Indexed annotation.

Chapter 11. The Health Check API

11.1. The Health Check API

The Health Check API allows users to monitor the health of the cluster, and the caches contained within. This information is particularly important when working in a cloud environment, as it provides a method of querying to report the status of the cluster or cache.

This API exposes the following information:

  • The name of the cluster.
  • The number of machines in the cluster.
  • The overall status of the cluster or cache, represented in one of three values:

    • Healthy - The entity is healthy.
    • Unhealthy - The entity is unhealthy. This value indicates that one or more caches are in a degraded state.
    • Rebalancing - The entity is operational, but a rebalance is in progress. Cluster nodes should not be adjusted when this value is reported.
  • The status of each cache.
  • A tail of the server log.

For information on using the Health Check API programmatically, refer to the JBoss Data Grid Developer Guide.

11.2. Accessing the Health API using JMX

The Health Check API may be accessed through JMX, as seen in the following steps:

  1. Connect to the JBoss Data Grid node using JMX, such as by Connecting to JDG via JConsole.
  2. Expand jboss.datagrid-infinispan.
  3. Expand CacheManager.
  4. Select the desired cache manager. By default the cache manager will be named local, if the server was started in local mode, or clustered, if the server was started in a clustered mode.
  5. Expand the CacheContainerHealth object.
  6. The Health Check API attributes are now available to be viewed.

An example of this using JConsole is seen below:

Viewing the Health Check API using JMX

11.3. Accessing the Health Check API using the CLI

The Health Check API may be accessed using the included CLI. Once connected to the server use the following command, substituting the desired cache container for CONTAINERNAME:

/subsystem=datagrid-infinispan/cache-container=CONTAINERNAME/health=HEALTH:read-resource(include-runtime=true)

The following demonstrates sample output from the above command, using the clustered cache-container:

[standalone@localhost:9990 health=HEALTH] /subsystem=datagrid-infinispan/cache-container=clustered/health=HEALTH:read-resource(include-runtime=true)
{
    "outcome" => "success",
    "result" => {
        "cache-health" => [
            "default",
            "HEALTHY",
            "_protobuf_metadata", "HEALTHY", "memcachedCache", "HEALTHY", "repl", "HEALTHY", "_script_cache",
            "HEALTHY"
        ],
        "cluster-health" => "HEALTHY",
        "cluster-name" => "clustered",
        "free-memory" => 936823L,
        "log-tail" => [
            "2018-03-04 16:22:28,138 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-7) DGENDPT10001: MemcachedServer listening on 127.0.0.1:11211",
            "2018-03-04 16:22:28,146 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-3) DGENDPT10000: REST starting",
            "2018-03-04 16:22:28,188 INFO  [org.jboss.as.clustering.infinispan] (MSC service thread 1-3) DGISPN0001: Started _protobuf_metadata cache from clustered container", "2018-03-04 16:22:28,195 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-3) DGISPN0001: Started _script_cache cache from clustered container",
            "2018-03-04 16:22:28,515 INFO  [org.jboss.as.clustering.infinispan] (MSC service thread 1-4) DGISPN0001: Started ___hotRodTopologyCache cache from clustered container",
            "2018-03-04 16:22:28,552 INFO  [org.infinispan.rest.NettyRestServer] (MSC service thread 1-3) ISPN012003: REST server starting, listening on 127.0.0.1:8080",
            "2018-03-04 16:22:28,552 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-3) DGENDPT10002: REST mapped to /rest",
            "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management",
            "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990",
            "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: Data Grid 7.2.0 (WildFly Core 2.1.10.Final-redhat-1) started in 7608ms - Started 196 of 235 services (119 services are lazy, passive or on-demand)"
        ],
        "number-of-cpus" => 8,
        "number-of-nodes" => 1,
        "total-memory" => 1280000L
    }
}

11.4. Accessing the Health Check API using the Management REST Interface

The Health Check API is integrated into the Management REST interface as Metrics (read-only runtime resources).

Important

Due to the metrics being exposed in runtime a HTTP POST method must be used instead of the typical HTTP GET.

To access these Metrics a HTTP POST method must be sent that contains valid user credentials. The following command demonstrates one such request:

curl --digest -L -D - "http://JDGADDRESS:_JDGPORT_/management/subsystem/datagrid-infinispan/cache-container/CONTAINERNAME/health/HEALTH?operation=resource&include-runtime=true&json.pretty=1" --header "Content-Type: application/json" -u username:password

The following properties should be substituted from the above command:

  • JDGADDRESS - This should be the hostname or IP address where the JBoss Data Grid server is located.
  • JDGPORT - This should be the port where the management interface is listening. By default this is 9990.
  • CONTAINERNAME - This should be the name of the cache container to query. By default the cache manager will be named local, if the server was started in local mode, or clustered, if the server was started in a clustered mode.
  • username - The username for accessing the Administration Console.
  • password - The associated password for accessing the Administration Console.

If successful, a 200 response should be received along with the health status, such as seen below:

HTTP/1.1 401 Unauthorized
Connection: keep-alive
WWW-Authenticate: Digest realm="ManagementRealm",domain="/management",nonce="n1btFIY4yugNMTQ4ODY2NDY3NjUxMy4utKorhon/y+zSHie9V58=",opaque="00000000000000000000000000000000",algorithm=MD5,qop="auth"
X-Frame-Options: SAMEORIGIN
Content-Length: 77
Content-Type: text/html
Date: Sat, 04 Mar 2018 21:57:56 GMT

HTTP/1.1 200 OK
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
Authentication-Info: nextnonce="n1btFIY4yugNMTQ4ODY2NDY3NjUxMy4utKorhon/y+zSHie9V58=",qop="auth",rspauth="09ab5888ea71413b56dd724c13825a08",cnonce="MzdjOTMyZWQ2OTk5Y2Q0NmNlYzcxYzE2Zjg5NzdjZDE=",nc=00000001
Content-Type: application/json; charset=utf-8
Content-Length: 2108
Date: Sat, 04 Mar 2018 21:57:56 GMT

{
    "cache-health" : [
        "default",
        "HEALTHY",
        "___protobuf_metadata",
        "HEALTHY",
        "memcachedCache",
        "HEALTHY",
        "repl",
        "HEALTHY",
        "___script_cache",
        "HEALTHY"
    ],
    "cluster-health" : "HEALTHY",
    "cluster-name" : "clustered",
    "free-memory" : 1198983,
    "log-tail" : [
        "2018-03-04 16:22:28,138 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-7) DGENDPT10001: MemcachedServer listening on 127.0.0.1:11211",
        "2018-03-04 16:22:28,146 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-3) DGENDPT10000: REST starting",
        "2018-03-04 16:22:28,188 INFO  [org.jboss.as.clustering.infinispan] (MSC service thread 1-3) DGISPN0001: Started ___protobuf_metadata cache from clustered container",
        "2018-03-04 16:22:28,195 INFO  [org.jboss.as.clustering.infinispan] (MSC service thread 1-3) DGISPN0001: Started ___script_cache cache from clustered container",
        "2018-03-04 16:22:28,515 INFO  [org.jboss.as.clustering.infinispan] (MSC service thread 1-4) DGISPN0001: Started ___hotRodTopologyCache cache from clustered container",
        "2018-03-04 16:22:28,552 INFO  [org.infinispan.rest.NettyRestServer] (MSC service thread 1-3) ISPN012003: REST server starting, listening on 127.0.0.1:8080",
        "2018-03-04 16:22:28,552 INFO  [org.infinispan.server.endpoint] (MSC service thread 1-3) DGENDPT10002: REST mapped to /rest",
        "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management",
        "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990",
        "2018-03-04 16:22:28,613 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: Data Grid 7.2.0 (WildFly Core 2.1.10.Final-redhat-1) started in 7608ms - Started 196 of 235 services (119 services are lazy, passive or on-demand)"
    ],
    "number-of-cpus" : 8,
    "number-of-nodes" : 1,
    "total-memory" : 1280000

Part VI. Remote Client-Server Mode Interfaces

Chapter 12. Remote Client-Server Mode Interfaces

Red Hat JBoss Data Grid offers the following APIs to interact with the data grid in Remote Client-Server mode:

  • The Hot Rod Interface, including the RemoteCache API
  • The Asynchronous API (can only be used in conjunction with the Hot Rod Client in Remote Client-Server Mode)
  • The REST Interface
  • The Memcached Interface

Chapter 13. The Hot Rod Interface

13.1. About Hot Rod

Hot Rod is a binary TCP client-server protocol used in Red Hat JBoss Data Grid. It was created to overcome deficiencies in other client/server protocols, such as Memcached.

Hot Rod will failover on a server cluster that undergoes a topology change. Hot Rod achieves this by providing regular updates to clients about the cluster topology.

Hot Rod enables clients to do smart routing of requests in partitioned or distributed Red Hat JBoss Data Grid server clusters. To do this, Hot Rod allows clients to determine the partition that houses a key and then communicate directly with the server that has the key. This functionality relies on Hot Rod updating the cluster topology with clients, and that the clients use the same consistent hash algorithm as the servers.

Red Hat JBoss Data Grid contains a server module that implements the Hot Rod protocol. The Hot Rod protocol facilitates faster client and server interactions in comparison to other text-based protocols and allows clients to make decisions about load balancing, failover and data location operations.

13.2. The Benefits of Using Hot Rod over Memcached

Red Hat JBoss Data Grid offers a choice of protocols for allowing clients to interact with the server in a Remote Client-Server environment. When deciding between using memcached or Hot Rod, the following should be considered.

Memcached

The memcached protocol causes the server endpoint to use the memcached text wire protocol. The memcached wire protocol has the benefit of being commonly used, and is available for almost any platform. All of JBoss Data Grid’s functions, including clustering, state sharing for scalability, and high availability, are available when using memcached.

However the memcached protocol lacks dynamicity, resulting in the need to manually update the list of server nodes on your clients in the event one of the nodes in a cluster fails. Also, memcached clients are not aware of the location of the data in the cluster. This means that they will request data from a non-owner node, incurring the penalty of an additional request from that node to the actual owner, before being able to return the data to the client. This is where the Hot Rod protocol is able to provide greater performance than memcached.

Hot Rod

JBoss Data Grid’s Hot Rod protocol is a binary wire protocol that offers all the capabilities of memcached, while also providing better scaling, durability, and elasticity.

The Hot Rod protocol does not need the hostnames and ports of each node in the remote cache, whereas memcached requires these parameters to be specified. Hot Rod clients automatically detect changes in the topology of clustered Hot Rod servers; when new nodes join or leave the cluster, clients update their Hot Rod server topology view. Consequently, Hot Rod provides ease of configuration and maintenance, with the advantage of dynamic load balancing and failover.

Additionally, the Hot Rod wire protocol uses smart routing when connecting to a distributed cache. This involves sharing a consistent hash algorithm between the server nodes and clients, resulting in faster read and writing capabilities than memcached.

Warning

When using JCache over Hot Rod it is not possible to create remote clustered caches, as the operation is executed on a single node as opposed to the entire cluster; however, once a cache has been created on the cluster it may be obtained using the cacheManager.getCache method.

It is recommended to create caches using either configuration files or the CLI.

13.3. Hot Rod Hash Functions

Hot Rod uses the same algorithm as on the server. The Hot Rod client always connects to the primary owner of the key, which is the first node in the list of owners. For more information about consistent hashing in Red Hat JBoss Data Grid, see Distribution Mode’s Consistent Hash Algorithm.

13.4. The Hot Rod Interface Connector

13.4.1. The Hot Rod Interface Connector

The following enables a Hot Rod server using the hotrod socket binding.

<hotrod-connector socket-binding="hotrod"
		  cache-container="local" />

The connector creates a supporting topology cache with default settings. These settings can be tuned by adding the <topology-state-transfer /> child element to the connector as follows:

<hotrod-connector socket-binding="hotrod"
		  cache-container="local">
   <topology-state-transfer lazy-retrieval="false"
   			    lock-timeout="1000"
   			    replication-timeout="5000" />
</hotrod-connector>

The Hot Rod connector can be tuned with additional settings. See Configure Hot Rod Connectors for more information on how to configure the Hot Rod connector.

Note

The Hot Rod connector can provide security and authentication, using TLS/SSL and SASL, respectively. See the Securing Interfaces section of the Developer Guide for more information.

13.4.2. Configure Hot Rod Connectors

The following procedure describes the attributes used to configure the Hot Rod connector in Red Hat JBoss Data Grid’s Remote Client-Server Mode. Both the hotrod-connector and topology-state-transfer elements must be configured based on the following procedure.

Configuring Hot Rod Connectors for Remote Client-Server Mode

<subsystem xmlns="urn:infinispan:server:endpoint:8.1">
	<hotrod-connector socket-binding="hotrod"
			  cache-container="local"
			  worker-threads="${VALUE}"
			  idle-timeout="${SECONDS}"
			  tcp-nodelay="${TRUE/FALSE}"
			  send-buffer-size="${VALUE}"
			  receive-buffer-size="${VALUE}" >
		<topology-state-transfer lock-timeout"="${MILLISECONDS}"
				 replication-timeout="${MILLISECONDS}"
				 external-host="${HOSTNAME}"
				 external-port="${PORT}"
				 lazy-retrieval="${TRUE/FALSE}"  />
	</hotrod-connector>
</subsystem>

  1. The hotrod-connector element defines the configuration elements for use with Hot Rod.

    • The socket-binding parameter specifies the socket binding port used by the Hot Rod connector. This is a mandatory parameter.
    • The cache-container parameter names the cache container used by the Hot Rod connector. This is a mandatory parameter.
    • The worker-threads parameter specifies the number of worker threads available for the Hot Rod connector. The default value for this parameter is 160. This is an optional parameter.
    • The idle-timeout parameter specifies the time, in seconds, that the connector can remain idle before the connection times out. The default value for this parameter is 0, which means that no timeout period is set. This is an optional parameter.
    • The tcp-nodelay parameter specifies whether TCP packets will be delayed and sent out in batches. Valid values for this parameter are true and false. The default value for this parameter is true. This is an optional parameter.
    • The send-buffer-size parameter indicates the size of the send buffer for the Hot Rod connector. The default value for this parameter is the size of the TCP stack buffer. This is an optional parameter.
    • The receive-buffer-size parameter indicates the size of the receive buffer for the Hot Rod connector. The default value for this parameter is the size of the TCP stack buffer. This is an optional parameter.
  2. The topology-state-transfer element specifies the topology state transfer configurations for the Hot Rod connector. This element can only occur once within a hotrod-connector element.

    • The lock-timeout parameter specifies the time (in milliseconds) after which the operation attempting to obtain a lock times out. The default value for this parameter is 10 seconds. This is an optional parameter.
    • The replication-timeout parameter specifies the time (in milliseconds) after which the replication operation times out. The default value for this parameter is 10 seconds. This is an optional parameter.
    • The external-host parameter specifies the hostname sent by the Hot Rod server to clients listed in the topology information. The default value for this parameter is the host address. This is an optional parameter.
    • The external-port parameter specifies the port sent by the Hot Rod server to clients listed in the topology information. The default value for this parameter is the configured port. This is an optional parameter.
    • The lazy-retrieval parameter indicates whether the Hot Rod connector will carry out retrieval operations lazily. The default value for this parameter is true. This is an optional parameter.

Chapter 14. The REST Interface

14.1. The REST Interface

Red Hat JBoss Data Grid provides a REST interface, allowing for loose coupling between the client and server. Its primary benefit is interoperability with existing HTTP clients, along with providing a connection for php clients. In addition, the need for specific versions of client libraries and bindings is eliminated.

The REST API introduces an overhead, and requires a REST client or custom code to understand and create REST calls. It is recommended to use the Hot Rod client where performance is a concern.

To interact with Red Hat JBoss Data Grid’s REST API only a HTTP client library is required. For Java, this may be the Apache HTTP Commons Client, or the java.net API.

Important

The following examples assume that REST security is disabled on the REST connector. To disable REST security remove the authentication and encryption elements from the connector.

14.2. The REST Interface Connector

14.2.1. The REST Interface Connector

The REST connector differs from the Hot Rod and Memcached connectors because it requires a web subsystem. Therefore configurations such as socket-binding, worker threads, timeouts, etc, must be performed on the web subsystem.

Once the REST interface has been enabled on the server it may be used normally for adding, removing, and retrieving data. For information on these processes refer to the JBoss Data Grid Developer Guide .

14.2.2. Configure REST Connectors

Use the following procedure to configure the rest-connector element in Red Hat JBoss Data Grid’s Remote Client-Server mode.

Configuring REST Connectors for Remote Client-Server Mode

<subsystem xmlns="urn:infinispan:server:endpoint:8.1">
   <rest-connector cache-container="local"
                   context-path="${CONTEXT_PATH}"/>
</subsystem>

The rest-connector element specifies the configuration information for the REST connector.

  1. The cache-container parameter names the cache container used by the REST connector. This is a mandatory parameter.
  2. The context-path parameter specifies the context path for the REST connector. The default value for this parameter is an empty string (""). This is an optional parameter.

Chapter 15. The Memcached Interface

15.1. The Memcached Interface

Memcached is an in-memory caching system used to improve response and operation times for database-driven websites. The Memcached caching system defines a text based protocol called the Memcached protocol. The Memcached protocol uses in-memory objects or (as a last resort) passes to a persistent store such as a special memcached database.

Red Hat JBoss Data Grid offers a server that uses the Memcached protocol, removing the necessity to use Memcached separately with JBoss Data Grid. Additionally, due to JBoss Data Grid’s clustering features, its data failover capabilities surpass those provided by Memcached.

15.2. About Memcached Servers

Red Hat JBoss Data Grid contains a server module that implements the memcached protocol. This allows memcached clients to interact with one or multiple JBoss Data Grid based memcached servers.

The servers can be either:

  • Standalone, where each server acts independently without communication with any other memcached servers.
  • Clustered, where servers replicate and distribute data to other memcached servers.

15.3. Memcached Statistics

The following table contains a list of valid statistics available using the memcached protocol in Red Hat JBoss Data Grid.

Table 15.1. Memcached Statistics
StatisticData TypeDetails

uptime

32-bit unsigned integer.

Contains the time (in seconds) that the memcached instance has been available and running.

time

32-bit unsigned integer.

Contains the current time.

version

String

Contains the current version.

curr_items

32-bit unsigned integer.

Contains the number of items currently stored by the instance.

total_items

32-bit unsigned integer.

Contains the total number of items stored by the instance during its lifetime.

cmd_get

64-bit unsigned integer

Contains the total number of get operation requests (requests to retrieve data).

cmd_set

64-bit unsigned integer

Contains the total number of set operation requests (requests to store data).

get_hits

64-bit unsigned integer

Contains the number of keys that are present from the keys requested.

get_misses

64-bit unsigned integer

Contains the number of keys that were not found from the keys requested.

delete_hits

64-bit unsigned integer

Contains the number of keys to be deleted that were located and successfully deleted.

delete_misses

64-bit unsigned integer

Contains the number of keys to be deleted that were not located and therefore could not be deleted.

incr_hits

64-bit unsigned integer

Contains the number of keys to be incremented that were located and successfully incremented

incr_misses

64-bit unsigned integer

Contains the number of keys to be incremented that were not located and therefore could not be incremented.

decr_hits

64-bit unsigned integer

Contains the number of keys to be decremented that were located and successfully decremented.

decr_misses

64-bit unsigned integer

Contains the number of keys to be decremented that were not located and therefore could not be decremented.

cas_hits

64-bit unsigned integer

Contains the number of keys to be compared and swapped that were found and successfully compared and swapped.

cas_misses

64-bit unsigned integer

Contains the number of keys to be compared and swapped that were not found and therefore not compared and swapped.

cas_badval

64-bit unsigned integer

Contains the number of keys where a compare and swap occurred but the original value did not match the supplied value.

evictions

64-bit unsigned integer

Contains the number of eviction calls performed.

bytes_read

64-bit unsigned integer

Contains the total number of bytes read by the server from the network.

bytes_written

64-bit unsigned integer

Contains the total number of bytes written by the server to the network.

15.4. The Memcached Interface Connector

15.4.1. The Memcached Interface Connector

The following enables a Memcached server using the memcached socket binding, and exposes the memcachedCache cache declared in the local container, using defaults for all other settings.

<memcached-connector socket-binding="memcached"
		     cache-container="local"/>

Due to the limitations in the Memcached protocol, only one cache can be exposed by a connector. To expose more than one cache, declare additional memcached-connectors on different socket-bindings. See Configure Memcached Connectors.

15.4.2. Configure Memcached Connectors

The following procedure describes the attributes used to configure the memcached connector within the connectors element in Red Hat JBoss Data Grid’s Remote Client-Server Mode.

Configuring the Memcached Connector in Remote Client-Server Mode

The memcached-connector element defines the configuration elements for use with memcached.

<subsystem xmlns="urn:infinispan:server:endpoint:8.1">
<memcached-connector socket-binding="memcached"
                     cache-container="local"
                     worker-threads="${VALUE}"
                     idle-timeout="{SECONDS}"
                     tcp-nodelay="{TRUE/FALSE}"
                     send-buffer-size="{VALUE}"
                     receive-buffer-size="${VALUE}" />
</subsystem>
  1. The socket-binding parameter specifies the socket binding port used by the memcached connector. This is a mandatory parameter.
  2. The cache-container parameter names the cache container used by the memcached connector. This is a mandatory parameter.
  3. The worker-threads parameter specifies the number of worker threads available for the memcached connector. The default value for this parameter is 160. This is an optional parameter.
  4. The idle-timeout parameter specifies the time, in seconds, that the connector can remain idle before the connection times out. The default value for this parameter is 0, which means that no timeout period is set. This is an optional parameter.
  5. The tcp-nodelay parameter specifies whether TCP packets will be delayed and sent out in batches. Valid values for this parameter are true and false. The default value for this parameter is true. This is an optional parameter.
  6. The send-buffer-size parameter indicates the size of the send buffer for the memcached connector. The default value for this parameter is the size of the TCP stack buffer. This is an optional parameter.
  7. The receive-buffer-size parameter indicates the size of the receive buffer for the memcached connector. The default value for this parameter is the size of the TCP stack buffer. This is an optional parameter.

Part VII. Set Up Locking for the Cache

Chapter 16. Locking

16.1. Locking

Red Hat JBoss Data Grid provides locking mechanisms to prevent dirty reads (where a transaction reads an outdated value before another transaction has applied changes to it) and non-repeatable reads.

16.2. Configure Locking (Remote Client-Server Mode)

In Remote Client-Server mode, locking is configured using the locking element within the cache tags (for example, invalidation-cache, distributed-cache, replicated-cache or local-cache).

Note

The default isolation mode for the Remote Client-Server mode configuration is READ_COMMITTED. If the isolation attribute is included to explicitly specify an isolation mode, it is ignored, a warning is thrown, and the default value is used instead.

The following is a sample procedure of a basic locking configuration for a default cache in Red Hat JBoss Data Grid’s Remote Client-Server mode.

Configure Locking (Remote Client-Server Mode)

<distributed-cache name="distributedCache">
	<locking acquire-timeout="30000"
	         concurrency-level="1000"
	         striping="false" />
	         <!-- Additional configuration here -->
</distributed-cache>

  1. The acquire-timeout parameter specifies the number of milliseconds after which lock acquisition will time out.
  2. The concurrency-level parameter defines the number of lock stripes used by the LockManager.
  3. The striping parameter specifies whether lock striping will be used for the local cache.

16.3. Configure Locking (Library Mode)

For Library mode, the locking element and its parameters are set within the default element found within cache element. An example of this configuration on a local cache is below:

Configure Locking (Library Mode)

<local-cache name="default">
		<locking concurrency-level="${VALUE}"
			isolation="${LEVEL}"
			acquire-timeout="${TIME}"
			striping="${TRUE/FALSE}"
			write-skew="${TRUE/FALSE}" />
</local-cache>

  1. The concurrency-level parameter specifies the concurrency level for the lock container. Set this value according to the number of concurrent threads interacting with the data grid.
  2. The isolation parameter specifies the cache’s isolation level. Valid isolation levels are READ_COMMITTED and REPEATABLE_READ. For details about isolation levels, see About Isolation Levels.
  3. The acquire-timeout parameter specifies time (in milliseconds) after which a lock acquisition attempt times out.
  4. The striping parameter specifies whether a pool of shared locks are maintained for all entries that require locks. If set to FALSE, locks are created for each entry in the cache. For details, see About Lock Striping.
  5. The write-skew parameter is only valid if the isolation is set to REPEATABLE_READ. If this parameter is set to FALSE, a disparity between a working entry and the underlying entry at write time results in the working entry overwriting the underlying entry. If the parameter is set to TRUE, such conflicts (namely write skews) throw an exception. The write-skew parameter can be only used with OPTIMISTIC transactions and it requires entry versioning to be enabled, with SIMPLE versioning scheme.

16.4. Locking Types

16.4.1. About Optimistic Locking

Optimistic locking allows multiple transactions to complete simultaneously by deferring lock acquisition to the transaction prepare time.

Optimistic mode assumes that multiple transactions can complete without conflict. It is ideal where there is little contention between multiple transactions running concurrently, as transactions can commit without waiting for other transaction locks to clear. With write-skew enabled, transactions in optimistic locking mode roll back if one or more conflicting modifications are made to the data before the transaction completes.

16.4.2. About Pessimistic Locking

Pessimistic locking is also known as eager locking.

Pessimistic locking prevents more than one transaction to modify a value of a key by enforcing cluster-wide locks on each write operation. Locks are only released once the transaction is completed either through committing or being rolled back.

Pessimistic mode is used where a high contention on keys is occurring, resulting in inefficiencies and unexpected roll back operations.

16.4.3. Pessimistic Locking Types

Red Hat JBoss Data Grid includes explicit pessimistic locking and implicit pessimistic locking:

  • Explicit Pessimistic Locking, which uses the JBoss Data Grid Lock API to allow cache users to explicitly lock cache keys for the duration of a transaction. The Lock call attempts to obtain locks on specified cache keys across all nodes in a cluster. This attempt either fails or succeeds for all specified cache keys. All locks are released during the commit or rollback phase.
  • Implicit Pessimistic Locking ensures that cache keys are locked in the background as they are accessed for modification operations. Using Implicit Pessimistic Locking causes JBoss Data Grid to check and ensure that cache keys are locked locally for each modification operation. Discovering unlocked cache keys causes JBoss Data Grid to request a cluster-wide lock to acquire a lock on the unlocked cache key.

16.4.4. Explicit Pessimistic Locking Example

The following is an example of explicit pessimistic locking that depicts a transaction that runs on one of the cache nodes:

Transaction with Explicit Pessimistic Locking

tx.begin()
cache.lock(K)
cache.put(K,V5)
tx.commit()

  1. When the line cache.lock(K) executes, a cluster-wide lock is acquired on K.
  2. When the line cache.put(K,V5) executes, it guarantees success.
  3. When the line tx.commit() executes, the locks held for this process are released.

16.4.5. Implicit Pessimistic Locking Example

An example of implicit pessimistic locking using a transaction that runs on one of the cache nodes is as follows:

Transaction with Implicit Pessimistic locking

tx.begin()
cache.put(K,V)
cache.put(K2,V2)
cache.put(K,V5)
tx.commit()

  1. When the line cache.put(K,V) executes, a cluster-wide lock is acquired on K.
  2. When the line cache.put(K2,V2) executes, a cluster-wide lock is acquired on K2.
  3. When the line cache.put(K,V5) executes, the lock acquisition is non operational because a cluster-wide lock for K has been previously acquired. The put operation will still occur.
  4. When the line tx.commit() executes, all locks held for this transaction are released.

16.4.6. Configure Locking Mode (Remote Client-Server Mode)

To configure a locking mode in Red Hat JBoss Data Grid’s Remote Client-Server mode, use the transaction element as follows:

<transaction locking="{OPTIMISTIC/PESSIMISTIC}" />

16.4.7. Configure Locking Mode (Library Mode)

In Red Hat JBoss Data Grid’s Library mode, the locking mode is set within the transaction element as follows:

<transaction transaction-manager-lookup="{TransactionManagerLookupClass}"
	     mode="{NONE, BATCH, NON_XA, NON_DURABLE_XA, FULL_XA}"
	     locking="{OPTIMISTIC,PESSIMISTIC}">
</transaction>

Set the locking value to OPTIMISTIC or PESSIMISTIC to configure the locking mode used for the transactional cache.

16.5. Locking Operations

16.5.1. About the LockManager

The LockManager component is responsible for locking an entry before a write process initiates. The LockManager uses a LockContainer to locate, hold and create locks. There are two types of LockContainers JBoss Data Grid uses internally and their choice is dependent on the useLockStriping setting. The first type offers support for lock striping while the second type supports one lock per entry.

See Also: Set Up Lock Striping

16.5.2. About Lock Acquisition

Red Hat JBoss Data Grid acquires remote locks lazily by default. The node running a transaction locally acquires the lock while other cluster nodes attempt to lock cache keys that are involved in a two phase prepare/commit phase. JBoss Data Grid can lock cache keys in a pessimistic manner either explicitly or implicitly.

16.5.3. About Concurrency Levels

Concurrency refers to the number of threads simultaneously interacting with the data grid. In Red Hat JBoss Data Grid, concurrency levels refer to the number of concurrent threads used within a lock container.

In JBoss Data Grid, concurrency levels determine the size of each striped lock container. Additionally, concurrency levels tune all related JDK ConcurrentHashMap based collections, such as those internal to DataContainers.

Chapter 17. Set Up Lock Striping

17.1. About Lock Striping

Lock Striping allocates locks from a shared collection of (fixed size) locks in the cache. Lock allocation is based on the hash code for each entry’s key. Lock Striping provides a highly scalable locking mechanism with fixed overhead. However, this comes at a cost of potentially unrelated entries being blocked by the same lock.

Lock Striping is disabled by default in Red Hat JBoss Data Grid. If lock striping remains disabled, a new lock is created for each entry. This alternative approach can provide greater concurrent throughput, but also results in additional memory usage, garbage collection churn, and other disadvantages.

17.2. Configure Lock Striping (Remote Client-Server Mode)

Lock striping in Red Hat JBoss Data Grid’s Remote Client-Server mode is enabled by setting the striping element to true.

Lock Striping (Remote Client-Server Mode)

<locking acquire-timeout="20000"
	 concurrency-level="500"
	 striping="true" />

Note

The default isolation mode for the Remote Client-Server mode configuration is READ_COMMITTED. If the isolation attribute is included to explicitly specify an isolation mode, it is ignored, a warning is thrown, and the default value is used instead.

The locking element uses the following attributes:

  • The acquire-timeout attribute specifies the maximum time to attempt a lock acquisition. The default value for this attribute is 10000 milliseconds.
  • The concurrency-level attribute specifies the concurrency level for lock containers. Adjust this value according to the number of concurrent threads interacting with JBoss Data Grid. The default value for this attribute is 32.
  • The striping attribute specifies whether a shared pool of locks is maintained for all entries that require locking (true). If set to false, a lock is created for each entry. Lock striping controls the memory footprint but can reduce concurrency in the system. The default value for this attribute is false.

17.3. Configure Lock Striping (Library Mode)

Lock striping is disabled by default in Red Hat JBoss Data Grid. Configure lock striping in JBoss Data Grid’s Library mode using the striping parameter as demonstrated in the following procedure.

Configure Lock Striping (Library Mode)

<local-cache>
		<locking concurrency-level="${VALUE}"
			 isolation="${LEVEL}"
			 acquire-timeout="${TIME}"
			 striping="${TRUE/FALSE}"
			 write-skew="${TRUE/FALSE}" />
</local-cache>

  1. The concurrency-level is used to specify the size of the shared lock collection use when lock striping is enabled.
  2. The isolation parameter specifies the cache’s isolation level. Valid isolation levels are READ_COMMITTED and REPEATABLE_READ.
  3. The acquire-timeout parameter specifies time (in milliseconds) after which a lock acquisition attempt times out.
  4. The striping parameter specifies whether a pool of shared locks are maintained for all entries that require locks. If set to FALSE, locks are created for each entry in the cache. If set to TRUE, lock striping is enabled and shared locks are used as required from the pool.
  5. The write-skew check determines if a modification to the entry from a different transaction should roll back the transaction. Write skew set to true requires isolation_level set to REPEATABLE_READ. The default value for write-skew and isolation_level are FALSE and READ_COMMITTED respectively. The write-skew parameter can be only used with OPTIMISTIC transactions and it requires entry versioning to be enabled, with SIMPLE versioning scheme.

Chapter 18. Set Up Isolation Levels

18.1. About Isolation Levels

Isolation levels determine when readers can view a concurrent write. READ_COMMITTED and REPEATABLE_READ are the two isolation modes offered in Red Hat JBoss Data Grid.

  • READ_COMMITTED. This isolation level is applicable to a wide variety of requirements. This is the default value in Remote Client-Server and Library modes.
  • REPEATABLE_READ.

    Important

    The only valid value for locks in Remote Client-Server mode is the default READ_COMMITTED value. The value explicitly specified with the isolation value is ignored.

    If the locking element is not present in the configuration, the default isolation value is READ_COMMITTED.

For isolation mode configuration examples in JBoss Data Grid, see the lock striping configuration samples:

18.2. About READ_COMMITTED

READ_COMMITTED is one of two isolation modes available in Red Hat JBoss Data Grid.

In JBoss Data Grid’s READ_COMMITTED mode, write operations are made to copies of data rather than the data itself. A write operation blocks other data from being written, however writes do not block read operations. As a result, both READ_COMMITTED and REPEATABLE_READ modes permit read operations at any time, regardless of when write operations occur.

In READ_COMMITTED mode multiple reads of the same key within a transaction can return different results due to write operations in different transactions modifying data between reads. This phenomenon is known as non-repeatable reads and is avoided in REPEATABLE_READ mode.

18.3. About REPEATABLE_READ

REPEATABLE_READ is one of two isolation modes available in Red Hat JBoss Data Grid.

Traditionally, REPEATABLE_READ does not allow write operations while read operations are in progress, nor does it allow read operations when write operations occur. This prevents the "non-repeatable read" phenomenon, which occurs when a single transaction has two read operations on the same row but the retrieved values differ (possibly due to a write operation modifying the value between the two read operations).

JBoss Data Grid’s REPEATABLE_READ isolation mode preserves the value of an entry before a modification occurs. As a result, the "non-repeatable read" phenomenon is avoided because a second read operation on the same entry retrieves the preserved value rather than the new modified value. As a result, the two values retrieved by the two read operations in a single transaction will always match, even if a write operation occurs in a different transaction between the two reads.

Part VIII. Set Up and Configure a Cache Store

Chapter 19. Cache Stores

19.1. Cache Stores

The cache store connects Red Hat JBoss Data Grid to the persistent data store. Cache stores are associated with individual caches. Different caches attached to the same cache manager can have different cache store configurations.

Note

If a clustered cache is configured with an unshared cache store (where shared is set to false), on node join, stale entries which might have been removed from the cluster might still be present in the stores and can reappear.

19.2. Cache Loaders and Cache Writers

Integration with the persistent store is done through the following SPIs located in org.infinispan.persistence.spi:

  • CacheLoader
  • CacheWriter
  • AdvancedCacheLoader
  • AdvancedCacheWriter

CacheLoader and CacheWriter provide basic methods for reading and writing to a store. CacheLoader retrieves data from a data store when the required data is not present in the cache, and CacheWriter is used to enforce entry passivation and activation on eviction in a cache.

AdvancedCacheLoader and AdvancedCacheWriter provide operations to manipulate the underlying storage in bulk: parallel iteration and purging of expired entries, clear and size.

The org.infinispan.persistence.file.SingleFileStore is a good starting point to write your own store implementation.

Note

Previously, JBoss Data Grid used the old API (CacheLoader, extended by CacheStore), which is also still available.

19.3. Cache Store Configuration

19.3.1. Configuring the Cache Store

Cache stores can be configured in a chain. Cache read operations checks each cache store in the order configured until a valid non-null element of data has been located. Write operations affect all cache stores unless the ignoreModifications element has been set to "true" for a specific cache store.

19.3.2. Configure the Cache Store using XML (Library Mode)

The following example demonstrates cache store configuration using XML in JBoss Data Grid’s Library mode:

<persistence passivation="false">
   <file-store shared="false"
               preload="true"
               fetch-state="true"
               purge-startup="false"
               singleton="true"
               location="${java.io.tmpdir}" >
      <write-behind enabled="true"
             flush-lock-timeout="15000"
             thread-pool-size="5" />
   </singleFile>
</persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

19.3.3. About SKIP_CACHE_LOAD Flag

In Red Hat JBoss Data Grid’s Remote Client-Server mode, when the cache is preloaded from a cache store and eviction is disabled, read requests go to the memory. If the entry is not found in a memory during a read request, it accesses the cache store which may impact the read performance.

To avoid referring to the cache store when a key is not found in the memory, use the SKIP_CACHE_LOAD flag.

19.3.4. About the SKIP_CACHE_STORE Flag

When the SKIP_CACHE_STORE Flag is used then the cache store will not be considered for the specified cache operations. This flag can be useful to place an entry in the cache without having it included in the configured cache store, along with determining if an entry is found within a cache without retrieving it from the associated cache store.

19.3.5. About the SKIP_SHARED_CACHE_STORE Flag

When the SKIP_SHARED_CACHE_STORE Flag is enabled then any shared cache store will not be considered for the specified cache operations. This flag can be useful to place an entry in the cache without having it included in the shared cache store, along with determining if an entry is found within a cache without retrieving it from the shared cache store.

19.4. Shared Cache Stores

19.4.1. Shared Cache Stores

A shared cache store is a cache store that is shared by multiple cache instances.

A shared cache store is useful when all instances in a cluster communicate with the same remote, shared database using the same JDBC settings. In such an instance, configuring a shared cache store prevents the unnecessary repeated write operations that occur when various cache instances attempt to write the same data to the cache store.

19.4.2. Invalidation Mode and Shared Cache Stores

When used in conjunction with a shared cache store, Red Hat JBoss Data Grid’s invalidation mode causes remote caches to see the shared cache store to retrieve modified data.

The benefits of using invalidation mode in conjunction with shared cache stores include the following:

  • Compared to replication messages, which contain the updated data, invalidation messages are much smaller and result in reduced network traffic.
  • The remaining cluster caches look up modified data from the shared cache store lazily and only when required to do so, resulting in further reduced network traffic.

19.4.3. The Cache Store and Cache Passivation

In Red Hat JBoss Data Grid, a cache store can be used to enforce the passivation of entries and to activate eviction in a cache. Whether passivation mode or activation mode are used, the configured cache store both reads from and writes to the data store.

When passivation is disabled in JBoss Data Grid, after the modification, addition or removal of an element is carried out the cache store steps in to persist the changes in the store.

19.4.4. Application Cachestore Registration

It is not necessary to register an application cache store for an isolated deployment. This is not a requirement in Red Hat JBoss Data Grid because lazy deserialization is used to work around this problem.

19.5. Connection Factories

19.5.1. Connection Factories

In Red Hat JBoss Data Grid, all JDBC cache stores rely on a ConnectionFactory implementation to obtain a database connection. This process is also known as connection management or pooling.

A connection factory can be specified using the ConnectionFactoryClass configuration attribute. JBoss Data Grid includes the following ConnectionFactory implementations:

  • ManagedConnectionFactory
  • SimpleConnectionFactory.
  • PooledConnectionFactory.

19.5.2. About ManagedConnectionFactory

ManagedConnectionFactory is a connection factory that is ideal for use within managed environments such as application servers. This connection factory can explore a configured location in the JNDI tree and delegate connection management to the DataSource.

19.5.3. About SimpleConnectionFactory

SimpleConnectionFactory is a connection factory that creates database connections on a per invocation basis. This connection factory is not designed for use in a production environment.

19.5.4. About PooledConnectionFactory

PooledConnectionFactory is a connection factory based on C3P0, and is typically recommended for standalone deployments as opposed to deployments utilizing a servlet container, such as JBoss EAP. This connection factory functions by allowing the user to define a set of parameters which may be used for all DataSource instances generated by the factory.

Chapter 20. Cache Store Implementations

20.1. Cache Stores

The cache store connects Red Hat JBoss Data Grid to the persistent data store. Cache stores are associated with individual caches. Different caches attached to the same cache manager can have different cache store configurations.

Note

If a clustered cache is configured with an unshared cache store (where shared is set to false), on node join, stale entries which might have been removed from the cluster might still be present in the stores and can reappear.

20.2. Cache Store Comparison

Select a cache store based on your requirements. The following is a summary of high level differences between the cache stores available in Red Hat JBoss Data Grid:

  • The Single File Cache Store is a local file cache store. It persists data locally for each node of the clustered cache. The Single File Cache Store provides superior read and write performance, but keeps keys in memory which limits its use when persisting large data sets at each node. See Single File Cache Store for details.
  • The LevelDB file cache store is a local file cache store which provides high read and write performance. It does not have the limitation of Single File Cache Store of keeping keys in memory. See LevelDB Cache Store for details.
  • The JDBC cache store is a cache store that may be shared, if required. When using it, all nodes of a clustered cache persist to a single database or a local JDBC database for every node in the cluster. The shared cache store lacks the scalability and performance of a local cache store such as the LevelDB cache store, but it provides a single location for persisted data. The JDBC cache store persists entries as binary blobs, which are not readable outside JBoss Data Grid. See JDBC Based Cache Stores for details.
  • The JPA Cache Store (supported in Library mode only) is a shared cache store like JDBC cache store, but preserves schema information when persisting to the database. Therefore, the persisted entries can be read outside JBoss Data Grid. See JPA Cache Store for details.

20.3. Cache Store Configuration Details (Library Mode)

The following lists contain details about the configuration elements and parameters for cache store elements in JBoss Data Grid’s Library mode. The following list is meant to highlight certain parameters on each element, and a full list may be found in the schemas.

The persistence Element

  • The passivation parameter affects the way in which Red Hat JBoss Data Grid interacts with stores. When an object is evicted from in-memory cache, passivation writes it to a secondary data store, such as a system or a database. Valid values for this parameter are true and false but passivation is set to false by default.

The file-store Element

  • The shared parameter indicates that the cache store is shared by different cache instances. For example, where all instances in a cluster use the same JDBC settings to talk to the same remote, shared database. shared is false by default. When set to true, it prevents duplicate data being written to the cache store by different cache instances. For the LevelDB cache stores, this parameter must be excluded from the configuration, or set to false because sharing this cache store is not supported.
  • The preload parameter is set to false by default. When set to true the data stored in the cache store is preloaded into the memory when the cache starts. This allows data in the cache store to be available immediately after startup and avoids cache operations delays as a result of loading data lazily. Preloaded data is only stored locally on the node, and there is no replication or distribution of the preloaded data. Red Hat JBoss Data Grid will only preload up to the maximum configured number of entries in eviction.
  • The fetch-state parameter determines whether or not to fetch the persistent state of a cache and apply it to the local cache store when joining the cluster. If the cache store is shared the fetch persistent state is ignored, as caches access the same cache store. A configuration exception will be thrown when starting the cache service if more than one cache store has this property set to true. The fetch-state property is false by default.
  • In order to speed up lookups, the single file cache store keeps an index of keys and their corresponding position in the file. To avoid this index resulting in memory consumption problems, this cache store can be bounded by a maximum number of entries that it stores, defined by the max-entries parameter. If this limit is exceeded, entries are removed permanently using the LRU algorithm both from the in-memory index and the underlying file based cache store. The default value is -1, allowing unlimited entries.
  • The singleton parameter enables a singleton store cache store. SingletonStore is a delegating cache store used when only one instance in a cluster can interact with the underlying store; however, singleton parameter is not recommended for file-store. The default value is false.
  • The purge parameter controls whether cache store is purged when it starts up.
  • The location configuration element sets a location on disk where the store can write.

The write-behind Element

The write-behind element contains parameters that configure various aspects of the cache store.

  • The thread-pool-size parameter specifies the number of threads that concurrently apply modifications to the store. The default value for this parameter is 1.
  • The flush-lock-timeout parameter specifies the time to acquire the lock which guards the state to be flushed to the cache store periodically. The default value for this parameter is 1.
  • The modification-queue-size parameter specifies the size of the modification queue for the asynchronous store. If updates are made at a rate that is faster than the underlying cache store can process this queue, then the asynchronous store behaves like a synchronous store for that period, blocking until the queue can accept more elements. The default value for this parameter is 1024 elements.
  • The shutdown-timeout parameter specifies maximum amount of time that can be taken to stop the cache store. Default value for this parameter is 25000 milliseconds.

The remote-store Element

  • The cache attribute specifies the name of the remote cache to which it intends to connect in the remote Infinispan cluster. The default cache will be used if the remote cache name is unspecified.
  • The fetch-state attribute, when set to true, ensures that the persistent state is fetched when the remote cache joins the cluster. If multiple cache stores are chained, only one cache store can have this property set to true . The default for this value is false.
  • The shared attribute is set to true when multiple cache instances share a cache store, which prevents multiple cache instances writing the same modification individually. The default for this attribute is false.
  • The preload attribute ensures that the cache store data is pre-loaded into memory and is immediately accessible after starting up. The disadvantage of setting this to true is that the start up time increases. The default value for this attribute is false.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.
  • The purge attribute ensures that the cache store is purged during the start up process. The default value for this attribute is false.
  • The tcp-no-delay attribute triggers the TCPNODELAY stack. The default value for this attribute is true.
  • The ping-on-start attribute sends a ping request to a back end server to fetch the cluster topology. The default value for this attribute is true.
  • The key-size-estimate attribute provides an estimation of the key size. The default value for this attribute is 64.
  • The value-size-estimate attribute specifies the size of the byte buffers when serializing and deserializing values. The default value for this attribute is 512.
  • The force-return-values attribute sets whether FORCE_RETURN_VALUE is enabled for all calls. The default value for this attribute is false.

The remote-server Element

Create a remote-server element within the remote-store element to define the server information.

  • The host attribute configures the host address.
  • The port attribute configures the port used by the Remote Cache Store. This defaults to 11222.

The connection-pool Element (Remote Store)

  • The max-active parameter indicates the maximum number of active connections for each server at a time. The default value for this attribute is -1 which indicates an infinite number of active connections.
  • The max-idle parameter indicates the maximum number of idle connections for each server at a time. The default value for this attribute is -1 which indicates an infinite number of idle connections.
  • The max-total parameter indicates the maximum number of persistent connections within the combined set of servers. The default setting for this attribute is -1 which indicates an infinite number of connections.
  • The min-idle-time parameter sets a target value for the minimum number of idle connections (per server) that should always be available. If this parameter is set to a positive number and timeBetweenEvictionRunsMillis 0, each time the idle connection eviction thread runs, it will try to create enough idle instances so that there will be minIdle idle instances available for each server. The default setting for this parameter is 1.
  • The eviction-interval parameter indicates how long the eviction thread should sleep before "runs" of examining idle connections. When non-positive, no eviction thread will be launched. The default setting for this parameter is 120000 milliseconds, or 2 minutes.
  • The min-evictable-idle-time parameter specifies the minimum amount of time that an connection may sit idle in the pool before it is eligible for eviction due to idle time. When non-positive, no connection will be dropped from the pool due to idle time alone. This setting has no effect unless timeBetweenEvictionRunsMillis 0. The default setting for this parameter is 1800000, or (30 minutes).
  • The test-idle parameter indicates whether or not idle connections should be validated by sending an TCP packet to the server, during idle connection eviction runs. Connections that fail to validate will be dropped from the pool. This setting has no effect unless timeBetweenEvictionRunsMillis 0. The default setting for this parameter is true.

The leveldb-store Element

  • The relative-to parameter specifies the base directory in which to store the cache state.
  • The path parameter specifies the location within the relative-to parameter to store the cache state.
  • The shared parameter specifies whether the cache store is shared. The only supported value for this parameter in the LevelDB cache store is false.
  • The preload parameter specifies whether the cache store will be pre-loaded. Valid values are true and false.
  • The block-size parameter defines the block size of the cache store.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.
  • The cache-size parameter defines the cache size of the cache store.
  • The clear-threshold parameter defines the cache clear threshold of the cache store.

The jpa-store Element

  • The persistence-unit attribute specifies the name of the JPA cache store.
  • The entity-class attribute specifies the fully qualified class name of the JPA entity used to store the cache entry value.
  • The batch-size (optional) attribute specifies the batch size for cache store streaming. The default value for this attribute is 100.
  • The store-metadata (optional) attribute specifies whether the cache store keeps the metadata (for example expiration and versioning information) with the entries. The default value for this attribute is true.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.

The binary-keyed-jdbc-store, string-keyed-jdbc-store, and mixed-keyed-jdbc-store Elements

  • The fetch-state parameter determines whether the persistent state is fetched when joining a cluster. Set this to true if using a replication and invalidation in a clustered environment. Additionally, if multiple cache stores are chained, only one cache store can have this property enabled. If a shared cache store is used, the cache does not allow a persistent state transfer despite this property being set to true. The fetch-state parameter is false by default.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.
  • The purge parameter specifies whether the cache store is purged when initially started.
  • The key-to-string-mapper parameter specifies the class name used to map keys to strings for the database tables.

The connection-pool Element (JDBC Store)

  • The connection-url parameter specifies the JDBC driver-specific connection URL.
  • The username parameter contains the username used to connect via the connection-url.
  • The password parameter contains the password to use when connecting via the connection-url
  • The driver parameter specifies the class name of the driver used to connect to the database.

The binary-keyed-table and string-keyed-table Elements

  • The prefix attribute defines the string prepended to name of the target cache when composing the name of the cache bucket table.
  • The drop-on-exit parameter specifies whether the database tables are dropped upon shutdown.
  • The create-on-start parameter specifies whether the database tables are created by the store on startup.
  • The fetch-size parameter specifies the size to use when querying from this table. Use this parameter to avoid heap memory exhaustion when the query is large.
  • The batch-size parameter specifies the batch size used when modifying this table.

The id-column, data-column, and timestamp-column Elements

  • The name parameter specifies the name of the column used.
  • The type parameter specifies the type of the column used.

The custom-store Element

  • The class parameter specifies the class name of the cache store implementation.
  • The preload parameter specifies whether to load entries into the cache during start up. Valid values for this parameter are true and false.
  • The shared parameter specifies whether the cache store is shared. This is used when multiple cache instances share a cache store. Valid values for this parameter are true and false.

The property Element

A property may be defined inside of a cache store, with the entry between the property tags being the stored value. For instance, in the below example a value of 1 is defined for minOccurs.

<property name="minOccurs">1</property>
  • The name attribute specifies the name of the property.

20.4. Cache Store Configuration Details (Remote Client-Server Mode)

The following tables contain details about the configuration elements and parameters for cache store elements in JBoss Data Grid’s Remote Client-Server mode. The following list is meant to highlight certain parameters on each element, and a full list may be found in the schemas.

The local-cache Element

  • The name parameter of the local-cache attribute is used to specify a name for the cache.
  • The statistics parameter specifies whether statistics are enabled at the container level. Enable or disable statistics on a per-cache basis by setting the statistics attribute to false.

The file-store Element

  • The name parameter of the file-store element is used to specify a name for the file store.
  • The passivation parameter determines whether entries in the cache are passivated (true) or if the cache store retains a copy of the contents in memory (false).
  • The purge parameter specifies whether or not the cache store is purged when it is started. Valid values for this parameter are true and false.
  • The shared parameter is used when multiple cache instances share a cache store. This parameter can be set to prevent multiple cache instances writing the same modification multiple times. Valid values for this parameter are true and false. However, the shared parameter is not recommended for the LevelDB cache store because this cache store cannot be shared.
  • The relative-to property is the directory where the file-store stores the data. It is used to define a named path.
  • The path property is the name of the file where the data is stored. It is a relative path name that is appended to the value of the relative-to property to determine the complete path.
  • The max-entries parameter provides maximum number of entries allowed. The default value is -1 for unlimited entries.
  • The fetch-state parameter when set to true fetches the persistent state when joining a cluster. If multiple cache stores are chained, only one of them can have this property enabled. Persistent state transfer with a shared cache store does not make sense, as the same persistent store that provides the data will just end up receiving it. Therefore, if a shared cache store is used, the cache does not allow a persistent state transfer even if a cache store has this property set to true. It is recommended to set this property to true only in a clustered environment. The default value for this parameter is false.
  • The preload parameter when set to true, loads the data stored in the cache store into memory when the cache starts. However, setting this parameter to true affects the performance as the startup time is increased. The default value for this parameter is false.
  • The singleton parameter enables a singleton store cache store. SingletonStore is a delegating cache store used when only one instance in a cluster can interact with the underlying store; however, singleton parameter is not recommended for file-store. The default value is false.

The store Element

  • The class parameter specifies the class name of the cache store implementation.

The property Element

  • The name parameter specifies the name of the property.
  • The value parameter specifies the value assigned to the property.

The remote-store Element

  • The cache parameter defines the name for the remote cache. If left undefined, the default cache is used instead.
  • The socket-timeout parameter sets whether the value defined in SO_TIMEOUT (in milliseconds) applies to remote Hot Rod servers on the specified timeout. A timeout value of 0 indicates an infinite timeout. The default value is 60,000 ms, or one minute.
  • The tcp-no-delay sets whether TCP_NODELAY applies on socket connections to remote Hot Rod servers.
  • The hotrod-wrapping sets whether a wrapper is required for Hot Rod on the remote store.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.

The remote-server Element

  • The outbound-socket-binding parameter sets the outbound socket binding for the remote server.

The binary-keyed-jdbc-store, string-keyed-jdbc-store, and mixed-keyed-jdbc-store Elements

  • The datasource parameter defines the name of a JNDI for the datasource.
  • The passivation parameter determines whether entries in the cache are passivated (true) or if the cache store retains a copy of the contents in memory (false).
  • The preload parameter specifies whether to load entries into the cache during start up. Valid values for this parameter are true and false.
  • The purge parameter specifies whether or not the cache store is purged when it is started. Valid values for this parameter are true and false.
  • The shared parameter is used when multiple cache instances share a cache store. This parameter can be set to prevent multiple cache instances writing the same modification multiple times. Valid values for this parameter are true and false.
  • The singleton parameter enables a singleton store cache store. SingletonStore is a delegating cache store used when only one instance in a cluster can interact with the underlying store

The binary-keyed-table and string-keyed-table Elements

  • The prefix parameter specifies a prefix string for the database table name.

The id-column, data-column, and timestamp-column Elements

  • The name parameter specifies the name of the database column.
  • The type parameter specifies the type of the database column.

The leveldb-store Element

  • The relative-to parameter specifies the base directory to store the cache state. This value defaults to jboss.server.data.dir.
  • The path parameter defines where, within the directory specified in the relative-to parameter, the cache state is stored. If undefined, the path defaults to the cache container name.
  • The passivation parameter specifies whether passivation is enabled for the LevelDB cache store. Valid values are true and false.
  • The singleton parameter enables the SingletonStore delegating cache store, used in situations when only one instance in a cluster should interact with the underlying store. The default value is false.
  • The purge parameter specifies whether the cache store is purged when it starts up. Valid values are true and false.

20.5. Single File Cache Store

20.5.1. Single File Cache Store

Red Hat JBoss Data Grid includes one file system based cache store: the SingleFileCacheStore.

The SingleFileCacheStore is a simple file system based implementation and a replacement to the older file system based cache store: the FileCacheStore.

SingleFileCacheStore stores all key/value pairs and their corresponding metadata information in a single file. To speed up data location, it also keeps all keys and the positions of their values and metadata in memory. Hence, using the single file cache store slightly increases the memory required, depending on the key size and the amount of keys stored. Hence SingleFileCacheStore is not recommended for use cases where the keys are too big.

To reduce memory consumption, the size of the cache store can be set to a fixed number of entries to store in the file; however, this works only when JBoss Data Grid is used as a cache. When JBoss Data Grid is used this way, data which is not present in the cache can be recomputed or re-retrieved from the authoritative data store and stored in the JBoss Data Grid cache. This limitation exists so that once the maximum number of entries is reached older data in the cache store is removed. If JBoss Data Grid were used as an authoritative data store in this scenario it would lead to potential data loss.

Due to its limitations, SingleFileCacheStore can be used in a limited capacity in production environments. It can not be used on shared file system (such as NFS and Windows shares) due to a lack of proper file locking, resulting in data corruption. Furthermore, file systems are not inherently transactional, resulting in file writing failures during the commit phase if the cache is used in a transactional context.

20.5.2. Single File Store Configuration (Remote Client-Server Mode)

The following is an example of a Single File Store configuration for Red Hat JBoss Data Grid’s Remote Client-Server mode:

<local-cache name="default" statistics="true">
    <file-store name="myFileStore"
                passivation="true"
                purge="true"
                relative-to="{PATH}"
                path="{DIRECTORY}"
                max-entries="10000"
                fetch-state="true"
                preload="false" />
</local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.5.3. Single File Store Configuration (Library Mode)

In Red Hat JBoss Grid’s Library mode, configure a Single File Cache Store as follows:.

<local-cache name="writeThroughToFile">
      <persistence passivation="false">
         <file-store fetch-state="true"
                      purge="false"
                      shared="false"
                      preload="false"
                      location="/tmp/Another-FileCacheStore-Location"
                      max-entries="100">
            <write-behind enabled="true"
    	           threadPoolSize="500"
    	           flush-lock-timeout="1"
	           modification-queue-size="1024"
	           shutdown-timeout="25000"/>
        </singleFile>
      </persistence>
 </local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.5.4. Upgrade JBoss Data Grid Cache Stores

Red Hat JBoss Data Grid 7 stores data in a different format than previous versions of JBoss Data Grid. As a result, the newer version of JBoss Data Grid cannot read data stored by older versions. Use rolling upgrades to upgrade persisted data from the format used by the old JBoss Data Grid to the new format. Additionally, the newer version of JBoss Data Grid also stores persistence configuration information in a different location.

Rolling upgrades is the process by which a JBoss Data Grid installation is upgraded without a service shutdown. For JBoss Data Grid servers, this procedure refers to the server side components. The upgrade can be due to either hardware or software change, such as upgrading JBoss Data Grid.

Rolling upgrades are only available in JBoss Data Grid’s Remote Client-Server mode.

20.6. LevelDB Cache Store

20.6.1. LevelDB Cache Store

LevelDB is a key-value storage engine that provides an ordered mapping from string keys to string values.

The LevelDB Cache Store uses two filesystem directories. Each directory is configured for a LevelDB database. One directory stores the non-expired data and the second directory stores the keys pending to be purged permanently.

20.6.2. Configuring LevelDB Cache Store (Remote Client-Server Mode)

Procedure: To configure LevelDB Cache Store:

  1. Add the following elements to a cache definition in standalone.xml to configure the database:

    <leveldb-store path="/path/to/leveldb/data"
        	       passivation="false"
        	       purge="false" >
        <leveldb-expiration path="/path/to/leveldb/expires/data" />
        <implementation type="JNI" />
    </leveldb-store>
    Note

    Directories will be automatically created if they do not exist.

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.6.3. LevelDB Cache Store Sample XML Configuration (Library Mode)

The following is a sample XML configuration of LevelDB Cache Store:

<local-cache name="vehicleCache">
      <persistence passivation="false">
          <leveldb-store xmlns="urn:infinispan:config:store:leveldb:8.0
                        relative-to="/path/to/leveldb/data"
                        shared="false"
                        preload="true"/>
      </persistence>
   </local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.6.4. Configure a LevelDB Cache Store Using JBoss Operations Network

Use the following procedure to set up a new LevelDB cache store using the JBoss Operations Network.

  1. Ensure that Red Hat JBoss Operations Network 3.2 or higher is installed and started.
  2. Install the Red Hat JBoss Data Grid Plugin Pack for JBoss Operations Network 3.2.0.
  3. Ensure that JBoss Data Grid is installed and started.
  4. Import JBoss Data Grid server into the inventory.
  5. Configure the JBoss Data Grid connection settings.
  6. Create a new LevelDB cache store as follows:

    Figure 20.1. Create a new LevelDB Cache Store

    Use JBoss Operations Network to create a new cache store.
    1. Right-click the default cache.
    2. In the menu, mouse over the option.
    3. In the submenu, click menu:LevelDB Store[] .
  7. Name the new LevelDB cache store as follows:

    Figure 20.2. Name the new LevelDB Cache Store

    Name the new LevelDB Cache Store
    1. In the Resource Create Wizard that appears, add a name for the new LevelDB Cache Store.
    2. Click btn:[Next] to continue.
  8. Configure the LevelDB Cache Store settings as follows:

    Figure 20.3. Configure the LevelDB Cache Store Settings

    Configure the new LevelDB Cache Store
    1. Use the options in the configuration window to configure a new LevelDB cache store.
    2. Click menu:Finish[] to complete the configuration.
  9. Schedule a restart operation as follows:

    Figure 20.4. Schedule a Restart Operation

    Schedule a restart operation
    1. In the screen’s left panel, expand the JBoss AS7 Standalone Servers entry, if it is not currently expanded.
    2. Click JDG (0.0.0.0:9990) from the expanded menu items.
    3. In the screen’s right panel, details about the selected server display. Click the menu:Operations[] tab.
    4. In the Operation drop-down box, select the Restart operation.
    5. Select the radio button for the Now entry.
    6. Click menu:Schedule[] to restart the server immediately.
  10. Discover the new LevelDB cache store as follows:

    Figure 20.5. Discover the New LevelDB Cache Store

    Discover the new LevelDB cache store
    1. In the screen’s left panel, select each of the following items in the specified order to expand them: menu:JBoss AS7 Standalong Servers[JDG (0.0.0.0:9990) > infinispan > Cache Containers > local > Caches > default > LevelDB Stores]
    2. Click the name of your new LevelDB Cache Store to view its configuration information in the right panel.

20.7. JDBC Based Cache Stores

20.7.1. JDBC Based Cache Stores

Red Hat JBoss Data Grid offers several cache stores for use with common data storage formats. JDBC based cache stores are used with any cache store that exposes a JDBC driver. JBoss Data Grid offers the following JDBC based cache stores depending on the key to be persisted:

  • JdbcBinaryStore.
  • JdbcStringBasedStore.
  • JdbcMixedStore.
Important

Both Binary and Mixed JDBC stores are deprecated in JBoss Data Grid 7.2, and are not recommended for production use. It is recommended to utilize a String Based store instead.

20.7.2. JdbcBinaryStores

20.7.2.1. JdbcBinaryStores

The JdbcBinaryStore supports all key types. It stores all keys with the same hash value (hashCode method on the key) in the same table row/blob. The hash value common to the included keys is set as the primary key for the table row/blob. As a result of this hash value, JdbcBinaryStore offers excellent flexibility but at the cost of concurrency and throughput.

As an example, if three keys (k1, k2 and k3) have the same hash code, they are stored in the same table row. If three different threads attempt to concurrently update k1, k2 and k3, they must do it sequentially because all three keys share the same row and therefore cannot be simultaneously updated.

Important

Binary JDBC stores are deprecated in JBoss Data Grid 7.2, and are not recommended for production use. It is recommended to utilize a String Based store instead.

20.7.2.2. JdbcBinaryStore Configuration (Remote Client-Server Mode)

The following is a configuration for JdbcBinaryStore using Red Hat JBoss Data Grid’s Remote Client-Server mode with Passivation enabled:

<local-cache name="customCache">
    <!-- Additional configuration elements here -->
    <binary-keyed-jdbc-store datasource="java:jboss/datasources/JdbcDS"
   			     passivation="${true/false}"
			     preload="${true/false}"
			     purge="${true/false}">
        <binary-keyed-table prefix="JDG">
            <id-column name="id"
	               type="${id.column.type}"/>
            <data-column name="datum"
	  	         type="${data.column.type}"/>
            <timestamp-column name="version"
	 		      type="${timestamp.column.type}"/>
        </binary-keyed-table>
    </binary-keyed-jdbc-store>
</local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.7.2.3. JdbcBinaryStore Configuration (Library Mode)

The following is a sample configuration for the JdbcBinaryStore:

<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:8.5 http://www.infinispan.org/schemas/infinispan-config-8.5.xsd
            urn:infinispan:config:store:jdbc:8.0 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-8.0.xsd"
        xmlns="urn:infinispan:config:8.5">
    <!-- Additional configuration elements here -->
    <persistence>
    <binary-keyed-jdbc-store xmlns="urn:infinispan:config:store:jdbc:8.0
                             fetch-state="false"
			     purge="false">
        <connection-pool connection-url="jdbc:h2:mem:infinispan_binary_based;DB_CLOSE_DELAY=-1"
			 username="sa"
			 driver="org.h2.Driver"/>
        <binary-keyed-table dropOnExit="true"
			    createOnStart="true"
			    prefix="ISPN_BUCKET_TABLE">
            <id-column name="ID_COLUMN"
		       type="VARCHAR(255)" />
            <data-column name="DATA_COLUMN"
			 type="BINARY" />
	    <timestamp-column name="TIMESTAMP_COLUMN"
			      type="BIGINT" />
        </binary-keyed-table>
    </binary-keyed-jdbc-store>
</persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.7.3. JdbcStringBasedStores

20.7.3.1. JdbcStringBasedStores

The JdbcStringBasedStore stores each entry in its own row in the table, instead of grouping multiple entries into each row, resulting in increased throughput under a concurrent load. It also uses a (pluggable) bijection that maps each key to a String object. The key-to-string-mapper interface defines the bijection.

Red Hat JBoss Data Grid includes a default implementation called DefaultTwoWayKey2StringMapper that handles primitive types.

20.7.3.2. JdbcStringBasedStore Configuration (Remote Client-Server Mode)

The following is a sample JdbcStringBasedStore for Red Hat JBoss Data Grid’s Remote Client-Server mode:

<local-cache name="customCache">
    <!-- Additional configuration elements here -->
    <string-keyed-jdbc-store datasource="java:jboss/datasources/JdbcDS"
			     passivation="true"
			     preload="false"
			     purge="false"
			     shared="false"
			     singleton="true">
        <string-keyed-table prefix="JDG">
            <id-column name="id"
	 	       type="${id.column.type}"/>
	    <data-column name="datum"
		         type="${data.column.type}"/>
	    <timestamp-column name="version"
			      type="${timestamp.column.type}"/>
	</string-keyed-table>
    </string-keyed-jdbc-store>
</local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.7.3.3. JdbcStringBasedStore Configuration (Library Mode)

The following is a sample configuration for the JdbcStringBasedStore:

<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:8.5 http://www.infinispan.org/schemas/infinispan-config-8.5.xsd
            urn:infinispan:config:store:jdbc:8.0 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-8.0.xsd"
        xmlns="urn:infinispan:config:8.5">
    <!-- Additional configuration elements here -->
    <persistence>
        <string-keyed-jdbc-store xmlns="urn:infinispan:config:store:jdbc:8.0"
	                         fetch-state="false"
			         purge="false"
			         key2StringMapper="org.infinispan.loaders.keymappers.DefaultTwoWayKey2StringMapper">
            <dataSource jndiUrl="java:jboss/datasources/JdbcDS"/>
	    <string-keyed-table dropOnExit="true"
				createOnStart="true"
				prefix="ISPN_STRING_TABLE">
	        <id-column name="ID_COLUMN"
			   type="VARCHAR(255)" />
		<data-column name="DATA_COLUMN"
			     type="BINARY" />
		<timestamp-column name="TIMESTAMP_COLUMN"
			          type="BIGINT" />
            </string-keyed-table>
        </string-keyed-jdbc-store>
    </persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.7.3.4. JdbcStringBasedStore Multiple Node Configuration (Remote Client-Server Mode)

The following is a configuration for the JdbcStringBasedStore in Red Hat JBoss Data Grid’s Remote Client-Server mode. This configuration is used when multiple nodes must be used.

<subsystem xmlns="urn:infinispan:server:core:8.5" default-cache-container="default">
	<cache-container <!-- Additional configuration information here --> >
		<!-- Additional configuration elements here -->
      <replicated-cache>
			<!-- Additional configuration elements here -->
	      <string-keyed-jdbc-store datasource="java:jboss/datasources/JdbcDS"
	            		       fetch-state="true"
	            		       passivation="false"
	            		       preload="false"
	            		       purge="false"
	            		       shared="false"
	            		       singleton="true">
	         <string-keyed-table prefix="JDG">
	             <id-column name="id"
	                        type="${id.column.type}"/>
	             <data-column name="datum"
	                          type="${data.column.type}"/>
	             <timestamp-column name="version"
	                               type="${timestamp.column.type}"/>
				</string-keyed-table>
			</string-keyed-jdbc-store>
		</replicated-cache>
	</cache-container>
</subsystem>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.7.4. JdbcMixedStores

20.7.4.1. JdbcMixedStores

The JdbcMixedStore is a hybrid implementation that delegates keys based on their type to either the JdbcBinaryStore or JdbcStringBasedStore.

Important

Mixed JDBC stores are deprecated in JBoss Data Grid 7.2, and are not recommended for production use. It is recommended to utilize a String Based store instead.

20.7.4.2. JdbcMixedStore Configuration (Remote Client-Server Mode)

The following is a configuration for a JdbcMixedStore for Red Hat JBoss Data Grid’s Remote Client-Server mode:

<local-cache name="customCache">
	<mixed-keyed-jdbc-store datasource="java:jboss/datasources/JdbcDS"
				passivation="true"
				preload="false"
				purge="false">
		<binary-keyed-table prefix="MIX_BKT2">
			<id-column name="id"
				   type="${id.column.type}"/>
			<data-column name="datum"
				     type="${data.column.type}"/>
			<timestamp-column name="version"
				   	  type="${timestamp.column.type}"/>
		</binary-keyed-table>
		<string-keyed-table prefix="MIX_STR2">
			<id-column name="id"
				   type="${id.column.type}"/>
			<data-column name="datum"
				     type="${data.column.type}"/>
			<timestamp-column name="version"
				   	  type="${timestamp.column.type}"/>
		</string-keyed-table>
	</mixed-keyed-jdbc-store>
</local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.7.4.3. JdbcMixedStore Configuration (Library Mode)

The following is a sample configuration for the JdbcMixedStore:

<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:8.5 http://www.infinispan.org/schemas/infinispan-config-8.5.xsd
            urn:infinispan:config:store:jdbc:8.0 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-8.0.xsd"
        xmlns="urn:infinispan:config:8.5">
        <!-- Additional configuration elements here -->
	<persistence>
	<mixed-keyed-jdbc-store xmlns="urn:infinispan:config:store:jdbc:8.0"
	                      fetch-state="false"
			      purge="false"
			      key-to-string-mapper="org.infinispan.persistence.keymappers.DefaultTwoWayKey2StringMapper">
		<connection-pool connection-url="jdbc:h2:mem:infinispan_binary_based;DB_CLOSE_DELAY=-1"
				username="sa"
				driver="org.h2.Driver"/>
		<binary-keyed-table dropOnExit="true"
				  createOnStart="true"
				  prefix="ISPN_BUCKET_TABLE_BINARY">
			<id-column name="ID_COLUMN"
				  type="VARCHAR(255)" />
			<data-column name="DATA_COLUMN"
				    type="BINARY" />
			<timestamp-column name="TIMESTAMP_COLUMN"
					 type="BIGINT" />
		</binary-keyed-table>
		<string-keyed-table dropOnExit="true"
				  createOnStart="true"
				  prefix="ISPN_BUCKET_TABLE_STRING">
			<id-column name="ID_COLUMN"
				  type="VARCHAR(255)" />
			<data-column name="DATA_COLUMN"
				    type="BINARY" />
			<timestamp-column name="TIMESTAMP_COLUMN"
					 type="BIGINT" />
		</string-keyed-table>
	</mixed-keyed-jdbc-store>
</persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.7.5. Cache Store Troubleshooting

20.7.5.1. IOExceptions with JdbcStringBasedStore

An IOException Unsupported protocol version 48 error when using JdbcStringBasedStore indicates that your data column type is set to VARCHAR, CLOB or something similar instead of the correct type, BLOB or VARBINARY. Despite its name, JdbcStringBasedStore only requires that the keys are strings while the values can be any data type, so that they can be stored in a binary column.

20.8. The Remote Cache Store

20.8.1. Remote Cache Stores

The RemoteCacheStore is an implementation of the cache loader that stores data in a remote Red Hat JBoss Data Grid cluster. The RemoteCacheStore uses the Hot Rod client-server architecture to communicate with the remote cluster.

For remote cache stores, Hot Rod provides load balancing, fault tolerance and the ability to fine tune the connection between the RemoteCacheStore and the cluster.

20.8.2. Remote Cache Store Configuration (Remote Client-Server Mode)

The following is a sample remote cache store configuration for Red Hat JBoss Data Grid’s Remote Client-Server mode:

<remote-store cache="default"
              socket-timeout="60000"
              tcp-no-delay="true"
              hotrod-wrapping="true">
	<remote-server outbound-socket-binding="remote-store-hotrod-server" />
</remote-store>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Remote Client-Server Mode).

20.8.3. Remote Cache Store Configuration (Library Mode)

The following is a sample remote cache store configuration for Red Hat JBoss Data Grid’s Library mode:

<persistence passivation="false">
	<remote-store xmlns="urn:infinispan:config:store:remote:8.0"
	             cache="default"
		     fetch-state="false"
		     shared="true"
		     preload="false"
		     purge="false"
		     tcp-no-delay="true"
		     key-size-estimate="62"
		     value-size-estimate="512"
		     force-return-values="false">
		<remote-server host="127.0.0.1"
			port="1971" />
		<connectionPool max-active="99"
				max-idle="97"
				max-total="98" />
	</remote-store>
</persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.8.4. Define the Outbound Socket for the Remote Cache Store

The Hot Rod server used by the remote cache store is defined using the outbound-socket-binding element in a standalone.xml file.

An example of this configuration in the standalone.xml file is as follows:

Define the Outbound Socket

<server>
    <!-- Additional configuration elements here -->
    <socket-binding-group name="standard-sockets"
    			  default-interface="public"
    			  port-offset="${jboss.socket.binding.port-offset:0}">
        <!-- Additional configuration elements here -->
        <outbound-socket-binding name="remote-store-hotrod-server">
            <remote-destination host="remote-host"
                                port="11222"/>
        </outbound-socket-binding>
    </socket-binding-group>
</server>

20.9. JPA Cache Store

20.9.1. JPA Cache Stores

The JPA (Java Persistence API) Cache Store stores cache entries in the database using a formal schema, which allows other applications to read the persisted data and load data provided by other applications into Red Hat JBoss Data Grid. The database should not be used by the other applications concurrently with JBoss Data Grid.

Important

In Red Hat JBoss Data Grid, JPA cache stores are only supported in Library mode.

20.9.2. JPA Cache Store Sample XML Configuration (Library Mode)

To configure JPA Cache Stores using XML in Red Hat JBoss Data Grid, add the following configuration to the infinispan.xml file:

<local-cache name="users">
  <!-- Insert additional configuration elements here -->
	<persistence passivation="false">
            <jpa-store xmlns="urn:infinispan:config:store:jpa:8.0"
                      shared="true"
                      preload="true"
                      persistence-unit="MyPersistenceUnit"
                      entity-class="org.infinispan.loaders.jpa.entity.User" />
	</persistence>
</local-cache>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

20.9.3. Storing Metadata in the Database

When storeMetadata is set to true (default value), meta information about the entries such as expiration, creation and modification timestamps, and versioning is stored in the database. JBoss Data Grid stores the metadata in an additional table named _ispn_metadata_ because the entity table has a fixed layout that cannot accommodate the metadata.

The structure of this table depends on the database in use. Enable the automatic creation of this table using the same database as the test environment and then transfer the structure to the production database.

Configure persistence.xml for Metadata Entities

  1. Using Hibernate as the JPA implementation allows automatic creation of these tables using the property hibernate.hbm2ddl.auto in persistence.xml as follows:

    <property name="hibernate.hbm2ddl.auto" value="update"/>
  2. Declare the metadata entity class to the JPA provider by adding the following to persistence.xml :

    <class>org.infinispan.persistence.jpa.impl.MetadataEntity</class>

As outlined, metadata is always stored in a new table. If metadata information collection and storage is not required, set the storeMetadata attribute to false in the JPA Store configuration.

20.9.4. Deploying JPA Cache Stores in Various Containers

Red Hat JBoss Data Grid JPA Cache Store implementations are deployed normally for all supported containers, except Red Hat JBoss Enterprise Application Platform. The JBoss Data Grid JBoss EAP modules contain the JPA cache store and related libraries such as Hibernate. As a result, the relevant libraries are not packaged inside the application, but instead the application refers to the libraries in the JBoss EAP modules that have them installed.

These modules are not required for containers other than JBoss EAP. As a result, all the relevant libraries are packaged in the application’s WAR/EAR file, such as with the following Maven dependency:

<dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-cachestore-jpa</artifactId>
    <version>{FullInfinispanVersion}</version>
</dependency>

Deploy JPA Cache Stores in JBoss EAP 6.3.x and earlier

  • To add dependencies from the JBoss Data Grid modules to the application’s classpath, provide the JBoss EAP deployer a list of dependencies in one of the following ways:

    • Add a dependency configuration to the MANIFEST.MF file:

      Manifest-Version: 1.0
      Dependencies: org.infinispan:jdg-7.2 services, org.infinispan.persistence.jpa:jdg-7.2 services
    • Add a dependency configuration to the jboss-deployment-structure.xml file:

      <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
          <deployment>
              <dependencies>
                  <module name="org.infinispan.persistence.jpa" slot="jdg-7.2" services="export"/>
                  <module name="org.infinispan" slot="jdg-7.2" services="export"/>
              </dependencies>
          </deployment>
      </jboss-deployment-structure>

Deploy JPA Cache Stores in JBoss EAP 6.4 and later

  1. Add the following property in persistence.xml :

    <persistence-unit>
      [...]
      <properties>
        <property name="jboss.as.jpa.providerModule" value="application" />
      </properties>
    </persistence-unit>
  2. Add the following dependencies to the jboss-deployment-structure.xml :

    <jboss-deployment-structure>
        <deployment>
            <dependencies>
                <module name="org.infinispan" slot="jdg-7.2"/>
                <module name="org.jgroups" slot="jdg-7.2"/>
                <module name="org.infinispan.persistence.jpa" slot="jdg-7.2" services="export"/>
                <module name="org.hibernate"/>
            </dependencies>
        </deployment>
    </jboss-deployment-structure>
  3. Add any additional dependencies, such as additional JDG modules, are in use add these to the dependencies section in jboss-deployment-structure.xml .
Important

JPA Cache Store is not supported in Apache Karaf in JBoss Data Grid 7.2.

20.10. Cassandra Cache Store

20.10.1. Cassandra Cache Store

Red Hat JBoss Data Grid allows Apache Cassandra to function as a Cache Store, leveraging their distributed database architecture to provide a virtually unlimited, horizontally scalable persistent store for cache entries.

In order to use the Cassandra Cache Store an appropriate keyspace must first be created on the Cassandra database. This may either be performed automatically or by enabling the auto-create-keyspace parameter in the cache store configuration. A sample keyspace creation is demonstrated below:

CREATE KEYSPACE IF NOT EXISTS Infinispan WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};
CREATE TABLE Infinispan.InfinispanEntries (key blob PRIMARY KEY, value blob, metadata blob);

20.10.2. Enabling the Cassandra Cache Store

The Cassandra Cache Store is included based on the downloaded distribution. The following indicates where this is located, and steps to enable it if required:

  • Library Mode - The infinispan-cachestore-cassandra-8.5.0.Final-redhat-9-deployable.jar is included in the jboss-datagrid-${jdg-version}-library/ directory, and may be added to any projects that are using the Cassandra Cache Store.
  • Remote Client-Server Mode - The Cassandra Cache Store is prepackaged in the modules/ directory of the server, and may be used by default with no additional configuration necessary.
  • JBoss Data Grid modules for JBoss EAP - The Cassandra Cache Store is included in the modules distributed, and may be added by using the org.infinispan.persistence.cassandra as the module name.

20.10.3. Cassandra Cache Store Sample XML Configuration (Remote Client-Server Mode)

In Remote Client-Server mode the Cassandra Cache Store is defined by using the class org.infinispan.persistence.cassandra.CassandraStore and defining the properties individually within the store.

The following configuration snippet provides an example on how to define a Cassandra Cache Store inside of an xml file:

<local-cache name="cassandracache">
    <locking acquire-timeout="30000" concurrency-level="1000" striping="false"/>
    <transaction mode="NONE"/>
    <store name="cassstore1"
           class="org.infinispan.persistence.cassandra.CassandraStore"
           shared="true"
           passivation="false">
        <property name="autoCreateKeyspace">true</property>
        <property name="keyspace">store1</property>
        <property name="entryTable">entries1</property>
        <property name="consistencyLevel">LOCAL_ONE</property>
        <property name="serialConsistencyLevel">SERIAL</property>
        <property name="servers">127.0.0.1[9042],127.0.0.1[9041]</property>
        <property name="connectionPool.heartbeatIntervalSeconds">30</property>
        <property name="connectionPool.idleTimeoutSeconds">120</property>
        <property name="connectionPool.poolTimeoutMillis">5</property>
    </store>
</local-cache>

20.10.4. Cassandra Cache Store Sample XML Configuration (Library Mode)

In Library Mode the Cassandra Cache Store may be configured using two different methods:

  • Option 1: Using the same method discussed for Remote Client-Server Mode, found in Cassandra Cache Store Sample XML Configuration (Remote Client-Server Mode).
  • Option 2: Using the cassandra-store schema. The following snippet shows an example configuration defining a Cassandra Cache Store:

    <cache-container default-cache="cassandracache">
      <local-cache name="cassandracache">
        <persistence passivation="false">
          <cassandra-store xmlns="urn:infinispan:config:store:cassandra:8.2"
                auto-create-keyspace="true"
                keyspace="Infinispan"
                entry-table="InfinispanEntries" shared="true">
            <cassandra-server host="127.0.0.1" port="9042" />
            <connection-pool heartbeat-interval-seconds="30"
                idle-timeout-seconds="120"
                pool-timeout-millis="5" />
          </cassandra-store>
        </persistence>
      </local-cache>
    </cache-container>

20.10.5. Cassandra Configuration Parameters

When defining a backing Cassandra instance in Library Mode one or more cassandra-server elements may be specified in the configuration. Each of the elements has the following properties:

Table 20.1. Cassandra Server Configuration Parameters
Parameter NameDescriptionDefault Value

host

The hostname or ip address of a Cassandra server.

127.0.0.1

port

The port on which the server is listening.

9042

The following properties may be configured on the Cassandra Cache Store:

Table 20.2. Cassandra Configuration Parameter
Parameter NameDescriptionDefault Value

auto-create-keyspace

Determines whether the keyspace and entry table should be automatically created on startup.

true

keyspace

Name of the keyspace to use.

Infinispan

entry-table

Name of the table storing entries.

InfinispanEntries

consistency-level

Consistency level to use for the queries.

LOCAL_ONE

serial-consistency-level

Serial consistency level to use for the queries.

SERIAL

A connection-pool may also be defined with the following elements:

Table 20.3. Connection Pool Configuration Parameters
Parameter NameDescriptionDefault Value

pool-timeout-millis

Time that the driver blocks when no connection from hosts pool is available. After this timeout, the driver will try the next host.

5

heartbeat-interval-seconds

Application-side heartbeat to avoid the connections being dropped when no activity is happening. Set to 0 to disable.

30

idle-timeout-seconds

Timeout before an idle connection is removed.

120

20.11. Custom Cache Stores

20.11.1. Custom Cache Stores

Custom cache stores are a customized implementation of Red Hat JBoss Data Grid cache stores.

In order to create a custom cache store (or loader), implement all or a subset of the following interfaces based on the need:

  • CacheLoader
  • CacheWriter
  • AdvancedCacheLoader
  • AdvancedCacheWriter
  • ExternalStore
  • AdvancedLoadWriteStore

See Cache Loaders and Cache Writers for individual functions of the interfaces.

Note

If the AdvancedCacheWriter is not implemented, the expired entries cannot be purged or cleared using the given writer.

Note

If the AdvancedCacheLoader is not implemented, the entries stored in the given loader will not be used for preloading.

To migrate the existing cache store to the new API or to write a new store implementation, use SingleFileStore as an example. To view the SingleFileStore example code, download the JBoss Data Grid source code.

Use the following procedure to download SingleFileStore example code from the Customer Portal:

Download JBoss Data Grid Source Code

  1. To access the Red Hat Customer Portal, navigate to https://access.redhat.com/home in a browser.
  2. Click menu:Downloads[] .
  3. In the section labeled JBoss Development and Management , click menu:Red Hat JBoss Data Grid[] .
  4. Enter the relevant credentials in the Red Hat Login and Password fields and click menu:Log In[] .
  5. From the list of downloadable files, locate Red Hat JBoss Data Grid 7 Source Code and click menu:Download[] . Save and unpack it in a desired location.
  6. Locate the SingleFileStore source code by navigating through jboss-datagrid-7.2.3-sources/infinispan-8.5.3.Final-redhat-00002/core/src/main/java/org/infinispan/persistence/file/SingleFileStore.java .

20.11.2. Custom Cache Store Maven Archetype

An easy way to get started with developing a Custom Cache Store is to use the Maven archetype; creating an archetype will generate a new Maven project with the correct directory layout and sample code.

Generate a Maven Archetype

  1. Ensure the JBoss Data Grid Maven repository has been installed by following the instructions in the Red Hat JBoss Data Grid Getting Started Guide .
  2. Open a command prompt and execute the following command to generate an archetype in the current directory:

    mvn -Dmaven.repo.local="path/to/unzipped/jboss-datagrid-7.2.x-maven-repository/"
      archetype:generate
      -DarchetypeGroupId=org.infinispan
      -DarchetypeArtifactId=custom-cache-store-archetype
      -DarchetypeVersion=8.5.0.Final-redhat-9
    Note

    The above command has been broken into multiple lines for readability; however, when executed this command and all arguments must be on a single line.

20.11.3. Custom Cache Store Configuration (Remote Client-Server Mode)

20.11.3.1. Custom Cache Store Configuration (Remote Client-Server Mode)

The following is a sample configuration for a custom cache store in Red Hat JBoss Data Grid’s Remote Client-Server mode:

Custom Cache Store Configuration

<distributed-cache name="cacheStore" mode="SYNC" segments="256" owners="2" remote-timeout="30000">
    <store class="my.package.CustomCacheStore">
        <property name="customStoreProperty">10</property>
    </store>
</distributed-cache>

See the reference information for the elements and parameters in the preceding configuration example:

20.11.3.2. Option 1: Add Custom Cache Store using deployments (Remote Client-Server Mode)

Deploy Custom Cache Store .jar file to JDG server using deployments

  1. Add the following Java service loader file META-INF/services/org.infinispan.persistence.spi.AdvancedLoadWriteStore to the module and add a reference to the Custom Cache Store Class, such as seen below:

    my.package.CustomCacheStore
  2. Copy the jar to the $JDG_HOME/standalone/deployments/ directory.
  3. If the .jar file is available the server the following message will be displayed in the logs:

    JBAS010287: Registering Deployed Cache Store service for store 'my.package.CustomCacheStore'
  4. In the infinispan-core subsystem add an entry for the cache inside a cache-container, specifying the class that overrides one of the interfaces from Custom Cache Stores:

    <subsystem xmlns="urn:infinispan:server:core:8.5">
      [...]
      <distributed-cache name="cacheStore" mode="SYNC" segments="256" owners="2" remote-timeout="30000"">
        <store class="my.package.CustomCacheStore">
          <!-- If custom properties are included these may be specified as below -->
          <property name="customStoreProperty">10</property>
        </store>
      </distributed-cache>
      [...]
    </subsystem>
20.11.3.3. Option 2: Add Custom Cache Store using the CLI (Remote Client-Server Mode)

Deploying Custom Cache Store .jar file to JDG server using the CLI

  1. Connect to the JDG server by running the below command:

    [$JDG_HOME] $ bin/cli.sh --connect --controller=$IP:$PORT
  2. Deploy the .jar file by executing the following command:

    deploy /path/to/artifact.jar
20.11.3.4. Option 3: Add Custom Cache Store using JON (Remote Client-Server Mode)

Deploying Custom Cache Store .jar file to JDG server using JBoss Operation Network

  1. Log into JON.
  2. Navigate to Bundles along the upper bar.
  3. Click the New button and choose the Recipe radio button.
  4. Insert a deployment bundle file content that references the store, similar to the following example:

    <?xml version="1.0"?>
    <project name="cc-bundle" default="main" xmlns:rhq="antlib:org.rhq.bundle">
    
      <rhq:bundle name="Mongo DB Custom Cache Store" version="1.0" description="Custom Cache Store">
      	<rhq:deployment-unit name="JDG" compliance="full">
      	  <rhq:file name="custom-store.jar"/>
      	</rhq:deployment-unit>
      </rhq:bundle>
    
      <target name="main" />
    
    </project>
  5. Proceed with Next button to Bundle Groups configuration wizard page and proceed with Next button once again.
  6. Locate custom cache store .jar file using file uploader and Upload the file.
  7. Proceed with Next button to Summary configuration wizard page. Proceed with Finish button in order to finish bundle configuration.
  8. Navigate back to the Bundles tab along the upper bar.
  9. Select the newly created bundle and click Deploy button.
  10. Enter Destination Name and choose the proper Resource Group; this group should only consist of JDG servers.
  11. Choose Install Directory from Base Location's radio box group.
  12. Enter /standalone/deployments in Deployment Directory text field below.
  13. Proceed with the wizard using the default options.
  14. Validate the deployment using the following command on the server’s host:

    find $JDG_HOME -name "custom-store.jar"
  15. Confirm the bundle has been installed in $JDG_HOME/standalone/deployments.

Once the above steps are completed the .jar file will be successfully uploaded and registered by the JDG server.

Note

The JON plugin has been deprecated in JBoss Data Grid 7.2 and is expected to be removed in a subsequent version.

20.11.4. Custom Cache Store Configuration (Library Mode)

Note

Custom Cache Store classes must be in the JBoss Data Grid classpath. Either package the Custom Cache Store with JBoss Data Grid or define it as an EAP module that you list as a dependency.

The following is a sample configuration for a custom cache store in Red Hat JBoss Data Grid’s Library mode:

Custom Cache Store Configuration

<persistence>
	<store class="org.infinispan.custom.CustomCacheStore"
	       preload="true"
	       shared="true">
	       <property name="customStoreProperty">10</property>
	</store>
</persistence>

For details about the elements and parameters used in this sample configuration, see Cache Store Configuration Details (Library Mode).

Part IX. Set Up Passivation

Chapter 21. Activation and Passivation Modes

21.1. Activation and Passivation Modes

Activation is the process of restoring an entry from the data store into the in-memory cache. Activation occurs when a thread attempts to access an entry that is in the store but not the memory (namely a passivated entry).

Passivation mode allows entries to be stored in the cache store after they are evicted from memory. Passivation prevents unnecessary and potentially expensive writes to the cache store. It is used for entries that are frequently used or referenced and therefore not evicted from memory.

While passivation is enabled, the cache store is used as an overflow tank, similar to virtual memory implementation in operating systems that swap memory pages to disk.

The passivation flag is used to toggle passivation mode, a mode that stores entries in the cache store only after they are evicted from memory.

21.2. Passivation Mode Benefits

The primary benefit of passivation mode is that it prevents unnecessary and potentially expensive writes to the cache store. This is particularly useful if an entry is frequently used or referenced and therefore is not evicted from memory.

21.3. Configure Passivation

In Red Hat JBoss Data Grid’s Remote Client-Server mode, add the passivation parameter to the cache store element to toggle passivation for it:

Toggle Passivation in Remote Client-Server Mode

<local-cache name="customCache"/>
	<!-- Additional configuration elements for local-cache here -->
	<file-store passivation="true"
		<!-- Additional configuration elements for file-store here -->
</local-cache>

In Library mode, add the passivation parameter to the persistence element to toggle passivation:

Toggle Passivation in Library Mode

<persistence passivation="true">
   <!-- Additional configuration elements here -->
</persistence>

21.4. Evication and Passivation

21.4.1. Eviction and Passivation

To ensure that a single copy of an entry remains, either in memory or in a cache store, use passivation in conjunction with eviction.

The primary reason to use passivation instead of a normal cache store is that updating entries require less resources when passivation is in use. This is because passivation does not require an update to the cache store.

21.4.2. Eviction and Passivation Usage

If the eviction policy caused the eviction of an entry from the cache while passivation is enabled, the following occur as a result:

  • A notification regarding the passivated entry is emitted to the cache listeners.
  • The evicted entry is stored.

When an attempt to retrieve an evicted entry is made, the entry is lazily loaded into memory from the cache loader. After the entry and its children are loaded a notification regarding the entry’s activation is sent to the cache listeners.

Note

Entries which have been activated, will continue to exist in the cache store if it has been configured as shared. This happens because backup owners might still need to access it.

21.4.3. Cache Loader Behavior with Passivation Disabled vs Enabled

With passivation disabled, when an element is modified, added, or removed, the modification is persisted in the backend store via the cache loader. There is no direct relationship between eviction and cache loading. When eviction is not in use, the persistent store is effectively a copy of what’s in memory. If eviction is in use, the persistent store is effectively a superset of what’s in memory (i.e. it includes entries that have been evicted from memory).

When passivation is enabled and the cache store is unshared, there is a direct relationship between eviction and the cache loader. Writes to the persistent store via the cache loader only occur as part of the eviction process. Data is deleted from the persistent store when the application reads it back into memory. In this case, the data in memory and data in the persistent store are two subsets of the total information set, with no intersection between the subsets. With a shared store, entries which have been passivated in the past will continue to exist in the store, although they may have a stale value if this has been overwritten in memory.

21.4.4. Eviction Examples

The following example indicates the state of the memory and the persistent store during eviction operations in three different configurations: passivation off, passivation on with a cache store with shared off, and passivation on with a cache store with shared on.

OperationPassivation OffPassivation On, Shared OffPassivation On, Shared On

Insert keyOne

Memory: keyOne
Disk: keyOne

Memory: keyOne
Disk: (none)

Memory: keyOne
Disk: (none)

Insert keyTwo

Memory: keyOne, keyTwo
Disk: keyOne, keyTwo

Memory: keyOne, keyTwo
Disk: (none)

Memory: keyOne, keyTwo
Disk: (none)

Eviction thread runs, evicts keyOne

Memory: keyTwo
Disk: keyOne, keyTwo

Memory: keyTwo
Disk: keyOne

Memory: keyTwo
Disk: keyOne

Read keyOne

Memory: keyOne, keyTwo
Disk: keyOne, keyTwo

Memory: keyOne, keyTwo
Disk: (none)

Memory: keyOne, keyTwo
Disk: keyOne

Eviction thread runs, evicts keyTwo

Memory: keyOne
Disk: keyOne, keyTwo

Memory: keyOne
Disk: keyTwo

Memory: keyOne
Disk: keyOne, keyTwo

Remove keyTwo

Memory: keyOne
Disk: keyOne

Memory: keyOne
Disk: (none)

Memory: keyOne
Disk: keyOne

Part X. Set Up Cache Writing

Chapter 22. Cache Writing Modes

22.1. Cache Writing Modes

Red Hat JBoss Data Grid presents configuration options with a single or multiple cache stores. This allows it to store data in a persistent location, for example a shared JDBC database or a local file system. JBoss Data Grid supports two caching modes:

  • Write-Through (Synchronous)
  • Write-Behind (Asynchronous)

22.2. Write-Through Caching

22.2.1. Write-Through Caching

The Write-Through (or Synchronous) mode in Red Hat JBoss Data Grid ensures that when clients update a cache entry (usually via a Cache.put() invocation), the call does not return until JBoss Data Grid has located and updated the underlying cache store. This feature allows updates to the cache store to be concluded within the client thread boundaries.

22.2.2. Write-Through Caching Benefits and Disadvantages

Write-Through Caching Benefits

The primary advantage of the Write-Through mode is that the cache and cache store are updated simultaneously, which ensures that the cache store remains consistent with the cache contents.

Write-Through Caching Disadvantages

Due to the cache store being updated simultaneously with the cache entry, there is a possibility of reduced performance for cache operations that occur concurrently with the cache store accesses and updates.

22.2.3. Write-Through Caching Configuration (Library Mode)

No specific configuration operations are required to configure a Write-Through or synchronous cache store. All cache stores are Write-Through or synchronous unless explicitly marked as Write-Behind or asynchronous. The following procedure demonstrates a sample configuration file of a Write-Through unshared local file cache store.

Configure a Write-Through Local File Cache Store

<local-cache name="persistentCache">
		<persistence>
		    <file-store fetch-state="true"
			    purge="false"
			    shared="false"
			    location="${java.io.tmpdir}"/>
		</persistence>
</local-cache>

  1. The name parameter specifies the name of the local-cache to use.
  2. The fetch-state parameter determines whether the persistent state is fetched when joining a cluster. Set this to true if using a replication and invalidation in a clustered environment. Additionally, if multiple cache stores are chained, only one cache store can have this property enabled. If a shared cache store is used, the cache does not allow a persistent state transfer despite this property being set to true. The fetch-state parameter is false by default.
  3. The purge parameter specifies whether the cache is purged when initially started.
  4. The shared parameter is used when multiple cache instances share a cache store and is now defined at the cache store level. This parameter can be set to prevent multiple cache instances writing the same modification multiple times. Valid values for this parameter are true and false.

22.3. Write-Behind Caching

22.3.1. Write-Behind Caching

In Red Hat JBoss Data Grid’s Write-Behind (Asynchronous) mode, cache updates are asynchronously written to the cache store. Asynchronous updates ensure that cache store updates are carried out by a thread different from the client thread interacting with the cache.

One of the foremost advantages of the Write-Behind mode is that the cache operation performance is not affected by the underlying store update. However, because of the asynchronous updates, for a brief period the cache store contains stale data compared to the cache.

22.3.2. About Unscheduled Write-Behind Strategy

In the Unscheduled Write-Behind Strategy mode, Red Hat JBoss Enterprise Data Grid attempts to store changes as quickly as possible by applying pending changes in parallel. This results in multiple threads waiting for modifications to conclude. Once these modifications are concluded, the threads become available and the modifications are applied to the underlying cache store.

This strategy is ideal for cache stores with low latency and low operational costs. An example of this is a local unshared file based cache store in which the cache store is local to the cache itself. Using this strategy the period of time where an inconsistency exists between the contents of the cache and the contents of the cache store is reduced to the shortest possible interval.

22.3.3. Unscheduled Write-Behind Strategy Configuration (Remote Client-Server Mode)

To set the write-behind strategy in Red Hat JBoss Data Grid’s Remote Client-Server mode, add the write-behind element to the target cache store configuration as follows:

The write-behind Element

<file-store passivation="false"
            path="${PATH}"
            purge="true"
            shared="false">
    <write-behind modification-queue-size="1024"
                  shutdown-timeout="25000"
                  flush-lock-timeout="15000"
                  thread-pool-size="5" />
</file-store>

The write-behind element uses the following configuration parameters:

  1. The modification-queue-size parameter sets the modification queue size for the asynchronous store. If updates occur faster than the cache store can process the queue, the asynchronous store behaves like a synchronous store. The store behavior remains synchronous and blocks elements until the queue is able to accept them, after which the store behavior becomes asynchronous again.
  2. The shutdown-timeout parameter specifies the time in milliseconds after which the cache store is shut down. When the store is stopped some modifications may still need to be applied. Setting a large timeout value will reduce the chance of data loss. The default value for this parameter is 25000.
  3. The flush-lock-timeout parameter specifies the time (in milliseconds) to acquire the lock that guards the state to be periodically flushed. The default value for this parameter is 15000.
  4. The thread-pool-size parameter specifies the size of the thread pool. The threads in this thread pool apply modifications to the cache store. The default value for this parameter is 5.

22.3.4. Unscheduled Write-Behind Strategy Configuration (Library Mode)

To enable the write-behind strategy of the cache entries to a store, add the async element to the store configuration as follows:

The async Element

<persistence>
    <singleFile location="${LOCATION}">
        <async enabled="true"
                    modificationQueueSize="1024"
                    shutdownTimeout="25000"
                    flushLockTimeout="15000"
                    threadPoolSize="5"/>
    </singleFile>
</persistence>

  1. The async element uses the following configuration parameters: . The modificationQueueSize parameter sets the modification queue size for the asynchronous store. If updates occur faster than the cache store can process the queue, the asynchronous store behaves like a synchronous store. The store behavior remains synchronous and blocks elements until the queue is able to accept them, after which the store behavior becomes asynchronous again.
  2. The shutdownTimeout parameter specifies the time in milliseconds after which the cache store is shut down. This provides time for the asynchronous writer to flush data to the store when a cache is shut down. The default value for this parameter is 25000.
  3. The flushLockTimeout parameter specifies the time (in milliseconds) to acquire the lock that guards the state to be periodically flushed. The default value for this parameter is 15000.
  4. The threadPoolSize parameter specifies the number of threads that concurrently apply modifications to the store. The default value for this parameter is 5.

Part XI. Monitor Caches and Cache Managers

Chapter 23. Set Up Java Management Extensions (JMX)

23.1. About Java Management Extensions (JMX)

Java Management Extension (JMX) is a Java based technology that provides tools to manage and monitor applications, devices, system objects, and service oriented networks. Each of these objects is managed, and monitored by MBeans.

JMX is the de facto standard for middleware management and administration. As a result, JMX is used in Red Hat JBoss Data Grid to expose management and statistical information.

23.2. Using JMX with Red Hat JBoss Data Grid

Management in Red Hat JBoss Data Grid instances aims to expose as much relevant statistical information as possible. This information allows administrators to view the state of each instance. While a single installation can comprise of tens or hundreds of such instances, it is essential to expose and present the statistical information for each of them in a clear and concise manner.

In JBoss Data Grid, JMX is used in conjunction with JBoss Operations Network (JON) to expose this information and present it in an orderly and relevant manner to the administrator.

23.3. JMX Statistic Levels

JMX statistics can be enabled at two levels:

  • At the cache level, where management information is generated by individual cache instances.
  • At the CacheManager level, where the CacheManager is the entity that governs all cache instances created from it. As a result, the management information is generated for all these cache instances instead of individual caches.
Important

In Red Hat JBoss Data Grid, statistics are enabled by default in Remote Client-Server mode and disabled by default for Library mode. While statistics are useful in assessing the status of JBoss Data Grid, they adversely affect performance and must be disabled if they are not required.

23.4. Enabling JMX for Cache Instances

You can enable JMX statistics at the Cache level either declaratively or programmatically.

Declaratively Enabling JMX at the Cache Level

Add the statistics attribute to the target <*-cache> element as follows:

<*-cache statistics="true">

Programmatically Enabling JMX at the Cache Level

Programmatically enable JMX at the cache level as follows:

Configuration configuration = new
ConfigurationBuilder().jmxStatistics().enable().build();

23.5. Enabling JMX for CacheManagers

You can enable JMX statistics at the CacheManager level either declaratively or programmatically.

Declaratively Enabling JMX at the CacheManager Level

Add the statistics attribute to the <cache-container> element as follows:

<cache-container statistics="true">

Programmatically Enabling JMX at the CacheManager Level

Programmatically enable JMX at the CacheManager level as follows:

GlobalConfiguration globalConfiguration = new
GlobalConfigurationBuilder().globalJmxStatistics().enable().build();

23.6. Disabling the CacheStore via JMX When Using Rolling Upgrades

Red Hat JBoss Data Grid allows the CacheStore to be disabled via JMX by invoking the disconnectSource operation on the RollingUpgradeManager MBean.

See Also: RollingUpgradeManager

23.7. Multiple JMX Domains

Multiple JMX domains are used when multiple CacheManager instances exist on a single virtual machine, or if the names of cache instances in different CacheManagers clash.

To resolve this issue, name each CacheManager in manner that allows it to be easily identified and used by monitoring tools such as JMX and JBoss Operations Network.

Set a CacheManager Name Declaratively

Add the following snippet to the relevant CacheManager configuration:

<globalJmxStatistics enabled="true" cacheManagerName="Hibernate2LC"/>

23.8. MBeans

23.8.1. MBeans

An MBean represents a manageable resource such as a service, component, device or an application.

Red Hat JBoss Data Grid provides MBeans that monitor and manage multiple aspects. For example, MBeans that provide statistics on the transport layer are provided. If a JBoss Data Grid server is configured with JMX statistics, an MBean that provides information such as the hostname, port, bytes read, bytes written and the number of worker threads exists at the following location:

jboss.infinispan:type=Server,name=<Memcached|Hotrod>,component=Transport

MBeans are available under two JMX domains:

  • jboss.as - these MBeans are created by the server subsystem.
  • jboss.infinispan - these MBeans are symmetric to those created by embedded mode.

Only the MBeans under jboss.infinispan should be used for Red Hat JBoss Data Grid, as the ones under jboss.as are for Red Hat JBoss Enterprise Application Platform.

Note

A full list of available MBeans, their supported operations and attributes, is available in the Appendix

23.8.2. Understanding MBeans

When JMX reporting is enabled at either the Cache Manager or Cache level, use a standard JMX GUI such as JConsole or VisualVM to connect to a Java Virtual Machine running Red Hat JBoss Data Grid. When connected, the following MBeans are available:

  • If Cache Manager-level JMX statistics are enabled, an MBean named jboss.infinispan:type=CacheManager,name="DefaultCacheManager" exists, with properties specified by the Cache Manager MBean.
  • If the cache-level JMX statistics are enabled, multiple MBeans display depending on the configuration in use. For example, if a write behind cache store is configured, an MBean that exposes properties that belong to the cache store component is displayed. All cache-level MBeans use the same format:

    jboss.infinispan:type=Cache,name="<name-of-cache>(<cache-mode>)",manager="<name-of-cache-manager>",component=<component-name>

    In this format:

    • Specify the default name for the cache using the cache-container element’s default-cache attribute.
    • The cache-mode is replaced by the cache mode of the cache. The lower case version of the possible enumeration values represents the cache mode.
    • The component-name is replaced by one of the JMX component names from the JMX reference documentation.

As an example, the cache store JMX component MBean for a default cache configured for synchronous distribution would be named as follows:

jboss.infinispan:type=Cache,name="default(dist_sync)", manager="default",component=CacheStore

Each cache and cache manager name is within quotation marks to prevent the use of unsupported characters in these user-defined names.

23.8.3. Registering MBeans in Non-Default MBean Servers

The default location where all the MBeans used are registered is the standard JVM MBeanServer platform. Users can set up an alternative MBeanServer instance as well. Implement the MBeanServerLookup interface to ensure that the getMBeanServer() method returns the desired (non default) MBeanServer.

To set up a non default location to register your MBeans, create the implementation and then configure Red Hat JBoss Data Grid with the fully qualified name of the class. An example is as follows:

To Add the Fully Qualified Domain Name Declaratively

Add the following snippet:

<globalJmxStatistics enabled="true" mBeanServerLookup="com.acme.MyMBeanServerLookup"/>

Chapter 24. Set Up JBoss Operations Network (JON)

24.1. About JBoss Operations Network (JON)

The JBoss Operations Network (JON) is JBoss' administration and management platform used to develop, test, deploy and monitor the application life cycle. JBoss Operations Network is JBoss' enterprise management solution and is recommended for the management of multiple Red Hat JBoss Data Grid instances across servers. JBoss Operations Network’s agent and auto discovery features facilitate monitoring the Cache Manager and Cache instances in JBoss Data Grid. JBoss Operations Network presents graphical views of key runtime parameters and statistics and allows administrators to set thresholds and be notified if usage exceeds or falls under the set thresholds.

Important

In Red Hat JBoss Data Grid Remote Client-Server mode, statistics are enabled by default. While statistics are useful in assessing the status of JBoss Data Grid, they adversely affect performance and must be disabled if they are not required. In JBoss Data Grid Library mode, statistics are disabled by default and must be explicitly enabled when required.

Important

To achieve full functionality of JBoss Operations Network library plugin for JBoss Data Grid’s Library mode, upgrade to JBoss Operations Network 3.3.0 with patch Update 04 or higher. For information on upgrading the JBoss Operations Network, see the Upgrading JBoss ON section in the JBoss Operations Network Installation Guide .

Note

JBoss Data Grid will support the JON plugin until its end of life in June 2019.

24.2. Download JBoss Operations Network (JON)

24.2.1. Prerequisites for Installing JBoss Operations Network (JON)

In order to install JBoss Operations Network in Red Hat JBoss Data Grid, the following is required:

  • A Linux, Windows, or Mac OSX operating system, and an x86_64, i686, or ia64 processor.
  • Java 6 or higher is required to run both the JBoss Operations Network Server and the JBoss Operations Network Agent.
  • Synchronized clocks on JBoss Operations Network Servers and Agents.
  • An external database must be installed.

24.2.2. Download JBoss Operations Network

Use the following procedure to download Red Hat JBoss Operations Network (JON) from the Customer Portal:

Download JBoss Operations Network

  1. To access the Red Hat Customer Portal, navigate to https://access.redhat.com/home in a browser.
  2. Click Downloads.
  3. In the section labeled JBoss Development and Management , click Red Hat JBoss Data Grid.
  4. Enter the relevant credentials in the Red Hat Login and Password fields and click Log In.
  5. Select the appropriate version in the Version drop down menu list.
  6. Click the Download button next to the desired download file.

24.2.3. Remote JMX Port Values

A port value must be provided to allow Red Hat JBoss Data Grid instances to be located. The value itself can be any available port.

Provide unique (and available) remote JMX ports to run multiple JBoss Data Grid instances on a single machine. A locally running JBoss Operations Network agent can discover each instance using the remote port values.

24.2.4. Download JBoss Operations Network (JON) Plugin

Download Installation Files

  1. Open http://access.redhat.com in a web browser.
  2. Click Downloads in the menu across the top of the page.
  3. Click Red Hat JBoss Operations Network in the list under JBoss Development and Management.
  4. Enter your login information.

    You are taken to the Software Downloads page.

  5. Download the JBoss Operations Network Plugin

    If you intend to use the JBoss Operations Network plugin for JBoss Data Grid, select JBoss ON for Data Grid from either the Product drop-down box, or the menu on the left.

    If you intend to use the JBoss Operations Network plugin for JBoss Enterprise Web Server, select JBoss ON for Web Server from either the Product drop-down box, or the menu on the left.

    1. Click the Red Hat JBoss Operations Network VERSION Base Distribution Download button.
    2. Repeat the steps to download the Data Grid Management Plugin Pack for JBoss ON VERSION

24.3. JBoss Operations Network Server Installation

The core of JBoss Operations Network is the server, which communicates with agents, maintains the inventory, manages resource settings, interacts with content providers, and provides a central management UI.

Note

For more detailed information about configuring JBoss Operations Network, see the JBoss Operations Network Installation Guide .

24.4. JBoss Operations Network Agent

The JBoss Operations Network Agent is a standalone Java application. Only one agent is required per machine, regardless of how many resources you require the agent to manage.

The JBoss Operations Network Agent does not ship fully configured. Once the agent has been installed and configured it can be run as a Windows service from a console, or run as a daemon or init.d script in a UNIX environment.

A JBoss Operations Network Agent must be installed on each of the machines being monitored in order to collect data.

The JBoss Operations Network Agent is typically installed on the same machine on which Red Hat JBoss Data Grid is running, however where there are multiple machines an agent must be installed on each machine.

Note

For more detailed information about configuring JBoss Operations Network agents, see the JBoss Operations Network Installation Guide .

24.5. JBoss Operations Network for Remote Client-Server Mode

24.5.1. JBoss Operations Network for Remote Client-Server Mode

In Red Hat JBoss Data Grid’s Remote Client-Server mode, the JBoss Operations Network plug-in is used to

  • initiate and perform installation and configuration operations.
  • monitor resources and their metrics.

In Remote Client-Server mode, the JBoss Operations Network plug-in uses JBoss Enterprise Application Platform’s management protocol to obtain metrics and perform operations on the JBoss Data Grid server.

24.5.2. Installing the JBoss Operations Network Plug-in (Remote Client-Server Mode)

The following procedure details how to install the JBoss Operations Network plug-ins for Red Hat JBoss Data Grid’s Remote Client-Server mode.

  1. Install the plug-ins

    1. Copy the JBoss Data Grid server rhq plug-in to $JON_SERVER_HOME/plugins .
    2. Copy the JBoss Enterprise Application Platform plug-in to $JON_SERVER_HOME/plugins .

    The server will automatically discover plug-ins here and deploy them. The plug-ins will be removed from the plug-ins directory after successful deployment.

  2. Obtain plug-ins

    Obtain all available plug-ins from the JBoss Operations Network server. To do this, type the following into the agent’s console:

    plugins update
  3. List installed plug-ins

    Ensure the JBoss Enterprise Application Platform plug-in and the JBoss Data Grid server rhq plug-in are installed correctly using the following:

    plugins info

JBoss Operation Network can now discover running JBoss Data Grid servers.

24.6. JBoss Operations Network Remote-Client Server Plugin

24.6.1. JBoss Operations Network Plugin Metrics

Table 24.1. JBoss Operations Network Traits for the Cache Container (Cache Manager)
Trait NameDisplay NameDescription

cache-manager-status

Cache Container Status

The current runtime status of a cache container.

cluster-name

Cluster Name

The name of the cluster.

members

Cluster Members

The names of the members of the cluster.

coordinator-address

Coordinator Address

The coordinator node’s address.

local-address

Local Address

The local node’s address.

version

Version

The cache manager version.

defined-cache-names

Defined Cache Names

The caches that have been defined for this manager.

Table 24.2. JBoss Operations Network Metrics for the Cache Container (Cache Manager)
Metric NameDisplay NameDescription

cluster-size

Cluster Size

How many members are in the cluster.

defined-cache-count

Defined Cache Count

How many caches that have been defined for this manager.

running-cache-count

Running Cache Count

How many caches are running under this manager.

created-cache-count

Created Cache Count

How many caches have actually been created under this manager.

Table 24.3. JBoss Operations Network Traits for the Cache
Trait NameDisplay NameDescription

cache-status

Cache Status

The current runtime status of a cache.

cache-name

Cache Name

The current name of the cache.

version

Version

The cache version.

Table 24.4. JBoss Operations Network Metrics for the Cache
Metric NameDisplay NameDescription

cache-status

Cache Status

The current runtime status of a cache.

number-of-locks-available

[LockManager] Number of locks available

The number of exclusive locks that are currently available.

concurrency-level

[LockManager] Concurrency level

The LockManager’s configured concurrency level.

average-read-time

[Statistics] Average read time

Average number of milliseconds required for a read operation on the cache to complete.

hit-ratio

[Statistics] Hit ratio

The result (in percentage) when the number of hits (successful attempts) is divided by the total number of attempts.

elapsed-time

[Statistics] Seconds since cache started

The number of seconds since the cache started.

read-write-ratio

[Statistics] Read/write ratio

The read/write ratio (in percentage) for the cache.

average-write-time

[Statistics] Average write time

Average number of milliseconds a write operation on a cache requires to complete.

hits

[Statistics] Number of cache hits

Number of cache hits.

evictions

[Statistics] Number of cache evictions

Number of cache eviction operations.

remove-misses

[Statistics] Number of cache removal misses

Number of cache removals where the key was not found.

time-since-reset

[Statistics] Seconds since cache statistics were reset

Number of seconds since the last cache statistics reset.

number-of-entries

[Statistics] Number of current cache entries

Number of entries currently in the cache.

stores

[Statistics] Number of cache puts

Number of cache put operations

remove-hits

[Statistics] Number of cache removal hits

Number of cache removal operation hits.

misses

[Statistics] Number of cache misses

Number of cache misses.

success-ratio

[RpcManager] Successful replication ratio

Successful replications as a ratio of total replications in numeric double format.

replication-count

[RpcManager] Number of successful replications

Number of successful replications

replication-failures

[RpcManager] Number of failed replications

Number of failed replications

average-replication-time

[RpcManager] Average time spent in the transport layer

The average time (in milliseconds) spent in the transport layer.

commits

[Transactions] Commits

Number of transaction commits performed since the last reset.

prepares

[Transactions] Prepares

Number of transaction prepares performed since the last reset.

rollbacks

[Transactions] Rollbacks

Number of transaction rollbacks performed since the last reset.

invalidations

[Invalidation] Number of invalidations

Number of invalidations.

passivations

[Passivation] Number of cache passivations

Number of passivation events.

activations

[Activations] Number of cache entries activated

Number of activation events.

cache-loader-loads

[Activation] Number of cache store loads

Number of entries loaded from the cache store.

cache-loader-misses

[Activation] Number of cache store misses

Number of entries that did not exist in the cache store.

cache-loader-stores

[CacheStore] Number of cache store stores

Number of entries stored in the cache stores.

Note

Gathering of some of these statistics is disabled by default.

JBoss Operations Network Metrics for Connectors

The metrics provided by the JBoss Operations Network (JON) plugin for Red Hat JBoss Data Grid are for REST and Hot Rod endpoints only. For the REST protocol, the data must be taken from the Web subsystem metrics. For details about each of these endpoints, see the Getting Started Guide.

Table 24.5. JBoss Operations Network Metrics for the Connectors
Metric NameDisplay NameDescription

bytesRead

Bytes Read

Number of bytes read.

bytesWritten

Bytes Written

Number of bytes written.

Note

Gathering of these statistics is disabled by default.

24.6.2. JBoss Operations Network Plugin Operations

Table 24.6. JBoss ON Plugin Operations for the Cache
Operation NameDescription

Start Cache

Starts the cache.

Stop Cache

Stops the cache.

Clear Cache

Clears the cache contents.

Reset Statistics

Resets statistics gathered by the cache.

Reset Activation Statistics

Resets activation statistics gathered by the cache.

Reset Invalidation Statistics

Resets invalidations statistics gathered by the cache.

Reset Passivation Statistics

Resets passivation statistics gathered by the cache.

Reset Rpc Statistics

Resets replication statistics gathered by the cache.

Remove Cache

Removes the given cache from the cache-container.

Record Known Global Keyset

Records the global known keyset to a well-known key for retrieval by the upgrade process.

Synchronize Data

Synchronizes data from the old cluster to this using the specified migrator.

Disconnect Source

Disconnects the target cluster from the source cluster according to the specified migrator.

JBoss Operations Network Plugin Operations for the Cache Backups

The cache backups used for these operations are configured using cross-datacenter replication. In the JBoss Operations Network (JON) User Interface, each cache backup is the child of a cache. For more information about cross-datacenter replication, see Set Up Cross-Datacenter Replication.

Table 24.7. JBoss Operations Network Plugin Operations for the Cache Backups
Operation NameDescription

status

Display the site status.

bring-site-online

Brings the site online.

take-site-offline

Takes the site offline.

Cache (Transactions)

Red Hat JBoss Data Grid does not support using Transactions in Remote Client-Server mode. As a result, none of the endpoints can use transactions.

24.6.3. JBoss Operations Network Plugin Attributes

Table 24.8. JBoss ON Plugin Attributes for the Cache (Transport)
Attribute NameTypeDescription

cluster

string

The name of the group communication cluster.

executor

string

The executor used for the transport.

lock-timeout

long

The timeout period for locks on the transport. The default value is 240000.

machine

string

A machine identifier for the transport.

rack

string

A rack identifier for the transport.

site

string

A site identifier for the transport.

stack

string

The JGroups stack used for the transport.

24.6.4. Create a New Cache Using JBoss Operations Network (JON)

Use the following steps to create a new cache using JBoss Operations Network (JON) for Remote Client-Server mode.

Creating a new cache in Remote Client-Server mode

  1. Log into the JBoss Operations Network Console.

    1. From the JBoss Operations Network console, click Inventory.
    2. Select Servers from the Resources list on the left of the console.
  2. Select the specific Red Hat JBoss Data Grid server from the servers list.

    1. Below the server name, click infinispan and then Cache Containers.
  3. Select the desired cache container that will be parent for the newly created cache.

    1. Right-click the selected cache container. For example, clustered.
    2. In the context menu, navigate to Create Child and select Cache.
  4. Create a new cache in the resource create wizard.

    1. Enter the new cache name and click Next.
    2. Set the cache attributes in the Deployment Options and click Finish.
Note

Refresh the view of caches in order to see newly added resource. It may take several minutes for the Resource to show up in the Inventory.

24.7. JBoss Operations Network for Library Mode

24.7.1. JBoss Operations Network for Library Mode

In Red Hat JBoss Data Grid’s Library mode, the JBoss Operations Network plug-in is used to

  • initiate and perform installation and configuration operations.
  • monitor resources and their metrics.

In Library mode, the JBoss Operations Network plug-in uses JMX to obtain metrics and perform operations on an application using the JBoss Data Grid library.

24.7.2. Installing the JBoss Operations Network Plug-in (Library Mode)

Use the following procedure to install the JBoss Operations Network plug-in for Red Hat JBoss Data Grid’s Library mode.

Install JBoss Operations Network Library Mode Plug-in

  1. Open the JBoss Operations Network Console

    1. From the JBoss Operations Network console, select Administration.
    2. Select Agent Plugins from the Configuration options on the left side of the console.

    Figure 24.1. JBoss Operations Network Console for JBoss Data Grid

    1282
  2. Upload the Library Mode Plug-in

    1. Click Browse, locate the InfinispanPlugin on your local file system.
    2. Click Upload to add the plug-in to the JBoss Operations Network Server.

    Figure 24.2. Upload the InfinispanPlugin.

    1283
  3. Scan for Updates

    1. Once the file has successfully uploaded, click Scan For Updates at the bottom of the screen.
    2. The InfinispanPlugin will now appear in the list of installed plug-ins.

    Figure 24.3. Scan for Updated Plug-ins.

    1284

24.7.3. Monitoring of JBoss Data Grid Instances in Library Mode

24.7.3.1. Prerequisites

The following is a list of common prerequisites for Monitor an Application Deployed in Standalone Mode, Monitor an Application Deployed in Domain Mode, and Manually Adding JBoss Data Grid Instances in Library Mode.

  • A correctly configured instance of JBoss Operations Network (JON) 3.2.0 with patch Update 02 or higher version.
  • A running instance of JON Agent on the server where the application will run. For more information, see JBoss Operations Network Agent.
  • An operational instance of the RHQ agent with a full JDK. Ensure that the agent has access to the tools.jar file from the JDK in particular. In the JON agent’s environment file (bin/rhq-env.sh ), set the value of the RHQ_AGENT_JAVA_HOME property to point to a full JDK home.
  • The RHQ agent must have been initiated using the same user as the JBoss Enterprise Application Platform instance. As an example, running the JON agent as a user with root privileges and the JBoss Enterprise Application Platform process under a different user does not work as expected and must be avoided.
  • An installed JON plugin for JBoss Data GridLibrary Mode. For more information, see Installing the JBoss Operations Network Plug-in (Library Mode)
  • Generic JMX plugin from JBoss Operation Networks 3.2.0 with patch Update 02 or better version in use.
  • A custom application using Red Hat JBoss Data Grid’s Library mode with enabled JMX statistics for library mode caches in order to make statistics and monitoring working. For details how to enable JMX statistics for cache instances, see Enable JMX for Cache Instances and to enable JMX for cache managers see Enable JMX for CacheManagers.
  • The Java Virtual Machine (JVM) must be configured to expose the JMX MBean Server. For the Oracle/Sun JDK, see http://docs.oracle.com/javase/1.5.0/docs/guide/management/agent.html
  • A correctly added and configured management user for JBoss Enterprise Application Platform.
24.7.3.2. Manually Adding JBoss Data Grid Instances in Library Mode

To add Red Hat JBoss Data Grid instances to JBoss Operations Network manually, use the following procedure in the JBoss Operations Network interface.

Add JBoss Data Grid Instances in Library Mode

  1. Import the Platform

    1. Navigate to the Inventory and select Discovery Queue from the Resources list on the left of the console.
    2. Select the platform on which the application is running and click Import at the bottom of the screen.

    Figure 24.4. Import the Platform from the menu:Discovery Queue[].

    1285
  2. Access the Servers on the Platform

    1. The jdg Platform now appears in the Platforms list.
    2. Click on the Platform to access the servers that are running on it.

    Figure 24.5. Open the jdg Platform to view the list of servers.

    1286
  3. Import the JMX Server

    1. From the Inventory tab, select Child Resources.
    2. Click the Import button at the bottom of the screen and select the JMX Server** option from the list.

    Figure 24.6. Import the JMX Server

    1287
  4. Enable JDK Connection Settings

    1. In the Resource Import Wizard window, specify JDK 8 from the list of Connection Settings Template options.

    Figure 24.7. Select the JDK 5 Template.

    1288
  5. Modify the Connector Address

    1. In the Deployment Options menu, modify the supplied Connector Address with the hostname and JMX port of the process containing the Infinispan Library.
    2. Enter the JMX connector address of the new JBoss Data Grid instance you want to monitor. For example:

      Connector Address:

      service:jmx:rmi://127.0.0.1/jndi/rmi://127.0.0.1:7997/jmxrmi
      Note

      The connector address varies depending on the host and the JMX port assigned to the new instance. In this case, instances require the following system properties at start up:

      -Dcom.sun.management.jmxremote.port=7997 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
    3. Specify the Principal and Credentials information if required.
    4. Click Finish.

    Figure 24.8. Modify the values in the Deployment Options screen.

    1289
  6. View Cache Statistics and Operations

    1. Click Refresh to refresh the list of servers.
    2. The JMX Servers tree in the panel on the left side of the screen contains the Infinispan Cache Managers node, which contains the available cache managers. The available cache managers contain the available caches.
    3. Select a cache from the available caches to view metrics.
    4. Select the Monitoring tab.
    5. The Tables view shows statistics and metrics.
    6. The Operations tab provides access to the various operations that can be performed on the services.

    Figure 24.9. Metrics and operational data relayed through JMX is now available in the JBoss Operations Network console.

    1290
24.7.3.3. Monitor Custom Applications Using Library Mode Deployed On JBoss Enterprise Application Platform
24.7.3.3.1. Monitor an Application Deployed in Standalone Mode

Use the following instructions to monitor an application deployed in JBoss Enterprise Application Platform using its standalone mode:

Monitor an Application Deployed in Standalone Mode

  1. Start the JBoss Enterprise Application Platform Instance

    Start the JBoss Enterprise Application Platform instance as follows:

    1. Enter the following command at the command line or change standalone configuration file (/bin/standalone.conf ) respectively:

      JAVA_OPTS="$JAVA_OPTS -Dorg.rhq.resourceKey=MyEAP"
    2. Start the JBoss Enterprise Application Platform instance in standalone mode as follows:

      $JBOSS_HOME/bin/standalone.sh
  2. Deploy the Red Hat JBoss Data Grid Application

    Deploy the WAR file that contains the JBoss Data Grid Library mode application with globalJmxStatistics and jmxStatistics enabled.

  3. Run JBoss Operations Network (JON) Discovery

    Run the discovery --full command in the JBoss Operations Network (JON) agent.

  4. Locate Application Server Process

    In the JBoss Operations Network (JON) web interface, the JBoss Enterprise Application Platform process is listed as a JMX server.

  5. Import the Process Into Inventory

    Import the process into the JBoss Operations Network (JON) inventory.

  6. Optional: Run Discovery Again

    If required, run the discovery --full command again to discover the new resources.

24.7.3.3.2. Monitor an Application Deployed in Domain Mode

Use the following instructions to monitor an application deployed in JBoss Enterprise Application Platform 6 using its domain mode:

Monitor an Application Deployed in Domain Mode

  1. Edit the Host Configuration

    Edit the domain/configuration/host.xml file to replace the server element with the following configuration:

    <servers>
    	<server name="server-one" group="main-server-group">
    		<jvm name="default">
    			<jvm-options>
    				<option value="-Dorg.rhq.resourceKey=EAP1"/>
    			</jvm-options>
    		</jvm>
    	</server>
    	<server name="server-two" group="main-server-group" auto-start="true">
    		<socket-bindings port-offset="150"/>
    		<jvm name="default">
    			<jvm-options>
    				<option value="-Dorg.rhq.resourceKey=EAP2"/>
    			</jvm-options>
    		</jvm>
    	</server>
    </servers>
  2. Start JBoss Enterprise Application Platform 6

    Start JBoss Enterprise Application Platform 6 in domain mode:

    $JBOSS_HOME/bin/domain.sh
  3. Deploy the Red Hat JBoss Data Grid Application

    Deploy the WAR file that contains the JBoss Data Grid Library mode application with globalJmxStatistics and jmxStatistics enabled.

  4. Run Discovery in JBoss Operations Network (JON)

    If required, run the discovery --full command for the JBoss Operations Network (JON) agent to discover the new resources.

24.8. JBoss Operations Network Plug-in Quickstart

For testing or demonstrative purposes with a single JBoss Operations Network agent, upload the plug-in to the server then type "plugins update" at the agent command line to force a retrieval of the latest plugins from the server.

24.9. Other Management Tools and Operations

24.9.1. Other Management Tools and Operations

Managing Red Hat JBoss Data Grid instances requires exposing significant amounts of relevant statistical information. This information allows administrators to get a clear view of each JBoss Data Grid node’s state. A single installation can comprise of tens or hundreds of JBoss Data Grid nodes and it is important to provide this information in a clear and concise manner. JBoss Operations Network is one example of a tool that provides runtime visibility. Other tools, such as JConsole can be used where JMX is enabled.

24.9.2. Accessing Data via URLs

Caches that have been configured with a REST interface have access to Red Hat JBoss Data Grid using RESTful HTTP access.

The RESTful service only requires a HTTP client library, eliminating the need for tightly coupled client libraries and bindings. For more information about how to retrieve data using the REST interface, refer to the JBoss Data Grid Developer Guide .

HTTP put() and post() methods place data in the cache, and the URL used determines the cache name and key(s) used. The data is the value placed into the cache, and is placed in the body of the request.

A Content-Type header must be set for these methods. GET and HEAD methods are used for data retrieval while other headers control cache settings and behavior.

Note

It is not possible to have conflicting server modules interact with the data grid. Caches must be configured with a compatible interface in order to have access to JBoss Data Grid.

24.9.3. Limitations of Map Methods

Specific Map methods, such as size(), values(), keySet() and entrySet(), can be used with certain limitations with Red Hat JBoss Data Grid as they are unreliable. These methods do not acquire locks (global or local) and concurrent modification, additions and removals are excluded from consideration in these calls.

The listed methods have a significant impact on performance. As a result, it is recommended that these methods are used for informational and debugging purposes only.

Performance Concerns

In JBoss Data Grid 7.2 the map methods size(), values(), keySet(), and entrySet() include entries in the cache loader by default. The cache loader in use will determine the performance of these commands; for instance, when using a database these methods will run a complete scan of the table where data is stored, which may result in slower processing. To not load entries from the cache loader, and avoid any potential performance hit, use Cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD) before executing the desired method.

Understanding the size() Method (Embedded Caches)

In JBoss Data Grid 7.2 the Cache.size() method provides a count of all elements in both this cache and cache loader across the entire cluster. When using a loader or remote entries, only a subset of entries is held in memory at any given time to prevent possible memory issues, and the loading of all entries may be slow.

In this mode of operation, the result returned by the size() method is affected by the flags org.infinispan.context.Flag#CACHE_MODE_LOCAL, to force it to return the number of entries present on the local node, and org.infinispan.context.Flag#SKIP_CACHE_LOAD, to ignore any passivated entries. Either of these flags may be used to increase performance of this method, at the cost of not returning a count of all elements across the entire cluster.

Understanding the size() Method (Remote Caches)

In JBoss Data Grid 7.2 the Hot Rod protocol contain a dedicated SIZE operation, and the clients use this operation to calculate the size of all entries.

Part XII. Red Hat JBoss Data Grid Web Administration

Chapter 25. Red Hat JBoss Data Grid Administration Console

25.1. About JBoss Data Grid Administration Console

The Red Hat JBoss Data Grid Administration Console allows administrators to monitor caches and JBoss Data Grid clusters, while providing a web interface for making dynamic changes to caches, cache-containers, and cluster nodes.

25.2. Red Hat JBoss Data Grid Administration Console Prerequisites

The Red Hat JBoss Data Grid Administration Console is only available in Remote Client-Server Mode.

25.3. Red Hat JBoss Data Grid Administation Console Getting Started

25.3.1. Red Hat JBoss Data Grid Administration Console Getting Started

The Administration Console is started automatically when JBoss Data Grid is running in Remote Client-Server Mode. A management user must be added to the server instance, which will then be used to access the web console.

25.3.2. Adding Management User

In order to use the JBoss Data Grid Administration Console, a new management user must be created. To add a new user, execute the add-user.sh utility script within the bin folder of your JBoss Data Grid Server installation and enter the requested information.

The following procedure outlines the steps to add a new management user:

Adding a Management User

  1. Run the add-user script within the bin folder as follows:

    ./add-user.sh
  2. Select the option for the type of user to be added. For management user, select option a.
  3. Set the Username and password as per the listed recommendations.
  4. Enter the name of the group or groups in which the user has to be added. Leave blank for no group.

    Note

    See the Download and Install JBoss Data Grid section in the Red Hat JBoss Data Grid Getting Started Guide for download and installation details.

  5. Confirm if you need the user to be used for Application Server process connection.

    Note

    Before proceeding, make sure $JBOSS_HOME is not set to a different installation. Otherwise, you may get unpredictable results.

25.3.3. Logging in the JBoss Data Grid Administration Console

Once the JBoss Data Grid server is running, in either domain or standalone mode, the JBoss Data Grid Administration Console may be accessed at the following login page:

http://${jboss.bind.address.management}:9990/console/index.html

Figure 25.1. JBoss Data Grid Administration Console Login Screen

Description

Enter the user credentials to log in. After logging in, the cache container view is displayed.

25.4. Dashboard View

25.4.1. Dashboard View

The Dashboard view is split into 3 tabs namely:

  • Caches
  • Clusters
  • Status Events
Note

The Clusters and Status Events tabs are not available when running JBoss Data Grid in standalone non-clustered mode.

25.4.2. Cache Containers View

The first default view after logging in is the Cache Container list. A Cache Container is the primary mechanism for treating a cache instance and is used as a starting point for using a cache itself.

Cache centric view presents the list of configured caches. It is used for viewing and adding caches to clusters, adding and adjusting new cache configurations, adding and configuring endpoints and other cache related administrative tasks.

Figure 25.2. Cache Containers View

Description

In this instance, there is one cache container with the name clustered with two caches deployed on the cluster group with UDP transport and three Endpoints attached to it. There are no remote sites configured for this cache container.

25.4.3. Clusters View

The Cluster tab presents the summary of the clusters along with the current status, number of hosts and number of nodes.

Figure 25.3. Clusters View

Description
Note

The Cluster view will not appear when the server is running in standalone non-clustered mode.

25.4.4. Status Events View

The JBoss Data Grid Administration Console displays the cluster wide events such as local rebalancing, cluster start and stop, cluster-split and cluster-merge events in a consolidated section. To view the detailed status events, navigate to the Status Events tab from the Dashboard.

Figure 25.4. Status Events View

Description

The status events are displayed with the associated timestamp and the event description.

Note

The Status Events view will not appear when the server is running in standalone non-clustered mode.

25.5. Cache Administration

25.5.1. Adding a New Cache

To add a new cache, follow these steps:

Adding a New Cache

  1. In the Cache Containers view, click on the name of the cache container.

    Figure 25.5. Cache Containers View

    Description
  2. The Caches view is displayed listing all the configured caches. Click Add Cache to add and configure a new cache. The new cache creation window is opened.

    Figure 25.6. Add Cache

    Description
  3. Enter the new cache name, select the base configuration template from the drop-down menu, check the Edit button, and click Next. If the Edit button is not selected then the cache will be immediately created using the selected template.

    Figure 25.7. Cache Properties

    Description
  4. The cache configuration screen is displayed. Enter the cache parameters and click Create.

    Figure 25.8. Cache Configuration

    Description
  5. A confirmation screen is displayed. Click Create to create the cache.

    Figure 25.9. Cache Confirmation

    Description

25.5.2. Editing Cache Configuration

The JBoss Data Grid Administration Console allows administrators to edit the configuration of an existing cache.

The following procedure outlines the steps to edit a cache configuration:

Editing Cache Configuration

  1. Log into the JBoss Data Grid Administration Console and click on the cache container name.

    Figure 25.10. Cache Containers

    7487
  2. In the Caches view, click on the cache name.

    Figure 25.11. Caches View

    7488
  3. The cache statistics and properties page is displayed. On the right hand side, click the Configuration tab.

    Figure 25.12. Cache Configuration Button

    7541
  4. The edit cache configuration interface is opened. The editable cache properties are found in the cache properties menu at the left hand side.

    Figure 25.13. Editing Cache Configuration Interface

    7490
  5. Select the cache configuration property to be edited from the cache properties menu along the left-hand side. To get a description on the cache configuration parameters, hover the cursor over the information icon to the right of each field. The parameter description is presented in form of a tooltip.

    Figure 25.14. Cache configuration paramaters

    7493
  6. The General property is selected by default. Edit the required values in the given parameter input fields and click Apply changes below
  7. The restart dialogue box appears. Click Restart Now to apply the changes, or Restart Later to continue editing the cache properties.

    Figure 25.15. Restart Dialogue Box

    7553
    Note

    In standalone mode the dialog instead contains the following text:

    Config changes will only be made available after you manually restart the server!

25.5.3. Cache Statistics and Properties View

The JBoss Data Grid Administration Console allows administrators to view all the cache statistics including the average time for reads, average times for writes, total number of entries, total number of reads, total number of failed reads and total number of writes.

To view the cache statistics, follow these steps:

Viewing Cache Statistics

  1. Navigate to the list of caches by clicking on the name of the cache container in the Cache Container view.
  2. Click on the name of the cache from the list of caches. Optionally you can use the cache filter on the left side to filter caches. The caches can be filtered by a keyword, substring or by selecting the type, the trait, and the status.

    Figure 25.16. Caches View

    7550
  3. The next page displays the comprehensive cache statistics under the headings: Cache content, Operations performance and Caching Activity.

    Figure 25.17. Cache Statistics

    7433
  4. Additional cache statistics are displayed under the headings: Entries Lifecycle, Cache Loader and Locking

    Figure 25.18. Cache Statistics

    7434
  5. To view cache properties, click on Configuration at the right hand side.

    Figure 25.19. Configuration Button

    7551
  6. The cache properties menu is displayed at the left hand side.

    Figure 25.20. Cache Properties Menu

    7485

To view on which node a cache resides, click on the Nodes tab next to the General Status tab on the cache statistics page.

Figure 25.21. General Status Tab

7435

The name of the Node(s) is displayed along with the read-write statistics.

Figure 25.22. Cache Node Labels

7486

25.5.4. Enable and Disable Caches

The following procedure outlines the steps to disable a cache:

Disabling a Cache

  1. Navigate to the caches view by clicking on the name of the cache container in the Cache Container view. Click on the name of the cache to be disabled.

    Figure 25.23. Caches View

    7495
  2. The cache statistics will be displayed. On the right hand side of the interface, click on the Actions tab and then click Disable.

    Figure 25.24. Cache Disable

    7437
  3. A confirmation dialogue box will appear. Click Disable to disable the cache.

    Figure 25.25. Cache Disable Confirmation

    7438
  4. A subsequent dialogue box appears. Click Ok.

    Figure 25.26. Confirmation Box

    7554
  5. The selected cache is disabled successfully with a visual indicator Disabled next to the cache name label.

    Figure 25.27. Disabled Cache

    7555

The following procedure outlines the steps to enable a cache:

Enabling a Cache

  1. To enable a cache, click on the specific disabled cache from the Cache view.

    Figure 25.28. Caches View

    7495
  2. On the right hand side of the interface, click on the Actions tab.

    Description
  3. From the Actions tab, click Enable

    Figure 25.29. Actions Menu

    7542
  4. A confirmation dialogue box appears. Click Enable.

    Figure 25.30. Confirmation Box

    7556
  5. A subsequent dialogue box appears. Click Ok

    Figure 25.31. Information Box

    7558
  6. The selected cache is enabled successfully with a visual indicator Enabled next to the cache name label.

    Figure 25.32. Cache Enabled

    7559

25.5.5. Cache Flush and Clear

The JBoss Data Grid Administration Console allows administrators to remove all the entries from a cache and the cache stores through the cache Clear operation. The console also provides the Flush operation to store the entries from the cache memory to the cache store. These entries are not removed from the cache memory, as during a Clear operation.

Flushing a Cache

To flush a cache, follow these steps:

Flushing a Cache

  1. In the Cache Containers view, click on the name of the cache container.
  2. The Caches view is displayed. Click on the cache to be flushed.

    Figure 25.33. Caches View

    7503
  3. The cache statistics page is displayed. At the right hand side, click Actions.

    Figure 25.34. Actions Button

    7504
  4. From the Actions menu, click Flush.

    Figure 25.35. Actions Menu

    7543
  5. A confirmation dialogue box appears. Click Flush.

    Figure 25.36. Cache Flush Confirmation Box

    7560
  6. The cache is successfully flushed. Click Ok.

    Figure 25.37. Cache Flush Information Box

    7561
Clearing a Cache

To clear a cache, follow these steps:

Clearing a Cache

  1. In the Cache Containers view, click on the name of the cache container.
  2. The Caches view is displayed. Click on the cache to be cleared.

    Figure 25.38. Caches View

    7503
  3. On the cache statistics page, at the right hand side, click Actions.

    7504
  4. From the Actions menu, click Clear.

    Figure 25.39. Clear Button

    7543
  5. A confirmation dialogue box appears. Click Clear.

    Figure 25.40. Confirmation Box

    7562
  6. The cache is successfully cleared. Click Ok.

    Figure 25.41. Information Box

    7563

25.5.6. Server Tasks Execution

The JBoss Data Grid Administration Console allows administrators to start a server script job on the JBoss Data Grid cluster.

25.5.7. Server Tasks

25.5.7.1. New Server Task

The following procedure outlines the steps to launch a new server task:

Note

Launching a new task is not supported if the server is running in standalone non-clustered mode.

Launching a New Server Task

  1. In the Cache Containers view of the JBoss Data Grid Administration Console, click on the name of the Cache container.
  2. On the cache view page, click the Task Execution tab.

    Figure 25.42. Task Execution

    7439
  3. In the Tasks execution tab, click Launch new task.

    Figure 25.43. Launch New Task

    7440
  4. Enter the new task properties and click Launch task.

    Figure 25.44. Task Properties

    7441
25.5.7.2. Server Tasks View

After the server task is launched, it can be viewed in the Task execution tab along with the other running tasks. The set of completed server script jobs with the start time and end time can be viewed. Additionally, number of successful executions and number of failed executions can also be viewed.

Figure 25.45. Server Tasks View

7442

Figure 25.46. Task Start/End Time

7443

25.6. Cache Container Configuration

25.6.1. Cache Container Configuration

The JBoss Data Grid Administration Console allows users to view and set Cache Container level settings such as transport, thread pools, security, cache templates, deployment of remote Executables/Scripts. Each cache container is associated with a cluster.

The following procedure outlines the steps to aceess the Cache Container Configuration settings:

Accessing Cache Container Configuration Settings

  1. In the Cache Container View, click on the name of the cache container.

    Figure 25.47. Cache Container View

    7446
  2. Click Configuration setting button at the top right hand side of the interface.

    Figure 25.48. Configuration

    7444

The Cache Container Configuration interface is displayed.

Figure 25.49. Cache Container Configuration

7445

25.6.2. Defining Protocol Buffer Schema

A Protocol Buffer Schema is defined in the Cache Container Configuration interface.

The following procedure outlines the steps to define a protobuf schema:

Defining a Protobuf Schema

  1. Click Add at the right hand side of the Schema tab to launch the create schema window.
  2. Enter the schema name and the schema in the respective fields and click Create Schema.

    Figure 25.50. New Schema

    7448
  3. The protocol buffer schema is added.

    Figure 25.51. Protocol Buffer

    7449

25.6.3. Transport Setting

To access the Transport setting, click on the Transport tab in the Cache Container Configuration interface. Enter the Transport settings and click Save .

Figure 25.52. Transport Setting

7450

A dialog box will prompt to restart the server due to configuration changes. Restart to apply the changes.

Figure 25.53. Restart Confirmation

7451

25.6.4. Defining Thread Pools

To define thread pools for different cache related operations, click on the Thread Pools tab in the Cache Container Configuration interface.

The JBoss Data Grid Administration Console allows administrators to set Thread Pool values for the following cache level operations:

Async Operations

Figure 25.54. Async Operations

7510

The currently set value for each parameter is set by the console. Hover the cursor over the information icon to view the parameter description in form of a tooltip. To change a thread pool value, enter the new value in the parameter field and click Save . A server restart is needed after every change of values.

Expiration

For Expiration settings, the user can set values for the following parameters:

Figure 25.55. Expiration Values

7511

Listener

For Listener settings, the user can set values for the following parameters:

Figure 25.56. Listener Values

7513

Persistence

For Persistence settings, the user can set values for the following parameters:

Figure 25.57. Persistence Values

7514

Remote Commands

For Remote Commands settings, the user can set values for the following parameters:

Figure 25.58. Remote Commands

7515

Replication Queue

For Replication Queue settings, the user can set values for the following parameters:

Figure 25.59. Replication Queue Values

7516

State Transfer

For Listener settings, the user can set values for the following parameters:

Figure 25.60. State Transfer Values

7517

Transport

For Transport settings, the user can set values for the following parameters:

Figure 25.61. Transport Values

7518

25.6.5. Adding New Security Role

The following procedure outlines the steps to add a new security role:

Adding a Security Role

  1. Click on the Security tab. If authorization is not defined for a cache container, click Yes to define.

    Figure 25.62. Define Authorization

    7452
  2. Select the Role Mapper from the drop-down menu. Click Add to launch the permissions window.

    Figure 25.63. Role Mapper Selection

    7453
  3. In the Permissions window, enter the name of the new role and assign the permissions by checking the required check-boxes. Click Save changes to save the role.

    Figure 25.64. Role Permissions

    7454
  4. The new security role is added.

    Figure 25.65. New Security Role

    7455

25.6.6. Creating Cache Configuration Template

The Templates tab in the Cache Container Configuration interface lists all the configured and available cache templates.

Figure 25.66. Cache Templates View

7544

The following procedure outlines the steps to create a new Cache configuration template :

Creating New Cache Configuration Template

  1. Click Create new Template on the right hand side of the templates list.
  2. Enter the cache configuration template name and select the base configuration from the drop-down and click Next.

    Figure 25.67. Cache Configuration Template

    7457
  3. Set the cache template attributes for the various cache operations such as Locking, Expiration, Indexing and others.

    Figure 25.68. Cache Configuration Template

    7458
  4. After entering the values, click Create to create the Cache Template.

25.7. Cluster Administration

25.7.1. Cluster Nodes View

Clusters centric view allows to view the nodes created for each server group and the list of deployed servers can be viewed. In Clusters view, you can add new nodes to the cluster group and view performance metrics of the particular nodes.

Note

The Cluster view will not appear when the server is running in standalone non-clustered mode. When running in standalone clustered mode the Cluster view will be displayed, but no operations on cluster nodes may be performed.

To access the Clusters view, navigate to the Clusters tab from the Dashboard and click on the name of the cluster.

Figure 25.69. Nodes View

7545

25.7.2. Cluster Nodes Mismatch

The total number of server nodes on the JBoss Data Grid cluster should ideally match the number of nodes shown in the JBoss Data Grid Administration Console. If in case, due to some reason, the expected nodes in the console do not match with the exact number of nodes on the JBoss Data Grid physical cluster, the console issues a mismatch warning by displaying the number of nodes detected and the number of expected nodes. Knowing the expected number of server nodes helps in handling Network Partitions.

If nodes mismatch occurs, it can be viewed in the clusters view, above the list of nodes as a warning. To access the Clusters view, navigate to the Clusters tab from the Dashboard and click on the name of the cluster.

In the following screen, the Console alerts the user in the form of a warning. The expected number of server nodes are 5 but only 3 are detected by the console.

Figure 25.70. Cluster Nodes Mismatch

Description

25.7.3. Cluster Rebalancing

The Red Hat JBoss Data Grid Administration Console allows the user to enable and disable cluster rebalancing at the cache container and cache levels.

Note

Cluster rebalancing is enabled by default.

The following procedure outlines the steps to enable and disable cluster rebalancing at a cache container level :

Enable and Disable Rebalancing

  1. From the cache container view, click on the name of the cache container.
  2. In the caches view, at the right hand side, click on Actions.

    7534
  3. A callout menu is opened. Click Disable Rebalancing.

    7521
  4. A confirmation dialogue box appears. Click Accept.

    7522
  5. Cluster rebalancing is successfully disabled.

    7523
  6. To enable rebalancing, click Actions Enable Rebalancing.

    7524
  7. A confirmation dialogue box appears. Click Accept.

    7525

Rebalancing is successfully enabled.

7526

The following procedure outlines the steps to enable and disable cluster rebalancing at a cache level :

Enable and Disable Rebalancing

  1. From the cache container view, click on the name of the cache container.
  2. In the caches view, click on a specific cache.
  3. The cache statistics page is displayed. At the right hand side, click Actions.

    7534
  4. From the callout menu, click Disable Rebalance.

    7528
  5. A confirmation dialogue box appears. Click Disable Rebalance.

    7529
  6. The rebalancing for the cache is successfully disabled.

    7530
  7. To enable cache level rebalancing, click Enable rebalance from the Actions menu.

    7531
  8. A confirmation dialogue box appears. Click Enable rebalance.

    7533

The rebalancing for the cache is successfully enabled.

7532

25.7.4. Cluster Partition Handling

The JBoss Data Grid Administration Console alerts the user with a visual warning when the cluster changes state to DEGRADED.

The assumed causes for a DEGRADED cluster are occurrence of a network partition, unreachable node(s) or unexpected extra nodes.

The visual warning is displayed in the Clusters view.

To access the Clusters view, navigate to the Clusters tab from the Dashboard and click on the name of the cluster.

In the following screen, the visual warning DEGRADED is displayed next to the cluster name JDG Cluster #1.

Figure 25.71. Network Partition Warning

7546

This visual warning for a DEGRADED cluster is shown at Cluster, Cache Container, and Cache levels of the console.

Note

Partitions can enter Degraded mode only if the DENY_READ_WRITES partition handling strategy is configured. Otherwise all partitions are AVAILABLE in the JBoss Data Grid Administration Console.

25.7.5. Cluster Events

The JBoss Data Grid Console displays the cluster wide events such as cluster-split and cluster-merge events in a consolidated section.

Note

Cluster Events are not available when the server is running in standalone non-clustered mode.

Along with the cluster events, the console displays the timestamp of the associated event. Cluster events can be viewed in the Cache containers page, the Clusters view page and also in the Status Events tab of the Dashboard.

To view cluster events on the cache containers page, navigate to the default cache containers view which is the default landing interface after logging into the console. The Cluster events are displayed at the right hand side in a consolidated section under the title Latest Grid Events

7535

To view the cluster events on the Clusters view page, navigate to the Clusters view by clicking on the Clusters tab. The Cluster events are displayed at the right hand side in a consolidated section under the title Latest status Events

7536

25.7.6. Adding Nodes

The JBoss Data Grid Administration Console allows administrators to configure new nodes.

The following procedure outlines the steps to add a new Node:

Adding a New Node

  1. In the Dashboard view, click Cluster tab.

    Figure 25.72. Clusters Tab

    7460
  2. Click on the name of the cluster where the new node has to be added.

    Figure 25.73. Cluster Selection

    7461
  3. Click Add Node.

    Figure 25.74. Add Node Created

    7462
  4. The node configuration window is opened. Enter the node properties in the respective fields and click Create

    Figure 25.75. Node Properties

    7565
  5. The system boots up.

    Figure 25.76. System Boot

    7463
  6. The new node is successfully created.

    Figure 25.77. New Node

    7464

25.7.7. Node Statistics and Properties View

JBoss Data Grid Administration Console allows users to view the average time for reads, average times for writes, total number of entries, total number of reads, total number of failed reads, total number of writes and other data.

To view the Node statistics, click on the name of the Node in the Clusters tab on the JBoss Data Grid Administration Console.

Figure 25.78. Nodes Statistics

7547

25.7.8. Node Performance Metrics View

To view the Node performance metrics, click on the name of the node in the Clusters tab of the JBoss Data Grid Administration Console

Figure 25.79. Node Performance Metrics

7466

25.7.9. Disabling a Node

The JBoss Data Grid Administration Console allows administrators to disable nodes.

To disable a node of a cluster, follow these steps:

Adding a New Node

  1. Click on the name of the cluster in the Cluster View of the JBoss Data Grid Administration Console.
  2. In the Nodes view, click on the node to be disabled.

    Figure 25.80. Nodes View

    7467
  3. The Node statistics view is opened. Click on the Actions tab located at the right hand side of the page and then click Stop.

    Figure 25.81. Nodes Stop

    7468
  4. A confirmation box appears. Click Stop to shut down the node.

    Figure 25.82. Confirmation Box

    7566

25.7.10. Cluster Shutdown and Restart

25.7.10.1. Cluster Shutdown

JBoss Data Grid Administration Console allows convenient and controlled shutdown of JBoss Data Grid clusters for maintenance purposes. For caches with a configured cache store, the data will be persisted without any data loss.For caches without a configured cache store, data will be lost after cluster shutdown.

To shut down or stop a cluster, follow these steps:

Shutting Down Cluster

  1. Navigate to the Clusters view in the JBoss Data Grid Administration console and click on the name of the cluster.

    Figure 25.83. Clusters View

    7470
  2. On the Nodes view page, locate the Actions tab to the top right hand side of the interface. Click on Actions tab and then click Stop.

    Figure 25.84. Cluster Stop

    7471
  3. A confirmation box will appear. To confirm, click Stop.

    Figure 25.85. Confirmation Box

    7472
25.7.10.2. Cluster Start

JBoss Data Grid Administration Console allows restarting a stopped cluster. The cache data is preloaded without any data loss for caches with configured cache-store. Caches without a configured cache store, will initially contain no data.

Preloading will only happen if preload is enabled on the cache store. If the local cache state on one of the nodes is corrupt, the cache will not start and manual intervention will be required.

To a cluster, follow these steps:

Starting Cluster

  1. Navigate to the Clusters view in the JBoss Data Grid Administration console and click on the name of the cluster.
  2. On the Nodes view page, locate the Actions tab to the top right hand side of the interface. Click on Actions tab and then click Start.

    Figure 25.86. Cluster Start

    7473
  3. A confirmation box will appear. Click Start to start the cluster.

Part XIII. Securing Data in Red Hat JBoss Data Grid

Chapter 26. Introduction

26.1. Securing Data in Red Hat JBoss Data Grid

In Red Hat JBoss Data Grid, data security can be implemented in the following ways:

Role-based Access Control

JBoss Data Grid features role-based access control for operations on designated secured caches. Roles can be assigned to users who access your application, with roles mapped to permissions for cache and cache-manager operations. Only authenticated users are able to perform the operations that are authorized for their role.

In Library mode, data is secured via role-based access control for CacheManagers and Caches, with authentication delegated to the container or application. In Remote Client-Server mode, JBoss Data Grid is secured by passing identity tokens from the Hot Rod client to the server, and role-based access control of Caches and CacheManagers.

Node Authentication and Authorization

Node-level security requires new nodes or merging partitions to authenticate before joining a cluster. Only authenticated nodes that are authorized to join the cluster are permitted to do so. This provides data protection by preventing unauthorized servers from storing your data.

Encrypted Communications Within the Cluster

JBoss Data Grid increases data security by supporting encrypted communications between the nodes in a cluster by using a user-specified cryptography algorithm, as supported by Java Cryptography Architecture (JCA).

JBoss Data Grid also provides audit logging for operations, and the ability to encrypt communication between the Hot Rod Client and Server using Transport Layer Security (TLS/SSL).

Chapter 27. Red Hat JBoss Data Grid Security: Authorization and Authentication

27.1. Red Hat JBoss Data Grid Security: Authorization and Authentication

Red Hat JBoss Data Grid is able to perform authorization on CacheManagers and Caches. JBoss Data Grid authorization is built on standard security features available in a JDK, such as JAAS and the SecurityManager.

If an application attempts to interact with a secured CacheManager and Cache, it must provide an identity which JBoss Data Grid’s security layer can validate against a set of required roles and permissions. Once validated, the client is issued a token for subsequent operations. Where access is denied, an exception indicating a security violation is thrown.

When a cache has been configured for with authorization, retrieving it returns an instance of SecureCache. SecureCache is a simple wrapper around a cache, which checks whether the "current user" has the permissions required to perform an operation. The "current user" is a Subject associated with the AccessControlContext.

JBoss Data Grid maps Principals names to roles, which in turn, represent one or more permissions. The following diagram represents these relationships:

Figure 27.1. Roles and Permissions Mapping

Roles and Permissions Security Mapping

27.2. Permissions

Access to a CacheManager or a Cache is controlled using a set of required permissions. Permissions control the type of action that is performed on the CacheManager or Cache, rather than the type of data being manipulated. Some of these permissions can apply to specifically name entities, such as a named cache. Different types of permissions are available depending on the entity.

Table 27.1. CacheManager Permissions
PermissionFunctionDescription

CONFIGURATION

defineConfiguration

Whether a new cache configuration can be defined.

LISTEN

addListener

Whether listeners can be registered against a cache manager.

LIFECYCLE

stop, start

Whether the cache manager can be stopped or started respectively.

ALL

 

A convenience permission which includes all of the above.

Table 27.2. Cache Permissions
PermissionFunctionDescription

READ

get, contains

Whether entries can be retrieved from the cache.

WRITE

put, putIfAbsent, replace, remove, evict

Whether data can be written/replaced/removed/evicted from the cache.

EXEC

distexec, mapreduce

Whether code execution can be run against the cache.

LISTEN

addListener

Whether listeners can be registered against a cache.

BULK_READ

keySet, values, entrySet,query

Whether bulk retrieve operations can be executed.

BULK_WRITE

clear, putAll

Whether bulk write operations can be executed.

LIFECYCLE

start, stop

Whether a cache can be started / stopped.

ADMIN

getVersion, addInterceptor*, removeInterceptor, getInterceptorChain, getEvictionManager, getComponentRegistry, getDistributionManager, getAuthorizationManager, evict, getRpcManager, getCacheConfiguration, getCacheManager, getInvocationContextContainer, setAvailability, getDataContainer, getStats, getXAResource

Whether access to the underlying components/internal structures is allowed.

ALL

 

A convenience permission which includes all of the above.

ALL_READ

 

Combines READ and BULK_READ.

ALL_WRITE

 

Combines WRITE and BULK_WRITE.

Note

Some permissions may need to be combined with others in order to be useful. For example, EXEC with READ or with WRITE.

27.3. Role Mapping

In order to convert the Principals in a Subject into a set of roles used for authorization, a PrincipalRoleMapper must be specified in the global configuration. Red Hat JBoss Data Grid ships with three mappers, and also allows you to provide a custom mapper.

Table 27.3. Mappers
Mapper NameJavaXMLDescription

IdentityRoleMapper

org.infinispan.security.impl.IdentityRoleMapper

<identity-role-mapper />

Uses the Principal name as the role name.

CommonNameRoleMapper

org.infinispan.security.impl.CommonRoleMapper

<common-name-role-mapper />

If the Principal name is a Distinguished Name (DN), this mapper extracts the Common Name (CN) and uses it as a role name. For example the DN cn=managers,ou=people,dc=example,dc=com will be mapped to the role managers.

ClusterRoleMapper

org.infinispan.security.impl.ClusterRoleMapper

<cluster-role-mapper />

Uses the ClusterRegistry to store principal to role mappings. This allows the use of the CLI’s GRANT and DENY commands to add/remove roles to a Principal.

Custom Role Mapper

 

<custom-role-mapper class="a.b.c" />

Supply the fully-qualified class name of an implementation of org.infinispan.security.impl.PrincipalRoleMapper

27.4. Configuring Authentication and Role Mapping using Login Modules

When using the authentication login-module for querying roles from LDAP, you must implement your own mapping of Principals to Roles, as custom classes are in use. An example implementation of this conversion is found in the JBoss Data Grid Developer Guide , while a declarative configuration example is below:

Example of LDAP Login Module Configuration

 <security-domain name="ispn-secure" cache-type="default">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.LdapLoginModule" flag="required">
            <module-option name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
            <module-option name="java.naming.provider.url" value="ldap://localhost:389"/>
            <module-option name="java.naming.security.authentication" value="simple"/>
            <module-option name="principalDNPrefix" value="uid="/>
            <module-option name="principalDNSuffix" value=",ou=People,dc=infinispan,dc=org"/>
            <module-option name="rolesCtxDN" value="ou=Roles,dc=infinispan,dc=org"/>
            <module-option name="uidAttributeID" value="member"/>
            <module-option name="matchOnUserDN" value="true"/>
            <module-option name="roleAttributeID" value="cn"/>
            <module-option name="roleAttributeIsDN" value="false"/>
            <module-option name="searchScope" value="ONELEVEL_SCOPE"/>
        </login-module>
    </authentication>
</security-domain>

Example of Login Module Configuration

<security-domain name="krb-admin" cache-type="default">
    <authentication>
        <login-module code="Kerberos" flag="required">
            <module-option name="useKeyTab" value="true"/>
            <module-option name="principal" value="admin@INFINISPAN.ORG"/>
            <module-option name="keyTab" value="${basedir}/keytab/admin.keytab"/>
        </login-module>
    </authentication>
</security-domain>

When using GSSAPI authentication, this would typically involve using LDAP for role mapping, with the JBoss Data Grid server authenticating itself to the LDAP server via GSSAPI. For an example on configuring this authentication to an Active Directory server refer to Active Directory Authentication Using Kerberos (GSSAPI).

Important

For information on configuring an LDAP server, or specifying users and roles in an LDAP server, refer to the Red Hat Directory Server Administration Guide .

27.5. Configuring Red Hat JBoss Data Grid for Authorization

Authorization is configured at two levels: the cache container (CacheManager), and at the single cache.

CacheManager

The following is an example configuration for authorization at the CacheManager level:

CacheManager Authorization (Declarative Configuration)

<cache-container name="local" default-cache="default">
        <security>
           <authorization>
             <identity-role-mapper />
             <role name="admin" permissions="ALL"/>
             <role name="reader" permissions="READ"/>
             <role name="writer" permissions="WRITE"/>
             <role name="supervisor" permissions="ALL_READ ALL_WRITE"/>
           </authorization>
        </security>
</cache-container>

Each cache container determines:

  • whether to use authorization.
  • a class which will map principals to a set of roles.
  • a set of named roles and the permissions they represent.

You can choose to use only a subset of the roles defined at the container level.

Roles

Roles may be applied on a cache-per-cache basis, using the roles defined at the cache-container level, as follows:

Defining Roles

<local-cache name="secured">
  <security>
    <authorization roles="admin reader writer supervisor"/>
  </security>
</local-cache>

Important

Any cache that is intended to require authentication must have a listing of roles defined; otherwise authentication is not enforced as the no-anonymous policy is defined by the cache’s authorization.

Important

The REST protocol is not supported for use with authorization, and any attempts to access a cache with authorization enabled will result in a SecurityException.

27.6. Authorization Using a SecurityManager

In Red Hat JBoss Data Grid’s Remote Client-Server mode, authorization is able to work without a SecurityManager for basic cache operations. In Library mode, a SecurityManager may also be used to perform some of the more complex tasks, such as distexec and query among others.

In order to enforce access restrictions, enable the SecurityManager in your JVM using one of the following methods:

Command Line

java -Djava.security.manager ...

Programmaticaly

System.setSecurityManager(new SecurityManager());

Using the JDK’s default implementation is not required; however, an appropriate policy file must be supplied. The policy file defines a set of permissions, which the SecurityManager examines when an application performs an action. If the action is allowed by the policy file, then the SecurityManager will permit the action to take place; however, if the action is not allowed by the policy then the SecurityManager denies that action.

Example policy files are below:

Library Mode Security Policy File Example

// Grant permissions to all of the Infinispan libraries. Modify the URLs of the codebases below to actually point to the physical location of the infinispan-embedded uberjar in your environment

grant codeBase "file://path/to/infinispan-embedded-${version}.jar" {
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

    // Modify this depending on the naming and location of your configuration files
    permission java.io.FilePermission ".${/}jgroups.xml", "read";
    permission java.util.PropertyPermission "*" "read";
    permission java.net.SocketPermission "*";

    permission java.util.PropertyPermission "*" "read";

    // Modify this depending on the naming and location of your configuration files
    permission java.io.FilePermission ".${/}infinispan.xml", "read";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

    // ForkJoin backport
    permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";

    // Infinispan shutdown hooks
    permission java.lang.RuntimePermission "shutdownHooks";
    permission java.util.PropertyPermission "user.dir" "read";

    // ConcurrentHashMap backports
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.parallelism" "read";
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.exceptionHandler" "read";
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.threadFactory" "read";

    // Infinispan security
    permission javax.security.auth.AuthPermission "doAs";
    permission javax.security.auth.AuthPermission "getSubject";
    permission org.infinispan.security.CachePermission "ALL";
}

Remote Client-Server Security Policy File Example

// Grant permissions to all of the Infinispan libraries. Modify the URLs of the codebases below to actually point to the physical location of the libraries in your environment

grant codeBase "file://$JDG_HOME/modules/system/layers/base/org/jboss/marshalling/main/jboss-marshalling-osgi-${version}.jar" {
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
}

grant codeBase "file://$JDG_HOME/modules/system/layers/base/org/jgroups/main/jgroups-${version}.jar" {
    // Modify this depending on the naming and location of your configuration files
    permission java.io.FilePermission ".${/}jgroups.xml", "read";
    permission java.util.PropertyPermission "*" "read";
    permission java.net.SocketPermission "*";
}

grant codeBase "file://$JDG_HOME/modules/system/layers/base/org/infinispan/commons/main/infinispan-commons.jar" {
    permission java.util.PropertyPermission "*" "read";
}

grant codeBase "file://$JDG_HOME/modules/system/layers/base/org/infinispan/main/infinispan-core.jar" {
    // Modify this depending on the naming and location of your configuration files
    permission java.io.FilePermission ".${/}infinispan.xml", "read";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
    permission java.lang.RuntimePermission "accessClassInPackage.sun.misc"; // ForkJoin backport
    permission java.lang.RuntimePermission "shutdownHooks"; // Infinispan shutdown hooks
    permission java.util.PropertyPermission "user.dir" "read";

    // ConcurrentHashMap backport
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.parallelism" "read";
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.exceptionHandler" "read";
    permission java.util.PropertyPermission "java.util.concurrent.ForkJoinPool.common.threadFactory" "read";

    // Infinispan security
    permission javax.security.auth.AuthPermission "doAs";
    permission javax.security.auth.AuthPermission "getSubject";
    permission org.infinispan.security.CachePermission "ALL";
}

27.7. SecurityManager in Java

27.7.1. About the Java Security Manager

Java Security Manager

The Java Security Manager is a class that manages the external boundary of the Java Virtual Machine (JVM) sandbox, controlling how code executing within the JVM can interact with resources outside the JVM. When the Java Security Manager is activated, the Java API checks with the security manager for approval before executing a wide range of potentially unsafe operations.

The Java Security Manager uses a security policy to determine whether a given action will be permitted or denied.

27.7.2. About Java Security Manager Policies

Security Policy

A set of defined permissions for different classes of code. The Java Security Manager compares actions requested by applications against the security policy. If an action is allowed by the policy, the Security Manager will permit that action to take place. If the action is not allowed by the policy, the Security Manager will deny that action. The security policy can define permissions based on the location of code, on the code’s signature, or based on the subject’s principals.

The Java Security Manager and the security policy used are configured using the Java Virtual Machine options java.security.manager and java.security.policy.

Basic Information

A security policy’s entry consists of the following configuration elements, which are connected to the policytool:

CodeBase
The URL location (excluding the host and domain information) where the code originates from. This parameter is optional.
SignedBy
The alias used in the keystore to reference the signer whose private key was used to sign the code. This can be a single value or a comma-separated list of values. This parameter is optional. If omitted, presence or lack of a signature has no impact on the Java Security Manager.
Principals
A list of principal_type/principal_name pairs, which must be present within the executing thread’s principal set. The Principals entry is optional. If it is omitted, it signifies that the principals of the executing thread will have no impact on the Java Security Manager.
Permissions
A permission is the access which is granted to the code. Many permissions are provided as part of the Java Enterprise Edition 6 (Java EE 6) specification. This document only covers additional permissions which are provided by JBoss EAP 6.
Important

Refer to your container documentation on how to configure the security policy, as it may differ depending on the implementation.

27.7.3. Write a Java Security Manager Policy

Introduction

An application called policytool is included with most JDK and JRE distributions, for the purpose of creating and editing Java Security Manager security policies. Detailed information about policytool is linked from http://docs.oracle.com/javase/6/docs/technotes/tools/.

Setup a new Java Security Manager Policy

  1. Start policytool

    Start the policytool tool in one of the following ways.

    1. Red Hat Enterprise Linux

      From your GUI or a command prompt, run /usr/bin/policytool.

    2. Microsoft Windows Server

      Run policytool.exe from your Start menu or from the bin\ of your Java installation. The location can vary.

  2. Create a policy.

    To create a policy, select Add Policy Entry. Add the parameters you need, then click Done. .

  3. Edit an existing policy.

    Select the policy from the list of existing policies, and select the Edit Policy Entry button. Edit the parameters as needed.

  4. Delete an existing policy.

    Select the policy from the list of existing policies, and select the Remove Policy Entry button.

27.7.4. Run Red Hat JBoss Data Grid Server Within the Java Security Manager

To specify a Java Security Manager policy, you need to edit the Java options passed to the server instance during the bootstrap process. For this reason, you cannot pass the parameters as options to the standalone.sh script. The following procedure guides you through the steps of configuring your instance to run within a Java Security Manager policy.

Prerequisites

Before you following this procedure, you need to write a security policy, using the policytool command which is included with your Java Development Kit (JDK). This procedure assumes that your policy is located at JDG_HOME/bin/server.policy . As an alternative, write the security policy using any text editor and manually save it as JDG_HOME/bin/server.policy * The JBoss Data Grid server must be completely stopped before you edit any configuration files.

Perform the following procedure for each physical host or instance in your environment.

Configure the Security Manager for JBoss Data Grid Server

  1. Open the configuration file.

    Open the configuration file for editing. This location of this file is listed below by OS. Note that this is not the executable file used to start the server, but a configuration file that contains runtime parameters. For Linux: JDG_HOME/bin/standalone.conf For Windows: JDG_HOME\bin\standalone.conf.bat

  2. Add the Java options to the file.

    To ensure the Java options are used, add them to the code block that begins with:

    if [ "x$JAVA_OPTS" = "x" ]; then

    You can modify the -Djava.security.policy value to specify the exact location of your security policy. It should go onto one line only, with no line break. Using == when setting the -Djava.security.policy property specifies that the security manager will use only the specified policy file. Using = specifies that the security manager will use the specified policy combined with the policy set in the policy.url section of JAVA_HOME/lib/security/java.security .

    Important

    JBoss Enterprise Application Platform releases from 6.2.2 onwards require that the system property jboss.modules.policy-permissions is set to true.

    standalone.conf

    JAVA_OPTS="$JAVA_OPTS -Djava.security.manager -Djava.security.policy==$PWD/server.policy -Djboss.home.dir=$JBOSS_HOME -Djboss.modules.policy-permissions=true"

    standalone.conf.bat

    set "JAVA_OPTS=%JAVA_OPTS% -Djava.security.manager -Djava.security.policy==\path\to\server.policy -Djboss.home.dir=%JBOSS_HOME% -Djboss.modules.policy-permissions=true"

  3. Start the server.

    Start the server as normal.

27.8. Data Security for Remote Client Server Mode

27.8.1. About Security Realms

A security realm is a series of mappings between users and passwords, and users and roles. Security realms are a mechanism for adding authentication and authorization to your EJB and Web applications. Red Hat JBoss Data Grid Server provides two security realms by default:

  • ManagementRealm stores authentication information for the Management API, which provides the functionality for the Management CLI and web-based Management Console. It provides an authentication system for managing JBoss Data Grid Server itself. You could also use the ManagementRealm if your application needed to authenticate with the same business rules you use for the Management API.
  • ApplicationRealm stores user, password, and role information for Web Applications and EJBs.

Each realm is stored in two files on the filesystem:

  • REALM-users.properties stores usernames and hashed passwords.
  • REALM-roles.properties stores user-to-role mappings.
  • mgmt-groups.properties stores user-to-role mapping file for ManagementRealm.

The properties files are stored in the standalone/configuration/ directories. The files are written simultaneously by the add-user.sh or add-user.bat command. When you run the command, the first decision you make is which realm to add your new user to.

27.8.2. Add a New Security Realm

  1. Run the Management CLI

    Start the cli.sh or cli.bat command and connect to the server.

  2. Create the new security realm itself

    Run the following command to create a new security realm named MyDomainRealm on a domain controller or a standalone server.

    /host=master/core-service=management/security-realm=MyDomainRealm:add()
  3. Create the reference to the properties file which will store information about the new realm’s users

    Run the below command to define the location of the new security realm’s properties file; this file contains information regarding the users of this security realm. The following command references a file named myfile.properties in the jboss.server.config.dir.

    Note

    The newly-created properties file is not managed by the included add-user.sh and add-user.bat scripts. It must be managed externally.

    /host=master/core-service=management/security-realm=MyDomainRealm/authentication=properties:add(path="myfile.properties",relative-to="jboss.server.config.dir")
  4. Reload the server

    Reload the server so the changes will take effect.

    :reload

Result

The new security realm is created. When you add users and roles to this new realm, the information will be stored in a separate file from the default security realms. You can manage this new file using your own applications or procedures.

27.8.3. Add a User to a Security Realm

  1. Run the add-user.sh or add-user.bat command

    Open a terminal and change directories to the JDG_HOME/bin/ directory. If you run Red Hat Enterprise Linux or another UNIX-like operating system, run add-user.sh. If you run Microsoft Windows Server, run add-user.bat.

  2. Choose whether to add a Management User or Application User

    For this procedure, type b to add an Application User.

  3. Choose the realm this user will be added to

    By default, the only available realms are the ManagementRealm and ApplicationRealm; however, if a custom realm has been added, then its name may be entered instead.

  4. Type the username, password, and roles, when prompted

    Type the desired username, password, and optional roles when prompted. Verify your choice by typing yes, or type no to cancel the changes. The changes are written to each of the properties files for the security realm.

27.8.4. Configuring Security Realms Declaratively

In Remote Client-Server mode, a Hot Rod endpoint must specify a security realm.

The security realm declares an authentication and an authorization section.

Configuring Security Realms Declaratively

<security-realms>
            <security-realm name="ManagementRealm">
                <authentication>
                    <local default-user="$local" skip-group-loading="true"/>
                    <properties path="mgmt-users.properties" relative-to="jboss.server.config.dir"/>
                </authentication>
                <authorization map-groups-to-roles="false">
                    <properties path="mgmt-groups.properties" relative-to="jboss.server.config.dir"/>
                </authorization>
            </security-realm>
            <security-realm name="ApplicationRealm">
                <authentication>
                    <local default-user="$local" allowed-users="*" skip-group-loading="true"/>
                    <properties path="application-users.properties" relative-to="jboss.server.config.dir"/>
                </authentication>
                <authorization>
                    <properties path="application-roles.properties" relative-to="jboss.server.config.dir"/>
                </authorization>
            </security-realm>
        </security-realms>

The server-identities parameter can also be used to specify certificates.

27.8.5. Loading Roles from LDAP for Authorization (Remote Client-Server Mode)

An LDAP directory contains entries for user accounts and groups, cross referenced by attributes. Depending on the LDAP server configuration, a user entity may map the groups the user belongs to through memberOf attributes; a group entity may map which users belong to it through uniqueMember attributes; or both mappings may be maintained by the LDAP server.

Users generally authenticate against the server using a simple user name. When searching for group membership information, depending on the directory server in use, searches could be performed using this simple name or using the distinguished name of the user’s entry in the directory.

The authentication step of a user connecting to the server always happens first. Once the user is successfully authenticated the server loads the user’s groups. The authentication step and the authorization step each require a connection to the LDAP server. The realm optimizes this process by reusing the authentication connection for the group loading step. As will be shown within the configuration steps below it is possible to define rules within the authorization section to convert a user’s simple user name to their distinguished name. The result of a "user name to distinguished name mapping" search during authentication is cached and reused during the authorization query when the force attribute is set to "false". When force is true, the search is performed again during authorization (while loading groups). This is typically done when different servers perform authentication and authorization.

<authorization>
    <ldap connection="...">
    	<!-- OPTIONAL -->
       <username-to-dn force="true">
           <!-- Only one of the following. -->
           <username-is-dn />
           <username-filter base-dn="..." recursive="..." user-dn-attribute="..." attribute="..." />
           <advanced-filter base-dn="..." recursive="..." user-dn-attribute="..." filter="..." />
        </username-to-dn>

       <group-search group-name="..." iterative="..." group-dn-attribute="..." group-name-attribute="..." >
           <!-- One of the following -->
           <group-to-principal base-dn="..." recursive="..." search-by="...">
               <membership-filter principal-attribute="..." />
           </group-to-principal>
           <principal-to-group group-attribute="..." />
       </group-search>
    </ldap>
</authorization>
Important

These examples specify some attributes with their default values. This is done for demonstration. Attributes that specify their default values are removed from the configuration when it is persisted by the server. The exception is the force attribute. It is required, even when set to the default value of false.

username-to-dn

The username-to-dn element specifies how to map the user name to the distinguished name of their entry in the LDAP directory. This element is only required when both of the following are true:

  • The authentication and authorization steps are against different LDAP servers.
  • The group search uses the distinguished name.

    1:1 username-to-dn
    This specifies that the user name entered by the remote user is the user’s distinguished name.
<username-to-dn force="false">
   <username-is-dn />
</username-to-dn>

+ This defines a 1:1 mapping and there is no additional configuration.

username-filter
The next option is very similar to the simple option described above for the authentication step. A specified attribute is searched for a match against the supplied user name.
<username-to-dn force="true">
    <username-filter base-dn="dc=people,dc=harold,dc=example,dc=com" recursive="false" attribute="sn" user-dn-attribute="dn" />
</username-to-dn>

+ The attributes that can be set here are:

  • base-dn: The distinguished name of the context to begin the search.
  • recursive: Whether the search will extend to sub contexts. Defaults to false.
  • attribute: The attribute of the users entry to try and match against the supplied user name. Defaults to uid.
  • user-dn-attribute: The attribute to read to obtain the users distinguished name. Defaults to dn.

    advanced-filter
    The final option is to specify an advanced filter, as in the authentication section this is an opportunity to use a custom filter to locate the users distinguished name.
<username-to-dn force="true">
    <advanced-filter base-dn="dc=people,dc=harold,dc=example,dc=com" recursive="false" filter="sAMAccountName={0}" user-dn-attribute="dn" />
</username-to-dn>

+ For the attributes that match those in the username-filter example, the meaning and default values are the same. There is one new attribute:

  • filter: Custom filter used to search for a user’s entry where the user name will be substituted in the {0} place holder.

    Important

    The XML must remain valid after the filter is defined so if any special characters are used such as & ensure the proper form is used. For example & for the & character.

There are two different styles that can be used when searching for group membership information. The first style is where the user’s entry contains an attribute that references the groups the user is a member of. The second style is where the group contains an attribute referencing the users entry.

When there is a choice of which style to use Red Hat recommends that the configuration for a user’s entry referencing the group is used. This is because with this method group information can be loaded by reading attributes of known distinguished names without having to perform any searches. The other approach requires extensive searches to identify the groups that reference the user.

Before describing the configuration here are some LDIF examples to illustrate this.

Principal to Group - LDIF example.

This example illustrates where we have a user TestUserOne who is a member of GroupOne, GroupOne is in turn a member of GroupFive. The group membership is shown by the use of a memberOf attribute which is set to the distinguished name of the group of which the user (or group) is a member.

It is not shown here but a user could potentially have multiple memberOf attributes set, one for each group of which the user is directly a member.

dn: uid=TestUserOne,ou=users,dc=principal-to-group,dc=example,dc=org
objectClass: extensibleObject
objectClass: top
objectClass: groupMember
objectClass: inetOrgPerson
objectClass: uidObject
objectClass: person
objectClass: organizationalPerson
cn: Test User One
sn: Test User One
uid: TestUserOne
distinguishedName: uid=TestUserOne,ou=users,dc=principal-to-group,dc=example,dc=org
memberOf: uid=GroupOne,ou=groups,dc=principal-to-group,dc=example,dc=org
memberOf: uid=Slashy/Group,ou=groups,dc=principal-to-group,dc=example,dc=org
userPassword:: e1NTSEF9WFpURzhLVjc4WVZBQUJNbEI3Ym96UVAva0RTNlFNWUpLOTdTMUE9PQ==

dn: uid=GroupOne,ou=groups,dc=principal-to-group,dc=example,dc=org
objectClass: extensibleObject
objectClass: top
objectClass: groupMember
objectClass: group
objectClass: uidObject
uid: GroupOne
distinguishedName: uid=GroupOne,ou=groups,dc=principal-to-group,dc=example,dc=org
memberOf: uid=GroupFive,ou=subgroups,ou=groups,dc=principal-to-group,dc=example,dc=org

dn: uid=GroupFive,ou=subgroups,ou=groups,dc=principal-to-group,dc=example,dc=org
objectClass: extensibleObject
objectClass: top
objectClass: groupMember
objectClass: group
objectClass: uidObject
uid: GroupFive
distinguishedName: uid=GroupFive,ou=subgroups,ou=groups,dc=principal-to-group,dc=example,dc=org

Group to Principal - LDIF Example

This example shows the same user TestUserOne who is a member of GroupOne which is in turn a member of GroupFive - however in this case it is an attribute uniqueMember from the group to the user being used for the cross reference.

Again the attribute used for the group membership cross reference can be repeated, if you look at GroupFive there is also a reference to another user TestUserFive which is not shown here.

dn: uid=TestUserOne,ou=users,dc=group-to-principal,dc=example,dc=org
objectClass: top
objectClass: inetOrgPerson
objectClass: uidObject
objectClass: person
objectClass: organizationalPerson
cn: Test User One
sn: Test User One
uid: TestUserOne
userPassword:: e1NTSEF9SjR0OTRDR1ltaHc1VVZQOEJvbXhUYjl1dkFVd1lQTmRLSEdzaWc9PQ==

dn: uid=GroupOne,ou=groups,dc=group-to-principal,dc=example,dc=org
objectClass: top
objectClass: groupOfUniqueNames
objectClass: uidObject
cn: Group One
uid: GroupOne
uniqueMember: uid=TestUserOne,ou=users,dc=group-to-principal,dc=example,dc=org

dn: uid=GroupFive,ou=subgroups,ou=groups,dc=group-to-principal,dc=example,dc=org
objectClass: top
objectClass: groupOfUniqueNames
objectClass: uidObject
cn: Group Five
uid: GroupFive
uniqueMember: uid=TestUserFive,ou=users,dc=group-to-principal,dc=example,dc=org
uniqueMember: uid=GroupOne,ou=groups,dc=group-to-principal,dc=example,dc=org
General Group Searching

Before looking at the examples for the two approaches shown above we first need to define the attributes common to both of these.

<group-search group-name="..." iterative="..." group-dn-attribute="..." group-name-attribute="..." >
    ...
</group-search>
  • group-name: This attribute is used to specify the form that should be used for the group name returned as the list of groups of which the user is a member. This can either be the simple form of the group name or the group’s distinguished name. If the distinguished name is required this attribute can be set to DISTINGUISHED_NAME. Defaults to SIMPLE.
  • iterative: This attribute is used to indicate if, after identifying the groups a user is a member of, we should also iteratively search based on the groups to identify which groups the groups are a member of. If iterative searching is enabled we keep going until either we reach a group that is not a member if any other groups or a cycle is detected. Defaults to false.

Cyclic group membership is not a problem. A record of each search is kept to prevent groups that have already been searched from being searched again.

Important

For iterative searching to work the group entries need to look the same as user entries. The same approach used to identify the groups a user is a member of is then used to identify the groups of which the group is a member. This would not be possible if for group to group membership the name of the attribute used for the cross reference changes or if the direction of the reference changes.

  • group-dn-attribute: On an entry for a group which attribute is its distinguished name. Defaults to dn.
  • group-name-attribute: On an entry for a group which attribute is its simple name. Defaults to uid.

Principal to Group Example Configuration

Based on the example LDIF from above here is an example configuration iteratively loading a user’s groups where the attribute used to cross reference is the memberOf attribute on the user.

<authorization>
    <ldap connection="LocalLdap">
        <username-to-dn>
            <username-filter base-dn="ou=users,dc=principal-to-group,dc=example,dc=org" recursive="false" attribute="uid" user-dn-attribute="dn" />
        </username-to-dn>
        <group-search group-name="SIMPLE" iterative="true" group-dn-attribute="dn" group-name-attribute="uid">
            <principal-to-group group-attribute="memberOf" />
        </group-search>
    </ldap>
</authorization>

The most important aspect of this configuration is that the principal-to-group element has been added with a single attribute.

  • group-attribute: The name of the attribute on the user entry that matches the distinguished name of the group the user is a member of. Defaults to memberOf.

Group to Principal Example Configuration

This example shows an iterative search for the group to principal LDIF example shown above.

<authorization>
      <ldap connection="LocalLdap">
          <username-to-dn>
              <username-filter base-dn="ou=users,dc=group-to-principal,dc=example,dc=org" recursive="false" attribute="uid" user-dn-attribute="dn" />
          </username-to-dn>
          <group-search group-name="SIMPLE" iterative="true" group-dn-attribute="dn" group-name-attribute="uid">
              <group-to-principal base-dn="ou=groups,dc=group-to-principal,dc=example,dc=org" recursive="true" search-by="DISTINGUISHED_NAME">
                  <membership-filter principal-attribute="uniqueMember" />
              </group-to-principal>
          </group-search>
      </ldap>
  </authorization>

Here an element group-to-principal is added. This element is used to define how searches for groups that reference the user entry will be performed. The following attributes are set:

  • base-dn: The distinguished name of the context to use to begin the search.
  • recursive: Whether sub-contexts also be searched. Defaults to false.
  • search-by: The form of the role name used in searches. Valid values are SIMPLE and DISTINGUISHED_NAME. Defaults to DISTINGUISHED_NAME.

Within the group-to-principal element there is a membership-filter element to define the cross reference.

  • principal-attribute: The name of the attribute on the group entry that references the user entry. Defaults to member.

27.9. Securing Interfaces

27.9.1. Hot Rod Interface Security

27.9.1.1. Publish Hot Rod Endpoints as a Public Interface

Red Hat JBoss Data Grid’s Hot Rod server operates as a management interface as a default. To extend its operations to a public interface, alter the value of the interface parameter in the socket-binding element from management to public as follows:

<socket-binding name="hotrod" interface="public" port="11222" />
27.9.1.2. Encryption of communication between Hot Rod Server and Hot Rod client

Hot Rod can be encrypted using TLS/SSL, and has the option to require certificate-based client authentication.

Use the following procedure to secure the Hot Rod connector using SSL.

Secure Hot Rod Using SSL/TLS

  1. Generate a Keystore

    Create a Java Keystore using the keytool application distributed with the JDK and add your certificate to it. The certificate can be either self signed, or obtained from a trusted CA depending on your security policy.

  2. Place the Keystore in