arrow-left

All pages
gitbookPowered by GitBook
triangle-exclamation
Couldn't generate the PDF for 103 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

MaxScale 25.01 Change Data Capture (CDC) Protocol

hashtag
Change Data Capture (CDC) Protocol

The CDC protocol was deprecated in MaxScale 24.08 and will be removed in the next major release. KafkaCDC can be used instead.

CDC is a new protocol that allows compatible clients to authenticate and register for Change Data Capture events. The new protocol must be use in conjunction with AVRO router which currently converts MariaDB binlog events into AVRO records. Change Data Capture protocol is used by clients in order to interact with stored AVRO file and also allows registered clients to be notified with the new events coming from MariaDB 10.0/10.1 database.

hashtag
Creating Users

The users and their hashed passwords are stored in /var/cache/maxscale/<service name>/cdcusers where <service name> is the name of the service.

For example, the following service entry will look into /var/cache/maxscale/CDC-Service/ for a file called cdcusers. If that file is found, the users in that file will be used for authentication.

If the cdcusers file cannot be found, the service user (maxuser:maxpwd in the example) can be used to connect through the CDC protocol.

For more details, refer to the CDC users documentation.

hashtag
Protocol Phases

hashtag
Connection and Authentication

  • Client connects to MaxScale CDC protocol listener.

  • Send the authentication message which includes the user and the SHA1 of the password

In the future, optional flags could be implemented.

hashtag
Registration

  • Sending UUID

  • Specify the output format (AVRO or JSON) for data retrieval.

hashtag
Data Request

  • Send CDC commands to retrieve router statistics or to query for data events

hashtag
Protocol Details

hashtag
Authentication

The authentication starts when the client sends the hexadecimal representation of the username concatenated with a colon (:) and the SHA1 of the password.

bin2hex(username + ':' + SHA1(password))

For example the user foobar with a password of foopasswd should send the following hexadecimal string

Server returns OK on success and ERR on failure.

hashtag
Registration

REGISTER

REGISTER UUID=UUID, TYPE={JSON | AVRO}

Register as a client to the service.

Example:

Server returns OK on success and ERR on failure.

hashtag
Change Data Capture Commands

REQUEST-DATA

REQUEST-DATA DATABASE.TABLE[.VERSION] [GTID]

This command fetches data from specified table in a database and returns the output in the requested format (AVRO or JSON). Data records are sent to clients and if new AVRO versions are found (e.g. mydb.mytable.0000002.avro) the new schema and data will be sent as well.

The data will be streamed until the client closes the connection.

Clients should continue reading from network in order to automatically gets new events.

Example:

hashtag
Example Client

MaxScale includes an example CDC client application written in Python 3. You can find the source code for it in the MaxScale repositoryarrow-up-right.

This page is licensed: CC BY-SA / Gnu FDL

spinner
[CDC-Service]
type=service
router=avrorouter
user=maxuser
password=maxpwd
foobar:SHA1(foopasswd) ->  666f6f6261723a3137336363643535253331
REGISTER UUID=11ec2300-2e23-11e6-8308-0002a5d5c51b, TYPE=AVRO
REQUEST-DATA db1.table1
REQUEST-DATA dbi1.table1.000003
REQUEST-DATA db2.table4 0-11-345

MaxScale 25.01 Monitor Resource

hashtag
Monitor Resource

A monitor resource represents a monitor inside MaxScale that monitors one or more servers.

  • Monitor Resource

    • Resource Operations

      • Get a monitor

        • Response

      • Get all monitors

hashtag
Resource Operations

The :name in all of the URIs must be the name of a monitor in MaxScale.

hashtag
Get a monitor

GET /v1/monitors/:name

Get a single monitor.

Response

Status: 200 OK

{
    "data": {
        "attributes": {
            "module": "mariadbmon",
            "monitor_diagnostics": {
                "master": "server1",
                "master_gtid_domain_id": 0,
                "primary": null,
                "server_info": [
                    {
                        "gtid_binlog_pos": "0-3000-5",
                        "gtid_current_pos": "0-3000-5",
                        "lock_held": null,
                        "master_group": null,
                        "name": "server1",
                        "read_only": false,
                        "server_id": 3000,
                        "slave_connections": [],
                        "state_details": null
                    },
                    {
                        "gtid_binlog_pos": "0-3000-5",
                        "gtid_current_pos": "0-3000-5",
                        "lock_held": null,
                        "master_group": null,
                        "name": "server2",
                        "read_only": false,
                        "server_id": 3001,
                        "slave_connections": [
                            {
                                "connection_name": "",
                                "gtid_io_pos": "",
                                "last_io_error": "",
                                "last_sql_error": "",
                                "master_host": "127.0.0.1",
                                "master_port": 3000,
                                "master_server_id": 3000,
                                "master_server_name": "server1",
                                "seconds_behind_master": 0,
                                "slave_io_running": "Yes",
                                "slave_sql_running": "Yes",
                                "using_gtid": "No"
                            }
                        ],
                        "state_details": null
                    }
                ],
                "state": "Idle"
            },
            "parameters": {
                "assume_unique_hostnames": true,
                "auto_failover": false,
                "auto_rejoin": false,
                "backend_connect_attempts": 1,
                "backend_connect_timeout": "3000ms",
                "backend_read_timeout": "3000ms",
                "backend_write_timeout": "3000ms",
                "backup_storage_address": null,
                "backup_storage_path": null,
                "cooperative_monitoring_locks": "none",
                "cs_admin_api_key": null,
                "cs_admin_base_path": "/cmapi/0.4.0",
                "cs_admin_port": 8640,
                "demotion_sql_file": null,
                "disk_space_check_interval": "0ms",
                "disk_space_threshold": null,
                "enforce_read_only_slaves": false,
                "enforce_simple_topology": false,
                "enforce_writable_master": false,
                "events": "all,master_down,master_up,slave_down,slave_up,server_down,server_up,synced_down,synced_up,donor_down,donor_up,lost_master,lost_slave,lost_synced,lost_donor,new_master,new_slave,new_synced,new_donor",
                "failcount": 5,
                "failover_timeout": "90000ms",
                "handle_events": true,
                "journal_max_age": "28800000ms",
                "maintenance_on_low_disk_space": true,
                "mariadb-backup_parallel": 1,
                "mariadb-backup_use_memory": "1G",
                "master_conditions": "primary_monitor_master",
                "master_failure_timeout": "10000ms",
                "module": "mariadbmon",
                "monitor_interval": "1000ms",
                "password": "*****",
                "promotion_sql_file": null,
                "rebuild_port": 4444,
                "replication_custom_options": null,
                "replication_master_ssl": false,
                "replication_password": "*****",
                "replication_user": "maxuser",
                "script": null,
                "script_max_replication_lag": -1,
                "script_timeout": "90000ms",
                "servers_no_promotion": null,
                "slave_conditions": "",
                "ssh_check_host_key": true,
                "ssh_keyfile": null,
                "ssh_port": 22,
                "ssh_timeout": "10000ms",
                "ssh_user": null,
                "switchover_on_low_disk_space": false,
                "switchover_timeout": "90000ms",
                "type": "monitor",
                "user": "maxuser",
                "verify_master_failure": true
            },
            "source": {
                "file": "/etc/maxscale.cnf",
                "type": "static"
            },
            "state": "Running",
            "ticks": 12
        },
        "id": "MariaDB-Monitor",
        "links": {
            "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/"
        },
        "relationships": {
            "servers": {
                "data": [
                    {
                        "id": "server1",
                        "type": "servers"
                    },
                    {
                        "id": "server2",
                        "type": "servers"
                    }
                ],
                "links": {
                    "related": "http://localhost:8989/v1/servers/",
                    "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/relationships/servers/"
                }
            },
            "services": {
                "data": [
                    {
                        "id": "RW-Split-Router",
                        "type": "services"
                    }
                ],
                "links": {
                    "related": "http://localhost:8989/v1/services/",
                    "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/relationships/services/"
                }
            }
        },
        "type": "monitors"
    },
    "links": {
        "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/"
    }
}

hashtag
Get all monitors

GET /v1/monitors

Get all monitors.

Response

Status: 200 OK

{
    "data": [
        {
            "attributes": {
                "module": "mariadbmon",
                "monitor_diagnostics": {
                    "master": "server1",
                    "master_gtid_domain_id": 0,
                    "primary": null,
                    "server_info": [
                        {
                            "gtid_binlog_pos": "0-3000-5",
                            "gtid_current_pos": "0-3000-5",
                            "lock_held": null,
                            "master_group": null,
                            "name": "server1",
                            "read_only": false,
                            "server_id": 3000,
                            "slave_connections": [],
                            "state_details": null
                        },
                        {
                            "gtid_binlog_pos": "0-3000-5",
                            "gtid_current_pos": "0-3000-5",
                            "lock_held": null,
                            "master_group": null,
                            "name": "server2",
                            "read_only": false,
                            "server_id": 3001,
                            "slave_connections": [
                                {
                                    "connection_name": "",
                                    "gtid_io_pos": "",
                                    "last_io_error": "",
                                    "last_sql_error": "",
                                    "master_host": "127.0.0.1",
                                    "master_port": 3000,
                                    "master_server_id": 3000,
                                    "master_server_name": "server1",
                                    "seconds_behind_master": 0,
                                    "slave_io_running": "Yes",
                                    "slave_sql_running": "Yes",
                                    "using_gtid": "No"
                                }
                            ],
                            "state_details": null
                        }
                    ],
                    "state": "Idle"
                },
                "parameters": {
                    "assume_unique_hostnames": true,
                    "auto_failover": false,
                    "auto_rejoin": false,
                    "backend_connect_attempts": 1,
                    "backend_connect_timeout": "3000ms",
                    "backend_read_timeout": "3000ms",
                    "backend_write_timeout": "3000ms",
                    "backup_storage_address": null,
                    "backup_storage_path": null,
                    "cooperative_monitoring_locks": "none",
                    "cs_admin_api_key": null,
                    "cs_admin_base_path": "/cmapi/0.4.0",
                    "cs_admin_port": 8640,
                    "demotion_sql_file": null,
                    "disk_space_check_interval": "0ms",
                    "disk_space_threshold": null,
                    "enforce_read_only_slaves": false,
                    "enforce_simple_topology": false,
                    "enforce_writable_master": false,
                    "events": "all,master_down,master_up,slave_down,slave_up,server_down,server_up,synced_down,synced_up,donor_down,donor_up,lost_master,lost_slave,lost_synced,lost_donor,new_master,new_slave,new_synced,new_donor",
                    "failcount": 5,
                    "failover_timeout": "90000ms",
                    "handle_events": true,
                    "journal_max_age": "28800000ms",
                    "maintenance_on_low_disk_space": true,
                    "mariadb-backup_parallel": 1,
                    "mariadb-backup_use_memory": "1G",
                    "master_conditions": "primary_monitor_master",
                    "master_failure_timeout": "10000ms",
                    "module": "mariadbmon",
                    "monitor_interval": "1000ms",
                    "password": "*****",
                    "promotion_sql_file": null,
                    "rebuild_port": 4444,
                    "replication_custom_options": null,
                    "replication_master_ssl": false,
                    "replication_password": "*****",
                    "replication_user": "maxuser",
                    "script": null,
                    "script_max_replication_lag": -1,
                    "script_timeout": "90000ms",
                    "servers_no_promotion": null,
                    "slave_conditions": "",
                    "ssh_check_host_key": true,
                    "ssh_keyfile": null,
                    "ssh_port": 22,
                    "ssh_timeout": "10000ms",
                    "ssh_user": null,
                    "switchover_on_low_disk_space": false,
                    "switchover_timeout": "90000ms",
                    "type": "monitor",
                    "user": "maxuser",
                    "verify_master_failure": true
                },
                "source": {
                    "file": "/etc/maxscale.cnf",
                    "type": "static"
                },
                "state": "Running",
                "ticks": 12
            },
            "id": "MariaDB-Monitor",
            "links": {
                "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/"
            },
            "relationships": {
                "servers": {
                    "data": [
                        {
                            "id": "server1",
                            "type": "servers"
                        },
                        {
                            "id": "server2",
                            "type": "servers"
                        }
                    ],
                    "links": {
                        "related": "http://localhost:8989/v1/servers/",
                        "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/relationships/servers/"
                    }
                },
                "services": {
                    "data": [
                        {
                            "id": "RW-Split-Router",
                            "type": "services"
                        }
                    ],
                    "links": {
                        "related": "http://localhost:8989/v1/services/",
                        "self": "http://localhost:8989/v1/monitors/MariaDB-Monitor/relationships/services/"
                    }
                }
            },
            "type": "monitors"
        }
    ],
    "links": {
        "self": "http://localhost:8989/v1/monitors/"
    }
}

hashtag
Create a monitor

POST /v1/monitors

Create a new monitor. The request body must define at least the following fields.

  • data.id

  • Name of the monitor

  • data.type

  • Type of the object, must be monitors

  • data.attributes.module

  • The monitor module to use

  • data.attributes.parameters.user

  • The to use

  • data.attributes.parameters.password

  • The to use

All monitor parameters can be defined at creation time.

The following example defines a request body which creates a new monitor and assigns two servers to be monitored by it. It also defines a custom value for the monitor_interval parameter.

{
    data: {
        "id": "test-monitor", // Name of the monitor
        "type": "monitors",
        "attributes": {
            "module": "mariadbmon", // The monitor uses the mariadbmon module
            "parameters": { // Monitor parameters
                "monitor_interval": 1000,
                "user": "maxuser,
                "password": "maxpwd"
            }
        },
        "relationships": { // List of server relationships that this monitor uses
            "servers": {
                "data": [ // This monitor uses two servers
                    {
                        "id": "server1",
                        "type": "servers"
                    },
                    {
                        "id": "server2",
                        "type": "servers"
                    }
                ]
            }
        }
    }
}

Response

Monitor is created:

Status: 204 No Content

hashtag
Update a monitor

PATCH /v1/monitors/:name

The request body must be a valid JSON document representing the modified monitor.

hashtag
Modifiable Fields

The following standard server parameter can be modified.

  • user

  • password

  • monitor_interval

  • backend_connect_timeout

In addition to these standard parameters, the monitor specific parameters can also be modified. Refer to the monitor module documentation for details on these parameters.

Response

Monitor is modified:

Status: 204 No Content

Invalid request body:

Status: 400 Bad Request

hashtag
Update monitor relationships

PATCH /v1/monitors/:name/relationships/servers

The request body must be a JSON object that defines only the data field. The value of the data field must be an array of relationship objects that define the id and type fields of the relationship. This object will replace the existing relationships of the monitor.

The following is an example request and request body that defines a single server relationship for a monitor.

PATCH /v1/monitors/my-monitor/relationships/servers

{
    data: [
          { "id": "my-server", "type": "servers" }
    ]
}

All relationships for a monitor can be deleted by sending an empty array as the_data_ field value. The following example removes all servers from a monitor.

PATCH /v1/monitors/my-monitor/relationships/servers

{
    data: []
}

Response

Monitor relationships modified:

Status: 204 No Content

Invalid JSON body:

Status: 400 Bad Request

hashtag
Destroy a monitor

DELETE /v1/monitors/:name

Destroy a created monitor. The monitor must not have relationships to any servers in order to be destroyed.

This endpoint also supports the force=yes parameter that will unconditionally delete the monitor by first unlinking it from all servers that it uses.

Response

Monitor is deleted:

Status: 204 No Content

Monitor could not be deleted:

Status: 400 Bad Request

hashtag
Stop a monitor

PUT /v1/monitors/:name/stop

Stops a started monitor.

Response

Monitor is stopped:

Status: 204 No Content

hashtag
Start a monitor

PUT /v1/monitors/:name/start

Starts a stopped monitor.

Response

Monitor is started:

Status: 204 No Content

This page is licensed: CC BY-SA / Gnu FDL

spinner
Response
Create a monitor
Response
Update a monitor
Modifiable Fields
Response
Update monitor relationships
Response
Destroy a monitor
Response
Stop a monitor
Response
Start a monitor
Response
user
password
backend_write_timeout
backend_read_timeout
backend_connect_attempts

MariaDB MaxScale 25.01

This release of MariaDB MaxScale introduces powerful new features. It includes Workload Capture and Replay for production traffic analysis and a Diff Router for comparing server behavior.

MariaDB MaxScale 25.01 Getting Started

This is your starting point for MariaDB MaxScale 25.01. Find essential guides for installation, learn how to configure MaxScale for your needs, and explore tutorials to get up and running.

MariaDB MaxScale 25.01 Protocols

Protocol modules in MariaDB MaxScale interpret client-server communication. This section covers the available protocols, including the MariaDB, NoSQL, and Change Data Capture (CDC) modules.

MariaDB MaxScale 25.01 Reference

Setting up MariaDB MaxScale

This document is designed as a quick introduction to setting up MariaDB MaxScale.

The installation and configuration of the MariaDB Server is not covered in this document. See the following MariaDB documentation articles for more information on setting up a primary-replica-cluster or a Galera-cluster: and .

This tutorial assumes that one of the standard MaxScale binary distributions is used and that MaxScale is installed using default options.

Building from source code in GitHub is covered in Building from Source.

hashtag
Installing MaxScale

The precise installation process varies from one distribution to another. Details on package installation can be found in the .

hashtag
Creating a user account for MaxScale

MaxScale checks that incoming clients are valid. To do this, MaxScale needs to retrieve user authentication information from the backend databases. Create a special user account for this purpose by executing the following SQL commands on the primary server of your database cluster. The following tutorials will use these credentials.

MariaDB versions 10.2.2 to 10.2.10 also require GRANT SELECT ON mysql.* TO 'maxscale'@'%';

hashtag
Creating client user accounts

Because MariaDB MaxScale sits between the clients and the backend databases, the backend databases will see all clients as if they were connecting from MaxScale's address. This usually means that two sets of grants for each user are required.

For example, assume that the user 'jdoe'@'client-host' exists and MaxScale is located at_maxscale-host_. If 'jdoe'@'client-host' needs to be able to connect through MaxScale, another user, 'jdoe'@'maxscale-host', must be created. The second user must have the same password and similar grants as 'jdoe'@'client-host'.

The quickest way to do this is to first create the new user:

Then do a SHOW GRANTS query:

Then copy the same grants to the 'jdoe'@'maxscale-host' user.

An alternative to generating two separate accounts is to use one account with a wildcard host ('jdoe'@'%') which covers both hosts. This is more convenient but less secure than having specific user accounts as it allows access from all hosts.

hashtag
Creating the configuration file

MaxScale reads its configuration from /etc/maxscale.cnf. A template configuration is provided with the MaxScale installation.

A global maxscale section is included in every MaxScale configuration file. This section sets the values of various global parameters, such as the number of threads MaxScale uses to handle client requests. To set thread count to the number of available cpu cores, set the following.

hashtag
Configuring the servers

Read the mini-tutorial for server configuration instructions.

hashtag
Configuring the monitor

The type of monitor used depends on the type of cluster used. For a primary-replica cluster read . For a Galera cluster read .

hashtag
Configuring the services and listeners

This part is covered in two different tutorials. For a fully automated read-write-splitting setup, read the . For a simple connection based setup, read the .

hashtag
Starting MaxScale

After configuration is complete, MariaDB MaxScale is ready to start. For systems that use systemd, use the systemctl command.

For older SysV systems, use the service command.

If MaxScale fails to start, check the error log in /var/log/maxscale/maxscale.log to see if any errors are detected in the configuration file.

hashtag
Checking MaxScale status with MaxCtrl

The maxctrl-command can be used to confirm that MaxScale is running and the services, listeners and servers have been correctly configured. The following shows expected output when using a read-write-splitting configuration.

MariaDB MaxScale is now ready to start accepting client connections and route queries to the backend cluster.

More options can be found in the , and .

For more information about MaxCtrl and how to secure it, see the .

This page is licensed: CC BY-SA / Gnu FDL

Common Monitor Parameters

This document settings supported by all monitors. These should be defined in the monitor section of the configuration file.

  • Common Monitor Parameters

    • Settings

hashtag
Settings

hashtag
module

  • Type: string

  • Mandatory: Yes

  • Dynamic: No

The monitor module this monitor should use. Typically mariadbmon orgaleramon.

hashtag
user

  • Type: string

  • Mandatory: Yes

  • Dynamic: Yes

Username used by the monitor to connect to the backend servers. If a server defines the monitoruser parameter, that value will be used instead.

hashtag
password

  • Type: string

  • Mandatory: Yes

  • Dynamic: Yes

Password for the user defined with the user parameter. If a server defines the monitorpw parameter, that value will be used instead.

Note: In older versions of MaxScale this parameter was called passwd. The use of passwd was deprecated in MaxScale 2.3.0.

hashtag
servers

  • Type: string

  • Mandatory: Yes

  • Dynamic: Yes

A comma-separated list of servers the monitor should monitor.

hashtag
monitor_interval

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 2s

Defines how often the monitor updates the status of the servers. Choose a lower value if servers should be queried more often. The smallest possible value is 100 milliseconds. If querying the servers takes longer than monitor_interval, the effective update rate is reduced.

The interval is specified as documented . If no explicit unit is provided, the value is interpreted as milliseconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected.

hashtag
backend_connect_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 3s

This parameter controls the timeout for connecting to a monitored server. The interval is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second. The minimum value is 1 second.

hashtag
backend_write_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 3s

This parameter controls the timeout for writing to a monitored server. The timeout is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second. The minimum value is 1 seconds.

hashtag
backend_read_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 3s

This parameter controls the timeout for reading from a monitored server. The timeout is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second. The minimum value is 1 second.

hashtag
backend_connect_attempts

  • Type: number

  • Mandatory: No

  • Dynamic: Yes

  • Default: 1

