MySQL script automation and security

After MySQL installation, If you don’t have any enterprise level / any GUI interface for monitoring, backup then one of the option is, write your own scripts to automate these tasks.
In this Blog post, we are going to see few monitoring and backup scripts with covering common security issues.

Credential security

Following is a simple script, which will monitor MySQL service. In case MySQL service [mysqld] is down, then it will send email alert.


# Connection details
MYSQL_PASS="lemon_pwd@123" ----> [# Plain text password, Security thread]
SERVER_HOST=$( hostname ),

# MySQL status
mysqladmin -u${MYSQL_USER} -p${MYSQL_PASS} -h${MYSQL_HOST} ping 2>/dev/null 1>/dev/null
if [ $? -ne 0 ]; then
echo "MySQL database is down " | mail -s " MySQL not running on $SERVER_HOST" "$EMAIL"
# END!!

The Problem with above script is, it has mysql user credentials info in plain text. We should store mysql user credentials to somewhere safe in encrypted file.

mysql_config_editor and Credential security

The mysql_config_editor utility enables you to store authentication credentials in an encrypted login path file named .mylogin.cnf.

1. Create a user for monitoring with required privileges.

CREATE USER IF NOT EXISTS 'monitor'@'localhost' IDENTIFIED BY 'strong_pwd'; 


2. Store user credentials info into .mylogin.cnf (This conf file will get created under current OS user home directory)

shell> mysql_config_editor set --login-path=monitor_client --host=localhost --user=monitor --password                                                                                     

Enter password:<enter_mysql_monitor_user_password>

3. Verify the file contains

shell> mysql_config_editor print --login-path=monitor_client
user = monitor
password = *****
host = localhost

4. Implementation and use.

MySQL access with credentials:

shell> mysql -u monitor -h localhost -p  

MySQL access with mysql_config_editor login_path:

shell> mysql --login-path=minitor_client

Monitoring scripts

Shell script for MySQL service and replication monitoring.


SERVER_HOST=$( hostname ),

# MySQL service monitoring
mysqladmin --login-path=monitor_client ping 2>/dev/null 1>/dev/null
if [ $? -ne 0 ]; then
echo "MySQL database is down " | mail -s " MySQL not running on $SERVER_HOST" "$EMAIL"

# Replication monitoring 

for MYSQL_HOST in localhost
  MSG1=`/usr/bin/mysql --login-path=monitor_client -e "show slave status\G;" | grep 'Slave_IO_Running:'`
  OUTPUT=(${MSG1//:/ })
  STATUS1=`echo ${OUTPUT[1]}`
  MSG2=`/usr/bin/mysql --login-path=monitor_client -e "show slave status\G;" | grep 'Slave_SQL_Running:'`
  OUTPUT=(${MSG1//:/ })
  STATUS2=`echo ${OUTPUT[1]}`
  if [ "$STATUS1" == "Yes" ] && [ "$STATUS2" == "Yes" ];
    echo "$MYSQL_HOST = $STATUS1 - $STATUS2"
    echo "$SERVER_HOST replication not working"
    mail -s "Replication DOWN - $SERVER_HOST" "$EMAIL" <<EOF
Please check $SERVER_HOST database replication.
# End!!

Backup scripts

1. Create a user for backup with required privileges.

CREATE USER IF NOT EXISTS 'backup'@'localhost' IDENTIFIED BY 'strong_pwd'; 


2. Store backup user credentials info into .mylogin.cnf (This conf file will get created under current OS user home directory)

shell> mysql_config_editor set --login-path=backup_client --host=localhost --user=backup --password                                                                                          

Enter password:<enter_mysql_backup_user_password>

3. Backup script


NOW="$(date +"%d-%m-%Y")"
SERVER_HOST=$( hostname )

mkdir -p "$BKP_DIR"
touch "$BKP_DIR/backup.log"

echo "Dumping MySQL databases into separate SQL command files into dir=$BKP_DIR" >> $BKP_DIR/backup.log


for d in $(mysql -NBA --login-path=backup_client -e 'show databases')
   if [[ "$d" != information_schema ]] && [[ "$d" != mysql ]] && [[ "$d" !=  performance_schema ]] && [[ "$d" !=  sys ]]; then
    (( db_count++ ))
   echo "DUMPING DATABASE: $d " >> $BKP_DIR/backup.log
mysqldump --login-path=backup_client --single-transaction  $d | gzip > $BKP_DIR/$d.sql.gz
echo "Dumping --triggers --routines --events for databases $d into dir=$BKP_DIR" >> $BKP_DIR/backup.log
mysqldump --login-path=backup_client --triggers --routines --events --no-create-info --no-data --no-create-db --skip-opt $d | gzip > $BKP_DIR/$d-routines.sql.gz

echo "$db_count databases dumped into dir=$BKP_DIR" >> $BKP_DIR/backup.log

find /apps/backups/full_backups/ -type d -ctime +6 -exec rm -rf {} \;

echo "OLDER than 6 days BACKUPS deleted successfully" >> $BKP_DIR/backup.log

# End!!

Automate these scripts runs and All set!!


MySQL service : Unable to setup unix socket lock file.

How to solve mysqld service restart problem for above error?

Problem :
I was adding shell and home directory for mysql user,executed following cmd,

shell> usermod -m -d /home/mysql -s /bin/bash mysql

If mysql is running and process running with mysql , we need to stop mysql otherwise it will throw an error like usermod: user mysql is currently used by process 27768

After stopping MySQL service and adding shell and homedir for mysql user, at the time mysqld service startup it started throwing error.

shell> service mysqld restart
Redirecting to /bin/systemctl restart mysqld.service
Job for mysqld.service failed because the control process exited with error code. See "systemctl status mysqld.service" and "journalctl -xe" for details.
Shell> systemctl status mysqld.service

● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: deactivating (final-sigterm) (Result: exit-code) since Wed 2016-12-14 22:16:42 MST; 7min ago
Docs: man:mysqld(8)
Process: 35222 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/ $MYSQLD_OPTS (code=exited, status=1/FAILURE)
Process: 35204 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 27768 (code=exited, status=0/SUCCESS)
CGroup: /system.slice/mysqld.service
└─35226 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/

mysqld error logs:

[ERROR] Could not create unix socket lock file /var/lib/mysql/mysql.sock.lock.
[ERROR] Unable to setup unix socket lock file.
[ERROR] Aborting

Tried to stop, kill mysqld service but still it’s not going out from process list.

Root cause : Suspecting change in process id after modifying mysql user properties.


Just Move/Rename your my.cnf and start mysqld service with default configuration.You will see no more error at the time for service startup.
Move backuped up /renamed original my.cnf and restart mysqld service again.

service mysqld restart

And should start working fine, as it is.

ALl set!!

Strict sql mode and errors

After MySQL version upgrade, there is a possibility that application will start getting error/exception for INSERT/UPDATE operation due missing default data/values as follows,

ERROR:  Field ‘column_name’ doesn’t have a default value

Also above error will trigger for the wrong data type or out of range value for the column with INSERT/UPDATE sql operation.

Reason for this error is new SQL_MODE default values (MySQL 5.7 ) that included STRICT_TRANS_TABLES value in it and sql_mode value in default my.cnf created after installation[ Under /etc/my.cnf or /usr/my.cnf ]

sql_mode MySQL version Default

Lets take scenario where application was running with MySQL 5.5 /5.6 and then upgraded to MySQL version to 5.7.
After upgrade your application will start getting error/exception for INSERT/UPDATE operation  missing default values as follows.

ERROR:  Field ‘column_name’ doesn’t have a default value

If you do further troubleshooting for table which you are having issue, you will see that in the table definition column using NOT NULL constraint but there is no default value for it.
So, in such case if your application sending INSERT with no value for column with not null constraint then mysql will throw an error for that INSERT operation, because of  STRICT_TRANS_TABLES in sql_mode.


mysql> show variables like 'sql_mode';
| Variable_name | Value |
1 row in set (0.00 sec)

mysql> create table sqlmode_test (id int(11) primary key auto_increment, uname varchar(30) , language varchar(12) not null);
Query OK, 0 rows affected (0.04 sec)

mysql> set session sql_mode='STRICT_TRANS_TABLES';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> show variables like 'sql_mode';
| Variable_name | Value |
| sql_mode | STRICT_TRANS_TABLES |
1 row in set (0.00 sec)

mysql> insert into sqlmode_test(uname) values ('harsh');
ERROR 1364 (HY000): Field 'language' doesn't have a default value
mysql> set session sql_mode='';
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'sql_mode';
| Variable_name | Value |
| sql_mode | |
1 row in set (0.00 sec)

mysql> insert into sqlmode_test(uname) values ('harsh');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
| Level | Code | Message |
| Warning | 1364 | Field 'language' doesn't have a default value |
1 row in set (0.00 sec)

mysql> select * from sqlmode_test;
| id | uname | language |
| 1 | harsh | |
1 rows in set (0.00 sec)



Option 1:
Correct table column definition [ To avoid Error and warnings ]

Option 2:  [SQL with throw warning and not an error]
Remove strict sql mode
SET GLOBAL sql_mode=”;
-Persist in my.cnf
sql_mode= ”

All set !!

MySQL Architecture and Components

This blog post is all about new MySQL 5.7 physical, logical architecture and it’s components.In this blog post, I will try to explain things in flow including data processing and SQL execution in MySQL with the help of diagrams.

Unlike the other databases, MySQL is a very flexible and offers different kinds of storage engines as a plugin for different kinds of needs. Because of this, MySQL architecture and behavior will also change as per the use of storage engines, for example transactional [InnoDB] and non-transactional [MyISAM] engines data storage and SQL execution methods will be different and within the server it will use engine specific components like memory and buffers depending on type storage engine will get used for the SQL operation.
Will discuss more InnoDB, since it’s default and main storage engine for MySQL.

MySQL Physical Architecture:


Configuration files:

auto.cnf :  Contains server_uuid
my.cnf :     MySQL Configuration file.

Miscellaneous files:

The path to the MySQL binaries installation directory.
The path to the MySQL data directory contains data, status and log files.
The path name of the file in which the server should write its process ID.
–socket=file_name, -S file_name
On Unix, the name of the Unix socket file to use, for connections made using a named pipe to a local server.
Log errors and startup messages to this file.

MySQL Logical Architecture:


Client :
Utility to connect MySQL server.

Server :
MySQL instance where actual data getting stored and data processing is happening.

MySQL Server daemon program which runs in the background and manages database related incoming and outgoing requests from clients. mysqld is a multi-threaded process which allows connection to multiple sessions listen for all connections and manages MySQL instance.

MySQL memory allocation:
Main MySQL memory is dynamic, examples innodb_buffer_pool_size (from 5.7.5), key_buffer_size etc.Working on shared nothing principal which means, every session has unique execution plan and we can share data sets only for the same session.


  • Allocated once
  • Shared by the server process and its threads


  • Allocated for each mysql client session
  • Dynamically allocated and deallocated
  • Used for handling query result
  • Buffer size per session

Connection/Thread Handling:
Manages client connections/sessions [mysql threads]

Check for SQL syntax by checking every character in SQL query and generate SQL_ID for each SQL query.

Optimizer :
Created efficient query execution plan as per the storage engine.It will rewrite a query.Example: InnoDB has shared buffer so optimizer will get pre-cached data from it. Using table statistics optimizer will generate an execution plan for a SQL query.

Metadata cache:
Cache for object metadata information and statistics.

Query cache:
Shared identical queries from memory.If an identical query from client found in query cache then, the MySQL server retrieves the results from the query cache rather than parsing and executing that query again. It’s a shared cache for sessions, so a result set generated by one client can be sent in response to the same query issued by another client. Query cache based on SQL_ID.SELECT data into view is the best example to pre-cache data using query cache

key cache:
Cache table indexes.In MySQL keys are indexes(In oracle keys are constraints) if index size is small then it will cache index structure and data leaf.If an index is large then it will only cache index structure.Used by MyISAM storage engine.

Storage engine:
MySQL component that manages physical data (file management) and locations. Storage engine responsible for SQL statement execution and fetching data from data files. Use as a plugin and can load/unload from running MySQL server.Few of them as following,

  1. InnoDB :
    • Fully transactional ACID.
    • Offers REDO and UNDO for transactions.
    • Data storage in tablespace:

    – Multiple data files
    – Logical object structure using innodb data and log buffer

    • Row level locking.
  2. NDB (For MySQL Cluster):
    • Fully Transactional and ACID Storage engine.
    • Distribution execution of data and using multiple mysqld.
    • NDB use logical data with own buffer for each NDB engine.
    • Offers REDO and UNDO for transactions.
    • Row level locking.
  3. MyISAM:
    • Non-transactional storage engine
    • Speed for read
    • Data storage in files and use key, metadata and query cache

    – FRM  for table structure
    – MYI for table index
    – MYD for table data

    • Table level locking.
  4. MEMORY:
    • Non-transactional storage engine
    • All data stored in memory other than table metadata and structure.
    • Table level locking.
    • Non-transactional storage engine,
    • Store large amounts of compressed and unindexed data.
    • Allow INSERT, REPLACE, and SELECT, but not DELETE or UPDATE sql operations.
    • Table level locking.
  6. CSV:
    • Stores data in flat files using comma-separated values format.
    • Table structure need be created within MySQL server (.frm)

SQL execution


Other storage engines  like InnoDB,NDB are having logical structure for data and they have their own data buffer. This buffer define on storage engine level.

About InnoDB Storage Engine:

  • Fully transactional ACID.
  • Row level locking.
  • Offers REDO and UNDO for transactions.
  • Data storage in tablespace:
    – Multiple data files
    – Logical object structure using InnoDB data and log buffer
  • Use shared file to store objects [Data and Index in the same file]
  • InnoDB data is 100% of a logical structure, data stored physically.
  • InnoDB Read physical data and build logical structure[Blocks and Rows]
  • Logical storage called as TABLESPACE.

InnoDB storage engine architecture:



Storage for InnoDB is divided into tablespaces. A tablespace is a logical structure associated with multiple data files(objects). Each tablespace contains pages(blocks),extents and segments.


Pages: a Smallest piece of data for InnoDB also called as blocks. Default page size is 16kb and page can hold one or more rows depending on row size.

Available page sizes: 4kb,8kb,16kb,32kb,64kb
Variable name           : innodb_page_size
Need  to configure before initializing mysqld server.

Extents:  It’s a group of pages.For better I/O throughput innodb read or write a collection of pages i.e one extent at a time.
For a group of pages with default page size 16kb, extent size up to 1mb.
Doublewrite buffer read/write/allocate or free data as one extent at a time.

Segments:  Collection of files in InnoDB tablespace.Use up to 4 extents in a segment.

Innodb components:

In Memory:

InnodDB buffer pool:
Central buffer for InnoDB storage engine.In this data buffer, we load blocks and cache table and index data.
– The main memory where InnoDB cache table data and indexes.
–  Size up to 80% of physical memory on dedicated DB server.
– Shared buffer across all sessions.
– InnoDB use LRU (Least Recently Used ) page replacement algorithm.
– Data that is being reused is always in the same memory.
– Data that does not used get phased out eventually.

Change buffer:
In a memory change buffer is a part of InnoDB buffer pool and on disk, it is part of system tablespace, so even after database restart index changes remain buffered.Change buffer is a special data structure that caches changes to secondary index pages when affected pages not in the buffer pool.

Redo log buffer:
Buffer for redo logs, hold data to written to the redo log.Periodically data getting flushed from redo log buffer to redo logs. Flushing data from memory to disk managed by innodb_log_at_trx_commit and innodb_log_at_timeout configuration option.

– A large size of redo log buffer enables a large transaction to run without writing redo logs to disk before the transaction commit.
– Variable:
innodb_log_buffer_size (default 16M)

On Disk:

System tablespace:  
Apart from the table data storage, InnoDB’s functionality requires looking for table metadata and storing and retrieving MVCC info to support ACID compliance and Transaction Isolation. It contains several types of information for InnoDB objects.

  • Contains:
    Table Data Pages
    Table Index Pages
    Data Dictionary
    MVCC Control Data
    Undo Space
    Rollback Segments
    Double Write Buffer (Pages Written in the Background to avoid OS caching)
    Insert Buffer (Changes to Secondary Indexes)
  • Variables:
    innodb_data_file_path = /ibdata/ibdata1:10M:autoextend

    By enabling innodb_file_per_table (the default) option, we can store each newly created table (data and index) in a separate tablespace. Advantage for this storage method is less fragmentation within disk data file.

General tablespace:
Shared tablespace to store multiple table data. Introduce in MySQL 5.7.6. A user has to create this using CREATE TABLESPACE syntax. TABLESPACE option can be used with CREATE TABLE to create a table and ALTER TABLE to move a table in general table.

– Memory advantage over innodb_file_per_table  storage method.
– Support both Antelope and Barracuda file formats.
–  Supports all row formats and associated features.
–  Possible to create outside data directory.

InnoDB data dictionary:
Storage area in system tablespace made up of internal system tables with metadata information for objets[tables,index,columns etc.]

Double write buffer:
Storage area in system tablespace where innodb writes pages from innodb buffer pool, before writing to their proper location in the data files.
In case mysqld process crash in the middle of a page writes, at the time of crash recovery InnoDB can find a good copy of the page from doublewrite buffer.

Variable: inndb_doublewrite (default enable)

REDO logs:
Use for crash recovery. At the time of mysqld startup, InnoDB perform auto recovery to correct data written by incomplete transactions. Transactions that not finish updating data files before an unexpected mysqld shutdown are replayed automatically at the time of mysqld startup even before taking any connection. It uses LSN(Log Sequence Number) value.
Plenty of data changes can not get written to disk quickly, so it will go under redo and then to the disk.

Why we need a redo for recovery?
Let’s take an example, User changing data in innodb buffer and commit, somewhere it needs to go before writing into a disk. Because in the case of crash buffer data will lost, that’s why we need redo logs.

– In redo, all changes will go with info like row_id, old column value, new column value, session_id and time.
– One commit complete data will under disk in a data file.
– Variables:
Innodb_log_file_in_group= [# of redo file groups]
Innodb_log_file_size= [Size for each redo file]

UNDO tablespace and logs:
UNDO tablespace contains one or more undo logs files.
UNDO manages consistent reads by keeping modified uncommitted data for active transaction [MVCC]. Unmodified data is retrieved from this storage area.Undo logs also called as rollback segments
By default, UNDO logs are part of system tablespace, MySQL allows to store undo logs in separate UNDO tablespace/s [Introduce in MySQL 5.6]. Need to configure before initializing mysqld server.

– When we configure separate undo tablespace, the undo logs in the system tablespace become inactive.
– Need to configure before initializing mysqld server and can not change after that.
– We truncate undo logs, but can not drop.
– Variables :
innodb_undo_tablespace : # of undo tablespaces, default 0
innodb_undo_directory:Location for undo tablespace,default is data_dir with 10MB size.
innodb_undo_logs : # of undo logs, default and max value is ‘128’

Temporary tablespace:
Storage to keep and retrieve modified uncommitted data for temporary tables and related objects.Introduce in MySQL 5.7.2 and use for rollback temp table changes while a server is running.

– Undo logs for temporary tables reside in the temp tablespace.
– Default tablespace file ibtmp1 getting recreated on server startup.
–  Not getting used for crash recovery.
– Advantage: Performance gain by avoiding redo logging IO for temp tables and related objects.
– Variable:
innodb_temp_data_file_path = ibtmp1:12M:autoextend (default)

And All SET !!

MySQL 5.7 and administration

MySQL 5.7 improved as compare to previous releases in terms of transnational capabilities, performance with high load, high Availability, Security and it’s defaults.

Check my blog post : MySQL 5.7 features

This blog post will describe End to End implementation of MySQL on Linux distributions Which will cover MySQL Installation, configuration and administration in production environment with proper configuration. So you can start using your application by implementing following setup and in future you can change it if requires.

Database Installation:

There are number of ways to install MySQL,

  • Source code
  • Binaries : Compressed tar file binary distribution
  • Packages :  RPM-based Linux distributions
  • MySQL Installer MSI and ZIP Archive
  • Yum repository

MySQL installation using packages is one the easy way to install MySQL and you don’t have to worry about installation configuration part.Another option is installing MySQL using compressed tar file, with this installation method user has to perform installation and most of the configuration part.

On Windows : MySQL Installer MSI will take care of everything including installation of supporting monitoring tool and utilities, MySQL configuration settings and user management

Let’s Install MySQL RPM packages.For standard installation, we will install mysql-community-servermysql-community-clientmysql-community-libsmysql-community-common, and mysql-community-libs-compat packages.

Always use new version of MySQL GA release for new installations.

MySQL Installation steps:

1. Download RPM package from for your OS architecture :

2. Run following command to install MySQL.

sudo yum install mysql-community-{server,client,common,libs}-*

The installation also creates a user named mysql and a group named mysql on the system.

3. Default configuration file location /etc/my.cnf file.

4. Standard directory structure for MySQL:

A standard installation of MySQL using the RPM packages result in files and resources created under the system directories, shown in the following table.


MySQL basedir will have default distributed dir structure, except datadir. It is recommended to keep datadir in a different location for numerous reasons.For, this you just need to update ‘datadir’  variable value with new datadir location

5. MySQL configuration file: /etc/my.cnf

By, default my.cnf will get created by MySQL rpm installation with default configuration in it. We need to add few more configuration variables in order to make MySQL DB server ready for production use. Following are the standard configuration settings for a production database. These variable values may vary as per the application scope and data workload.

MySQL configuration file sections – MySQL configuration file have many sessions, such as [mysqld], [mysql], [client], [mysqld_safe] , [mysqldump] and so on.

  • Add/update following variables to appropriate configuration section of my.cnf.

user = mysql
port = 3306
default_storage_engine = InnoDB
socket = /var/lib/mysql/mysql.sock
pid_file = /var/run/mysql/

datadir =/var/lib/mysql/data

innodb_buffer_pool_size = 4000M (60-70 % of RAM memory)
innodb_data_file_path= ibdata1:1G;ibdata2:500M:autoextend
innodb_flush_method = O_DIRECT

log_error = /var/log/mysql/mysqld.log
master_info_repository = TABLE
relay_log_info_repository = TABLE
log-slave-updates= 1
expire_logs_days = 7

socket = /var/lib/mysql/mysql.sock

socket = /var/lib/mysql/mysql.sock
port = 3306

6. Start MySQL service

sudo service mysqld start

7. At the initial start-up of the server, the following happens, when MySQL data directory is empty:

  • The server is initialized.
  • An SSL certificate and key files are generated in the data directory.
  • Thevalidate_password plugin is installed and enabled.
  • A superuser account’root’@’localhost’ is created. A password for the superuser is set and stored in the error log file.
  • Look for root password in error log file.
sudo grep 'temporary password' /var/log/mysqld.log

8. After login first time into MySQL , we can not proceed further without resetting root password.

shell> mysql –uroot -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'r00t$PWD';

For any startup issue  check  /var/log/mysqld.log 

MySQL Variables and Configuration:

MySQL Variables
User mysql service user
Server-id Value : 1 default

Any number in DB group

Port Value: 3306 default
Skip-name-resolve Do not resolve host names when checking client connections. Use only IP addresses.
bind_address MySQL bind_address for network interfaces.

IPv4 :

IPv4 and IPv6 : *

Socket Unix socket file for listening local connections
Pid-file The path name of the process ID file.
default_storage_engine Default storage engine for MySQL

Value: Innodb

Datadir Main directory where database,system tablespace and log files will get store.
innodb_file_per_table Seperate tablespace for each table.Good for performance and reclaiming free space.

Value : on

Innodb_buffer_pool_size Value should be 60-70 percent of RAM memory of server
innodb_log_file_size Redo and undo logs ,useful for innodb recovery.

Value should be greater if you are using BLOB datatype in your database.

Value: innodb_log_file_size=150M

innodb_log_files_in_group Number for innodb_log_file

Value : 3

innodb_data_file_path= System tablespace configuration

Value:ibdata1:1G;ibdata2:1G:autoextend (vary)

innodb_flush_method Method used to flush data to the InnoDB data files and log files.

value : O_DIRECT

innodb_tmpdir tmp directory for ONLINE ALTER operations.
log_error mysql server log
log-bin Binary log file name

Value : mysql-bin152

binlog_format binary log formate for data




crash-safe replication settings, storing log info in table instead of file.

Value:  TABLE

relay-log relay log name


relay_log_recovery relay_log_recovery= on
log-slave-updates log-slave-updates=1
expire_logs_days Auto delete binary logs after mentioned days

expire_logs_days= 60

gtid-mode Enable GTID for transactions

Value : on

enforce-gtid-consistency Value : on

MySQL User Management

MySQL Database Users


CREATE USER [IF NOT EXISTS] 'local_user1'@'localhost' IDENTIFIED BY 'usr#PWD';

(Remote connection restricted for this user)

If you specify only the username part of the account name, a host name part of ‘%’ is used.


(Remote connection enabled for this user)

-User details getting stored under mysql.user table.


RENAME USER 'abc'@'localhost' TO 'xyz'@'%';

User password management:

  1. Change/Update user password. [IF EXISTS] -Optional
ALETR USER [IF EXISTS] 'remote_user1'@'%' IDENTIFIED BY 'usr#PWD';
  1. Password expire user account
  1. Locked User account


DROP USER 'remote_user1'@'%’;

MySQL Database Users Access Restrictions using privileges

Grant privileges to user:

Privileges can be granted on database and table only.


Case1:  Grant all privileges on ‘db1’ database to user ‘remote_user1’@’%’

GRANT ALL ON db1.* TO 'remote_user1'@'%';

Case2: Grant selected privileges on ‘db1’ database to user ‘remote_user1’@’%’

GRANT SELECT, INSERT, UPDATE, DELETE ON db1.* TO 'remote_user1'@'%';

Case3. Grant SELECT privilege single table access to user ‘remote_user1’@’%’

GRANT SELECT ON db1.table1 TO 'remote_user1'@'%';

Revoking privileges from user:



Check User Privileges using SHOW GRANTS command:


SHOW GRANTS FOR 'root'@'localhost';
SHOW GRANTS; (It will display the privileges granted to the current account)
SHOW GRANTS FOR 'remote_user1'@'%';

MySQL DB Backup and Restore:

Logical backup

The mysqldump client utility performs logical backups, which create a pain file with sql statements in it.

System database backup not required, so while taking backup only take backup of non-system database i.e. application databases


Full Database backup:

mysqldump -u root -h db_host -p --single-transaction --databases db1 --routines --events > db1_fullbkp.sql


mysqldump -u root -h db_host -p --single-transaction --databases db1 --routines --events | gzip > db1_fullbkp.sql.gz

Single table backup:

mysqldump -u db_username -h db_host -p --single-transaction db_name table_name > db1_full.sql


To reload a dump file, you must have the privileges required to execute the statements that it contains.

mysql -u username -p db_name < db1_fullbkp.sql


gunzip < db1_fullbkp.sql.gz | mysql -u username -p db_name

Note:  –single-transaction option for consistent non-blocking backup.

For InnoDB tables, it is possible to perform an online backup that takes no locks on tables using the –single-transaction option to mysqldump.

  • Create separate backup user with require backup privileges.
  • Schedule the backup script in crontab of mysql UNIX account.

Physical/Binary backup:

MySQL Enterprise Backup

Percona XtraBackup

Note: Binary backup mostly use for backing up large volume database.For small volume database use mysqldump.

MySQL DB Monitoring:

1. MySQL enterprise monitor

2.  MySQL workbench GUI tool.

3. Script automation : Write scripts with required monitoring command and automate this scripts using cronjobs. Email notification also can be added in this script for critical alerts.

– Create a separate user for monitoring with required privileges.

CREATE USER [IF NOT EXISTS] 'monitor'@'localhost' IDENTIFIED BY 'mon$pwd';
GRANT SELECT,PROCESS ON *.* TO 'monitor'@'localhost';

–  Create monitoring schedule it with cronjob for automatic runs.

Sample script To check server status:


# Connection details





SERVER_HOST=$( hostname )

# MySQL status

mysqladmin ${MYSQL_CONN} ping 2>/dev/null 1>/dev/null

if [ $? -ne 0 ]; then

echo "MySQL Down" | mail -s " MySQL not running on $SERVER_HOST" "$EMAIL_IDS"


NOTE: There are many other mysql monitoring command you can add in this script.

Replication :

We can setup relication using binlog and binlog position and other one is GTID based replication.Will setup GTID Replication which is new and more relable.

  1. Enable binary log and GTID on both master and slave.
  2. Create a replication user on MASTER as follow:
CREATE USER 'rpluser'@'%' IDENTIFIED BY 'rpluser1234';

3. Setup replication on slave using CHANGE MASTER TO cmd as follow:


4.  Start replication and check slave status.


5 .  Slave_IO_Running and Slave_SQL_Running column value should be ‘YES’.

Check My Blog post : GTID Replication and troubleshooting

All set !!

MySQL 5.7 for production

With the time MySQL as database getting better in terms of High performance , scalability and security.
MySQL 5.7 new features :

As a MySQL user my favorites are from above list:

  •  New options for replication :
    Changing replication filters online including and excluding table/db and enabling GTID transaction online.
  •  InnoDB related changes:
    Online buffer pool resize and many defaults are changed to more secure and optimized values.
  • Security features :
    Improved User authentication like default users, SSL and data encryption with key capabilities in order to secure overall database.
  • Monitoring and analysis statistics :
    Improved performance schema for live transactions analysis which we can not mostly find out with SHOW PROCESSLIST command or Be Using INFORMATION_SCHEMA database tables.
  • All in this very important is “Setting configuration variables dynamically while a server is running.This change will save many downtimes or mysqld service restarts.
  • Optimizer:
    New optimizer changes will be the one doing magic inside for Query performance.

Something New :

  • Multi-source replication
  • Innodb tablespace encryption using key
  • MySQL x-protocol and Document store using JSON datatype capabilities.
  • Optimized and secure defaults settings for initial MySQL database setup.

I believe these are the most imported MySQL database areas used by MySQL user in the production environment.

How many of you using mysql-5.7 in production or planning for implementation in future? Please share your experience with it.

Mysql table locking

Locking is important in many scenarios to prevent other sessions from modifying tables during periods when a session requires exclusive access to them. for example altering table definition online or any kind of table definition changes.locking Mysql provides an option to lock table/s with different types of locks, depends on need.

syntax for lock table:

    tbl_name [[AS] alias] lock_type
    [, tbl_name [[AS] alias] lock_type] ...



Following are the examples for READ and WRITE LOCK:


session1> create table t1( c1 int);
Query OK, 0 rows affected (0.06 sec)

session1> insert into test.t1 values(1001);
Query OK, 1 row affected (0.01 sec)

session1> lock table t1 READ;
Query OK, 0 rows affected (0.00 sec)

session1> select count(*) from t1;
| count(*) |
| 1 |
1 row in set (0.00 sec)
session1> insert into t1 values(1002);
ERROR 1099 (HY000): Table 't1' was locked with a READ lock and can't be updated

Session1 acquired READ lock on table t1 explicitly. After applying READ lock on table users can read the table but not write it.

session2> lock table t1 READ;
Query OK, 0 rows affected (0.00 sec)

session2> insert into t1 values(1002);
ERROR 1099 (HY000): Table 't1' was locked with a READ lock and can't be updated

session3> select * from t1;
| c1 |
| 1001 |
1 row in set (0.00 sec)

Multiple sessions can acquire a READ lock on the table at the same time and other sessions can read the table without explicitly acquiring a READ lock.

currently, READ lock s acquired by session1 and session2, both locks need to be unlocked in order to perform a write operation on lock table.

session1> UNLOCK TABLES;
session1> insert into t1 values(1005);

INSERT operation executed from session1  will go in waiting state, since READ lock acquired on table t1 by session2 and not  released yet.

You can see this using:

session3> show processlist;
| Id | User | Host | db | Command | Time | State | Info |
| 2 | session1 | localhost | test | Query | 89 | Waiting for table metadata lock | insert into test.t1 values(1005) |
| 3 | session3 | localhost | test | Query | 0 | starting | show processlist |
| 4 | session2 | localhost | test | Sleep | 77 | | NULL |
3 rows in set (0.00 sec)

After releasing READ lock by session2 insert operation will execute on t1 table.

session2> UNLOCK TABLES;
session1>  select * from t1;
| c1 |
| 1001 |
| 1005 |
2 rows in set (0.00 sec)


FLUSH TABLE:  Closes all open tables, forces all tables in use to be closed, and flushes the query cache. FLUSH TABLES also removes all query results from the query cache, like the RESET QUERY CACHE statement. FLUSH TABLE will not work when table acquires READ LOCK.

UNLOCK TABLES: UNLOCK TABLES explicitly releases any table locks held by the current session. LOCK TABLES implicitly releases any table locks held by the current session before acquiring new locks.



-The session that holds the lock can read and write the table.

session1> lock table t1 write;
Query OK, 0 rows affected (0.00 sec)

session1> insert into test.t1 values(1006);
Query OK, 1 row affected (0.01 sec)

session1> select count(*) from t1;
| c1 |
| 1001 |
| 1005 |
| 1006 |
3 rows in set (0.00 sec)

-Only the session that holds the lock can access the table. No other session can access it until the lock is released.

session2> select count(*) from t1;
session3> insert into test.t1 values(1002);

session1> show processlist;
| Id | User | Host | db | Command | Time | State | Info |
| 2 | session1 | localhost | test | Query | 0 | starting | show processlist |
| 3 | session2 | localhost | test | Query | 127 | Waiting for table metadata lock | select count(*) from t1 |
| 4 | session3 | localhost | test | Query | 116 | Waiting for table metadata lock | insert into test.t1 values(1002) |
3 rows in set (0.00 sec)

Look into performance_schema.metadata_locks table for more status information on table locks. (Thanks for the hint daniel )

– Enable Locking related instruments (if it’s not enabled) :

UPDATE performance_schema.setup_instruments SET ENABLED=’YES’, TIMED=’YES’ WHERE NAME=’wait/lock/metadata/sql/mdl’;

SELECT * FROM performance_schema.metadata_locks WHERE OBJECT_SCHEMA=’test’ AND OBJECT_NAME LIKE ‘t_’;

-Lock requests for the table by other sessions block while the WRITE lock is held.

All set  🙂 ……