mysql

Charmed MySQL

Channel Revision Published Runs on
8.0/stable 366 31 Mar 2025
Ubuntu 22.04
8.0/stable 367 31 Mar 2025
Ubuntu 22.04
8.0/candidate 366 24 Mar 2025
Ubuntu 22.04
8.0/candidate 367 24 Mar 2025
Ubuntu 22.04
8.0/beta 366 11 Mar 2025
Ubuntu 22.04
8.0/beta 367 11 Mar 2025
Ubuntu 22.04
8.0/edge 392 18 Jul 2025
Ubuntu 22.04
8.0/edge 391 18 Jul 2025
Ubuntu 22.04
juju deploy mysql --channel 8.0/stable
Show information

Platform:

Ubuntu
22.04

charms.mysql.v0.mysql

MySQL helper class and functions.

The mysql module provides an abstraction class and methods for for managing a Group Replication enabled MySQL cluster.

The MySQLBase abstract class must be inherited and have its abstract methods implemented for each platform (vm/k8s) before being directly used in charm code.

An example of inheriting MySQLBase and implementing the abstract methods plus extending it:

from charms.mysql.v0.mysql import MySQLBase
from tenacity import retry, stop_after_delay, wait_fixed

class MySQL(MySQLBase):
    def __init__(
        self,
        instance_address: str,
        cluster_name: str,
        root_password: str,
        server_config_user: str,
        server_config_password: str,
        cluster_admin_user: str,
        cluster_admin_password: str,
        new_parameter: str
    ):
        super().__init__(
                instance_address=instance_address,
                cluster_name=cluster_name,
                root_password=root_password,
                server_config_user=server_config_user,
                server_config_password=server_config_password,
                cluster_admin_user=cluster_admin_user,
                cluster_admin_password=cluster_admin_password,
            )
        # Add new attribute
        self.new_parameter = new_parameter

    # abstract method implementation
    @retry(reraise=True, stop=stop_after_delay(30), wait=wait_fixed(5))
    def wait_until_mysql_connection(self) -> None:
        if not os.path.exists(MYSQLD_SOCK_FILE):
            raise MySQLServiceNotRunningError()

    ...

The module also provides a set of custom exceptions, used to trigger specific error handling on the subclass and in the charm code.


Index

class Error

Description

Base class for exceptions in this module. None

Methods

Error. __init__( self , message: str )

Initialize the Error class.

Arguments

message

Optional message to pass to the exception.

Error. __repr__( self )

Description

String representation of the Error class. None

Error. name( self )

Description

Return a string representation of the model plus class. None

class MySQLConfigureMySQLUsersError

Description

Exception raised when creating a user fails. None

class MySQLCheckUserExistenceError

Description

Exception raised when checking for the existence of a MySQL user. None

class MySQLConfigureRouterUserError

Description

Exception raised when configuring the MySQLRouter user. None

class MySQLCreateApplicationDatabaseAndScopedUserError

Description

Exception raised when creating application database and scoped user. None

class MySQLGetRouterUsersError

Description

Exception raised when there is an issue getting MySQL Router users. None

class MySQLDeleteUsersForUnitError

Description

Exception raised when there is an issue deleting users for a unit. None

class MySQLDeleteUsersForRelationError

Description

Exception raised when there is an issue deleting users for a relation. None

class MySQLDeleteUserError

Description

Exception raised when there is an issue deleting a user. None

class MySQLRemoveRouterFromMetadataError

Description

Exception raised when there is an issue removing MySQL Router from cluster metadata. None

class MySQLConfigureInstanceError

Description

Exception raised when there is an issue configuring a MySQL instance. None

class MySQLCreateClusterError

Description

Exception raised when there is an issue creating an InnoDB cluster. None

class MySQLCreateClusterSetError

Description

Exception raised when there is an issue creating an Cluster Set. None

class MySQLAddInstanceToClusterError

Description

Exception raised when there is an issue add an instance to the MySQL InnoDB cluster. None

class MySQLRemoveInstanceRetryError

Exception raised when there is an issue removing an instance.

Description

Utilized by tenacity to retry the method.

class MySQLRemoveInstanceError

Exception raised when there is an issue removing an instance.

Description

Exempt from the retry mechanism provided by tenacity.

class MySQLInitializeJujuOperationsTableError