This parameter defines the maximum times a backend connection is attempted every monitoring loop. Every attempt may take up to backend_connect_timeout seconds to perform. If none of the attempts are successful, the backend is considered to be unreachable and down.

hashtag
disk_space_threshold

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

This parameter duplicates the disk_space_threshold. If the parameter has not been specified for a server, then the one specified for the monitor is applied.

NOTE: Since MariaDB 10.4.7, MariaDB 10.3.17 and MariaDB 10.2.26, the information will be available only if the monitor user has the FILE privilege.

That is, if the disk configuration is the same on all servers monitored by the monitor, it is sufficient (and more convenient) to specify the disk space threshold in the monitor section, but if the disk configuration is different on all or some servers, then the disk space threshold can be specified individually for each server.

For example, suppose server1, server2 and server3 are identical in all respects. In that case we can specify disk_space_threshold in the monitor.

However, if the servers are heterogeneous with the disk used for the data directory mounted on different paths, then the disk space threshold must be specified separately for each server.

If most of the servers have the data directory disk mounted on the same path, then the disk space threshold can be specified on the monitor and separately on the server with a different setup.

Above, server1 has the disk used for the data directory mounted at /DbData while both server2 and server3 have it mounted on/data and thus the setting in the monitor covers them both.

hashtag
disk_space_check_interval

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 0s

With this parameter it can be specified the minimum amount of time between disk space checks. The interval is specified as documented . If no explicit unit is provided, the value is interpreted as milliseconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. The default value is 0, which means that by default the disk space will not be checked.

Note that as the checking is made as part of the regular monitor interval cycle, the disk space check interval is affected by the value ofmonitor_interval. In particular, even if the value ofdisk_space_check_interval is smaller than that of monitor_interval, the checking will still take place at monitor_interval intervals.

hashtag
script

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

This command will be executed on a server state change. The parameter should be an absolute path to a command or the command should be in the executable path. The user running MaxScale should have execution rights to the file itself and the directory it resides in. The script may have placeholders which MaxScale will substitute with useful information when launching the script.

The placeholders and their substitution results are:

  • $INITIATOR -> IP and port of the server which initiated the event

  • $EVENT -> event description, e.g. "server_up"

  • $LIST -> list of IPs and ports of all servers

The expanded variable value can be an empty string if no servers match the variable's requirements. For example, if no primaries are available $MASTERLIST will expand into an empty string. The list-type substitutions will only contain servers monitored by the current monitor.

The above script could be executed as:

See section below for an example script.

Any output by the executed script will be logged into the MaxScale log. Each outputted line will be logged as a separate log message.

The log level on which the messages are logged depends on the format of the messages. If the first word in the output line is one of alert:, error:,warning:, notice:, info: or debug:, the message will be logged on the corresponding level. If the message is not prefixed with one of the keywords, the message will be logged on the notice level. Whitespace before, after or between the keyword and the colon is ignored and the matching is case-insensitive.

Currently, the script must not execute any of the following MaxCtrl calls as they cause a deadlock:

  • alter monitor to the monitor executing the script

  • stop monitor to the monitor executing the script

  • call command to a MariaDB-Monitor that is executing the script

hashtag
script_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 90s

The timeout for the executed script. The interval is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second.

If the script execution exceeds the configured timeout, it is stopped by sending a SIGTERM signal to it. If the process does not stop, a SIGKILL signal will be sent to it once the execution time is greater than twice the configured timeout.

hashtag
events

  • Type: enum

  • Mandatory: No

  • Dynamic: Yes

  • Values: master_down

A list of event names which cause the script to be executed. If this option is not defined, all events cause the script to be executed. The list must contain a comma separated list of event names.

The following table contains all the possible event types and their descriptions.

Event Name
Description

hashtag
journal_max_age

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 28800s

The maximum journal file age. The interval is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the max age is seconds, a max age specified in milliseconds will be rejected, even if the duration is longer than a second.

When the monitor starts, it reads any stored journal files. If the journal file is older than the value of journal_max_age, it will be removed and the monitor starts with no prior knowledge of the servers.

hashtag
Monitor Crash Safety

Starting with MaxScale 2.2.0, the monitor modules keep an on-disk journal of the latest server states. This change makes the monitors crash-safe when options that introduce states are used. It also allows the monitors to retain stateful information when MaxScale is restarted.

For MySQL monitor, options that introduce states into the monitoring process are the detect_stale_master and detect_stale_slave options, both of which are enabled by default. Galeramon has the disable_master_failback parameter which introduces a state.

The default location for the server state journal is in/var/lib/maxscale/<monitor name>/monitor.dat where <monitor name> is the name of the monitor section in the configuration file. If MaxScale crashes or is shut down in an uncontrolled fashion, the journal will be read when MaxScale is started. To skip the recovery process, manually delete the journal file before starting MaxScale.

hashtag
Script example

Below is an example monitor configuration which launches a script with all supported substitutions. The example script reads the results and prints it to file and sends it as email.

File "maxscale_monitor_alert_script.sh":

initiator="" parent="" children="" event="" node_list="" list="" master_list="" slave_list="" synced_list=""