Description

Exception raised when there is an issue initializing the juju units operations table. None

class MySQLClientError

Exception raised when there is an issue using the mysql cli or mysqlsh.

Description

Abstract platform specific exceptions for external commands execution Errors.

class MySQLGetClusterMembersAddressesError

Description

Exception raised when there is an issue getting the cluster members addresses. None

class MySQLGetMySQLVersionError

Description

Exception raised when there is an issue getting the MySQL version. None

class MySQLGetClusterPrimaryAddressError

Description

Exception raised when there is an issue getting the primary instance. None

class MySQLSetClusterPrimaryError

Description

Exception raised when there is an issue setting the primary instance. None

class MySQLGrantPrivilegesToUserError

Description

Exception raised when there is an issue granting privileges to user. None

class MySQLNoMemberStateError

Description

Exception raised when there is no member state. None

class MySQLUnableToGetMemberStateError

Description

Exception raised when unable to get member state. None

class MySQLGetClusterEndpointsError

Description

Exception raised when there is an issue getting cluster endpoints. None

class MySQLRebootFromCompleteOutageError

Description

Exception raised when there is an issue rebooting from complete outage. None

class MySQLSetInstanceOfflineModeError

Description

Exception raised when there is an issue setting instance as offline. None

class MySQLSetInstanceOptionError

Description

Exception raised when there is an issue setting instance option. None

class MySQLOfflineModeAndHiddenInstanceExistsError

Exception raised when there is an error checking if an instance is backing up.

Description

We check if an instance is in offline_mode and hidden from mysql-router to determine this.

class MySQLGetAutoTuningParametersError

Description

Exception raised when there is an error computing the innodb buffer pool parameters. None

class MySQLExecuteBackupCommandsError

Exception raised when there is an error executing the backup commands.

Description

The backup commands are executed in the workload container using the pebble API.

class MySQLDeleteTempBackupDirectoryError

Description

Exception raised when there is an error deleting the temp backup directory. None

class MySQLRetrieveBackupWithXBCloudError

Description

Exception raised when there is an error retrieving a backup from S3 with xbcloud. None

class MySQLPrepareBackupForRestoreError

Description

Exception raised when there is an error preparing a backup for restore. None

class MySQLEmptyDataDirectoryError

Description

Exception raised when there is an error emptying the mysql data directory. None

class MySQLRestoreBackupError

Description

Exception raised when there is an error restoring a backup. None

class MySQLRestorePitrError

Description

Exception raised when there is an error during point-in-time-recovery restore. None

class MySQLDeleteTempRestoreDirectoryError

Description

Exception raised when there is an error deleting the temp restore directory. None

class MySQLExecError

Description

Exception raised when there is an error executing commands on the mysql server. None

class MySQLStopMySQLDError

Description

Exception raised when there is an error stopping the MySQLD process. None

class MySQLStartMySQLDError

Description

Exception raised when there is an error starting the MySQLD process. None

class MySQLServiceNotRunningError

Description

Exception raised when the MySQL service is not running. None

class MySQLTLSSetupError

Description

Exception raised when there is an issue setting custom TLS config. None

class MySQLKillSessionError

Description

Exception raised when there is an issue killing a connection. None

class MySQLLockAcquisitionError

Description

Exception raised when a lock fails to be acquired. None

class MySQLRescanClusterError

Description

Exception raised when there is an issue rescanning the cluster. None

class MySQLSetVariableError

Description

Exception raised when there is an issue setting a variable. None

class MySQLGetVariableError

Description

Exception raised when there is an issue getting a variable. None

class MySQLServerNotUpgradableError

Description

Exception raised when there is an issue checking for upgradeability. None

class MySQLSecretError

Description

Exception raised when there is an issue setting/getting a secret. None

class MySQLGetAvailableMemoryError

Description

Exception raised when there is an issue getting the available memory. None

class MySQLCreateReplicaClusterError

Description

Exception raised when there is an issue creating a replica cluster. None

class MySQLRemoveReplicaClusterError

Description

Exception raised when there is an issue removing a replica cluster. None

class MySQLPromoteClusterToPrimaryError

Description

Exception raised when there is an issue promoting a replica cluster to primary. None

class MySQLFencingWritesError

Description

Exception raised when there is an issue fencing or unfencing writes. None

class MySQLRejoinClusterError

Description

Exception raised when there is an issue trying to rejoin a cluster to the cluster set. None

class MySQLPluginInstallError

Description

Exception raised when there is an issue installing a MySQL plugin. None

class MySQLGetGroupReplicationIDError

Description

Exception raised when there is an issue acquiring current current group replication id. None

class MySQLClusterMetadataExistsError

Description

Exception raised when there is an issue checking if cluster metadata exists. None

class RouterUser

Description

MySQL Router user. None

class MySQLCharmBase

Base class to encapsulate charm related functionality.

Description

Meant as a means to share common charm related code between the MySQL VM and K8s charms.

Methods

MySQLCharmBase. __init__( self )

MySQLCharmBase. get_unit_hostname( self )

Description

Return unit hostname. None

MySQLCharmBase. get_unit_address( self , unit: Unit , relation_name: str )

Description

Return unit address. None

MySQLCharmBase. get_unit_label( unit: Unit )

Description

Return unit label. None

MySQLCharmBase. create_cluster( self )

Create the MySQL InnoDB cluster on the unit.

Description

Should only be run by the leader unit.

MySQLCharmBase. peers( self )

Description

Retrieve the peer relation. None

MySQLCharmBase. cluster_initialized( self )

Description

Returns True if the cluster is initialized. None

MySQLCharmBase. only_one_cluster_node_thats_uninitialized( self )

Description

Check if only a single cluster node exists across all units. None

MySQLCharmBase. cluster_fully_initialized( self )

Returns True if the cluster is fully initialized.

Description

Fully initialized means that all unit that can be joined are joined.

MySQLCharmBase. unit_configured( self )

Description

Check if the unit is configured to be part of the cluster. None

MySQLCharmBase. app_peer_data( self )

Description

Application peer relation data object. None

MySQLCharmBase. unit_peer_data( self )

Description

Unit peer relation data object. None

MySQLCharmBase. app_units( self )

Description

The peer-related units in the application. None

MySQLCharmBase. unit_label( self )

Description

Return unit label. None

MySQLCharmBase. has_cos_relation( self )

Description

Returns a bool indicating whether a relation with COS is present. None

MySQLCharmBase. active_status_message( self )

Description

Active status message. None

MySQLCharmBase. removing_unit( self )

Description

Check if the unit is being removed. None

MySQLCharmBase. unit_initialized( self , raise_exceptions: bool )

Description

Check if the unit is added to the cluster. None

MySQLCharmBase. peer_relation_data( self , scope: Scopes )

Description

Returns the peer relation data per scope. None

MySQLCharmBase. get_cluster_endpoints( self , relation_name: str )

Description

Return (rw, ro, offline) endpoints tuple names or IPs. None

MySQLCharmBase. get_secret( self , scope: Scopes , key: str )

Get secret from the secret storage.

Description

Retrieve secret from juju secrets backend if secret exists there. Else retrieve from peer databag. This is to account for cases where secrets are stored in peer databag but the charm is then refreshed to a newer revision.

MySQLCharmBase. set_secret( self , scope: Scopes , key: str , value )

Description

Set a secret in the secret storage. None

MySQLCharmBase. remove_secret( self , scope: Scopes , key: str )

Description

Removing a secret. None

MySQLCharmBase. generate_random_hash( )

Generate a hash based on a random string.

Returns

A hash based on a random string.

class MySQLMemberState

Description

MySQL Cluster member state. None

class MySQLClusterState

Description

MySQL Cluster state. None

class MySQLTextLogs

Description

MySQL Text logs. None

class MySQLBase

Abstract class to encapsulate all operations related to the MySQL workload.

Description

This class handles the configuration of MySQL instances, and also the creation and configuration of MySQL InnoDB clusters via Group Replication. Some methods are platform specific and must be implemented in the related charm code.

Methods

MySQLBase. __init__( self , instance_address: str , socket_path: str , cluster_name: str , cluster_set_name: str , root_password: str , server_config_user: str , server_config_password: str , cluster_admin_user: str , cluster_admin_password: str , monitoring_user: str , monitoring_password: str , backups_user: str , backups_password: str )

Description

Initialize the MySQL class. None

MySQLBase. instance_def( self , user: str , host )

Return instance definition used on mysqlsh.