process_arguments() { while [ "$1" != "" ]; do if [[ "$1" =~ ^--initiator=.* ]]; then initiator=${1#'--initiator='} elif [[ "$1" =~ ^--parent.* ]]; then parent=${1#'--parent='} elif [[ "$1" =~ ^--children.* ]]; then children=${1#'--children='} elif [[ "$1" =~ ^--event.* ]]; then event=${1#'--event='} elif [[ "$1" =~ ^--node_list.* ]]; then node_list=${1#'--node_list='} elif [[ "$1" =~ ^--list.* ]]; then list=${1#'--list='} elif [[ "$1" =~ ^--master_list.* ]]; then master_list=${1#'--master_list='} elif [[ "$1" =~ ^--slave_list.* ]]; then slave_list=${1#'--slave_list='} elif [[ "$1" =~ ^--synced_list.* ]]; then synced_list=${1#'--synced_list='} fi shift done }

process_arguments $@ read -r -d '' MESSAGE << EOM A server has changed state. The following information was provided:

Initiator: $initiator Parent: $parent Children: $children Event: $event Node list: $node_list List: $list Primary list: $master_list Replica list: $slave_list Synced list: $synced_list EOM

hashtag
print message to file

echo "$MESSAGE" > /path/to/script_output.txt

hashtag
email the message

echo "$MESSAGE" | mail -s "MaxScale received $event event for initiator $initiator." mariadb_admin@domain.com |

This page is licensed: CC BY-SA / Gnu FDL

MariaDB Monitor

hashtag
Overview

MariaDB Monitor monitors a Primary-Replica replication cluster. It probes the state of the backends and assigns server roles such as primary and replica, which are used by the routers when deciding where to route a query. It can also modify the replication cluster by performing failover, switchover and rejoin. Backend server versions older than MariaDB/MySQL 5.5 are not supported. Failover and other similar operations require MariaDB 10.4 or later.

Up until MariaDB MaxScale 2.2.0, this monitor was called MySQL Monitor.

hashtag
Required Grants

The monitor user requires the following grant:

In MariaDB Server versions 10.5.0 to 10.5.8, the monitor user instead requires REPLICATION SLAVE ADMIN:

In MariaDB Server 10.5.9 and later, REPLICA MONITOR is required:

If the monitor needs to query server disk space (i.e. disk_space_threshold is set), then the FILE-grant is required with MariaDB Server versions 10.4.7, 10.3.17, 10.2.26 and 10.1.41 and later.

MariaDB Server 10.5.2 introduces CONNECTION ADMIN. This is recommended since it allows the monitor to log in even if server connection limit has been reached.

hashtag
Cluster Manipulation Grants

If are used, the following additional grants are required:

MariaDB 10.5.2 and later require read access to mysql.global_priv:

As of MariaDB Server 11.0.1, the SUPER-privilege no longer contains several of its former sub-privileges. These must be given separately.

If a separate replication user is defined (with replication_user andreplication_password), it requires the following grant:

hashtag
Primary selection

Only one backend can be primary at any given time. A primary must be running (successfully connected to by the monitor) and its read_only-setting must be off. A primary may not be replicating from another server in the monitored cluster unless the primary is part of a multiprimary group. Primary selection prefers to select the server with the most replicas, possibly in multiple replication layers. Only replicas reachable by a chain of running relays or directly connected to the primary count. When multiple servers are tied for primary status, the server which appears earlier in the servers-setting of the monitor is selected.

Servers in a cyclical replication topology (multiprimary group) are interpreted as having all the servers in the group as replicas. Even from a multiprimary group only one server is selected as the overall primary.

After a primary has been selected, the monitor prefers to stick with the choice even if other potential primaries with more replica servers are available. Only if the current primary is clearly unsuitable does the monitor try to select another primary. An existing primary turns invalid if:

  1. It is unwritable (read_only is on).

  2. It has been down for more than failcount monitor passes and has no running replicas. Running replicas behind a downed relay count. A replica in this context is any server with at least a partially running replication connection (either io or sql thread is running). The replicas must also be down for more than failcount monitor passes to allow new master selection.

  3. It did not previously replicate from another server in the cluster but it is now replicating.

Cases 1 and 2 cover the situations in which the DBA, an external script or even another MaxScale has modified the cluster such that the old primary can no longer act as primary. Cases 3 and 4 are less severe. In these cases the topology has changed significantly and the primary should be re-selected, although the old primary may still be the best choice.

The primary change described above is different from failover and switchover described in section . A primary change only modifies the server roles inside MaxScale but does not modify the cluster other than changing the targets of read and write queries. Failover and switchover perform a primary change on their own.

As a general rule, it's best to avoid situations where the cluster has multiple standalone servers, separate primary-replica pairs or separate multiprimary groups. Due to primary invalidation rule 2, a standalone primary can easily lose the primary status to another valid primary if it goes down. The new primary probably does not have the same data as the previous one. Non-standalone primaries are less vulnerable, as a single running replica or multiprimary group member will keep the primary valid even when down.

hashtag
Configuration

A minimal configuration for a monitor requires a set of servers for monitoring and a username and a password to connect to these servers.

From MaxScale 2.2.1 onwards, the module name is mariadbmon instead ofmysqlmon. The old name can still be used.

The grants required by user depend on which monitor features are used. A full list of the grants can be found in the section.

hashtag
Common Monitor Settings

For a list of optional parameters that all monitors support, read the document.

hashtag
Settings

These are optional parameters specific to the MariaDB Monitor. Failover, switchover and rejoin-specific parameters are listed in their own . Rebuild-related parameters are described in the . ColumnStore parameters are described in the .

hashtag
assume_unique_hostnames

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: true

When active, the monitor assumes that server hostnames and ports are consistent between the server definitions in the MaxScale configuration file and the "SHOW ALL SLAVES STATUS" outputs of the servers themselves. Specifically, the monitor assumes that if server A is replicating from server B, then A must have a replica connection with Master_Host andMaster_Port equal to B's address and port in the configuration file. If this is not the case, e.g. an IP is used in the server while a hostname is given in the file, the monitor may misinterpret the topology. The monitor attempts name resolution on the addresses if a simple string comparison does not find a match. Using exact matching addresses is, however, more reliable. In MaxScale 24.02.0, an alternative IP or hostname for a server can be given in .

This setting must be ON to use any cluster operation features such as failover or switchover, because MaxScale uses the addresses and ports in the configuration file when issuing "CHANGE MASTER TO"-commands.

If the network configuration is such that the addresses MaxScale uses to connect to backends are different from the ones the servers use to connect to each other and private_address is not used, assume_unique_hostnames should be set to OFF. In this mode, MaxScale uses server id:s it queries from the servers and the Master_Server_Id fields of the replica connections to deduce which server is replicating from which. This is not perfect though, since MaxScale doesn't know the id:s of servers it has never connected to (e.g. server has been down since MaxScale was started). Also, the Master_Server_Id-field may have an incorrect value if the replica connection has not been established. MaxScale will only trust the value if the monitor has seen the replica connection IO thread connected at least once. If this is not the case, the replica connection is ignored.

hashtag
private_address

String. This is an optional server setting, yet documented here since it's only used by MariaDB Monitor. If not set, the normal server address setting is used.

Defines an alternative IP-address or hostname for the server for use with replication. Whenever MaxScale modifies replication (e.g. during switchover), the private address is given as Master_Host to "CHANGE MASTER TO"-commands. Also, when detecting replication, any Master_Host-values from "SHOW SLAVE STATUS"-queries are compared to the private addresses of configured servers if the normal address doesn't match.

This setting is useful if replication and application traffic are separated to different network interfaces.

hashtag
master_conditions

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Values: none

Designate additional conditions for_Master_-status, i.e. qualified for read and write queries.

Normally, if a suitable primary candidate server is found as described in , MaxScale designates it Master.master_conditions sets additional conditions for a primary server. This setting is an enum_mask, allowing multiple conditions to be set simultaneously. Conditions 2, 3 and 4 refer to replica servers. A single replica must fulfill all of the given conditions for the primary to be viable.

If the primary candidate fails master_conditions but fulfills_slave_conditions_, it may be designated Slave instead.

The available conditions are:

  1. none : No additional conditions

  2. connecting_slave : At least one immediate replica (not behind relay) is attempting to replicate or is replicating from the primary (Slave_IO_Running is 'Yes' or 'Connecting', Slave_SQL_Running is 'Yes'). A replica with incorrect replication credentials does not count. If the replica is currently down, results from the last successful monitor tick are used.

  3. connected_slave : Same as above, with the difference that the replication connection must be up (Slave_IO_Running is 'Yes'). If the replica is currently down, results from the last successful monitor tick are used.

The default value of this setting ismaster_requirements=primary_monitor_master,disk_space_ok to ensure that both monitors use the same primary server when cooperating and that the primary is not out of disk space.

For example, to require that the primary must have a replica which is both connected and running, set

hashtag
slave_conditions

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Values: none

Designate additional conditions for Slave-status, i.e qualified for read queries.

Normally, a server is Slave if it is at least attempting to replicate from the primary candidate or a relay (Slave_IO_Running is 'Yes' or 'Connecting', Slave_SQL_Running is 'Yes', valid replication credentials). The primary candidate does not necessarily need to be writable, e.g. if it fails its_master_conditions_. slave_conditions sets additional conditions for a replica server. This setting is an enum_mask, allowing multiple conditions to be set simultaneously.

The available conditions are:

  1. none : No additional conditions. This is the default value.

  2. linked_master : The replica must be connected to the primary (Slave_IO_Running and Slave_SQL_Running are 'Yes') and the primary must be Running. The same applies to any relays between the replica and the primary.

  3. running_master : The primary must be running. Relays may be down.

For example, to require that the primary server of the cluster must be running and writable for any servers to have Slave-status, set

hashtag
failcount

  • Type: number

  • Mandatory: No

  • Dynamic: Yes

  • Default: 5

Number of consecutive monitor passes a primary server must be down before it is considered failed. If automatic failover is enabled (auto_failover=true), it may be performed at this time. A value of 0 or 1 enables immediate failover.

If automatic failover is not possible, the monitor will try to search for another server to fulfill the primary role. See section for more details. Changing the primary may break replication as queries could be routed to a server without previous events. To prevent this, avoid having multiple valid primary servers in the cluster.

The worst-case delay between the primary failure and the start of the failover can be estimated by summing up the timeout values and monitor_interval and multiplying that by failcount:

hashtag
enforce_writable_master

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

If set to ON, the monitor attempts to disable the read_only-flag on the primary when seen. The flag is checked every monitor tick. The monitor user requires the SUPER-privilege for this feature to work.

Typically, the primary server should never be in read-only-mode. Such a situation may arise due to misconfiguration or accident, or perhaps if MaxScale crashed during switchover.

When this feature is enabled, setting the primary manually to read_only will no longer cause the monitor to search for another primary. The primary will instead for a moment lose its [Master]-status (no writes), until the monitor again enables writes on the primary. When starting from scratch, the monitor still prefers to select a writable server as primary if possible.

hashtag
enforce_read_only_slaves

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

If set to ON, the monitor attempts to enable the read_only-flag on any writable replica server. The flag is checked every monitor tick. The monitor user requires the SUPER-privilege (or READ_ONLY ADMIN) for this feature to work. While the read_only-flag is ON, only users with the SUPER-privilege (or READ_ONLY ADMIN) can write to the backend server. If temporary write access is required, this feature should be disabled before attempting to disable read_only manually. Otherwise, the monitor will quickly re-enable it.

read_only won't be enabled on the master server, even if it has lost [Master]-status due to and is marked [Slave].

hashtag
enforce_read_only_servers

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

Works similar to except will set_read_only_ on any writable server that is not the primary and not in maintenance (a superset of the servers altered by enforce_read_only_slaves).

The monitor user requires the SUPER-privilege (or READ_ONLY ADMIN) for this feature to work. If the cluster has no valid primary or primary candidate, read_only is not set on any server as it is unclear which servers should be altered.

hashtag
maintenance_on_low_disk_space

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: true

If a running server that is not the primary or a relay primary is out of disk space the server is set to maintenance mode. Such servers are not used for router sessions and are ignored when performing a failover or other cluster modification operation. See the general monitor parameters and on how to enable disk space monitoring.

Once a server has been put to maintenance mode, the disk space situation of that server is no longer updated. The server will not be taken out of maintenance mode even if more disk space becomes available. The maintenance flag must be removed manually:

hashtag
cooperative_monitoring_locks

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Values: none

Using this setting is recommended when multiple MaxScales are monitoring the same backend cluster. When enabled, the monitor attempts to acquire exclusive locks on the backend servers. The monitor considers itself the primary monitor if it has a majority of locks. The majority can be either over all configured servers or just over running servers. See for more details on how this feature works and which value to use.

Allowed values:

  1. none Default value, no locking.

  2. majority_of_all Primary monitor requires a majority of locks, even counting servers which are [Down].

  3. majority_of_running Primary monitor requires a majority of locks over [Running] servers.

This setting is separate from the global MaxScale setting passive. If_passive_ is set to true, cluster operations are disabled even if monitor has acquired the locks. Generally, it's best not to mix cooperative monitoring with_passive_. Either set passive=false or do not set it at all.

hashtag
script_max_replication_lag

  • Type: number

  • Mandatory: No

  • Dynamic: Yes

  • Default: -1

Defines a replication lag limit in seconds for launching the monitor script configured in the script-parameter. If the replication lag of a server goes above this limit, the script is ran with the $EVENT-placeholder replaced by "rlag_above". If the lag goes back below the limit, the script is ran again with replacement "rlag_below".

Negative values disable this feature. For more information on monitor scripts, see .

hashtag
Cluster manipulation operations

MariaDB Monitor can perform several operations that modify the replication topology. The supported operations are:

  • , which replaces a failed primary with a replica

  • , which replaces a failed primary with a replica only if no data is clearly lost

  • , which swaps a running primary with a replica

See for more information on the implementation of the commands.

The cluster operations require that the monitor user (user) has the following privileges:

  • SUPER, to modify replica connections, set globals such as read_only and kill connections from other super-users

  • REPLICATION CLIENT (REPLICATION SLAVE ADMIN in MariaDB Server 10.5), to list replica connections

  • RELOAD, to flush binary logs

A list of the grants can be found in the section.

The privilege system was changed in MariaDB Server 10.5. The effects of this on the MaxScale monitor user are minor, as the SUPER-privilege contains many of the required privileges and is still required to kill connections from other super-users.

In MariaDB Server 11.0.1 and later, SUPER no longer contains all the required grants. The monitor requires:

  • READ_ONLY ADMIN, to set read_only

  • REPLICA MONITOR and REPLICATION SLAVE ADMIN, to view and manage replication connections

  • RELOAD, to flush binary logs

  • PROCESS, to check if the event_scheduler process is running

In addition, the monitor needs to know which username and password a replica should use when starting replication. These are given inreplication_user and replication_password.

The user can define files with SQL statements which are executed on any server being demoted or promoted by cluster manipulation commands. See the sections onpromotion_sql_file and demotion_sql_file for more information.

The monitor can manipulate scheduled server events when promoting or demoting a server. See the section on handle_events for more information.

All cluster operations can be activated manually through MaxCtrl. See section for more details.

See for information on possible issues with failover and switchover.

hashtag
Operation details

Failover

Failover replaces a failed primary with a running replica. It does the following:

  1. Select the most up-to-date replica of the old primary to be the new primary. The selection criteria is as follows in descending priority:

  2. gtid_IO_pos (latest event in relay log)

  3. gtid_current_pos (most processed events)

  4. log_slave_updates is on

Failover is considered successful if steps 1 to 3 succeed, as the cluster then has at least a valid primary server.

Failover-safe

Failover-safe performs the same steps as a normal failover but refuses to start if it's clear that data would be lost. Dataloss occurs if the primary had data which was not replicated to any replica before the primary went down. MaxScale detects this by looking at the GTIDs of the servers. Because the monitor queries the GTIDs only every monitor interval, this check is inaccurate. If the primary performs a write just before crashing and before MaxScale queries the GTID, data could be lost even with "safe" failover. Thus, this feature mainly protects against situations where the replicas are constantly lagging.

Switchover

Switchover swaps a running primary with a running replica. It does the following:

  1. Prepare the old primary for demotion:

  2. If backend_read_timeout is short, extend it and reconnect.

  3. Stop any external replication.

Similar to failover, switchover is considered successful if the new primary was successfully promoted.

Switchover-force

Switchover-force performs the same steps as a normal switchover but ignores any errors on the old primary. Switchover-force also does not expect the new primary to reach the gtid-position of the old, as the old primary could be receiving more events constantly. Thus, switchover-force may lose events and replication can break on multiple (or even all) replicas. This is an unsafe command and should only be used as a last resort.

Rejoin

Rejoin joins a standalone server to the cluster or redirects a replica replicating from a server other than the primary. A standalone server is joined by:

  1. Run the commands in demotion_sql_file.

  2. Enable the read_only-flag.

  3. Disable scheduled server events (if event handling is on).

A server which is replicating from the wrong primary is redirected simply with STOP SLAVE, RESET SLAVE, CHANGE MASTER TO and START SLAVE commands.

Reset Replication

Reset-replication (added in MaxScale 2.3.0) deletes binary logs and resets gtid:s. This destructive command is meant for situations where the gtid:s in the cluster are out of sync while the actual data is known to be in sync. The operation proceeds as follows:

  1. Reset gtid:s and delete binary logs on all servers:

  2. Stop (STOP SLAVE) and delete (RESET SLAVE ALL) all replica connections.

  3. Enable the read_only-flag.

  4. Disable scheduled server events (if event handling is on).

hashtag
Manual activation

Cluster operations can be activated manually through the REST API or MaxCtrl. The commands are only performed when MaxScale is in active mode. The commands generally match their automatic versions. The exception is rejoin, in which the manual command allows rejoining even when the joining server has empty gtid:s. This rule allows the user to force a rejoin on a server without binary logs.

All commands require the monitor instance name as the first parameter. Failover selects the new primary server automatically and does not require additional parameters. Rejoin requires the name of the joining server as second parameter. Replication reset accepts the name of the new primary server as second parameter. If not given, the current primary is selected.

Switchover takes one to three parameters. If only the monitor name is given, switchover will autoselect both the replica to promote and the current primary as the server to be demoted. If two parameters are given, the second parameter is interpreted as the replica to promote. If three parameters are given, the third parameter is interpreted as the current primary. The user-given current primary is compared to the primary server currently deduced by the monitor and if the two are unequal, an error is given.

Example commands are below:

The commands follow the standard module command syntax. All require the monitor configuration name (MyMonitor) as the first parameter. For switchover, the last two parameters define the server to promote (NewPrimaryServ) and the server to demote (OldPrimaryServ). For rejoin, the server to join (OldPrimaryServ) is required. Replication reset requires the server to promote (NewPrimaryServ).

It is safe to perform manual operations even with automatic failover, switchover or rejoin enabled since automatic operations cannot happen simultaneously with manual ones.

When a cluster modification is initiated via the REST-API, the URL path is of the form:

  • <operation> is the name of the command e.g. failover, switchover, rejoin or reset-replication.

  • <monitor-name> is the monitor name from the MaxScale configuration file.

  • <server-name1> and <server-name2>

Given a MaxScale configuration file like

with the assumption that server2 is the current primary, then the URL path for making server4 the new primary would be:

Example REST-API paths for other commands are listed below.

Queued switchover

Most cluster modification commands wait until the operation either succeeds or fails. async-switchover is an exception, as it returns immediately. Otherwise_async-switchover_ works identical to a normal switchover command. Use the module command fetch-cmd-result to view the result of the queued command.fetch-cmd-result returns the status or result of the latest manual command, whether queued or not.

Switchover with key-value arguments

As of MaxScale 24.08.0, switchover can be launched using an alternate command syntax which passes arguments as key-value pairs. This allows for greater flexibility as a variable number of arguments can be easily defined in the call. This alternative form of switchover accepts the following arguments:

argument
type
default
description

The key-value syntax thus supports the same features as the old switchover,async-switchover and switchover-force-commands.

In addition, key-value argument passing supports old_primary_maint. This feature leaves the old primary server in maintenance mode without replication. This is useful when performing rolling MariaDB Server version upgrades. After all replicas have been upgraded, switch out the old primary withold_primary_maint=1 to promote one of the replicas while leaving the old primary as standalone.

hashtag
Automatic activation

Failover can activate automatically if auto_failover is on. The activation begins when the primary has been down at least failcount monitor iterations. Before modifying the cluster, the monitor checks that all prerequisites for the failover are fulfilled. If the cluster does not seem ready, an error is printed and the cluster is rechecked during the next monitor iteration.

Switchover can also activate automatically with theswitchover_on_low_disk_space-setting. The operation begins if the primary server is low on disk space but otherwise the operating logic is quite similar to automatic failover.

Rejoin stands for starting replication on a standalone server or redirecting a replica replicating from the wrong primary (any server that is not the cluster primary). The rejoined servers are directed to replicate from the current cluster primary server, forcing the replication topology to a 1-primary-N-replicas configuration.

A server is categorized as standalone if the server has no replica connections, not even stopped ones. A server is replicating from the wrong primary if the replica IO thread is connected but the primary server id seen by the replica does not match the cluster primary id. Alternatively, the IO thread may be stopped or connecting but the primary server host or port information differs from the cluster primary info. These criteria mean that a STOP SLAVE does not yet set a replica as standalone.

With auto_rejoin active, the monitor will try to rejoin any servers matching the above requirements. Rejoin does not obey failcount and will attempt to rejoin any valid servers immediately. When activating rejoin manually, the user-designated server must fulfill the same requirements.

hashtag
Limitations and requirements

Switchover and failover are meant for simple topologies (one primary and several replicas). Using these commands with complicated topologies (multiple primaries, relays, circular replication) may give unpredictable results and should be tested before use on a production system.

The server cluster is assumed to be well-behaving with no significant replication lag (within failover_timeout/switchover_timeout) and all commands that modify the cluster (such as "STOP SLAVE", "CHANGE MASTER", "START SLAVE") complete in a few seconds (faster than backend_read_timeout and backend_write_timeout).

The backends must all use GTID-based replication, and the domain id should not change during a switchover or failover. Replicas should not have extra local events so that GTIDs are compatible across the cluster.

Failover cannot be performed if MaxScale was started only after the primary server went down. This is because MaxScale needs reliable information on the gtid domain of the cluster and the replication topology in general to properly select the new primary. enforce_simple_topology=1 relaxes this requirement.

Failover may lose events. If a primary goes down before sending new events to at least one replica, those events are lost when a new primary is chosen. If the old primary comes back online, the other servers have likely moved on with a diverging history and the old primary can no longer join the replication cluster.

To reduce the chance of losing data, use . In semisynchronous mode, the primary waits for a replica to receive an event before returning an acknowledgement to the client. This does not yet guarantee a clean failover. If the primary fails after preparing a transaction but before receiving replica acknowledgement, it will still commit the prepared transaction as part of its crash recovery. If the replicas never saw this transaction, the old primary has diverged from the cluster. See for more information. This situation is much less likely in MariaDB Server 10.6.2 and later, as the improved crash recovery logic will delete such transactions.

Even a controlled shutdown of the primary may lose events. The server does not by default wait for all data to be replicated to the replicas when shutting down and instead simply closes all connections. Before shutting down the primary with the intention of having a replica promoted, run switchover first to ensure that all data is replicated. For more information on server shutdown, see .

Switchover requires that the cluster is "frozen" for the duration of the operation. This means that no data modifying statements such as INSERT or UPDATE are executed and the GTID position of the primary server is stable. When switchover begins, the monitor sets the global read_only flag on the old primary backend to stop any updates. read_only does not affect users with the SUPER-privilege so any such user can issue writes during a switchover. These writes have a high chance of breaking replication, because the write may not be replicated to all replicas before they switch to the new primary. To prevent this, any users who commonly do updates should NOT have the SUPER-privilege. For even more security, the only SUPER-user session during a switchover should be the MaxScale monitor user. This also applies to users running scheduled server events. Although the monitor by default disables events on the master, an event may already be executing. If the event definer has SUPER-privilege, the event can write to the database even through read_only.

When mixing rejoin with failover/switchover, the backends should have_log_slave_updates_ on. The rejoining server is likely lagging behind the rest of the cluster. If the current cluster primary does not have binary logs from the moment the rejoining server lost connection, the rejoining server cannot continue replication. This is an issue if the primary has changed and the new primary does not have log_slave_updates on.

If an automatic cluster operation such as auto-failover or auto-rejoin fails, all cluster modifying operations are disabled for failcount monitor iterations, after which the operation may be retried. Similar logic applies if the cluster is unsuitable for such operations, e.g. replication is not using GTID.

hashtag
External primary support

The monitor detects if a server in the cluster is replicating from an external primary (a server that is not monitored by the monitor). If the replicating server is the cluster primary server, then the cluster itself is considered to have an external primary.

If a failover/switchover happens, the new primary server is set to replicate from the cluster external primary server. The username and password for the replication are defined in replication_user and replication_password. The address and port used are the ones shown by SHOW ALL SLAVES STATUS on the old cluster primary server. In the case of switchover, the old primary also stops replicating from the external server to preserve the topology.

After failover the new primary is replicating from the external primary. If the failed old primary comes back online, it is also replicating from the external server. To normalize the situation, either have auto_rejoin on or manually execute a rejoin. This will redirect the old primary to the current cluster primary.

hashtag
Settings for Cluster manipulation operations

auto_failover

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Values: true

Enable automatic primary failover. true, on, yes and 1 enable normal failover. false, off, no and 0 disable the feature. safe enables .

When automatic failover is enabled, MaxScale will elect a new primary server for the cluster if the old primary goes down. A server is assumed Down if it cannot be connected to, even if this is caused by incorrect credentials. Failover triggers if the primary stays down for monitor intervals. Failover will not take place if MaxScale is set .

As failover alters replication, it requires more privileges than normal monitoring. See for a list of grants.

Failover is designed to be used with simple primary-replica topologies. More complicated topologies, such as multilayered or circular replication, are not guaranteed to always work correctly. Test before using failover with such setups.

auto_rejoin

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

Enable automatic joining of servers to the cluster. When enabled, MaxScale will attempt to direct servers to replicate from the current cluster primary if they are not currently doing so. Replication will be started on any standalone servers. Servers that are replicating from another server will be redirected. This effectively enforces a 1-primary-N-replicas topology. The current primary itself is not redirected, so it can continue to replicate from an external primary. Rejoin is also not performed on any server that is replicating from multiple sources, as this indicates a complicated topology (this rule is overridden by ).

This feature is often paired with to redirect the former primary when it comes back online. Sometimes this kind of rejoin will fail as the old primary may have transactions that were never replicated to the current one. See for more information.

As an example, consider the following series of events:

  1. Replica A goes down

  2. Primary goes down and a failover is performed, promoting Replica B

  3. Replica A comes back

  4. Old primary comes back

Replica A is still trying to replicate from the downed primary, since it wasn't online during failover. If auto_rejoin is on, Replica A will quickly be redirected to Replica B, the current primary. The old primary will also rejoin the cluster if possible.

switchover_on_low_disk_space

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

If enabled, the monitor will attempt to switchover a primary server low on disk space with a replica. The switch is only done if a replica without disk space issues is found. Ifmaintenance_on_low_disk_space is also enabled, the old primary (now a replica) will be put to maintenance during the next monitor iteration.

For this parameter to have any effect, disk_space_threshold must be specified for the or the . Also, must be defined for the monitor.

enforce_simple_topology

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

This setting tells the monitor to assume that the servers should be arranged in a 1-primary-N-replicas topology and the monitor should try to keep it that way. Ifenforce_simple_topology is enabled, the settings assume_unique_hostnames,auto_failover and auto_rejoin are also activated regardless of their individual settings.

By default, mariadbmon will not rejoin servers with more than one replication stream configured into the cluster. Starting with MaxScale 6.2.0, whenenforce_simple_topology is enabled, all servers will be rejoined into the cluster and any extra replication sources will be removed. This is done to make automated failover with multi-source external replication possible.

This setting also allows the monitor to perform a failover to a cluster where the primary server has not been seen [Running]. This is usually the case when the primary goes down before MaxScale is started. When using this feature, the monitor will guess the GTID domain id of the primary from the replicas. For reliable results, the GTID:s of the cluster should be simple.

replication_user

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

This and replication_password specify the username and password of the replication user. These are given as the values for MASTER_USER andMASTER_PASSWORD whenever a CHANGE MASTER TO command is executed.

Both replication_user and replication_password parameters must be defined if a custom replication user is used. If neither of the parameters is defined, theCHANGE MASTER TO-command will use the monitor credentials for the replication user.

The credentials used for replication must have the REPLICATION SLAVE privilege.

replication_password uses the same encryption scheme as other password parameters. If password encryption is in use, replication_password must be encrypted with the same key to avoid erroneous decryption.

replication_password

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

See

replication_master_ssl

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: false

If set to ON, any CHANGE MASTER TO-command generated will set MASTER_SSL=1 to enable encryption for the replication stream. This setting should only be enabled if the backend servers are configured for ssl. This typically means setting ssl_ca, ssl_cert and_ssl_key_ in the server configuration file. Additionally, credentials for the replication user should require an encrypted connection (e.g. ALTER USER repl@'%' REQUIRE SSL;).

If the setting is left OFF, MASTER_SSL is not set at all, which will preserve existing settings when redirecting a replica connection.

replication_custom_options

Type: string

A custom string added to "CHANGE MASTER TO"-commands sent by the monitor whenever setting up replication (e.g. during switchover). Useful for defining ssl certificates or other specialized replication options. MaxScale does not check the contents of the string, so care should be taken to ensure that only valid options are set and that the contents do not interfere with the options MaxScale sets on its own (e.g. MASTER_HOST). This setting can also be configured for an individual server. If configured for both the monitor and a server, the server setting takes priority.

failover_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 90s

Time limit for failover operation. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second.

If no successful failover takes place within the configured time period, a message is logged and automatic failover is disabled. This prevents further automatic modifications to the misbehaving cluster.

switchover_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 90s

Time limit for switchover operations. The timeout is also used as the time limit for a rejoin operation. Rejoin should rarely time out, since it is a faster operation than switchover. Note that since the granularity of the timeouts is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second.

verify_master_failure

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: true

Enable additional primary failure verification for automatic failover.verify_master_failure enables this feature and defines the timeout.

The primary failure timeout is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second.

Failure verification is performed by checking whether the replica servers are still connected to the primary and receiving events. An event is either a change in the Gtid_IO_Pos-field of the SHOW SLAVE STATUS output or a heartbeat event. Effectively, if a replica has received an event withinmaster_failure_timeout duration, the primary is not considered down when deciding whether to failover, even if MaxScale cannot connect to the primary.master_failure_timeout should be longer than the Slave_heartbeat_period of the replica connection to be effective.

If every replica loses its connection to the primary (Slave_IO_Running is not "Yes"), primary failure is considered verified regardless of timeout. This allows faster failover when the primary properly disconnects.

For automatic failover to activate, the failcount requirement must also be met.

master_failure_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 10s

master_failure_timeout is specified as documented . If no explicit unit is provided, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. Note that since the granularity of the timeout is seconds, a timeout specified in milliseconds will be rejected, even if the duration is longer than a second.

servers_no_promotion

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

This is a comma-separated list of server names that will not be chosen for primary promotion during a failover or autoselected for switchover. This does not affect switchover if the user selects the server to promote. Using this setting can disrupt new primary selection for failover such that a non-optimal server is chosen. At worst, this will cause replication to break. Alternatively, failover may fail if all valid promotion candidates are in the exclusion list.

As of MaxScale 24.02.4 and 24.08.1, this setting also affects primary server selection during MaxScale startup or due to replication topology changes. A server listed in servers_no_promotion will thus not be selected as primary unless manually designated in a switchover-command.

promotion_sql_file

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

This and demotion_sql_file are paths to text files with SQL statements in them. During promotion or demotion, the contents are read line-by-line and executed on the backend. Use these settings to execute custom statements on the servers to complement the built-in operations.

Empty lines or lines starting with '#' are ignored. Any results returned by the statements are ignored. All statements must succeed for the failover, switchover or rejoin to continue. The monitor user may require additional privileges and grants for the custom commands to succeed.

When promoting a replica to primary during switchover or failover, thepromotion_sql_file is read and executed on the new primary server after its read-only flag is disabled. The commands are ran before starting replication from an external primary if any.

demotion_sql_file is ran on an old primary during demotion to replica, before the old primary starts replicating from the new primary. The file is also ran before rejoining a standalone server to the cluster, as the standalone server is typically a former primary server. When redirecting a replica replicating from a wrong primary, the sql-file is not executed.

Since the queries in the files are ran during operations which modify replication topology, care is required. If promotion_sql_file contains data modification (DML) queries, the new primary server may not be able to successfully replicate from an external primary. demotion_sql_file should never contain DML queries, as these may not replicate to the replica servers before replica threads are stopped, breaking replication.

demotion_sql_file

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

See .

handle_events

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: true

If enabled, the monitor continuously queries the servers for enabled scheduled events and uses this information when performing cluster operations, enabling and disabling events as appropriate.

When a server is being demoted, any events with "ENABLED" status are set to "SLAVESIDE_DISABLED". When a server is being promoted to primary, events that are either "SLAVESIDE_DISABLED" or "DISABLED" are set to "ENABLED" if the same event was also enabled on the old primary server last time it was successfully queried. Events are considered identical if they have the same schema and name. When a standalone server is rejoined to the cluster, its events are also disabled since it is now a replica.

The monitor does not check whether the same events were disabled and enabled during a switchover or failover/rejoin. All events that meet the criteria above are altered.

The monitor does not enable or disable the event scheduler itself. For the events to run on the new primary server, the scheduler should be enabled by the admin. Enabling it in the server configuration file is recommended.

Events running at high frequency may cause replication to break in a failover scenario. If an old primary which was failed over restarts, its event scheduler will be on if set in the server configuration file. Its events will also remember their "ENABLED"-status and run when scheduled. This may happen before the monitor rejoins the server and disables the events. This should only be an issue for events running more often than the monitor interval or events that run immediately after the server has restarted.

hashtag
Cooperative monitoring

As of MaxScale 2.5, MariaDB-Monitor supports cooperative monitoring. This means that multiple monitors (typically in different MaxScale instances) can monitor the same backend server cluster and only one will be the primary monitor. Only the primary monitor may perform switchover, failover or rejoin operations. The primary also decides which server is the primary. Cooperative monitoring is enabled with the -setting. Even with this setting, only one monitor per server per MaxScale is allowed. This limitation can be circumvented by defining multiple copies of a server in the configuration file.

Cooperative monitoring uses for coordinating between monitors. When cooperating, the monitor regularly checks the status of a lock named maxscale_mariadbmonitor on every server and acquires it if free. If the monitor acquires a majority of locks, it is the primary. If a monitor cannot claim majority locks, it is a secondary monitor.

The primary monitor of a cluster also acquires the lockmaxscale_mariadbmonitor_master on the primary server. Secondary monitors check which server this lock is taken on and only accept that server as the primary. This arrangement is required so that multiple monitors can agree on which server is the primary regardless of replication topology. If a secondary monitor does not see the primary-lock taken, then it won't mark any server as [Master], causing writes to fail.

The lock-setting defines how many locks are required for primary status. Settingcooperative_monitoring_locks=majority_of_all means that the primary monitor needs n_servers/2 + 1 (rounded down) locks. For example, a cluster of three servers needs two locks for majority, a cluster of four needs three, and a cluster of five needs three. This scheme is resistant against split-brain situations in the sense that multiple monitors cannot be primary simultaneously. However, a split may cause both monitors to consider themselves secondary, in which case a primary server won't be detected.

Even without a network split, cooperative_monitoring_locks=majority_of_all will lead to neither monitor claiming lock majority once too many servers go down. This scenario is depicted in the image below. Only two out of four servers are running when three are needed for majority. Although both MaxScales see both running servers, neither is certain they have majority and the cluster stays in read-only mode. If the primary server is down, no failover is performed either.

Setting cooperative_monitoring_locks=majority_of_running changes the way_n_servers_ is calculated. Instead of using the total number of servers, only servers currently [Running] are considered. This scheme adapts to multiple servers going down, ensuring that claiming lock majority is always possible. However, it can lead to multiple monitors claiming primary status in a split-brain situation. As an example, consider a cluster with servers 1 to 4 with MaxScales A and B, as in the image below. MaxScale A can connect to servers 1 and 2 (and claim their locks) but not to servers 3 and 4 due to a network split. MaxScale A thus assumes servers 3 and 4 are down. MaxScale B does the opposite, claiming servers 3 and 4 and assuming 1 and 2 are down. Both MaxScales claim two locks out of two available and assume that they have lock majority. Both MaxScales may then promote their own primaries and route writes to different servers.

The recommended strategy depends on which failure scenario is more likely and/or more destructive. If it's unlikely that multiple servers are ever down simultaneously, then majority_of_all is likely the safer choice. On the other hand, if split-brain is unlikely but multiple servers may be down simultaneously, then majority_of_running would keep the cluster operational.

To check if a monitor is primary, fetch monitor diagnostics with maxctrl show monitors or the REST API. The boolean field primary indicates whether the monitor has lock majority on the cluster. If cooperative monitoring is disabled, the field value is null. Lock information for individual servers is listed in the server-specific field lock_held. Again, null indicates that locks are not in use or the lock status is unknown.

If a MaxScale instance tries to acquire the locks but fails to get majority (perhaps another MaxScale was acquiring locks simultaneously) it will release any acquired locks and try again after a random number of monitor ticks. This prevents multiple MaxScales from fighting over the locks continuously as one MaxScale will eventually wait less time than the others. Conflict probability can be further decreased by configuring each monitor with a different_monitor_interval_.

The flowchart below illustrates the lock handling logic.

hashtag
Releasing locks

Monitor cooperation depends on the server locks. The locks are connection-specific. The owning connection can manually release a lock, allowing another connection to claim it. Also, if the owning connection closes, the MariaDB Server process releases the lock. How quickly a lost connection is detected affects how quickly the primary monitor status moves from one monitor and MaxScale to another.

If the primary MaxScale or its monitor is stopped normally, the monitor connections are properly closed, releasing the locks. This allows the secondary MaxScale to quickly claim the locks. However, if the primary simply vanishes (broken network), the connection may just look idle. In this case, the MariaDB Server may take a long time before it considers the monitor connection lost. This time ultimately depends on TCP keepalive settings on the machines running MariaDB Server.

On MariaDB Server 10.3.3 and later, the TCP keepalive settings can be configured for just the server process. See for information on settings tcp_keepalive_interval, tcp_keepalive_probes and_tcp_keepalive_time_. These settings can also be set on the operating system level, as described .

As of MaxScale 6.4.16, 22.08.13, 23.02.10, 23.08.6 and 24.02.2, configuring TCP keepalive is no longer necessary as monitor sets the session wait_timeout variable when acquiring a lock. This causes the MariaDB Server to close the monitor connection if the connection appears idle for too long. The value of_wait_timeout_ used depends on the monitor interval and connection timeout settings, and is logged at MaxScale startup.

A monitor can also be ordered to manually release its locks via the module command release-locks. This is useful for manually changing the primary monitor. After running the release-command, the monitor will not attempt to reacquire the locks for one minute, even if it wasn't the primary monitor to begin with. This command can cause the cluster to become temporarily unusable by MaxScale. Only use it when there is another monitor ready to claim the locks.

hashtag
Primary server write test

Some backend failures are not observable just by connecting to the server and running standard monitor queries. A server may be connectable and respond to queries sent by the monitor, but its disk could be full or malfunctioning or the storage engine could be locked in some way. Normally, MariaDB Monitor would consider such a server to be in good health, even if in reality the server could not perform any writes.

To detect such errors, MariaDB Monitor can be configured to perform a regular write test if the gtid_binlog_pos of the primary server is not advancing otherwise. Testing that writes are going through and are being saved to the binary log increases the chance of detecting storage failures. The monitor can also be configured to perform a failover if the primary server fails the write test. Even this test may miss storage issues, as the monitor write test performs a small insert that may go through even when a large write done by a real application does not.

See the following configuration parameters for more information on how to configure this feature.

hashtag
Settings for Primary server write test

write_test_interval

  • Type:

  • Dynamic: Yes

  • Default: 0s

If enabled (value > 0s), the monitor will perform a write test on the primary server if its gtid_binlog_pos has not changed within the configured interval. This test inserts one row to the table configured in . If the insert fails or does not complete within , the server fails the write test. What happens after that depends on .

write_test_table

  • Type: string

  • Dynamic: Yes

  • Default: mxs.maxscale_write_test

The write test target table. The table name should be fully qualified i.e. include the database name. If the table does not exist or does not contain expected columns, the monitor (re)creates it. The table is created with a query like

The database must be created manually. The monitor user requires privileges to create, drop, read and manipulate the table:

write_test_fail_action

  • Type:

  • Default: log

  • Values: log, failover

Which action to take if primary server fails the write test. log means that MaxScale will simply log the failure but perform no other action. This is mainly useful for testing the feature.

If set to failover, the monitor will perform a failover if the primary server fails the write test consecutive times. That is, the first write test is performed after write_test_interval has passed without writes. If the test fails, the monitor will repeat the test during the next monitor tick. After failcount monitor ticks with failed write tests, failover begins. After failover, the former primary server is set into maintenance mode. Manual intervention is required to take the server into use again.

hashtag
Backup operations

Backup operations manipulate the contents of a MariaDB Server, saving it or overwriting it. MariaDB-Monitor supports three backup operations:

  1. rebuild-server: Replace the contents of a database server with the contents of another.

  2. create-backup: Copy the contents of a database server to a storage location.

  3. restore-from-backup: Overwrite the contents of a database server with a backup.

These operations do not modify server config files, only files in the data directory (typically /var/lib/mysql) are affected.

All of these operations are monitor commands and best launched with MaxCtrl. The operations are asynchronous, which means MaxCtrl won't wait for the operation to complete and instead immediately returns "OK". To see the current status of an operation, either check MaxScale log or use the fetch-cmd-result-command (e.g. maxctrl call command mariadbmon fetch-cmd-result MyMonitor).

To perform backup operations, MaxScale requires ssh-access on all affected machines. The ssh_user and ssh_keyfile-settings define the SSH credentials MaxScale uses to access the servers. MaxScale must be able to run commands with_sudo_ on both the source and target servers. See and below for more information.

The following tools need to be installed on the backends:

  1. mariadb-backup. Backs up and restores MariaDB Server contents. Installed e.g. with yum install MariaDB-backup. See for more information.

  2. pigz. Compresses and decompresses the backup stream. Installed e.g. withyum install pigz.

  3. socat. Streams data from one machine to another. Is likely already installed. If not, can be installed e.g. with yum install socat

mariadb-backup needs server credentials to log in and authenticate to the MariaDB Server being copied from. For this, MaxScale uses the monitor user. The monitor user may thus require additional privileges. See for more details.

hashtag
Rebuild server

The rebuild server-operation replaces the contents of a database server with the contents of another server. The source server is effectively cloned and all data on the target server is lost. This is useful when a replica server has diverged from the primary server, or when adding a new server to the cluster. MaxScale performs this operation by running mariadb-backup on both the source and target servers.

When launched, the rebuild operation proceeds as below. If any step fails, the operation is stopped and the target server will be left in an unspecified state.

  1. Log in to both servers with ssh and check that the tools listed above are present (e.g. mariadb-backup -v should succeed).

  2. Check that the port used for transferring the backup is free on the source server. If not, kill the process holding it. This requires running lsof and kill.

  3. Test the connection by streaming a short message from the source host to the target.

The rebuild-operation is a monitor module command and takes four arguments:

  1. Monitor name, e.g. MyMonitor.

  2. Target server name, e.g. MyTargetServer.

  3. Source server name, e.g. MySourceServer. This parameter is optional. If not specified, the monitor prefers to autoselect an up-to-date replica server to avoid increasing load on the primary server. Due to the--safe-slave-backup-option, the replica will stop replicating until the backup data has been transferred.

The following example rebuilds MyTargetServer with contents of MySourceServer.

The following example uses a custom data directory on the target.

The operation does not launch if the target server is already replicating or if the source server is not a primary or replica.

Steps 6 and 8 can take a long time depending on the size of the database and if writes are ongoing. During these steps, the monitor will continue monitoring the cluster normally. After each monitor tick the monitor checks if the rebuild-operation can proceed. No other monitor operations, either manual or automatic, can run until the rebuild completes.

hashtag
Create backup

The create backup-operation copies the contents of a database server to the backup storage. The source server is not modified but may slow down during backup creation. MaxScale performs this operation by running mariadb-backup on both the source and storage servers. The storage location is defined by the backup_storage_address and backup_storage_path settings. Normal ssh-settings are used to access the storage server. The backup storage machine does not need to have a MariaDB Server installed.

Backup creation runs somewhat similar to rebuild-server. The main difference is that the backup data is simply saved to a directory and not prepared or used to start a MariaDB Server. If any step fails, the operation is stopped and the backup storage directory will be left in an unspecified state.

  1. Init. See rebuild-server.

  2. Check listen port on backup storage machine. See rebuild-server.

  3. Check that the backup storage main directory exists. Check that it does not contain a backup with the same name as the one being created. Create the final backup directory.

Backup creation is a monitor module command and takes three arguments: the monitor name, source server name and backup name. Backup name defines the subdirectory where the backup is saved and should be a valid directory name. The command

would save the backup of MySourceServer to<backup_storage_path>/wednesday_161122 on the host defined inbackup_storage_address. ssh_user needs to have read and write access to the main storage directory. The source server must be a primary or replica.

Similar to rebuild-server, the monitor will continue monitoring the servers while the backup is transferred.

hashtag
Restore from backup

The restore-operation is the reverse of create-backup. It overwrites the contents of an existing MariaDB Server with a backup from the backup storage. The backup is not removed and can be used again. MaxScale performs this operation by transferring the backup contents as a tar archive and overwriting the target server data directory. The backup storage is defined in monitor settings similar to create-backup.

The restore-operation runs somewhat similar to rebuild-server. The main difference is that the backup data is copied with tar instead of mariadb-backup. If any step fails, the operation is stopped and the target server will be left in an unspecified state.

  1. Init. See rebuild-server.

  2. Check listen port on target machine. See rebuild-server.

  3. Check that the backup storage main directory exists and that it contains a backup with the name requested.

  4. Test the connection by streaming a short message from the backup storage to the target machine.

Server restoration is a monitor module command and takes four arguments.

  1. Monitor name, e.g. MyMonitor.

  2. Target server name, e.g. MyNewServer.

  3. Backup name. This parameter defines the subdirectory where the backup is read from and should be an existing directory on the backup storage host.

  4. Data directory on target server. This parameter is optional. If not specified, the monitor will ask the target server. If target server is not running, monitor will assume /var/lib/mysql. Thus, this only needs to be defined with non-standard directory setups.

The command

would erase the contents of MyTargetServer and replace them with the backup contained in<backup_storage_path>/wednesday_161122 on the host defined inbackup_storage_address. ssh_user needs to have read access to the main storage directory and the backup. The target server must not be a primary or replica.

The following example uses a custom data directory on the target.

Similar to rebuild-server, the monitor will continue monitoring the servers while the backup is transferred and prepared.

hashtag
Settings for Backup operations

ssh_user

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

Ssh username. Used when logging in to backend servers to run commands.

ssh_keyfile

  • Type: path

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

Path to file with an ssh private key. Used when logging in to backend servers to run commands.

ssh_check_host_key

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: true

Boolean, default: true. When logging in to backends, require that the server is already listed in the known_hosts-file of the user running MaxScale.

ssh_timeout

  • Type:

  • Mandatory: No

  • Dynamic: Yes

  • Default: 10s

The rebuild operation consists of multiple ssh commands. Most of the commands are assumed to complete quickly. If these commands take more than ssh_timeout to complete, the operation fails. Adjust this setting if rebuild fails due to ssh commands timing out. This setting does not affect steps 5 and 6, as these are assumed to take significant time.

ssh_port

  • Type: number

  • Mandatory: No

  • Dynamic: Yes

  • Default: 22

SSH port. Used for running remote commands on servers.

rebuild_port

  • Type: number

  • Mandatory: No

  • Dynamic: Yes

  • Default: 4444

The port which the source server listens on for a connection. The port must not be blocked by a firewall or listened on by any other program. If another process is listening on the port when rebuild is starting, MaxScale will attempt to kill the process.

mariadb-backup_use_memory

String, default: "1G". Given as is tomariadb-backup --prepare --use-memory=<mariadb-backup_use_memory>. If set to empty, no --use-memory is set and mariadb-backup will use its internal default. See for more information.

mariadb-backup_parallel

Numeric, default: 1. Given as is tomariadb-backup --backup --parallel=<val>. Defines the number of threads used for parallel data file transfer. See for more information.

backup_storage_address

  • Type: string

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

Address of the backup storage. Does not need to have MariaDB Server running or be monitored by the monitor. Connected to with ssh. Must have enough disk space to store all backups.

backup_storage_path

  • Type: path

  • Mandatory: No

  • Dynamic: Yes

  • Default: None

Path to main backup storage directory on backup storage host. ssh_user needs to have full access to this directory to save and read backups.

hashtag
sudoers.d configuration

If giving MaxScale general sudo-access is out of the question, MaxScale must be allowed to run the specific commands required by the backup operations. This can be achieved by creating a file with the commands in the/etc/sudoers.d-directory. In the example below, the user johnny is given the power to run commands as root. The contents of the file may need to be tweaked due to changes in install locations.

hashtag
ColumnStore commands

Since MaxScale version 22.08, MariaDB Monitor can run ColumnStore administrative commands against a ColumnStore cluster. The commands interact with the ColumnStore REST-API present in recent ColumnStore versions and have been tested with MariaDB-Server 10.6 running the ColumnStore plugin version 6.2. None of the commands affect monitor configuration or replication topology. MariaDB Monitor simply relays the commands to the backend cluster.

MariaDB Monitor can fetch cluster status, add and remove nodes, start and stop the cluster, and set cluster read-only or readwrite. MaxScale only communicates with the first server in the servers-list.

Most of the commands are asynchronous, i.e. they do not wait for the operation to complete on the ColumnStore backend before returning to the command prompt. MariaDB Monitor itself, however, runs the command in the background and does not perform normal monitoring until the operation completes or fails. After an operation has started the user should use fetch-cmd-result to check its status. The examples below show how to run the commands using MaxCtrl. If a command takes a timeout-parameter, the timeout can be given in seconds (s), minutes (m) or hours (h).

ColumnStore command settings are listed . At leastcs_admin_api_key must be set.

hashtag
Get status

Fetch cluster status. Returns the result as is. Status fetching has an automatic timeout of ten seconds.

Examples:

hashtag
Add or remove node

Add or remove a node to/from the ColumnStore cluster.

<node-host> is the hostname or IP of the node being added or removed.

Examples:

hashtag
Start and stop cluster

Examples:

hashtag
Set read-only or readwrite

Examples:

hashtag
Settings for Columnstore commands

cs_admin_port

Numeric, default: 8640. The REST-API port on the ColumnStore nodes. All nodes are assumed to listen on the same port.

cs_admin_api_key

String. The API-key MaxScale sends to the ColumnStore nodes when making a REST-API request. Should match the value configured on the ColumnStore nodes.

cs_admin_base_path

String, default: /cmapi/0.4.0. Base path sent with the REST-API request.

hashtag
Other commands

hashtag
fetch-cmd-result

Fetches the result of the last manual command. Requires monitor name as parameter. Most commands only return a generic success message or an error description. ColumnStore commands may return more data. Scheduling another command clears a stored result.

hashtag
cancel-cmd

Cancels the latest operation, whether manual or automatic, if possible. Requires monitor name as parameter. A scheduled manual command is simply canceled before it can run. If a command is already running, it stops as soon as possible. The cancel-cmd itself does not wait for a running operation to stop. Use fetch-cmd-result or check the log to see if the operation has truly completed. Canceling is most useful for stopping a stalled rebuild operation.

hashtag
Troubleshooting

hashtag
Failover/switchover fails

See the .

Before performing failover or switchover, the monitor checks that prerequisites are fulfilled, printing any errors and warnings found. This should catch and explain most issues with failover or switchover not working. If the operations are attempted and still fail, then most likely one of the commands the monitor issued to a server failed or timed out. The log should explain which query failed.

A typical failure reason is that a command such as STOP SLAVE takes longer than thebackend_read_timeout of the monitor, causing the connection to break. As of 2.3, the monitor will retry most such queries if the failure was caused by a timeout. The retrying continues until the total time for a failover or switchover has been spent. If the log shows warnings or errors about commands timing out, increasing the backend timeout settings of the monitor should help. Other settings to look at are query_retries andquery_retry_timeout. These are general MaxScale settings described in the . Settingquery_retries to 2 is a reasonable first try.

If switchover causes the old primary (now replica) to fail replication, then most likely a user or perhaps a scheduled event performed a write while monitor had set read_only=1. This is possible if the user performing the write has "SUPER" or "READ_ONLY ADMIN" privileges. The switchover-operation tries to kick out SUPER-users but this is not certain to succeed. Remove these privileges from any users that regularly do writes to prevent them from interfering with switchover.

The server configuration files should have log-slave-updates=1 to ensure that a newly promoted primary has binary logs of previous events. This allows the new primary to replicate past events to any lagging replicas.

To print out all queries sent to the servers, start MaxScale with--debug=enable-statement-logging. This setting prints all queries sent to the backends by monitors and authenticators. The printed queries may include usernames and passwords.

hashtag
Replica detection shows external primaries

If a replica is shown in maxctrl as "Slave of External Server" instead of "Slave", the reason is likely that the "Master_Host"-setting of the replication connection does not match the MaxScale server definition. As of 2.3.2, the MariaDB Monitor by default assumes that the replica connections (as shown by SHOW ALL SLAVES STATUS) use the exact same "Master_Host" as used the MaxScale configuration file server definitions. This is controlled by the setting .

hashtag
Using the MariaDB Monitor With Binlogrouter

Since MaxScale 2.2 it's possible to detect a replication setup which includes Binlog Server: the required action is to add the binlog server to the list of servers only if master_id identity is set.

This page is licensed: CC BY-SA / Gnu FDL

MaxScale 25.01 Getting-Started

MaxScale 25.01 Monitors

spinner
spinner

MariaDB MaxScale 25.01 REST API

Manage MariaDB MaxScale programmatically using the REST API. This interface allows for the dynamic administration and monitoring of MaxScale resources like servers, services, and listeners.

MariaDB MaxScale 25.01 Authenticators

Secure your MariaDB MaxScale deployment with authenticators. These modules manage client authentication with backend servers, supporting diverse mechanisms for enhanced security.

$NODELIST -> list of IPs and ports of all running servers

  • $SLAVELIST -> list of IPs and ports of all replica servers

  • $MASTERLIST -> list of IPs and ports of all primary servers

  • $SYNCEDLIST -> list of IPs and ports of all synced Galera nodes

  • $PARENT -> IP and port of the parent of the server which initiated the event. For primary-replica setups, this will be the primary if the initiating server is a replica.

  • $CHILDREN -> list of IPs and ports of the child nodes of the server who initiated the event. For primary-replica setups, this will be a list of replica servers if the initiating server is a primary.

  • ,
    master_up
    ,
    slave_down
    ,
    slave_up
    ,
    server_down
    ,
    server_up
    ,
    lost_master
    ,
    lost_slave
    ,
    new_master
    ,
    new_slave
  • Default: All events

  • A Replica server has come up

    server_down

    A server with no assigned role has gone down

    server_up

    A server with no assigned role has come up

    lost_master

    A server lost Primary status

    lost_slave

    A server lost Replica status

    new_master

    A new Primary was detected

    new_slave

    A new Replica was detected

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    #!/usr/bin/env bash

    master_down

    A Primary server has gone down

    master_up

    A Primary server has come up

    slave_down

    A Replica server has gone down

    1

    2

    3

    4

    module
    user
    password
    servers
    monitor_interval
    backend_connect_timeout
    backend_write_timeout
    backend_read_timeout
    backend_connect_attempts
    disk_space_threshold
    disk_space_check_interval
    script
    script_timeout
    events
    journal_max_age
    Monitor Crash Safety
    Script example
    duration
    here
    duration
    here
    duration
    here
    duration
    here
    server parameter
    duration
    here
    Script example
    duration
    here
    duration
    here
    spinner

    slave_up

    5

    servers=MyServer1,MyServer2
    monitor_interval=2s
    backend_connect_timeout=3s
    backend_write_timeout=3s
    backend_read_timeout=3s
    backend_connect_attempts=1
    [server1]
    type=server
    ...
    
    [server2]
    type=server
    ...
    
    [server3]
    type=server
    ...
    
    [monitor]
    type=monitor
    servers=server1,server2,server3
    disk_space_threshold=/data:80
    ...
    [server1]
    type=server
    disk_space_threshold=/data:80
    ...
    
    [server2]
    type=server
    disk_space_threshold=/Data:80
    ...
    
    [server3]
    type=server
    disk_space_threshold=/DBData:80
    ...
    
    [monitor]
    type=monitor
    servers=server1,server2,server3
    ...
    [server1]
    type=server
    disk_space_threshold=/DbData:80
    ...
    
    [server2]
    type=server
    ...
    
    [server3]
    type=server
    ...
    
    [monitor]
    type=monitor
    servers=server1,server2,server3
    disk_space_threshold=/data:80
    ...
    script=/home/user/myscript.sh initiator=$INITIATOR event=$EVENT live_nodes=$NODELIST
    /home/user/myscript.sh initiator=[192.168.0.10]:3306 event=master_down live_nodes=[192.168.0.201]:3306,[192.168.0.121]:3306
    events=master_down,slave_down
    [MyMonitor]
    type=monitor
    module=mariadbmon
    servers=C1N1,C1N2,C1N3
    user=maxscale
    password=password
    monitor_interval=10s
    script=/path/to/maxscale_monitor_alert_script.sh --initiator=$INITIATOR --parent=$PARENT --children=$CHILDREN --event=$EVENT --node_list=$NODELIST --list=$LIST --master_list=$MASTERLIST --slave_list=$SLAVELIST --synced_list=$SYNCEDLIST
    It was previously part of a multiprimary group but is no longer, or the multiprimary group is replicating from a server not in the group.
    ,
    connecting_slave
    ,
    connected_slave
    ,
    running_slave
    ,
    primary_monitor_master
    ,
    disk_space_ok
  • Default: primary_monitor_master, disk_space_ok

  • running_slave : Same as connecting_slave, with the addition that the replica must also be Running.

  • primary_monitor_master : If this MaxScale is cooperating with another MaxScale and this is the secondary MaxScale, require that the candidate primary is selected also by the primary MaxScale.

  • disk_space_ok : The candidate primary must not be low on disk space. This option only takes effect if disk space check is enabled. Added in MaxScale 23.08.5.

  • ,
    linked_master
    ,
    running_master
    ,
    writable_master
    ,
    primary_monitor_master
  • Default: none

  • writable_master : The primary must be writable, i.e. labeled Master.
  • primary_monitor_master : If this MaxScale is cooperating with another MaxScale and this is the secondary MaxScale, require that the candidate primary is selected also by the primary MaxScale.

  • disk_space_ok : The replica must not be low on disk space. This option only takes effect if disk space check is enabled. Added in MaxScale 23.08.5.

  • ,
    majority_of_all
    ,
    majority_of_running
  • Default: none

  • switchover-force, which swaps a running primary with a replica, ignoring most errors. Can break replication.
  • async-switchover, which schedules a switchover and returns

  • rejoin, which directs servers to replicate from the primary

  • reset-replication (added in MaxScale 2.3.0), which deletes binary logs and resets gtid:s

  • PROCESS, to check if the event_scheduler process is running
  • SHOW DATABASES and EVENT, to list and modify server events

  • SELECT on mysql.user, to see which users have SUPER

  • SELECT on mysql.global_priv so see to see which users have READ_ONLY ADMIN

  • SHOW DATABASES, EVENT and SET USER, to list and modify server events

  • BINLOG ADMIN, to delete binary logs (during reset-replication)

  • CONNECTION ADMIN, to kill connections

  • SELECT on mysql.user, to see which users have SUPER

  • SELECT on mysql.global_priv so see to see which users have READ_ONLY ADMIN

  • disk space is not low

  • If the new primary has unprocessed relay log items, cancel and try again later.

  • Prepare the new primary:

  • Remove the replica connection the new primary used to replicate from the old primary.

  • Disable the read_only-flag.

  • Enable scheduled server events (if event handling is on). Only events that were enabled on the old primary are enabled.

  • Run the commands in promotion_sql_file.

  • Start replication from external primary if one existed.

  • Redirect all other replicas to replicate from the new primary:

  • STOP SLAVE

  • CHANGE MASTER TO

  • START SLAVE

  • Check that all replicas are replicating.

  • Enable the read_only-flag to stop writes from normal users.
  • Kill connections from super and read-only admin users since read_only does not affect them. During this step, all writes are blocked with "FLUSH TABLES WITH READ LOCK".

  • Disable scheduled server events (if event handling is on).

  • Run the commands in demotion_sql_file.

  • Flush the binary log ("flush logs") so that all events are on disk.

  • Wait a moment to check that gtid is stable.

  • Wait for the new primary to catch up with the old primary.

  • Promote new primary and redirect replicas as in failover steps 3 and 4. Also redirect the demoted old primary.

  • Check that all replicas are replicating.

  • Start replication: CHANGE MASTER TO and START SLAVE.

    Delete binary logs (RESET MASTER).

  • Set the sequence number of gtid_slave_pos to zero. This also affects gtid_current_pos.

  • Prepare new primary:

  • Disable the read_only-flag.

  • Enable scheduled server events (if event handling is on). Events are only enabled if the cluster had a primary server when starting the reset-replication operation. Only events that were enabled on the previous primary are enabled on the new.

  • Direct other servers to replicate from the new primary as in the other operations.

  • are server names as described above for MaxCtrl. Only switchover accepts both, failover doesn't need any and both rejoin and reset-replication accept one.

    Which server to promote

    old_primary

    server

    empty (autoselect)

    Which server to demote

    async

    boolean

    false

    Run command asynchronously

    force

    boolean

    false

    Ignore most errors

    old_primary_maint

    boolean

    false

    Leave old primary to maintenance

    ,
    on
    ,
    yes
    ,
    1
    ,
    false
    ,
    off
    ,
    no
    ,
    0
    ,
    safe
  • Default: false

  • Dynamic: Yes

    .

    Launch mariadb-backup on the source machine, compress the stream and listen for an incoming connection. This is performed with a command likemariadb-backup --backup --safe-slave-backup --stream=xbstream --parallel=1 | pigz -c | socat - TCP-LISTEN:<port>.

  • Ask the target server what its data directory is (select @@datadir;). Stop MariaDB Server on the target machine and delete all contents of the data directory.

  • On the target machine, connect to the source machine, read the backup stream, decompress it and write to the data directory. This is performed with a command like socat -u TCP:<host>:<port> STDOUT | pigz -dc | mbstream -x. This step can take a long time if there is much data to transfer.

  • Check that the data directory on the target machine is not empty, i.e. that the transfer at least appears to have succeeded.

  • Prepare the backup on the target server with a command likemariadb-backup --use-memory=1G --prepare. This step can also take some time if the source server performed writes during data transfer.

  • On the target server, change ownership of datadir contents to the mysql-user and start MariaDB-server.

  • Read gtid from the data directory. Have the target server start replicating from the primary if it is not one already.

  • Data directory on target server. This parameter is optional. If not specified, the monitor will ask the target server. If target server is not running, monitor will assume /var/lib/mysql. Thus, this only needs to be defined with non-standard directory setups.

    Test the connection by streaming a short message from the source host to the backup storage.
  • Serve backup on source. Similar to rebuild-server step 4.

  • Transfer backup directly to the final storage directory. Similar to rebuild-server step 5.

  • Check that the copied backup data looks ok.

  • On the backup storage machine, compress the backup with tar and serve it with socat, listening for an incoming connection. This is performed with a command like tar -zc -C <backup_dir> . | socat - TCP-LISTEN:<port>.

  • Ask the target server what its data directory is (select @@datadir;). Stop MariaDB Server on the target machine and delete all contents of the data directory.

  • On the target machine, connect to the source machine, read the backup stream, decompress it and write to the data directory. This is performed with a command like socat -u TCP:<host>:<port> STDOUT | sudo tar -xz -C /var/lib/mysql/. This step can take a long time if there is much data to transfer.

  • From here on, the operation proceeds as from rebuild-server step 7.

  • CREATE USER 'maxscale'@'maxscalehost' IDENTIFIED BY 'maxscale-password';
    GRANT REPLICATION CLIENT ON *.* TO 'maxscale'@'maxscalehost';
    GRANT REPLICATION SLAVE ADMIN ON *.* TO 'maxscale'@'maxscalehost';
    GRANT REPLICA MONITOR ON *.* TO 'maxscale'@'maxscalehost';
    GRANT FILE ON *.* TO 'maxscale'@'maxscalehost';
    GRANT CONNECTION ADMIN ON *.* TO 'maxscale'@'maxscalehost';
    GRANT SUPER, RELOAD, PROCESS, SHOW DATABASES, EVENT ON *.* TO 'maxscale'@'maxscalehost';
    GRANT SELECT ON mysql.user TO 'maxscale'@'maxscalehost';
    GRANT SELECT ON mysql.global_priv TO 'maxscale'@'maxscalehost';
    GRANT RELOAD, PROCESS, SHOW DATABASES, EVENT, SET USER, READ_ONLY ADMIN ON *.* TO 'maxscale'@'maxscalehost';
    GRANT REPLICATION SLAVE ADMIN, BINLOG ADMIN, CONNECTION ADMIN ON *.* TO 'maxscale'@'maxscalehost';
    GRANT SELECT ON mysql.user TO 'maxscale'@'maxscalehost';
    GRANT SELECT ON mysql.global_priv TO 'maxscale'@'maxscalehost';
    CREATE USER 'replication'@'replicationhost' IDENTIFIED BY 'replication-password';
    GRANT REPLICATION SLAVE ON *.* TO 'replication'@'replicationhost';
    [MyMonitor]
    type=monitor
    module=mariadbmon
    servers=server1,server2,server3
    user=myuser
    password=mypwd
    master_conditions=connected_slave,running_slave
    slave_conditions=running_master,writable_master
    (monitor_interval + backend_connect_timeout) * failcount
    maxctrl clear server server2 Maint
    call command mariadbmon failover MONITOR
    call command mariadbmon failover-safe MONITOR
    call command mariadbmon switchover MONITOR [NEW_PRIMARY] [OLD_PRIMARY]
    call command mariadbmon switchover-force MONITOR [NEW_PRIMARY] [OLD_PRIMARY]
    call command mariadbmon rejoin MONITOR OLD_PRIMARY
    maxctrl call command mariadbmon reset-replication MONITOR [NEW_PRIMARY]
    maxctrl call command mariadbmon failover MyMonitor
    maxctrl call command mariadbmon failover-safe MyMonitor
    maxctrl call command mariadbmon rejoin MyMonitor OldPrimaryServ
    maxctrl call command mariadbmon reset-replication MyMonitor
    maxctrl call command mariadbmon reset-replication MyMonitor NewPrimaryServ
    maxctrl call command mariadbmon switchover MyMonitor
    maxctrl call command mariadbmon switchover MyMonitor NewPrimaryServ
    maxctrl call command mariadbmon switchover MyMonitor NewPrimaryServ OldPrimaryServ
    maxctrl call command mariadbmon switchover-force MyMonitor NewPrimaryServ
    /v1/maxscale/modules/mariadbmon/<operation>?<monitor-name>&<server-name1>&<server-name2>
    [Cluster1]
    type=monitor
    module=mariadbmon
    servers=server1, server2, server3, server 4
    ...
    /v1/maxscale/modules/mariadbmon/switchover?Cluster1&server4&server2
    /v1/maxscale/modules/mariadbmon/failover?Cluster1
    /v1/maxscale/modules/mariadbmon/rejoin?Cluster1&server3
    /v1/maxscale/modules/mariadbmon/reset-replication?Cluster1&server3
    maxctrl call command mariadbmon async-switchover Cluster1
    OK
    maxctrl call command mariadbmon fetch-cmd-result Cluster1
    {
        "links": {
            "self": "http://localhost:8989/v1/maxscale/modules/mariadbmon/fetch-cmd-result"
        },
        "meta": "switchover completed successfully."
    }

    monitor

    monitor

    none (mandatory)

    Monitor name

    new_primary

    server

    maxctrl call command mariadbmon switchover monitor=MyMonitor new_primary=MyServer2 async=1 force=1
    maxctrl call command mariadbmon switchover monitor=MyMonitor old_primary_maint=1
    switchover_on_low_disk_space=true
    enforce_simple_topology=true
    replication_custom_options=MASTER_SSL_CERT = '/tmp/certs/client-cert.pem',
                               MASTER_SSL_KEY = '/tmp/certs/client-key.pem',
                               MASTER_SSL_CA = '/tmp/certs/ca.pem',
                               MASTER_SSL_VERIFY_SERVER_CERT=0
    servers_no_promotion=backup_dc_server1,backup_dc_server2
    promotion_sql_file=/home/root/scripts/promotion.sql
    demotion_sql_file=/home/root/scripts/demotion.sql
    maxctrl call command mariadbmon release-locks MyMonitor1
    write_test_interval=20s
    CREATE OR REPLACE TABLE mxs.maxscale_write_test
    (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
    `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `gtid` TEXT NULL);
    GRANT SELECT, INSERT, DELETE, CREATE, DROP ON `mxs`.* TO 'maxscale'@'maxscalehost';
    write_test_table=mxs.my_write_test_table
    maxctrl call command mariadbmon async-rebuild-server MyMonitor MyTargetServer MySourceServer
    maxctrl call command mariadbmon async-rebuild-server MyMonitor MyTargetServer MySourceServer /my_datadir
    maxctrl call command mariadbmon async-create-backup MyMonitor MySourceServer wednesday_161122
    maxctrl call command mariadbmon async-restore-from-backup MyMonitor MyTargetServer wednesday_161122
    maxctrl call command mariadbmon async-restore-from-backup MyMonitor MyTargetServer wednesday_161122 /my_datadir
    mariadb-backup_use_memory=2G
    mariadb-backup_parallel=2
    backup_storage_address=192.168.1.11
    backup_storage_path=/home/maxscale_ssh_user/backup_storage
    johnny ALL= NOPASSWD: /bin/systemctl stop mariadb
    johnny ALL= NOPASSWD: /bin/systemctl start mariadb
    johnny ALL= NOPASSWD: /usr/sbin/lsof
    johnny ALL= NOPASSWD: /bin/kill
    johnny ALL= NOPASSWD: /usr/bin/mariadb-backup
    johnny ALL= NOPASSWD: /bin/mbstream
    johnny ALL= NOPASSWD: /bin/rm -rf /var/lib/mysql/*
    johnny ALL= NOPASSWD: /bin/chown -R mysql\:mysql /var/lib/mysql
    johnny ALL= NOPASSWD: /bin/cat /var/lib/mysql/xtrabackup_binlog_info
    johnny ALL= NOPASSWD: /bin/tar -xz -C /var/lib/mysql/
    maxctrl call command mariadbmon cs-get-status <monitor-name>
    maxctrl call command mariadbmon async-cs-get-status <monitor-name>
    maxctrl call command mariadbmon cs-get-status MyMonitor
    {
        "mcs1": {
            "cluster_mode": "readwrite",
            "dbrm_mode": "master",
    <snip>
    
    maxctrl call command mariadbmon async-cs-get-status MyMonitor
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "mcs1": {
            "cluster_mode": "readwrite",
            "dbrm_mode": "master",
    <snip>
    maxctrl call command mariadbmon async-cs-add-node <monitor-name> <node-host> <timeout>
    maxctrl call command mariadbmon async-cs-remove-node <monitor-name> <node-host> <timeout>
    maxctrl call command mariadbmon async-cs-add-node MyMonitor mcs3 1m
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "node_id": "mcs3",
        "timestamp": "2022-05-05 08:07:51.518268"
    }
    maxctrl call command mariadbmon async-cs-remove-node MyMonitor mcs3 1m
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "node_id": "mcs3",
        "timestamp": "2022-05-05 10:46:46.506947"
    }
    maxctrl call command mariadbmon async-cs-start-cluster <monitor-name> <timeout>
    maxctrl call command mariadbmon async-cs-stop-cluster <monitor-name> <timeout>
    maxctrl call command mariadbmon async-cs-start-cluster MyMonitor 1m
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "timestamp": "2022-05-05 09:41:57.140732"
    }
    maxctrl call command mariadbmon async-cs-stop-cluster MyMonitor 1m
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "mcs1": {
            "timestamp": "2022-05-05 09:45:33.779837"
        },
    <snip>
    maxctrl call command mariadbmon async-cs-set-readonly <monitor-name> <timeout>
    maxctrl call command mariadbmon async-cs-set-readwrite <monitor-name> <timeout>
    maxctrl call command mariadbmon async-cs-set-readonly MyMonitor 30s
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "cluster-mode": "readonly",
        "timestamp": "2022-05-05 09:49:18.365444"
    }
    maxctrl call command mariadbmon async-cs-set-readwrite MyMonitor 30s
    OK
    maxctrl call command mariadbmon fetch-cmd-result MyMonitor
    {
        "cluster-mode": "readwrite",
        "timestamp": "2022-05-05 09:50:30.718972"
    }
    cs_admin_port=8641
    cs_admin_api_key=somekey123
    maxctrl call command mariadbmon fetch-cmd-result MariaDB-Monitor
    "switchover completed successfully."
    maxctrl call command mariadbmon cancel-cmd MariaDB-Monitor
    OK
    cluster manipulation operations
    Failover, switchover and auto-rejoin
    Required Grants
    Monitor Common
    section
    Rebuild server-section
    ColumnStore commands-section
    boolean
    private_address
    enum_mask
    Primary selection
    enum_mask
    Primary selection
    boolean
    boolean
    master_conditions
    boolean
    enforce_read_only_slaves
    boolean
    disk_space_threshold
    disk_space_check_interval
    enum
    Cooperative monitoring
    general monitor documentationarrow-up-right
    failover
    failover-safe
    switchover
    operation details
    Required Grants
    Manual activation
    Limitations and requirements
    enum
    safe failover
    failcount
    passive
    here
    boolean
    enforce_simple_topology
    auto_failover
    limitations
    boolean
    server
    monitor
    disk_space_check_interval
    boolean
    replication_user
    boolean
    duration
    duration
    boolean
    master_failure_timeout
    here
    duration
    here
    promotion_sql_file
    boolean
    cooperative_monitoring_locks
    herearrow-up-right
    duration
    write_test_table
    backend_read_timeout
    write_test_fail_action
    enum
    failcount
    settings
    sudoers.d configuration
    mariadb-backup documentationarrow-up-right
    mariadb-backup documentationarrow-up-right
    boolean
    duration
    herearrow-up-right
    herearrow-up-right
    here
    Limitations and requirements-section
    Configuration guide
    assume_unique_hostnames
    spinner

    empty (autoselect)

    CREATE USER 'maxscale'@'%' IDENTIFIED BY 'maxscale_pw';
    GRANT SELECT ON mysql.user TO 'maxscale'@'%';
    GRANT SELECT ON mysql.db TO 'maxscale'@'%';
    GRANT SELECT ON mysql.tables_priv TO 'maxscale'@'%';
    GRANT SELECT ON mysql.columns_priv TO 'maxscale'@'%';
    GRANT SELECT ON mysql.procs_priv TO 'maxscale'@'%';
    GRANT SELECT ON mysql.proxies_priv TO 'maxscale'@'%';
    GRANT SELECT ON mysql.roles_mapping TO 'maxscale'@'%';
    GRANT SHOW DATABASES ON *.* TO 'maxscale'@'%';
    CREATE USER 'jdoe'@'maxscale-host' IDENTIFIED BY 'my_secret_password';
    MariaDB [(none)]> SHOW GRANTS FOR 'jdoe'@'client-host';
    +-----------------------------------------------------------------------+
    | Grants for jdoe@client-host                                           |
    +-----------------------------------------------------------------------+
    | GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO 'jdoe'@'client-host'   |
    +-----------------------------------------------------------------------+
    1 row in set (0.01 sec)
    GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO 'jdoe'@'maxscale-host';
    [maxscale]
    threads=auto
    sudo systemctl start maxscale
    sudo service maxscale start
    % sudo maxctrl list services
    
    ┌──────────────────┬────────────────┬─────────────┬───────────────────┬───────────────────────────┐
    │ Service          │ Router         │ Connections │ Total Connections │ Servers                   │
    ├──────────────────┼────────────────┼─────────────┼───────────────────┼───────────────────────────┤
    │ Splitter-Service │ readwritesplit │ 1           │ 1                 │ dbserv1, dbserv2, dbserv3 │
    └──────────────────┴────────────────┴─────────────┴───────────────────┴───────────────────────────┘
    
    % sudo maxctrl list servers
    
    ┌─────────┬─────────────┬──────┬─────────────┬─────────────────┬───────────┐
    │ Server  │ Address     │ Port │ Connections │ State           │ GTID      │
    ├─────────┼─────────────┼──────┼─────────────┼─────────────────┼───────────┤
    │ dbserv1 │ 192.168.2.1 │ 3306 │ 0           │ Master, Running │ 0-3000-62 │
    ├─────────┼─────────────┼──────┼─────────────┼─────────────────┼───────────┤
    │ dbserv2 │ 192.168.2.2 │ 3306 │ 0           │ Slave, Running  │ 0-3000-62 │
    ├─────────┼─────────────┼──────┼─────────────┼─────────────────┼───────────┤
    │ dbserv3 │ 192.168.2.3 │ 3306 │ 0           │ Slave, Running  │ 0-3000-62 │
    └─────────┴─────────────┴──────┴─────────────┴─────────────────┴───────────┘
    
    % sudo maxctrl list listeners Splitter-Service
    
    ┌───────────────────┬──────┬──────┬─────────┐
    │ Name              │ Port │ Host │ State   │
    ├───────────────────┼──────┼──────┼─────────┤
    │ Splitter-Listener │ 3306 │      │ Running │
    └───────────────────┴──────┴──────┴─────────┘
    Installation Guide
    Configuring Servers
    Configuring MariaDB Monitor
    Configuring Galera Monitor
    Read Write Splitting Tutorial
    Connection Routing Tutorial
    Configuration Guide
    readwritesplit module documentation
    readconnroute module documentation
    REST-API Tutorial
    spinner
    Getting Started With MariaDB Galera Cluster

    MaxScale 25.01 MariaDB/MySQL Authenticator

    hashtag

    hashtag
    MariaDB/MySQL Authenticator

    The MariaDBAuth-module implements the client and backend authentication for the server plugin mysql_native_password. This is the default authentication plugin used by both MariaDB and MySQL.

    hashtag
    Settings

    The following settings may be given in the authenticator_options of the listener.

    hashtag
    clear_pw_passthrough

    Boolean, default value is "false". Activates passthrough-mode. In this mode, MaxScale does not check client credentials at all and defers authentication to the backend server. It may be useful in any situation where MaxScale cannot check the existence of client user account nor authenticate the client.

    When a client connects to a listener with this setting enabled, MaxScale will change authentication method to "mysql_clear_password", causing the client to send their cleartext password to MaxScale. MaxScale will then attempt to use the password to authenticate to backends. The authentication result of the first backend to respond will be sent to the client. The backend may ask MaxScale for either cleartext password or standard ("mysql_native_password") authentication token. MaxScale can work with both backend plugins since it has the original password.

    This feature is incompatible with service setting lazy_connect. Either leave it unspecified or set lazy_connect=false in the linked service. Also, multiple client authenticators are not allowed on the listener when passthrough-mode is on.

    Because passwords are sent in cleartext, the listener should be configured for ssl.

    hashtag
    log_password_mismatch

    • Type:

    • Mandatory: No

    • Dynamic: No

    • Default: false

    The service setting log_auth_warnings must also be enabled for this setting to have effect. When both settings are enabled, password hashes are logged if a client gives a wrong password. This feature may be useful when diagnosing authentication issues. It should only be enabled on a secure system as the logging of password hashes may be a security risk.

    hashtag
    cache_dir

    Deprecated and ignored.

    hashtag
    inject_service_user

    Deprecated and ignored.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 MariaDB Protocol Module

    hashtag
    MariaDB Protocol Module

    The mariadbprotocol module implements the MariaDB client-server protocol.

    The legacy protocol names mysqlclient, mariadb and mariadbclient are all aliases to mariadbprotocol.

    hashtag
    Configuration

    Protocol level parameters are defined in the listeners. They must be defined using the scoped parameter syntax where the protocol name is used as the prefix.

    For the MariaDB protocol module, the prefix is always mariadbprotocol.

    hashtag
    Settings

    hashtag
    allow_replication

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: true

    Whether the use of the replication protocol is allowed through this listener. If disabled with mariadbprotocol.allow_replication=false, all attempts to start replication will be rejected with a ER_FEATURE_DISABLED error (error number 1289).

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Module commands

    hashtag
    Module commands

    Introduced in MaxScale 2.1, the module commands are special, module-specific commands. They allow the modules to expand beyond the capabilities of the module API. Currently, only MaxCtrl implements an interface to the module commands.

    All registered module commands can be shown with maxctrl list commands and they can be executed with maxctrl call command <module> <name> ARGS... whereis the name of the module and is the name of the command.ARGS is a command specific list of arguments.

    hashtag
    Developer reference

    The module command API is defined in the modulecmd.h header. It consists of various functions to register and call module commands. Read the function documentation in the header for more details.

    The following example registers the module command my_command for module_my_module_.

    The array my_args of type modulecmd_arg_type_t is used to tell what kinds of arguments the command expects. The first argument is a boolean and the second argument is an optional string.

    Arguments are passed to the parsing function as an array of void pointers. They are interpreted as the types the command expects.

    When the module command is executed, the argv parameter for the_my_simple_cmd_ contains the parsed arguments received from the caller of the command.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Ed25519 Authenticator

    hashtag
    Ed25519 Authenticator

    MaxScale 25.01 Comment Filter

    hashtag
    Comment Filter

    MaxScale 25.01 Change Data Capture (CDC) users

    hashtag
    Change Data Capture (CDC) users

    Change Data Capture (CDC) is a new MaxScale protocol that allows compatible clients to authenticate and register for Change Data Capture events. The new protocol must be use in conjunction with AVRO router which currently converts MariaDB binlog events into AVRO records. Clients connect to CDC listener and authenticate using credentials provided in a format described in the .

    Note: If no users are found in that file or if it doesn't exist, the only available user will be the service user:

    MariaDB MaxScale 25.01 Connectors

    Explore the connectors available for MariaDB MaxScale 25.01. This section details the MaxScale CDC Connector, a C++ API allowing applications to consume a stream of database change events.

    MariaDB MaxScale 25.01 Filters

    Filters in MariaDB MaxScale intercept and modify database traffic. Use them to transform, block, or log queries, enabling fine-grained control over your database workload and security.

    MariaDB MaxScale 25.01 Monitors

    Monitors are essential for high availability, tracking the status of backend servers. They detect failures, promote replicas, and enable automatic failover, ensuring service continuity.

    MaxScale 25.01 Authenticators

    spinner

    MaxScale 25.01 Connectors

    spinner

    MaxScale 25.01 Hint Syntax

    hashtag
    Hint Syntax

    Refer to the Hintfilter documentation for the MaxScale hint syntax.

    This page is licensed: CC BY-SA / Gnu FDL

    spinner

    MariaDB MaxScale 25.01 Tutorials

    Get hands-on experience with MariaDB MaxScale 25.01. These tutorials provide step-by-step instructions for common tasks like setting up read-write splitting, failover, and sharding.

    MaxScale 25.01 Routers

    Routers are the core of MariaDB MaxScale services, intelligently managing database traffic. This section details available routers, from read-write splitting to sharding and replication.

    boolean
    spinner
    allow_replication
    MariaDB Protocol Module
    Configuration
    Settings
    boolean
    spinner
    spinner
    Overview
  • Settings

    • inject

  • Examples

    • Example 1 - Inject IP address of the connected client into statements

  • hashtag
    Overview

    With the comment filter it is possible to define comments that are injected before the actual statements. These comments appear as sql comments when they are received by the server.

    hashtag
    Settings

    The Comment filter requires one mandatory parameter to be defined.

    hashtag
    inject

    • Type: string

    • Mandatory: Yes

    • Dynamic: Yes

    A parameter that contains the comment injected before the statements. There is also defined variable $IP that can be used to comment the IP address of the client in the injected comment. Variables must be written in all caps.

    hashtag
    Examples

    hashtag
    Example 1 - Inject IP address of the connected client into statements

    as comment.

    The following configuration adds the IP address of the client to the comment.

    In this example when MaxScale receives statement like:

    It would look like

    when received by server.

    This page is licensed: CC BY-SA / Gnu FDL

    Comment Filter
    spinner
    hashtag
    Creating new CDC users

    Starting with MaxScale 2.1, users can also be created through maxctrl:

    The should be the service name where the user is created. Older versions of MaxScale should use the cdc_users.py script.

    The output of this command should be appended to the cdcusers file at/var/lib/maxscale/<service name>/.

    Users can be deleted by removing the related rows in 'cdcusers' file. For more details on the format of the cdcusers file, read the CDC Protocol documentation.

    This page is licensed: CC BY-SA / Gnu FDL

    [avro-service]
    type=service
    router=avrorouter
    source=replication-service
    user=cdc_user
    password=cdc_password
    CDC Protocol documentation
    spinner
    [MyListener]
    type=listener
    authenticator=mariadbauth
    authenticator_options=clear_pw_passthrough=true
    ssl=true
    <other options>
    [MyListener]
    type=listener
    service=MyService
    protocol=mariadbprotocol
    mariadbprotocol.allow_replication=false
    port=3306
    #include <maxscale/modulecmd.hh>
    
    bool my_simple_cmd(const MODULECMD_ARG *argv)
    {
        printf("%d arguments given\n", argv->argc);
    }
    
    int main(int argc, char **argv)
    {
        modulecmd_arg_type_t my_args[] =
        {
            {MODULECMD_ARG_BOOLEAN, "This is a boolean parameter"},
            {MODULECMD_ARG_STRING | MODULECMD_ARG_OPTIONAL, "This is an optional string parameter"}
        };
    
        // Register the command
        modulecmd_register_command("my_module", "my_command", my_simple_cmd, 2, my_args);
    
        // Find the registered command
        const MODULECMD *cmd = modulecmd_find_command("my_module", "my_command");
    
        // Parse the arguments for the command
        const void *arglist[] = {"true", "optional string"};
        MODULECMD_ARG *arg = modulecmd_arg_parse(cmd, arglist, 2);
    
        // Call the module command
        modulecmd_call_command(cmd, arg);
    
        // Free the parsed arguments
        modulecmd_arg_free(arg);
        return 0;
    }
    [MyComment]
    type=filter
    module=comment
    inject="Comment to be injected"
    
    [MyService]
    type=service
    router=readwritesplit
    servers=server1
    user=myuser
    password=mypasswd
    filters=MyComment
    [IPComment]
    type=filter
    module=comment
    inject="IP=$IP"
    
    [MyService]
    type=service
    router=readwritesplit
    servers=server1
    user=myuser
    password=mypasswd
    filters=IPComment
    SELECT user FROM people;
    /* IP=::ffff:127.0.0.1 */SELECT user FROM people;
    maxctrl call command cdc add_user <service> <name> <password>
    bash$ cdc_users.py [-h] USER PASSWORD
    bash$ cdc_users.py user1 pass1 >> /var/lib/maxscale/avro-service/cdcusers
    Configuration
    • ed_mode

    • ed_rsa_privkey_path and ed_rsa_pubkey_path

  • Using a mapping file

  • Using sha256-authentication

  • Ed25519 is a highly secure authentication method based on public key cryptography. It is used with the auth_ed25519-plugin of MariaDB Server.

    When a client authenticates via ed25519, MaxScale first sends them a random message. The client signs the message using their password as private key and sends the signature back. MaxScale then checks the signature using the public key fetched from the mysql.user-table. The client password or an equivalent token is never exposed. For more information, see .

    The security of this authentication scheme presents a problem for a proxy such as MaxScale since MaxScale needs to log in to backend servers on behalf of the client. Since each server will generate their own random messages, MaxScale cannot simply forward the original signature. Either the real password is required, or a different authentication scheme must be used between MaxScale and backends. The MaxScale ed25519auth-plugin supports both alternatives.

    hashtag
    Configuration

    To begin, add "ed25519auth" to the list of authenticators for a listener.

    MaxScale will now authenticate incoming clients with ed25519 if their user account has plugin set to "ed25519" in the mysql.user-table. However, routing queries will fail since MaxScale cannot authenticate to backends. To continue, either use a mapping file or enable sha256-mode. Sha256-mode is enabled with the following settings.

    hashtag
    ed_mode

    This setting defines the authentication mode used. Two values are supported:

    • ed25519 (default) Digital signature based authentication. Requires mapping for backend support.

    • sha256 Authenticate client with caching_sha2_password-plugin instead. Requires either SSL or configured RSA-keys.

    hashtag
    ed_rsa_privkey_path and ed_rsa_pubkey_path

    Defines the RSA-keys used for encrypting the client password if SSL is not in use. Should point to files with the private and public keys.

    hashtag
    Using a mapping file

    To enable MaxScale to authenticate to backends,user mapping can be used. The mapping and backend passwords are given in a json-file. The client can map to an identical username or to another user, and the backend authentication scheme can be something else than ed25519.

    The following example maps user "alpha" to "beta" and MaxScale then uses standard authentication to log into backends as "beta". User "alpha" authenticates to MaxScale using whatever method configured in the server. User "gamma" does not map to another user, just the password is given.

    MaxScale configuration:

    /home/joe/mapping.json:

    hashtag
    Using sha256-authentication

    The mapping-based solution requires the DBA to maintain a file with user passwords, which has security and upkeep implications. To avoid this, MaxScale can instead use the caching_sha2_password-plugin to authenticate the client. This authentication scheme transmits the client password to MaxScale in full, allowing MaxScale to log into backends using ed25519. MaxScale effectively lies to the client about its authentication plugin and then uses the correct plugin with the backends. Enable sha256-authentication by setting authentication option ed_mode to "sha256".

    sha256-authentication is best used with encrypted connections. The example below shows a listener configured for sha256-mode and SSL.

    If SSL is not in use, caching_sha2_password transmits the password using RSA-encryption. In this case, MaxScale needs the public and private RSA-keys. MaxScale sends the public key to the client if they don't already have it and the client uses it to encrypt the password. MaxScale then uses the private key to decrypt the password. The example below shows a listener configured for sha256-mode without SSL.

    The keyfiles can be generated with OpenSSL using the following commands.

    This page is licensed: CC BY-SA / Gnu FDL

    Ed25519 Authenticator
    [Read-Write-Listener]
    type=listener
    address=::
    service=Read-Write-Service
    authenticator=ed25519auth
    authenticator_options=ed_mode=sha256
    authenticator_options=ed_mode=sha256,
     ed_rsa_privkey_path=/tmp/sha_private_key.pem,
     ed_rsa_pubkey_path=/tmp/sha_public_key.pem
    [Read-Write-Listener]
    type=listener
    address=::
    service=Read-Write-Service
    authenticator=ed25519auth,mariadbauth
    user_mapping_file=/home/joe/mapping.json
    {
        "user_map": [
            {
                "original_user": "alpha",
                "mapped_user": "beta"
            },
            {
                "original_user": "gamma",
                "mapped_user": "gamma"
            }
        ],
        "server_credentials": [
            {
                "mapped_user": "beta",
                "password": "hunter2",
                "plugin": "mysql_native_password"
            },
            {
                "mapped_user": "gamma",
                "password": "letmein",
                "plugin": "ed25519"
            }
        ]
    }
    [Read-Write-Listener]
    type=listener
    address=::
    service=Read-Write-Service
    authenticator=ed25519auth
    authenticator_options=ed_mode=sha256
    ssl=true
    ssl_key=/tmp/my-key.pem
    ssl_cert=/tmp/my-cert.pem
    ssl_ca=/tmp/myCA.pem
    [Read-Write-Listener]
    type=listener
    address=::
    service=Read-Write-Service
    authenticator=ed25519auth
    authenticator_options=ed_mode=sha256,
     ed_rsa_privkey_path=/tmp/sha_private_key.pem,
     ed_rsa_pubkey_path=/tmp/sha_public_key.pem
    openssl genrsa -out sha_private_key.pem 2048
    openssl rsa -in sha_private_key.pem -pubout -out sha_public_key.pem
    spinner

    MaxScale 25.01 Installing MariaDB MaxScale using a tarball

    hashtag
    Installing MariaDB MaxScale using a tarball

    MariaDB MaxScale is also made available as a tarball, which is named likemaxscale-x.y.z.OS.tar.gz where x.y.z is the same as the corresponding version and OS identifies the operating system, e.g. maxscale-2.5.6.centos.7.tar.gz.

    In order to use the tarball, the following libraries are required:

    • libcurl

    • libaio

    • OpenSSL

    • gnutls

    The tarball has been built with the assumption that it will be installed in /usr/local. However, it is possible to install it in any directory, but in that case MariaDB MaxScale must be invoked with a flag.

    hashtag
    Installing as root in /usr/local

    If you have root access to the system you probably want to install MariaDB MaxScale under the user and group maxscale.

    The required steps are as follows:

    Creating the symbolic link is necessary, since MariaDB MaxScale has been built with the assumption that the plugin directory is /usr/local/maxscale/lib/maxscale.

    The symbolic link also makes it easy to switch between different versions of MariaDB MaxScale that have been installed side by side in /usr/local; just make the symbolic link point to another installation.

    In addition, the first time you install MariaDB MaxScale from a tarball you need to create the following directories:

    and make maxscale the owner of them:

    The following step is to create the MariaDB MaxScale configuration file /etc/maxscale.cnf. The file etc/maxscale.cnf.template can be used as a base. Please refer to for details.

    When the configuration file has been created, MariaDB MaxScale can be started.

    The -d flag causes maxscale not to turn itself into a daemon, which is advisable the first time MariaDB MaxScale is started, as it makes it easier to spot problems.

    If you want to place the configuration file somewhere else but in /etc you can invoke MariaDB MaxScale with the --config flag, for instance, --config=/usr/local/maxscale/etc/maxscale.cnf.

    Note also that if you want to keep everything under /usr/local/maxscale you can invoke MariaDB MaxScale using the flag --basedir.

    That will cause MariaDB MaxScale to look for its configuration file in/usr/local/maxscale/etc and to store all runtime files under /usr/local/maxscale/var.

    hashtag
    Installing in any Directory

    Enter a directory where you have the right to create a subdirectory. Then do as follows.

    The next step is to create the MaxScale configuration file maxscale-x.y.z/etc/maxscale.cnf. The file maxscale-x.y.z/etc/maxscale.cnf.template can be used as a base. Please refer to for details.

    When the configuration file has been created, MariaDB MaxScale can be started.

    With the flag --basedir, MariaDB MaxScale is told where the lib, etc and var directories are found. Unless it is specified, MariaDB MaxScale assumes the lib directory is found in /usr/local/maxscale, and the var and etc directories in /.

    It is also possible to specify the directories and the location of the configuration file individually. Invoke MaxScale like

    to find out the appropriate flags.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 MariaDB MaxScale Installation Guide

    hashtag
    MariaDB MaxScale Installation Guide

    We recommend to install MaxScale on a separate server, to ensure that there can be no competition of resources between MaxScale and a MariaDB Server that it manages.

    hashtag

    Read-Write Splitting with MariaDB MaxScale

    The goal of this tutorial is to configure a system that appears to the client as a single database. MariaDB MaxScale will split the statements such that write statements are sent to the primary server and read statements are balanced across the replica servers.

    hashtag
    Setting up MariaDB MaxScale

    This tutorial is a part of . Please read it and follow the instructions. Return here once basic setup is complete.

    MaxScale 25.01 Optimistic Transaction Execution Filter

    hashtag
    Optimistic Transaction Execution Filter

    The optimistictrx filter implements optimistic transaction execution. The filter is designed for a use-case where most of the transactions are read-only and writes happen rarely but each set of read-only statements is still grouped into a read-write transaction (i.e. START TRANSACTION, BEGIN orSET autocommit=0).

    MaxScale 25.01 Psreuse

    hashtag
    Psreuse

    The psreuse filter reuses identical prepared statements inside the same client connection. This filter only works with binary protocol prepared statements and not with text protocol prepared statements executed with the PREPARE SQL command.

    When this filter is enabled and the connection prepares an identical prepared statement multiple times, instead of preparing it on the server the existing prepared statement handle is reused. This also means that whenever prepared statements are closed by the client, they will be left open by readwritesplit.

    MaxScale 25.01 About

    MaxScale 25.01 REST-API

    MaxScale 25.01 Protocols

    MaxScale 25.01 Getting-Started

    MaxScale 25.01 Reference

    MaxScale 25.01 Filters

    spinner
    spinner
    spinner
    spinner
    spinner

    libatomic

  • unixODBC

  • Configuration Guide
    Configuration Guide
    spinner
    hashtag
    Configuring the service

    After configuring the servers and the monitor, we create a read-write-splitter service configuration. Create the following section in your configuration file. The section name is also the name of the service and should be meaningful. For this tutorial, we use the name Splitter-Service.

    router defines the routing module used. Here we use readwritesplit for query-level read-write-splitting.

    A service needs a list of servers where queries will be routed to. The server names must match the names of server sections in the configuration file and not the hostnames or addresses of the servers.

    The user and password parameters define the credentials the service uses to populate user authentication data. These users were created at the start of the MaxScale Tutorial.

    For increased security, see password encryption.

    hashtag
    Configuring the Listener

    To allow network connections to a service, a network ports must be associated with it. This is done by creating a separate listener section in the configuration file. A service may have multiple listeners but for this tutorial one is enough.

    The service parameter tells which service the listener connects to. For the_Splitter-Listener_ we set it to Splitter-Service.

    A listener must define the network port to listen on.

    The optional address-parameter defines the local address the listener should bind to. This may be required when the host machine has multiple network interfaces. The default behavior is to listen on all network interfaces (the IPv6 address ::).

    hashtag
    Starting MariaDB MaxScale

    For the last steps, please return to MaxScale Tutorial.

    This page is licensed: CC BY-SA / Gnu FDL

    MariaDB MaxScale Tutorial
    spinner
    This filter will replace the BEGIN and START TRANSACTION SQL commands withSTART TRANSACTION READ ONLY. If the transaction is fully read-only, the transaction completes normally. However, if a write happens in the middle of a transaction, the filter issues a ROLLBACK command and then replays the read-only part of the transaction, including the original BEGIN statement. If the results of the replayed read-only part of the transaction is identical to the one that was returned to the client, the transaction proceeds normally. If the result checksum does not match, the connection is closed to prevent a write with the wrong transaction state from happening.

    hashtag
    Configuration

    To add the filter to a service, define an instance of the filter and then add it to a service's filters list:

    This can also be done at runtime with:

    This page is licensed: CC BY-SA / Gnu FDL

    [OptimisticTrx]
    type=filter
    module=optimistictrx
    
    [MyService]
    ...
    filters=OptimisticTrx
    spinner
    Enabling this feature will increase memory usage of a session. The amount of memory stored per prepared statement is proportional to the length of the prepared SQL statement and the number of parameters the statement has.

    hashtag
    Configuration

    To add the filter to a service, define an instance of the filter and then add it to a service's filters list:

    hashtag
    Limitations

    • If the SQL in the prepared statement is larger than 1677723 bytes, the prepared statement will not be cached.

    • If the same SQL is prepared more than once at the same time, only one of them will succeed. This happens as the prepared statement reuse uses the SQL string in the comparison to detect if a statement is already prepared.

    This page is licensed: CC BY-SA / Gnu FDL

    spinner
    $ sudo groupadd maxscale
    $ sudo useradd -g maxscale maxscale
    $ cd /usr/local
    $ sudo tar -xzvf maxscale-x.y.z.OS.tar.gz
    $ sudo ln -s maxscale-x.y.z.OS maxscale
    $ cd maxscale
    $ sudo chown -R maxscale var
    $ sudo mkdir /var/log/maxscale
    $ sudo mkdir /var/lib/maxscale
    $ sudo mkdir /run/maxscale
    $ sudo mkdir /var/cache/maxscale
    $ sudo chown maxscale /var/log/maxscale
    $ sudo chown maxscale /var/lib/maxscale
    $ sudo chown maxscale /run/maxscale
    $ sudo chown maxscale /var/cache/maxscale
    $ sudo bin/maxscale --user=maxscale -d
    $ sudo bin/maxscale --user=maxscale --basedir=/usr/local/maxscale -d
    $ tar -xzvf maxscale-x.y.z.OS.tar.gz
    $ cd maxscale-x.y.z.OS
    $ bin/maxscale -d --basedir=.
    $ bin/maxscale --help
    [Splitter-Service]
    type=service
    router=readwritesplit
    servers=dbserv1, dbserv2, dbserv3
    user=maxscale
    password=maxscale_pw
    [Splitter-Listener]
    type=listener
    service=Splitter-Service
    port=3306
    maxctrl create filter OptimisticTrx optimistictrx
    maxctrl alter service-filter MyService OptimisticTrx
    [PsReuse]
    type=filter
    module=psreuse
    
    [MyService]
    ...
    filters=PsReuse
    Install MariaDB MaxScale From MariaDB Repositories

    The recommended approach is to use to install MaxScale. After enabling the repository by following the instructions, MaxScale can be installed with the following commands.

    • For RHEL/Rocky Linux/Alma Linux, use dnf install maxscale.

    • For Debian and Ubuntu, run apt update followed by apt install maxscale.

    • For SLES, use zypper install maxscale.

    hashtag
    Install MariaDB MaxScale From a RPM/DEB Package

    Download the correct MaxScale package for your CPU architecture and operating system from the MariaDB Downloads pagearrow-up-right. MaxScale can be installed with the following commands.

    • For RHEL/Rocky Linux/Alma Linux, use dnf install /path/to/maxscale-*.rpm

    • For Debian and Ubuntu, use apt install /path/to/maxscale-*.deb.

    • For SLES, use zypper install /path/to/maxscale-*.rpm.

    hashtag
    Install MariaDB MaxScale Using a Tarball

    MaxScale can also be installed using a tarball. That may be required if you are using a Linux distribution for which there exist no installation package or if you want to install many different MaxScale versions side by side. For instructions on how to do that, please refer to Install MariaDB MaxScale using a Tarball.

    hashtag
    Building MariaDB MaxScale From Source Code

    Alternatively you may download the MariaDB MaxScale source and build your own binaries. To do this, refer to the separate document Building MariaDB MaxScale from Source Code

    hashtag
    Assumptions

    hashtag
    Memory allocation behavior

    MaxScale assumes that memory allocations always succeed and in general does not check for memory allocation failures. This assumption is compatible with the Linux kernel parameter vm.overcommit_memoryarrow-up-right having the value 0, which is also the default on most systems.

    With vm.overcommit_memory being 0, memory allocations made by an application never fail, but instead the application may be killed by the so-called OOM (out-of-memory) killer if, by the time the application actually attempts to use the allocated memory, there is not available free memory on the system.

    If the value is 2, then a memory allocation made by an application may fail and unless the application is prepared for that possibility, it will likely crash with a SIGSEGV. As MaxScale is not prepared to handle memory allocation failures, it will crash in this situation.

    The current value of vm.overcommit_memory can be checked with

    or

    hashtag
    Configuring MariaDB MaxScale

    The MaxScale Tutorial covers the first steps in configuring your MariaDB MaxScale installation. Follow this tutorial to learn how to configure and start using MaxScale.

    For a detailed list of all configuration parameters, refer to the Configuration Guide and the module specific documents listed in the Documentation Contents.

    hashtag
    Encrypting Passwords

    Read the Encrypting Passwords section of the configuration guide to set up password encryption for the configuration file.

    hashtag
    Administration Of MariaDB MaxScale

    There are various administration tasks that may be done with MariaDB MaxScale. A command line tools is available, maxctrl, that will interact with a running MariaDB MaxScale and allow the status of MariaDB MaxScale to be monitored and give some control of the MariaDB MaxScale functionality.

    The administration tutorial covers the common administration tasks that need to be done with MariaDB MaxScale.

    hashtag
    Copying or Backing Up MaxScale

    The main configuration file for MaxScale is in /etc/maxscale.cnf and additional user-created configuration files are in/etc/maxscale.cnf.d/. Objects created or modified at runtime are stored in/var/lib/maxscale/maxscale.cnf.d/. Some modules also store internal data in/var/lib/maxscale/ named after the module or the configuration object.

    The simplest way to back up the configuration and runtime data of a MaxScale installation is to create an archive from the following files and directories:

    • /etc/maxscale.cnf

    • /etc/maxscale.cnf.d/

    • /var/lib/maxscale/

    This can be done with the following command:

    If MaxScale is configured to store data in custom locations, these should be included in the backup as well.

    This page is licensed: CC BY-SA / Gnu FDL

    sysctl vm.overcommit_memory
    cat /proc/sys/vm/overcommit_memory
    tar -caf maxscale-backup.tar.gz /etc/maxscale.cnf /etc/maxscale.cnf.d/ /var/lib/maxscale/
    spinner
    spinner

    WEBINAR

    New innovations in MaxScale 25.01 and Enterprise Platform

    MaxScale 25.01 Building MariaDB MaxScale from Source Code

    hashtag
    Building MariaDB MaxScale from Source Code

    MariaDB MaxScale can be built on any system that meets the requirements. The main requirements are as follows:

    • CMake version 3.16 or later (Packaging requires CMake 3.25.1 or later)

    • GCC version 4.9 or later

    • OpenSSL version 1.0.1 or later

    • GNUTLS

    • Node.js 14 or newer for building MaxCtrl and the GUI (webpack), Node.js 10 or newer for running MaxCtrl

    • PAM

    • SASL2 (cyrus-sasl)

    • SQLite3 version 3.3 or later

    • Tcl

    • git

    • jansson

    • libatomic

    • libcurl

    • libmicrohttpd

    • libuuid

    • libxml2

    • libssh

    • pcre2

    • zstd

    This is the minimum set of requirements that must be met to build the MaxScale core package. Some modules in MaxScale require optional extra dependencies.

    • libuuid (binlogrouter)

    • boost (binlogrouter)

    • Bison 2.7 or later (dbfwfilter)

    • Flex 2.5.35 or later (dbfwfilter)

    Some of these dependencies are not available on all operating systems and are downloaded automatically during the build step. To skip the building of modules that need automatic downloading of the dependencies, use -DBUNDLE=N when configuring CMake.

    hashtag
    Quickstart

    This installs MaxScale as if it was installed from a package. Install git before running the following commands.

    hashtag
    Required Packages

    For a definitive list of packages, consult the script.

    hashtag
    Configuring the Build

    The tests and other parts of the build can be controlled via CMake arguments.

    Here is a small table with the names of the most common parameters and what they control. These should all be given as parameters to the -D switch inNAME=VALUE format (e.g. -DBUILD_TESTS=Y).

    Argument Name
    Explanation

    Note: You can look into for a list of the CMake variables.

    hashtag
    Running unit tests

    To run the MaxScale unit test suite, configure the build with -DBUILD_TESTS=Y, compile and then run the make test command.

    hashtag
    Building MariaDB MaxScale packages

    If you wish to build packages, just add -DPACKAGE=Y to the CMake invocation and build the package with make package instead of installing MaxScale withmake install. This process will create a RPM/DEB package depending on your system.

    To build a tarball, add -DTARBALL=Y to the cmake invocation. This will create a maxscale-x.y.z.tar.gz file where x.y.z is the version number.

    Some Debian and Ubuntu systems suffer from a bug where make package fails with errors from dpkg-shlibdeps. This can be fixed by running make beforemake package and adding the path to the libmaxscale-common.so library to the LD_LIBRARY_PATH environment variable.

    hashtag
    Installing optional components

    The MaxScale build system is split into multiple components. The main component is the core MaxScale package which contains MaxScale and all the modules. This is the default component that is build, installed and packaged. There is also the experimental component that contains all experimental modules which are not considered as part of the core MaxScale package and are either alpha or beta quality modules.

    To build the experimental modules along with the MaxScale core components, invoke CMake with -DTARGET_COMPONENT=core,experimental.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 MariaDB MaxScale MaxGUI Guide

    hashtag
    MariaDB MaxScale MaxGUI Guide

    • MariaDB MaxScale MaxGUI Guide

    • Introduction

    hashtag
    Introduction

    MaxGUI is a browser-based interface for MaxScale REST-API and query execution.

    hashtag
    Enabling MaxGUI

    To enable MaxGUI in a testing mode, add admin_host=0.0.0.0 andadmin_secure_gui=false under the [maxscale] section of the MaxScale configuration file. Once enabled, MaxGUI will be available on port 8989:http://127.0.0.1:8989/

    hashtag
    Securing the GUI

    To make MaxGUI secure, set admin_secure_gui=true and configure both theadmin_ssl_key and admin_ssl_cert parameters.

    See and for instructions on how to harden your MaxScale installation for production use.

    hashtag
    Authentication

    MaxGUI uses the same credentials as maxctrl. The default username is admin with mariadb as the password.

    Internally, MaxGUI uses as the authentication method for persisting the user's session. If the Remember me checkbox is ticked, the session will persist for 24 hours. Otherwise, the session will expire as soon as MaxGUI is closed.

    To log out, simply click the username section in the top right corner of the page header to access the logout menu.

    hashtag
    Pages

    hashtag
    Dashboard

    This page provides an overview of MaxScale configuration which includes Monitors, Servers, Services, Sessions, Listeners, and Filters.

    By default, the refresh interval is 10 seconds.

    hashtag
    Detail

    This page shows information on each and allow to edit its parameter, relationships and perform other manipulation operations.

    Access this page by clicking on the MaxScale object name on the

    hashtag
    Visualization

    This page visualizes MaxScale configuration and clusters.

    • Configuration: Visualizing MaxScale configuration.

    • Cluster: Visualizing a replication cluster into a tree graph and provides manual cluster manipulation operations such asswitchover, reset-replication, release-locks, failover, rejoin . At the moment, it supports only servers monitored by Monitor using module.

    Access this page by clicking the graph icon on the sidebar navigation.

    hashtag
    Settings

    This page shows and allows editing of MaxScale parameters.

    Access this page by clicking the gear icon on the sidebar navigation.

    hashtag
    Logs Archive

    Realtime MaxScale logs can be accessed by clicking the logs icon on the sidebar navigation.

    hashtag
    Workspace

    The "Workspace" page offers a versatile set of tools for effectively managing data and database interactions. It includes the following key tasks:

    hashtag
    1. Run Queries

    Execute queries on various servers, services, or listeners to retrieve data and perform database operations. Visualize query results using different graph types such as line, bar, or scatter graphs. Export query results in formats like CSV or JSON for further analysis and sharing.

    hashtag
    2. Data Migration

    The "Data Migration" feature facilitates seamless transitions from PostgreSQL to MariaDB. Transfer data and database structures between the two systems while ensuring data integrity and consistency throughout the process.

    hashtag
    3. Create an ERD

    Generating Entity-Relationship Diagrams (ERDs) to gain insights regarding data structure, optimizing database design for both efficiency and clarity.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Binlog Filter

    hashtag
    Binlog Filter

    This filter was introduced in MariaDB MaxScale 2.3.0.

    • Binlog Filter

    hashtag
    Overview

    The binlogfilter can be combined with a binlogrouter service to selectively replicate the binary log events to replica servers.

    The filter uses two settings, match and exclude, to determine which events are replicated. If a binlog event does not match or is excluded, the event is replaced with an empty data event. The empty event is always 35 bytes which translates to a space reduction in most cases.

    When statement-based replication is used, any query events that are filtered out are replaced with a SQL comment. This causes the query event to do nothing and thus the event will not modify the contents of the database. The GTID position of the replicating database will still advance which means that downstream servers replicating from it keep functioning correctly.

    The filter works with both row based and statement based replication but we recommend using row based replication with the binlogfilter. This guarantees that there are no ambiguities in the event filtering.

    hashtag
    Settings

    hashtag
    match

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: None

    Include queries that match the regex. See next entry, exclude, for more information.

    hashtag
    exclude

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: None

    Exclude queries that match the regex.

    If neither match nor exclude are defined, the filter does nothing and all events are replicated. This filter does not accept regular expression options as a separate setting, such settings must be defined in the patterns themselves. See the for more information.

    The two settings are matched against the database and table name concatenated with a period. For example, the string the patterns are matched against for the database test and table t1 is test.t1.

    For statement based replication, the pattern is matched against all the tables in the statements. If any of the tables matches the match pattern, the event is replicated. If any of the tables matches the exclude pattern, the event is not replicated.

    hashtag
    rewrite_src

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: None

    See the next entry, rewrite_dest, for more information.

    hashtag
    rewrite_dest

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: None

    rewrite_src and rewrite_dest control the statement rewriting of the binlogfilter. The rewrite_src setting is a PCRE2 regular expression that is matched against the default database and the SQL of statement based replication events (query events). rewrite_dest is the replacement string which supports the normal PCRE2 backreferences (e.g the first capture group is $1, the second is $2, etc.).

    Both rewrite_src and rewrite_dest must be defined to enable statement rewriting.

    When statement rewriting is enabled must be used. The filter will disallow replication for all replicas that attempt to replicate with traditional file-and-position based replication.

    The replacement is done both on the default database as well as the SQL statement in the query event. This means that great care must be taken when defining the rewriting rules. To prevent accidental modification of the SQL into a form that is no longer valid, use database and table names that never occur in the inserted data and is never used as a constant value.

    hashtag
    Example Configuration

    With the following configuration, only events belonging to database customers are replicated. In addition to this, events for the table orders are excluded and thus are not replicated.

    For more information about the binlogrouter and how to use it, refer to the .

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Maxscale CDC Connector

    hashtag
    Maxscale CDC Connector

    The C++ connector for the MariaDB MaxScalearrow-up-rightCDC system.

    hashtag
    Usage

    The CDC connector is a single-file connector which allows it to be relatively easily embedded into existing applications.

    To start using the connector, either download it from the or and install the maxscale-cdc-connector package.

    hashtag
    API Overview

    A CDC connection object is prepared by instantiating the CDC::Connection class. To create the actual connection, call the CDC::Connection::connect method of the class.

    After the connection has been created, call the CDC::Connection::read method to get a row of data. The CDC::Row::length method tells how many values a row has and CDC::Row::value is used to access that value. The field name of a value can be extracted with the CDC::Row::key method and the current GTID of a row of data is retrieved with the CDC::Row::gtid method.

    To close the connection, destroy the instantiated object.

    hashtag
    Examples

    The source code that demonstrates basic usage of the MaxScale CDC Connector.

    hashtag
    Dependencies

    The CDC connector depends on:

    • OpenSSL

    hashtag
    RHEL/CentOS 7

    hashtag
    Debian Stretch and Ubuntu Xenial

    hashtag
    Debian Jessie

    hashtag
    openSUSE Leap 42.3

    hashtag
    Building and Packaging

    To build and package the connector as a library, follow MaxScale build instructions with the exception of adding -DTARGET_COMPONENT=devel to the CMake call.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 GSSAPI Client Authenticator

    hashtag
    MaxScale 25.01 GSSAPI Client Authenticator

    hashtag
    GSSAPI Client Authenticator

    GSSAPI is an authentication protocol that is commonly implemented with Kerberos on Unix or Active Directory on Windows. This document describes GSSAPI authentication in MaxScale. The authentication module name in MaxScale is_GSSAPIAuth_.

    hashtag
    Preparing the GSSAPI system

    For Unix systems, the usual GSSAPI implementation is Kerberos. This is a short guide on how to set up Kerberos for MaxScale.

    The first step is to configure MariaDB to use GSSAPI authentication. The MariaDB documentation for the is a good example on how to set it up.

    The next step is to copy the keytab file from the server where MariaDB is installed to the server where MaxScale is located. The keytab file must be placed in the configured default location which almost always is/etc/krb5.keytab. Alternatively, the keytab filepath can be given as an authenticator option.

    The location of the keytab file can be changed with the KRB5_KTNAME environment variable:

    To take GSSAPI authentication into use, add the following to the listener.

    The principal name should be the same as on the MariaDB servers.

    hashtag
    Settings

    hashtag
    principal_name

    • Type: string

    • Mandatory: No

    • Dynamic: No

    • Default: mariadb/localhost.localdomain

    The service principal name to send to the client. This parameter is a string parameter which is used by the client to request the token.

    This parameter must be the same as the principal name that the backend MariaDB server uses.

    hashtag
    gssapi_keytab_path

    • Type: path

    • Mandatory: No

    • Dynamic: No

    • Default: Kerberos Default

    Keytab file location. This should be an absolute path to the file containing the keytab. If not defined, Kerberos will search from a default location, usually/etc/krb5.keytab. This path is set to an environment variable. This means that multiple listeners with GSSAPIAuth will override each other. If using multiple GSSAPI authenticators, either do not set this option or use the same value for all listeners.

    hashtag
    Implementation details

    Read the document for more details on how authentication modules work in MaxScale.

    hashtag
    GSSAPI authentication

    The GSSAPI plugin authentication starts when the database server sends the service principal name in the AuthSwitchRequest packet. The principal name will usually be in the form service@REALM.COM.

    The client searches its local cache for a token for the service or may request it from the GSSAPI server. If found, the client sends the token to the database server. The database server verifies the authenticity of the token using its keytab file and sends the final OK packet to the client.

    hashtag
    Building the module

    The GSSAPI authenticator modules require the GSSAPI development libraries (krb5-devel on CentOS 7).

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Cat

    hashtag

    hashtag
    Cat

    The cat router is a special router that concatenates result sets.

    Note: This module is experimental and must be built from source. The module is deprecated in MaxScale 23.08 and might be removed in a future release.

    hashtag
    Configuration

    The router has no special parameters. To use it, define a service withrouter=cat and add the servers you want to use.

    hashtag
    Behavior

    The order the servers are defined in is the order in which the servers are queried. This means that the results are ordered based on the servers parameter of the service. The result will only be completed once all servers have executed this.

    All commands executed via this router will be executed on all servers. This means that an INSERT through the cat router will send it to all servers. In the case of commands that do not return resultsets, the response of the last server is sent to the client. This means that if one of the earlier servers returns a different result, the client will not see it.

    As the intended use-case of the router is to mainly reduce multiple result sets into one, it has no mechanisms to prevent writes from being executed on slave servers (which would cause data corruption or replication failure). Take great care when performing administrative operations though this router.

    If a connection to one of the servers is lost, the client connection will also be closed.

    hashtag
    Example

    Here is a simple example service definition that uses the servers from the tutorial and the credentials from the .

    This page is licensed: CC BY-SA / Gnu FDL

    Configuring the Galera Monitor

    This document describes how to configure a Galera cluster monitor.

    hashtag
    Configuring the Monitor

    Define the monitor that monitors the servers.

    [Galera-Monitor]
    type=monitor
    module=galeramon
    servers=dbserv1, dbserv2, dbserv3
    user=monitor_user
    password=my_password
    monitor_interval=2000ms

    The mandatory parameters are the object type, the monitor module to use, the list of servers to monitor and the username and password to use when connecting to the servers. The monitor_interval parameter controls for how long the monitor waits between each monitoring loop.

    This monitor module will assign one node within the Galera Cluster as the current primary and other nodes as replica. Only those nodes that are active members of the cluster are considered when making the choice of primary node. The primary node will be the node with the lowest value of wsrep_local_index.

    hashtag
    Monitor User

    The monitor user does not require any special grants to monitor a Galera cluster. To create a user for the monitor, execute the following SQL.

    This page is licensed: CC BY-SA / Gnu FDL

    Configuring Servers

    The first step is to define the servers that make up the cluster. These servers will be used by the services and are monitored by the monitor.

    [dbserv1]
    type=server
    address=192.168.2.1
    port=3306
    
    [dbserv2]
    type=server
    address=192.168.2.2
    port=3306
    
    [dbserv3]
    type=server
    address=192.168.2.3
    port=3306

    The address and port parameters tell where the server is located.

    hashtag
    Enabling TLS

    To enable encryption for the MaxScale-to-MariaDB communication, add ssl=true to the server section. To enable server certificate verification, addssl_verify_peer_certificate=true.

    The ssl and ssl_verify_peer_certificate parameters are similar to the--ssl and --ssl-verify-server-cert options of the mysql command line client.

    For more information about TLS, refer to the .

    This page is licensed: CC BY-SA / Gnu FDL

    Configuring the MariaDB Monitor

    This document describes how to configure a MariaDB primary-replica cluster monitor to be used with MaxScale.

    hashtag
    Configuring the Monitor

    Define the monitor that monitors the servers.

    [Replication-Monitor]
    type=monitor
    module=mariadbmon
    servers=dbserv1, dbserv2, dbserv3
    user=monitor_user
    password=my_password
    monitor_interval=2000ms

    The mandatory parameters are the object type, the monitor module to use, the list of servers to monitor and the username and password to use when connecting to the servers. The monitor_interval parameter controls for how long the monitor waits between each monitoring loop.

    hashtag
    Monitor User

    The monitor user requires the REPLICATION CLIENT privileges to do basic monitoring. To create a user with the proper grants, execute the following SQL.

    Note: If the automatic failover of the MariaDB Monitor will used, the user will require additional grants. Execute the following SQL to grant them.

    This page is licensed: CC BY-SA / Gnu FDL

    mariadb-maxscale-2501-maxscale-2501-encrypting-passwords

    hashtag
    MaxScale 25.01 Encrypting Passwords

    hashtag
    Encrypting Passwords

    Note: The password encryption format changed in MaxScale 2.5. All encrypted passwords created with MaxScale 2.4 or older need to be re-encrypted.

    There are two options for representing the password, either plain text or encrypted passwords may be used. In order to use encrypted passwords a set of keys must be generated that will be used by the encryption and decryption process. To generate the keys, use the maxkeys command.

    By default the key file will be generated in /var/lib/maxscale. If a different directory is required, it can be given as the first argument to the program. For more information, see maxkeys --help.

    Once the keys have been created the maxpasswd command can be used to generate the encrypted password.

    The username and password, either encrypted or plain text, are stored in the service section using the user and password parameters.

    If a custom location was used for the key file, give it as the first argument tomaxpasswd and pass the password to be encrypted as the second argument. For more information, see maxkeys --help.

    Here is an example configuration that uses an encrypted password.

    If the key file is not in the default location, the parameter must be set to the directory that contains it.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Transaction Performance Monitoring Filter

    hashtag
    Transaction Performance Monitoring Filter

    Note: This module is experimental and must be built from source. The module is deprecated in MaxScale 23.08 and might be removed in a future release.

    MaxScale 25.01 Consistent Critical Read Filter

    hashtag

    hashtag
    Consistent Critical Read Filter

    This filter was introduced in MariaDB MaxScale 2.1.

  • Settings

  • Logs Archive

  • Workspace

    • 1. Run Queries

    • 2. Data Migration

    • 3. Create an ERD

  • Enabling MaxGUI
    Securing the GUI
    Authentication
    Pages
    Dashboard
    Detail
    Visualization
    Configuration Guide
    Configuration and Hardening
    JSON Web Tokensarrow-up-right
    MaxScale object
    dashboard page
    mariadbmon
    spinner
    Configuration Guide
    spinner
    Watch Nowarrow-up-right

    librdkafka (kafkacdc, kafkaimporter and mirror)

  • memcached (storage_memcached for the cache filter)

  • hiredis (storage_redis for the cache filter)

  • Enable building of packages

    TARGET_COMPONENT

    Which component to install, default is the 'core' package. Other targets are 'experimental', which installs experimental packages and 'all' which installs all components.

    TARBALL

    Build tar.gz packages, requires PACKAGE=Y

    CMAKE_INSTALL_PREFIX

    Location where MariaDB MaxScale will be installed to. Set this to /usr if you want MariaDB MaxScale installed into the same place the packages are installed.

    BUILD_TESTS

    Build unit tests

    WITH_SCRIPTS

    Install systemd and init.d scripts

    install_build_deps.sharrow-up-right
    defaults.cmakearrow-up-right
    spinner

    PACKAGE

    Configuring Servers
    MaxScale Tutorial
    spinner
    CREATE USER 'monitor_user'@'%' IDENTIFIED BY 'my_password';
    spinner
    CREATE USER 'monitor_user'@'%' IDENTIFIED BY 'my_password';
    GRANT REPLICATION CLIENT ON *.* TO 'monitor_user'@'%';
    GRANT SUPER, RELOAD on *.* to 'monitor_user'@'%';
    spinner
    maxkeys
    datadir
    spinner
    git clone https://github.com/mariadb-corporation/MaxScale
    mkdir build
    cd build
    ../MaxScale/BUILD/install_build_deps.sh
    cmake ../MaxScale -DCMAKE_INSTALL_PREFIX=/usr
    make
    sudo make install
    sudo ./postinst
    make
    LD_LIBRARY_PATH=$PWD/server/core/ make package
    [concat-service]
    type=service
    router=cat
    servers=dbserv1,dbserv2,dbserv3
    user=maxscale
    password=maxscale_pw
    maxpasswd plainpassword
    96F99AA1315BDC3604B006F427DD9484
    [My-Service]
    type=service
    router=readconnroute
    router_options=master
    servers=dbserv1, dbserv2, dbserv3
    user=maxscale
    password=96F99AA1315BDC3604B006F427DD9484
  • rewrite_dest

  • [BinlogFilter]
    type=filter
    module=binlogfilter
    match=/customers[.]/
    exclude=/[.]orders/
    
    [BinlogServer]
    type=service
    router=binlogrouter
    server_id=33
    filters=BinlogFilter
    
    [BinlogListener]
    type=listener
    service=BinlogServer
    port=4000
    Overview
    Settings
    match
    exclude
    rewrite_src
    Example Configuration
    regex
    regex
    PCRE2 api documentationarrow-up-right
    regex
    regex
    binlogrouter documentation
    spinner

    Overview

  • Configuration

  • Filter Options

  • Settings

    • Filename

    • Source

    • User

  • Log Output Format

  • Examples

    • Example 1 - Log Transactions for Performance Analysis

  • hashtag
    Overview

    The Transaction Performance Monitoring (TPM) filter is a filter module for MaxScale that monitors every SQL statement that passes through the filter. The filter groups a series of SQL statements into a transaction by detecting 'commit' or 'rollback' statements. It logs all committed transactions with necessary information, such as timestamp, client, SQL statements, latency, etc., which can be used later for transaction performance analysis.

    hashtag
    Configuration

    The configuration block for the TPM filter requires the minimal filter options in it's section within the maxscale.cnf file, stored in /etc/maxscale.cnf.

    hashtag
    Filter Options

    The TPM filter does not support any filter options currently.

    hashtag
    Settings

    The TPM filter accepts a number of optional parameters.

    hashtag
    Filename

    The name of the output file created for performance logging. The default filename is tpm.log.

    hashtag
    Source

    The optional source parameter defines an address that is used to match against the address from which the client connection to MaxScale originates. Only sessions that originate from this address will be logged.

    hashtag
    User

    The optional user parameter defines a user name that is used to match against the user from which the client connection to MaxScale originates. Only sessions that are connected using this username are logged.

    hashtag
    Delimiter

    The optional delimiter parameter defines a delimiter that is used to distinguish columns in the log. The default delimiter is :::.

    hashtag
    Query_delimiter

    The optional query_delimiter defines a delimiter that is used to distinguish different SQL statements in a transaction. The default query delimiter is @@@.

    hashtag
    Named_pipe

    named_pipe is the path to a named pipe, which TPM filter uses to communicate with 3rd-party applications (e.g., DBSeerarrow-up-right). Logging is enabled when the router receives the character '1' and logging is disabled when the router receives the character '0' from this named pipe. The default named pipe is /tmp/tpmfilter and logging is disabled by default.

    For example, the following command enables the logging:

    Similarly, the following command disables the logging:

    hashtag
    Log Output Format

    For each transaction, the TPM filter prints its log in the following format:

    <timestamp> | <server_name> | <user_name> | <latency of the transaction> | <latencies of individual statements in the transaction> (delimited by 'query_delimiter') | <actual SQL statements>

    hashtag
    Examples

    hashtag
    Example 1 - Log Transactions for Performance Analysis

    You want to log every transaction with its SQL statements and latency for future transaction performance analysis.

    Add a filter with the following definition:

    After the filter reads the character '1' from its named pipe, the following is an example log that is generated from the above TPM filter with the above configuration:

    Note that 3 and 6 are latencies of each transaction in milliseconds, while 0.165 and 0.123 are latencies of the first statement of each transaction in milliseconds.

    This page is licensed: CC BY-SA / Gnu FDL

    Transaction Performance Monitoring Filter
    [MyLogFilter]
    type=filter
    module=tpmfilter
    
    [MyService]
    type=service
    router=readconnroute
    servers=server1
    user=myuser
    password=mypasswd
    filters=MyLogFilter
    filename=/tmp/SqlQueryLog
    source=127.0.0.1
    user=john
    delimiter=:::
    query_delimiter=@@@
    named_pipe=/tmp/tpmfilter
    $ echo '1' > /tmp/tpmfilter
    $ echo '0' > /tmp/tpmfilter
    [PerformanceLogger]
    type=filter
    module=tpmfilter
    delimiter=:::
    query_delimiter=@@@
    filename=/var/logs/tpm/perf.log
    named_pipe=/tmp/tpmfilter
    
    [Product-Service]
    type=service
    router=readconnroute
    servers=server1
    user=myuser
    password=mypasswd
    filters=PerformanceLogger
    1484086477::::server1::::root::::3::::0.165@@@@0.108@@@@0.102@@@@0.092@@@@0.121@@@@0.122@@@@0.110@@@@2.081::::UPDATE WAREHOUSE SET W_YTD = W_YTD + 3630.48  WHERE W_ID = 2 @@@@SELECT W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP, W_NAME FROM WAREHOUSE WHERE W_ID = 2@@@@UPDATE DISTRICT SET D_YTD = D_YTD + 3630.48 WHERE D_W_ID = 2 AND D_ID = 9@@@@SELECT D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP, D_NAME FROM DISTRICT WHERE D_W_ID = 2 AND D_ID = 9@@@@SELECT C_FIRST, C_MIDDLE, C_LAST, C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, C_PHONE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT, C_BALANCE, C_YTD_PAYMENT, C_PAYMENT_CNT, C_SINCE FROM CUSTOMER WHERE C_W_ID = 2 AND C_D_ID = 9 AND C_ID = 1025@@@@UPDATE CUSTOMER SET C_BALANCE = 1007749.25, C_YTD_PAYMENT = 465215.47, C_PAYMENT_CNT = 203 WHERE C_W_ID = 2 AND C_D_ID = 9 AND C_ID = 1025@@@@INSERT INTO HISTORY (H_C_D_ID, H_C_W_ID, H_C_ID, H_D_ID, H_W_ID, H_DATE, H_AMOUNT, H_DATA)  VALUES (9,2,1025,9,2,'2017-01-10 17:14:37',3630.48,'locfljbe    xtnfqn')
    1484086477::::server1::::root::::6::::0.123@@@@0.087@@@@0.091@@@@0.098@@@@0.078@@@@0.106@@@@0.094@@@@0.074@@@@0.089@@@@0.073@@@@0.098@@@@0.073@@@@0.088@@@@0.072@@@@0.087@@@@0.071@@@@0.085@@@@0.078@@@@0.088@@@@0.098@@@@0.081@@@@0.076@@@@0.082@@@@0.073@@@@0.077@@@@0.070@@@@0.105@@@@0.093@@@@0.088@@@@0.089@@@@0.087@@@@0.087@@@@0.086@@@@1.883::::SELECT C_DISCOUNT, C_LAST, C_CREDIT, W_TAX  FROM CUSTOMER, WAREHOUSE WHERE W_ID = 2 AND C_W_ID = 2 AND C_D_ID = 10 AND C_ID = 1267@@@@SELECT D_NEXT_O_ID, D_TAX FROM DISTRICT WHERE D_W_ID = 2 AND D_ID = 10 FOR UPDATE@@@@UPDATE DISTRICT SET D_NEXT_O_ID = D_NEXT_O_ID + 1 WHERE D_W_ID = 2 AND D_ID = 10@@@@INSERT INTO OORDER (O_ID, O_D_ID, O_W_ID, O_C_ID, O_ENTRY_D, O_OL_CNT, O_ALL_LOCAL) VALUES (286871, 10, 2, 1267, '2017-01-10 17:14:37', 7, 1)@@@@INSERT INTO NEW_ORDER (NO_O_ID, NO_D_ID, NO_W_ID) VALUES ( 286871, 10, 2)@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 24167@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 24167 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 96982@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 96982 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 40679@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 40679 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 31459@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 31459 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 6143@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 6143 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 12001@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 12001 AND S_W_ID = 2 FOR UPDATE@@@@SELECT I_PRICE, I_NAME , I_DATA FROM ITEM WHERE I_ID = 40407@@@@SELECT S_QUANTITY, S_DATA, S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05,        S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 FROM STOCK WHERE S_I_ID = 40407 AND S_W_ID = 2 FOR UPDATE@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,1,24167,2,7,348.31998,'btdyjesowlpzjwnmxdcsion')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,2,96982,2,1,4.46,'kudpnktydxbrbxibbsyvdiw')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,3,40679,2,7,528.43,'nhcixumgmosxlwgabvsrcnu')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,4,31459,2,9,341.82,'qbglbdleljyfzdpfbyziiea')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,5,6143,2,3,152.67,'tmtnuupaviimdmnvmetmcrc')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,6,12001,2,5,304.3,'ufytqwvkqxtmalhenrssfon')@@@@INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, OL_I_ID, OL_SUPPLY_W_ID,  OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) VALUES (286871,10,2,7,40407,2,1,30.32,'hvclpfnblxchbyluumetcqn')@@@@UPDATE STOCK SET S_QUANTITY = 65 , S_YTD = S_YTD + 7, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 24167 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 97 , S_YTD = S_YTD + 1, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 96982 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 58 , S_YTD = S_YTD + 7, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 40679 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 28 , S_YTD = S_YTD + 9, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 31459 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 86 , S_YTD = S_YTD + 3, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 6143 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 13 , S_YTD = S_YTD + 5, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 12001 AND S_W_ID = 2@@@@UPDATE STOCK SET S_QUANTITY = 44 , S_YTD = S_YTD + 1, S_ORDER_CNT = S_ORDER_CNT + 1, S_REMOTE_CNT = S_REMOTE_CNT + 0  WHERE S_I_ID = 40407 AND S_W_ID = 2
    ...
    spinner

    Consistent Critical Read Filter

    • Overview

      • Controlling the Filter with SQL Comments

    • Settings

    hashtag
    Overview

    The Consistent Critical Read (CCR) filter allows consistent critical reads to be done through MaxScale while still allowing scaleout of non-critical reads.

    When the filter detects a statement that would modify the database, it attaches a routing hint to all following statements done by that connection. This routing hint guides the routing module to route the statement to the primary server where data is guaranteed to be in an up-to-date state. Writes from one session do not, by default, propagate to other sessions.

    Note: This filter does not work with prepared statements. Only text protocol queries are handled by this filter.

    hashtag
    Controlling the Filter with SQL Comments

    The triggering of the filter can be limited further by adding MaxScale supported comments to queries and/or by using regular expressions. The query comments take precedence: if a comment is found it is obeyed even if a regular expression parameter might give a different result. Even a comment cannot cause a SELECT-query to trigger the filter. Such a comment is considered an error and ignored.

    The comments must follow the MaxScale hint syntax and the HintFilter needs to be in the filter chain before the CCR-filter. If a query has a MaxScale supported comment line which defines the parameter ccr, that comment is caught by the CCR-filter. Parameter values match and ignore are supported, causing the filter to trigger (match) or not trigger (ignore) on receiving the write query. For example, the query

    would normally cause the filter to trigger, but does not because of the comment. The match-comment typically has no effect, since write queries by default trigger the filter anyway. It can be used to override an ignore-type regular expression that would otherwise prevent triggering.

    hashtag
    Settings

    The CCR filter has no mandatory parameters.

    hashtag
    time

    • Type: duration

    • Mandatory: No

    • Dynamic: Yes

    • Default: 60s

    The time window during which queries are routed to the primary. The duration can be specified as documented here but the value will always be rounded to the nearest second. If no explicit unit has been specified, the value is interpreted as seconds in MaxScale 2.4. In subsequent versions a value without a unit may be rejected. The default value for this parameter is 60 seconds.

    When a data modifying SQL statement is processed, a timer is set to the value of_time_. Once the timer has elapsed, all statements are routed normally. If a new data modifying SQL statement is processed within the time window, the timer is reset to the value of time.

    Enabling this parameter in combination with the count parameter causes both the time window and number of queries to be inspected. If either of the two conditions are met, the query is re-routed to the primary.

    hashtag
    count

    • Type: count

    • Mandatory: No

    • Dynamic: Yes

    • Default: 0

    The number of SQL statements to route to primary after detecting a data modifying SQL statement. This feature is disabled by default.

    After processing a data modifying SQL statement, a counter is set to the value of count and all statements are routed to the primary. Each executed statement after a data modifying SQL statement cause the counter to be decremented. Once the counter reaches zero, the statements are routed normally. If a new data modifying SQL statement is processed, the counter is reset to the value of_count_.

    hashtag
    match

    • Type: regex

    • Mandatory: No

    • Dynamic: No

    • Default: ""

    These regular expression settings control which statements trigger statement re-routing. Only non-SELECT statements are inspected. For CCRFilter, the exclude-parameter is instead named ignore, yet works similarly.

    hashtag
    ignore

    • Type: regex

    • Mandatory: No

    • Dynamic: No

    • Default: ""

    See documentation for match.

    hashtag
    options

    • Type: enum

    • Mandatory: No

    • Dynamic: No

    • Values: ignorecase, case, extended

    • Default: ignorecase

    Regular expression options for match and ignore.

    hashtag
    global

    • Type: boolean

    • Mandatory: No

    • Dynamic: Yes

    • Default: false

    global is a boolean parameter that when enabled causes writes from one connection to propagate to all other connections. This can be used to work around cases where one connection writes data and another reads it, expecting the write done by the other connection to be visible.

    This parameter only works with the time parameter. The use of global andcount at the same time is not allowed and will be treated as an error.

    hashtag
    Example Configuration

    Here is a minimal filter configuration for the CCRFilter which should solve most problems with critical reads after writes.

    With this configuration, whenever a connection does a write, all subsequent reads done by that connection will be forced to the primary for 5 seconds.

    This prevents read scaling until the modifications have been replicated to the replicas. For best performance, the value of time should be slightly greater than the actual replication lag between the primary and its replicas. If the number of critical read statements is known, the count parameter could be used to control the number reads that are sent to the primary.

    This page is licensed: CC BY-SA / Gnu FDL

    INSERT INTO departments VALUES ('d1234', 'NewDepartment'); -- maxscale ccr=ignore
    match=.*INSERT.*
    ignore=.*UPDATE.*
    options=case,extended
    [CCRFilter]
    type=filter
    module=ccrfilter
    time=5
    spinner
    sudo yum -y install epel-release
    sudo yum -y install jansson openssl-devel cmake make gcc-c++ git
    sudo apt-get update
    sudo apt-get -y install libjansson-dev libssl-dev cmake make g++ git
    sudo apt-get update
    sudo apt-get -y install libjansson-dev libssl-dev cmake make g++ git
    sudo zypper install -y libjansson-devel openssl-devel cmake make gcc-c++ git
    MariaDB websitearrow-up-right
    contains an examplearrow-up-right
    Janssonarrow-up-right
    spinner
    authenticator=GSSAPIAuth
    authenticator_options=principal_name=mariadb/localhost.localdomain@EXAMPLE.COM
    authenticator_options=principal_name=mymariadb@EXAMPLE.COM,gssapi_keytab_path=/home/user/mymariadb.keytab
    keytab_def.htmlarrow-up-right
    Authentication Modulesarrow-up-right
    spinner

    MaxScale 25.01 LDI Filter

    hashtag

    hashtag
    LDI Filter

    The ldi (LOAD DATA INFILE) filter was introduced in MaxScale 23.08.0 and it extends the MariaDB LOAD DATA INFILE syntax to support loading data from any object storage that supports the S3 API. This includes cloud offerings like AWS S3 and Google Cloud Storage as well as locally run services like Minio.

    If the filename starts with either S3:// or gs://, the path is interpreted as a S3 object file. The prefix is case-insensitive. For example, the following command would load the file my-data.csv from the bucket my-bucket into the table t1.

    hashtag
    How to Upload Data

    Here is a minimal configuration for the filter that can be used to load data from AWS S3:

    The first step is to move the file to be loaded into the same region that MaxScale and the MariaDB servers are in. One factor in the speed of the upload is the network latency and minimizing it by moving the source and the destination closer improves the data loading speed.

    The next step is to connect to MaxScale and prepare the session for an upload by providing the service account access and secret keys.

    Once the credentials are configured, the data loading can be started:

    hashtag
    Data Uploads with MariaDB Xpand

    This feature has been removed in MaxScale 24.02.

    hashtag
    Common Problems With Data Loading

    hashtag
    Missing Files

    If you are using self-hosted object storage programs like Minio, a common problem is that they do not necessarily support the newer virtual-hosted-style requests that is used by AWS. This usually manifests as an error either about a missing file or a missing bucket.

    If the host parameter is set to a hostname, it's assumed that the object storage supports the newer virtual-hosted-style requests. If this not the case, the filter must be configured with protocol_version=1.

    Conversely, if the host parameter is set to a plain IP address, it is assumed that it does not support the newer virtual-hosted-style request. If the host does support it, the filter must be configured with protocol_version=2.

    hashtag
    Settings

    hashtag
    key

    • Type: string

    • Mandatory: No

    • Dynamic: Yes

    The S3 access key used to perform all requests to it.

    This must be either configured in the MaxScale configuration file or set withSET @maxscale.ldi.s3_key='<key>' before starting the data load.

    hashtag
    secret

    • Type: string

    • Mandatory: No

    • Dynamic: Yes

    The S3 secret key used to perform all requests to it.

    This must be either configured in the MaxScale configuration file or set withSET @maxscale.ldi.s3_secret='<secret>' before starting the data load.

    hashtag
    region

    • Type: string

    • Mandatory: No

    • Dynamic: Yes

    • Default: us-east-1

    The S3 region where the data is located.

    The value can be overridden with SET @maxscale.ldi.s3_region='<region>' before starting the data load.

    hashtag
    host

    • Type: string

    • Mandatory: No

    • Dynamic: Yes

    • Default: s3.amazonaws.com

    The location of the S3 object storage. By default the original AWS S3 host is used. The corresponding value for Google Cloud Storage isstorage.googleapis.com.

    The value can be overridden with SET @maxscale.ldi.s3_host='<host>' before starting the data load.

    hashtag
    port

    • Type: integer

    • Mandatory: No

    • Dynamic: Yes

    • Default: 0

    The port on which the S3 object storage is listening. If unset or set to the value of 0, the default S3 port is used.

    The value can be overridden with SET @maxscale.ldi.s3_port=<port> before starting the data load. Note that unlike the other values, the value for this variable must be an SQL integer and not an SQL string.

    hashtag
    no_verify

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: false

    If set to true, TLS certificate verification for the object storage is skipped.

    hashtag
    use_http

    • Type:

    • Mandatory: No

    • Dynamic: Yes

    • Default: false

    If set to true, communication with the object storage is done unencrypted using HTTP instead of HTTPS.

    hashtag
    protocol_version

    • Type: integer

    • Mandatory: No

    • Dynamic: Yes

    • Default: 0

    Which protocol version to use. By default the protocol version is derived from the value of host but this automatic protocol version deduction will not always produce the correct result. For the legacy path-style requests used by older S3 storage buckets, the value must be set to 1. All new buckets use the protocol version 2.

    For object storage programs like Minio, the value must be set to 1 as the bucket name cannot be resolved via the subdomain like it is done for object stores in the cloud.

    hashtag
    import_user

    This parameter has been removed in MaxScale 24.02.

    hashtag
    import_password

    This parameter has been removed in MaxScale 24.02.

    This page is licensed: CC BY-SA / Gnu FDL

    MaxScale 25.01 Hintfilter

    hashtag
    Hintfilter

    This filter adds routing hints to a service. The filter has no parameters.

    • Hintfilter

    hashtag
    Hint Syntax

    Note: If a query has more than one comment only the first comment is processed. Always place any MaxScale related comments first before any other comments that might appear in the query.

    hashtag
    Comments and comment types

    The client connection will need to have comments enabled. For example themariadb and mysql command line clients have comments disabled by default and they need to be enabled by passing the --comments or -c option to it. Most, if not all, connectors keep all comments intact in executed queries.

    For comment types, use either -- (notice the whitespace after the double hyphen) or # after the semicolon or /* ... */ before the semicolon.

    Inline comment blocks, i.e. /* .. */, do not require a whitespace character after the start tag or before the end tag but adding the whitespace is advised.