Arguments

user

User name.

host

Host name, default to unit address.

MySQLBase. render_mysqld_configuration( self )

Description

Render mysqld ini configuration file. None

MySQLBase. configure_mysql_users( self )

Description

Configure the MySQL users for the instance. None

MySQLBase. install_plugins( self , plugins )

Description

Install extra plugins. None

MySQLBase. uninstall_plugins( self , plugins )

Description

Uninstall plugins. None

MySQLBase. does_mysql_user_exist( self , username: str , hostname: str )

Description

Checks if a mysql user already exists. None

MySQLBase. configure_mysqlrouter_user( self , username: str , password: str , hostname: str , unit_name: str )

Description

Configure a mysqlrouter user and grant the appropriate permissions to the user. None

MySQLBase. create_application_database_and_scoped_user( self , database_name: str , username: str , password: str , hostname: str )

Description

Create an application database and a user scoped to the created database. None

MySQLBase. get_mysql_router_users_for_unit( self )

Description

Get users for related MySQL Router unit. None

MySQLBase. delete_users_for_unit( self , unit_name: str )

Description

Delete users for a unit. None

MySQLBase. delete_users_for_relation( self , username: str )

Description

Delete users for a relation. None

MySQLBase. delete_user( self , username: str )

Description

Delete user. None

MySQLBase. remove_router_from_cluster_metadata( self , router_id: str )

Description

Remove MySQL Router from InnoDB Cluster metadata. None

MySQLBase. set_dynamic_variable( self , variable: str , value: str , persist: bool , instance_address )

Description

Set a dynamic variable value for the instance. None

MySQLBase. get_variable_value( self , variable: str )

Description

Get the value of a variable. None

MySQLBase. configure_instance( self , create_cluster_admin: bool )

Configure the instance to be used in an InnoDB cluster.

Arguments

create_cluster_admin

Whether to create the cluster admin user.

MySQLBase. create_cluster( self , unit_label: str )

Description

Create an InnoDB cluster with Group Replication enabled. None

MySQLBase. create_cluster_set( self )

Description

Create a cluster set for the cluster on cluster primary. None

MySQLBase. create_replica_cluster( self , endpoint: str , replica_cluster_name: str , instance_label: str , donor , method )

Description

Create a replica cluster from the primary cluster. None

MySQLBase. promote_cluster_to_primary( self , cluster_name: str , force: bool )

Description

Promote a cluster to become the primary cluster on the cluster set. None

MySQLBase. fence_writes( self )

Description

Fence writes on the primary cluster. None

MySQLBase. unfence_writes( self )

Description

Unfence writes on the primary cluster and reset read_only flag. None

MySQLBase. is_cluster_writes_fenced( self )

Description

Check if the cluster is fenced against writes. None

MySQLBase. is_cluster_in_cluster_set( self , cluster_name: str )

Description

Check if a cluster is in the cluster set. None

MySQLBase. cluster_metadata_exists( self , from_instance )

Check if this cluster metadata exists on database.

Description

Use mysqlsh when querying clusters from remote instances. However, use mysqlcli when querying locally since this method can be called before the cluster is initialized (before serverconfig and root users are set up correctly)

MySQLBase. rejoin_cluster( self , cluster_name )

Description

Try to rejoin a cluster to the cluster set. None

MySQLBase. remove_replica_cluster( self , replica_cluster_name: str , force: bool )

Description

Remove a replica cluster from the cluster-set. None

MySQLBase. initialize_juju_units_operations_table( self )

Description

Initialize the mysql.juju_units_operations table using the serverconfig user. None

MySQLBase. add_instance_to_cluster( self )

Description

Add an instance to the InnoDB cluster. None

MySQLBase. is_instance_configured_for_innodb( self , instance_address: str , instance_unit_label: str )

Description

Confirm if instance is configured for use in an InnoDB cluster. None

MySQLBase. drop_group_replication_metadata_schema( self )

Description

Drop the group replication metadata schema from current unit. None

MySQLBase. are_locks_acquired( self , from_instance )

Description

Report if any topology change is being executed. None

MySQLBase. rescan_cluster( self , from_instance , remove_instances: bool , add_instances: bool )

Description

Rescan the cluster for topology changes. None

MySQLBase. is_instance_in_cluster( self , unit_label: str )

Description

Confirm if instance is in the cluster. None

MySQLBase. get_cluster_status( self , from_instance , extended )

Description

Get the cluster status dictionary. None

MySQLBase. get_cluster_set_status( self , extended , from_instance )

Description

Get the cluster-set status dictionary. None

MySQLBase. get_cluster_names( self )

Description

Get the names of the clusters in the cluster set. None

MySQLBase. get_replica_cluster_status( self , replica_cluster_name )

Description

Get the replica cluster status. None

MySQLBase. get_cluster_node_count( self , from_instance , node_status )

Description

Retrieve current count of cluster nodes, optionally filtered by status. None

MySQLBase. execute_remove_instance( self , connect_instance , force: bool )

Execute the remove_instance() script with mysqlsh.

Arguments

connect_instance

(optional) The instance from where to run the remove_instance()

force

(optional) Whether to force the removal of the instance

MySQLBase. remove_instance( self , unit_label: str , lock_instance )

Remove instance from the cluster.

Description

This method is called from each unit being torn down, thus we must obtain locks on the cluster primary. There is a retry mechanism for any issues obtaining the lock, removing instances/dissolving the cluster, or releasing the lock.

MySQLBase. dissolve_cluster( self )

Description

Dissolve the cluster independently of the unit teardown process. None

MySQLBase. get_cluster_primary_address( self , connect_instance_address )

Description

Get the cluster primary's address. None

MySQLBase. get_cluster_set_global_primary_address( self , connect_instance_address )

Description

Get the cluster set global primary's address. None

MySQLBase. get_cluster_topology( self )

Description

Get the cluster topology. None

MySQLBase. get_primary_label( self )

Description

Get the label of the cluster's primary. None

MySQLBase. is_unit_primary( self , unit_label: str )

Description

Test if a given unit is the cluster primary. None

MySQLBase. set_cluster_primary( self , new_primary_address: str )

Description

Set the cluster primary. None

MySQLBase. verify_server_upgradable( self , instance )

Description

Wrapper for API check_for_server_upgrade. None

MySQLBase. get_mysql_version( self )

Description

Get the running mysqld version. None

MySQLBase. grant_privileges_to_user( self , username , hostname , privileges , with_grant_option )

Description

Grants specified privileges to the provided database user. None

MySQLBase. update_user_password( self , username: str , new_password: str , host: str )

Description

Updates user password in MySQL database. None

MySQLBase. get_member_state( self )

Description

Get member status (MEMBER_STATE, MEMBER_ROLE) in the cluster. None

MySQLBase. is_cluster_auto_rejoin_ongoing( self )

Description

Check if the instance is performing a cluster auto rejoin operation. None

MySQLBase. is_cluster_replica( self , from_instance )

Description

Check if this cluster is a replica in a cluster set. None

MySQLBase. get_cluster_set_name( self , from_instance )

Description

Get cluster set name. None

MySQLBase. stop_group_replication( self )

Description

Stop Group replication if enabled on the instance. None

MySQLBase. start_group_replication( self )

Description

Start Group replication on the instance. None

MySQLBase. reboot_from_complete_outage( self )

Description

Wrapper for reboot_cluster_from_complete_outage command. None

MySQLBase. hold_if_recovering( self )

Description

Hold execution if member is recovering. None

MySQLBase. set_instance_offline_mode( self , offline_mode: bool )

Description

Sets the instance offline_mode. None

MySQLBase. set_instance_option( self , option: str , value: Any )

Description

Sets an instance option. None

MySQLBase. offline_mode_and_hidden_instance_exists( self )

Description

Indicates whether an instance exists in offline_mode and hidden from router. None

MySQLBase. get_innodb_buffer_pool_parameters( self , available_memory: int )

Description

Calculate innodb buffer pool parameters for the instance. None

MySQLBase. get_max_connections( self , available_memory: int )

Description

Calculate max_connections parameter for the instance. None

MySQLBase. get_available_memory( self )

Description

Platform dependent method to get the available memory for mysql-server. None

MySQLBase. execute_backup_commands( self , s3_path: str , s3_parameters , xtrabackup_location: str , xbcloud_location: str , xtrabackup_plugin_dir: str , mysqld_socket_file: str , tmp_base_directory: str , defaults_config_file: str , user , group )

Description

Executes commands to create a backup with the given args. None

MySQLBase. delete_temp_backup_directory( self , tmp_base_directory: str , user , group )

Description

Delete the temp backup directory. None

MySQLBase. retrieve_backup_with_xbcloud( self , backup_id: str , s3_parameters , temp_restore_directory: str , xbcloud_location: str , xbstream_location: str , user , group )

Description

Retrieve the specified backup from S3. None

MySQLBase. prepare_backup_for_restore( self , backup_location: str , xtrabackup_location: str , xtrabackup_plugin_dir: str , user , group )

Description

Prepare the backup in the provided dir for restore. None

MySQLBase. empty_data_files( self , mysql_data_directory: str , user , group )

Description

Empty the mysql data directory in preparation of backup restore. None

MySQLBase. restore_backup( self , backup_location: str , xtrabackup_location: str , defaults_config_file: str , mysql_data_directory: str , xtrabackup_plugin_directory: str , user , group )

Description

Restore the provided prepared backup. None

MySQLBase. restore_pitr( self , host: str , mysql_user: str , password: str , s3_parameters , restore_to_time: str , user , group )

Run point-in-time-recovery using binary logs from the S3 repository.

Arguments

host

the MySQL host to connect to.

mysql_user

the MySQL user to connect to.

password

the password of the provided MySQL user.

s3_parameters

S3 relation parameters.

restore_to_time

the MySQL timestamp to restore to or keyword latest.

user

the user with which to execute the commands.

group

the group with which to execute the commands.

MySQLBase. delete_temp_restore_directory( self , temp_restore_directory: str , user , group )

Description

Delete the temp restore directory from the mysql data directory. None

MySQLBase. tls_setup( self , ca_path: str , key_path: str , cert_path: str , require_tls: bool )

Description

Setup TLS files and requirement mode. None

MySQLBase. kill_unencrypted_sessions( self )

Description

Kill non local, non system open unencrypted connections. None

MySQLBase. kill_client_sessions( self )

Description

Kill non local, non system open unencrypted connections. None

MySQLBase. check_mysqlcli_connection( self )

Description

Checks if it is possible to connect to the server with mysqlcli. None

MySQLBase. get_pid_of_port_3306( self )

Description

Retrieves the PID of the process that is bound to port 3306. None

MySQLBase. flush_mysql_logs( self , logs_type )

Description

Flushes the specified logs_type logs. None

MySQLBase. get_databases( self )

Description

Return a set with all databases on the server. None

MySQLBase. get_non_system_databases( self )

Description

Return a set with all non system databases on the server. None

MySQLBase. strip_off_passwords( self , input_string )

Description

Strips off passwords from the input string. None

MySQLBase. strip_off_passwords_from_exception( self , e: Exception )

Remove password from execution exceptions.

Description

Checks from known exceptions for password. Known exceptions are:

  • ops.pebble: ExecError
  • subprocess: CalledProcessError, TimeoutExpired

MySQLBase. get_current_group_replication_id( self )

Description

Get the current group replication id. None

MySQLBase. is_mysqld_running( self )

Description

Returns whether mysqld is running. None

MySQLBase. is_server_connectable( self )

Description

Returns whether the server is connectable. None

MySQLBase. stop_mysqld( self )

Description

Stops the mysqld process. None

MySQLBase. start_mysqld( self )

Description

Starts the mysqld process. None

MySQLBase. restart_mysql_exporter( self )

Description

Restart the mysqld exporter. None

MySQLBase. wait_until_mysql_connection( self , check_port: bool )

Wait until a connection to MySQL has been obtained.

Description

Implemented in subclasses, test for socket file existence.

MySQLBase. reset_data_dir( self )

Description

Reset the data directory. None

MySQLBase. reconcile_binlogs_collection( self , force_restart: bool , ignore_inactive_error: bool )

Start or stop binlogs collecting service.

Arguments

force_restart

whether to restart service even if it's already running.

ignore_inactive_error

whether to not log an error when the service should be enabled but not active right now.

Description

Based on the binlogs-collecting app peer data value and unit leadership.

MySQLBase. get_cluster_members( self )

Get cluster members in MySQL MEMBER_HOST format.

Description

Returns: list of the cluster members in the MySQL MEMBER_HOST format.