Showing posts with label MySQL DBA. Show all posts
Showing posts with label MySQL DBA. Show all posts

Sunday, March 28, 2010

MySQL Server Connection System Variables Setting and Tuning

MySQL Performance Tunning: Server Connection Variables Setting and Tunning

The max_connections MySQL server configuration variables sets the maximum concurrent connections allow to the database server. If there is not enough connections for all the clients to connect, an error message, “too many connects”, is sent back the client and connection is refused. While the max_connections variable dictiated how many connections are allowed to connect to the server, all the variables list bellow should be configured and tuned to maximize the server connection performance.

  •  Max_Connections
  •  Max_user_connections
  •  Table_open_caches (table_cache)
  •  Open_files_limit
  •  thread_cache_size


First, as mentioned above, the connections variable sets the number of concurrent connections to the MySQL server at one time. The default value is 100 which is low for most systems Hower, The value should not be set to too hight because each connection require memory and file descriptor. On the other hand, setting a large number of connections benefit persistent connection because large number of connections allow persistent connection to remain opened rather than being close and reopen frequently. For linux system, the number is range from 500 to 1000. If there is no enough connections, the client will receive a “Too many connections” error message and will be refused to connected to the database server.

The max_user_connections variable sets the maximum number of simultaneous connections allowed to any given MySQL user account. The default is set to 0 which means “no limit.” This variable has a global value that can be set at server startup or runtime. It also has a read-only session value that indicates the effective simultaneous-connection limit that applies to the account associated with the current session. The session value is initialized as follows:
· If the user account has a nonzero MAX_USER_CONNECTIONS resource limit, the session max_user_connections value is set to that limit.
· Otherwise, the session max_user_connections value is set to the global value.

The table_open_cache (table_cache for MySql version before 5.1.3) sets the vaules for the number of open table for all threads that the server allows. The default values is 64. Increase this values will increase the number of file descriptors that MySql requires. It is important to make sure that the OS can handle the open file desriter set by the table_opne_cache variable. If the values of table_open_cache is set to too high a value, the MySql server may run out of file descriptots and refuse connections, fail to excute queries, and has unreliable behavior.

The open_file_limit variable sets the number of open file descriptors the operating system allows to open.

The thread_cache_size variable sets the amount of threads will be cached after a connection disconeects for the purpose of maintaining memory for new connection. When a client disconnects, the client's threads are put in the cache if there are fewer than thread_cache_size threads there. Requests for threads are satisfied by reusing threads taken from the cache if possible, and only when the cache is empty is a new thread created.

1.Setting Variables

To determind what value to be set for each variable, we should start by getting some statistics from the current system. If it is going to be a newly deploy system, we should do some scientifit extimation for each values and mornitoring the system for a few days and correct the statistics from the running system, then, change the configuration values as needed.

To check server status from mysql prompt do the following:
mysql>show status \G;

The about commond will display all the status variables. You can also choose to display a sub set of the status variable by using the ‘Like’ clause.

mysql> show global status like '%connection%';
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| Connections | 76 |
| Max_used_connections | 5 |
+----------------------+-------+
2 rows in set (0.00 sec)

mysql> show global status like 'open%table%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Open_table_definitions | 77 |
| Open_tables | 4 |
| Opened_table_definitions | 73 |
| Opened_tables | 11531 |
+--------------------------+-------+
4 rows in set (0.02 sec)

To set server variables, use the SET GLOBAL variable_name=value command in the mysql prompt:

mysql> set global max_connections=300;
Query OK, 0 rows affected (0.00 sec)

Please remember to update the my.cnf file with the updated variable values so the server will start with the new variables in the next restart.

1.1 Getting Server Status

First, check the following server status variables are related to server connections.

· Connections
· Max_used_connections
· Open_tables
· Opened_tables
· Opened_table_definitions
· Open_files
· Threads_cached
· Threads_connected
· Threads_created
· Threads_running

Connections status show the number of connections attemts (successful or fail) to the MySql server since the server started.

Max_used_connections status show the maximum number of connections that have been used simultaneously since the server started. This maximum number this status variable will show is connections + 1. Therefore the connections system variable should be set to above this status number and increased when this status number increased. It is a good idead to set up an alert to monitor the Max_used_connections status variable and proactively change the connections system variable value when the status variable value is close to the connections value.

Open_tables status show the number of currently open tables. A single table open 10 times will add 10 to open_table status. Since mysql is a multi-threaded system, each running quering will open one or more tables, same or different. Truce, open_tables status values will much larger that the total physical number of table a database has. If the open_tables status return a large number, it is a sign that table_cache is not big enough.

Opened_tables status show the number of tables that have been opened. If opend_tables is big, it means that not all the tables are being cached; therefore, table_cache value need to be increased.

Opened_table_definitions status (MySql v5.1.24 or later) show the number of .frm files (table definitions) that have been cached.

Open_files status shows the number of open files descriptors that are currently active.

Threads_cache status shows the number of threads in the thread_cashe

Thread_connected status shows the number of currently opend connections.

Thread_created status shows the number of threads created to handle connections. If the Thread_created status values is big or close to the number of the thread_cache_size server variable, then we should consider to increase the thread_cache_size server variable value. It is good to evaluate the cache miss rate from time to time using the following formular:
Theads_created / Connections.

One way to check if the thread_cache_size is large enough is to gradutely increase it value until the thread_created status value increases increase at a low rate. Thread connection overhead is quite low on linux system.

Thread_running status shows the number if threads that are currently active and not sleeping.

Show Processlist command can also be used (with PROCESS privilege) to obtain the total running processes.

It is also worth to take a look the difference between a process and a thread and how MySQL utilizes threads. A processe has their own heap (memory space), whereas threads share this space. When a new process is created, the operating system has to create a new address space for it to execute a set of instructions with full control over various resources to complete the tasks. On the other hand, threads work under the address space given to its parent process and can change state without having to create a new process. MySQL is a single process multi-threads architecture (a thread-based server architecture) which allows the various executing threads (or lightweight processes) to access key shared resources.

If MySQL is running on Linux, we should also check the open file descriptors (sockets). To check current open file descriptors limits, use the following command:

#>cat /proc/sys/fs/file-max
8192

The above example show that the max open file discriptors is 8192.
We should also check open file limit per shell:
#> ulimit –aH

core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
pending signals (-i) 1024
max locked memory (kbytes, -l) 32
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
stack size (kbytes, -s) unlimited
cpu time (seconds, -t) unlimited
max user processes (-u) 77824
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited

In the above example, the open file limit is 1024.

1.2 Setting the values

The following server variables are related to connections which should be mornitored and tuned reqularly.

· Max_connections
· Max_user_connections
· Table_open_cache (table_cache for MySQL version prior to 5.1.3)
· Table_definition_cache
· Open_files_limit
· thread_cache_size

The max_connections variable values is default to 100. We should check the max_used_connections status often to reset the connections values when the max_connections status values is closed to the connections variable values.

The Max_user_connections variable values is default to 0 which means unlimit. Nomally, this variable should set to a few connections less than the max_connections. This way, you will always have a few connections reserve for the supper user, root. For example, if your max_connections was set to 500, and you have three application users for three applications to connect to the database, the total connections (max_user_conections) should set to less than 500, say 480.
The table_open_cache variable values is default to 64. We should monitoring the opend_tables status variable frequenry to see if the number are going up constanly. If the opened_tables status going up more than 1 per every 10 minutes on average, then we need to increase the table_open_cache variable values.

The table_definition_cache set the number of table definitions that can be stored in the definition cache. If you use a large number of tables, you can create a large table definition cache to speed up opening of tables. The table definition cache takes less space and does not use file descriptors, unlike the normal table cache. This variable was added in MySQL 5.1.3. The minimum and default values are 1 and 128 before MySQL 5.1.25. The minimum and default are both 256 as of MySQL 5.1.25.

The open_files_limit variable changes the number of file descriptors available to mysqld. You should try increasing the value of this option if mysqld gives you the error Too many open files and preven connections in the error log, it means that the requested number of file descriptors cannot be allocated; therefore, it is time to increase the open_files_limit variable.

The Thread_cache_size variable is default to 8. We should check the threads_created status variable to ensure that this status values is not increased in a high value constantly. Please note that thread_created will show a large numbers if the the thread_cache_size number was not set or set to a small value when the server started because very few threads were cahed. It is not nesccessary to set the thread_cache_size value to the same value as thread_created. We should start by setting the value of thread_cache_size to the values of threads_coonected or the total number of prcesses from show proccesslist command. And, continue monitor the system and increase the value only if the thread_created status value increase in a hight rate more.


In addition to setting the MySQL server variables, we should also set the linux open file descriptor limits to make sure the there is enough file descriptors for MySQL to use. To change the file-max values to 65535, do the following:

# echo "65535" > /proc/sys/fs/file-max

We should also add or change this new value in /etc/sysctl.conf so the server will boot up with this value if it ever need to reboot.
# Maximum number of open files permited
fs.file-max = 65535

To load new values from the sysctl.conf file, do the following:
% sysctl -p /etc/sysctl.conf

Also, we should incress this to the mysql user if you use mysql user to run your server (do it as root):

# vi /etc/security/limits.conf

Modify or add "nofile" (number of file) entries (if the server is run by root, replace mysql with a *.

mysql soft nofile 65535
mysql hard nofile 65535

And add the following to the /etc/pam.d/login file:

# vi /etc/pam.d/login
[Add the line]
session required /lib/security/pam_limits.so

2. Monitoring

We should continue monitoring the status variables, which were mentioned in section 7.2.2 above, to make sure all the server variables were set accurately. Again, performance changes over time. One set of the serser variables work well now will not guarantee will work well three months later. Past performance dose not guarantee future results, it is true for the stock market; it is true for server performance as well.

References:
Related Posts:
----------------------------------

Post Update History:
2010-03-28: Initial post. Draft from initial tuning note.
2010-05-06: Added Reference and Related Posts


Saturday, February 27, 2010

MySql: Install Enterprise Monitor




Contents
1. Instroduction
2. Install Service manager
2.1 Prepare For Installation
2.2 Installation Using Command Line Mode
3. Install monitor agent
3.1 Prepare for installation
3.2 Install Agent

1. INSTRODUCTION

2. INSTALL SERVICE MANAGER

2.1 Prepare For Installation

1. Create a mysql group and mysql user in the system if there is not one already.
#>groupadd mysql
#>useradd -s /bin/csh -m -d /home/mysql -c "Mysql User" -g mysql mysql
2. Check required linux package
As a prerequisite for installing the MySQL Enterprise Monitor Agent on Linux systems you must have the Linux Standards Base (LSB) initialization functions installed.
   rpm -qa |grep -i lsb
   redhat-lsb-3.0-8.EL

By deault, the installation using the following port:
Tomcat Server Port [18080]:
Tomcat Shutdown Port [18005]:
Tomcat SSL Port [18443]:
MySQL Database Port [13306]:


If you want to use the default ports, you need to install the service manager with root user since the ports are only can access by root. If you want to install using user other than root (unprivileged user), you need to use other ports.

You can change default to use the ports of your choices. However, you need to make sure that all the ports you are going to use are opened.

Since we are using mysql user to install the monitor, we are going to use the following ports:Tomcat Server Port [18080]: 8080

Tomcat Shutdown Port [18005]: 8005
Tomcat SSL Port [18443]: 8443
MySQL Database Port [13306]: 3306

To see if a port is open, use the following command to check individual port:
#> netstat -tulpn | grep 8080
(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)
tcp 0 0 :::8080 :::* LISTEN -

or you can use
#> netstat -tulpn | less

You can enable the ports by editing the /etc/service file in Redhat linux and restart xinetd.

3. To install the Service Manager find the file named mysqlmonitor-version-installer.bin (where version indicates the version number, the OS, and the architecture ). For example, following is a Linux 64 bit package.

   mysqlmonitor-2.1.1.1141-linux-x86_64-installer.bin

4. Ensure that this file is executable by typing:
#l> chmod +x mysqlmonitor-version-installer.bin

5. To install to the default directory (/opt/mysql/enterprise/monitor) you need to be logged in as root. Installing as an unprivileged user installs to the /home/user_name/mysql/enterprise/monitor/ directory.


7. Have your product key ready. The product key is in a xml file which should had beed downloaded along with the monitor package. The product key file will have a file name like:

 mysql_monitoring_service.key

You also shoul have the advisor.jar file ready,

2.2 Installation Using Command Line Mode

1. Begin Installation

Become the mysql user and from the shell, type:

#> ./ mysqlmonitor-2.1.1.1141-linux-x86_64-installer.bin

2. Select the language of your choice
Please select the installation language
[1] English - English
[2] Japanese - 日本語
Please choose an option [1] :1

3. Specify the installation directory:
Installation directory [/nethome/sweng/user/mysql/enterprise/monitor]: /opt/mysql/enterprise/monitor

4. Specify Tomcat Port. Use the default or pick one of your own.
Tomcat Server Options
Please specify the following parameters for the bundled Tomcat Server
Tomcat Server Port [18080]: 8080
Tomcat Shutdown Port [18005]: 8005
Tomcat SSL Port [18443]:8443

5. Specify SSL support. Select ‘y’ unless you don’t want ssh support

Is SSL support required? [y/N]:

6. Specify Repository configuration. It uses a MySql database to store information the service manager gathered. If you already have MySql database running on your server, you can use it

Repository Configuration

You can use the default username and password or you can create one your own.
Manager/password

Select the default port or select one your own when prompt.

Please specify the following parameters for the bundled MySQL server
Repository Username [service_manager]: manager
Password :
re-enter :
Bundled MySQL Database Port [13306]:3306
configuration Report

7. Note the configuration reports. It is in:
/opt/mysql/enterprise/monitor/configuration_report.txt

Note:
The settings you specified will be saved here:
/opt/mysql/enterprise/monitor/configuration_report.txt
IMPORTANT: This configuration report includes passwords stored in plain text; it is intended to help you install and configure your agents. We strongly advise you to secure or delete this text file immediately after installation

You have not installed the MySQL Enterprise Monitor as the root user. Therefore it could not be configured to auto-start on reboot. See the Installation section of the MySQL Enterprise Monitor documentation for instructions on how to do this manually.

Press [Enter] to continue :

8. Start Enterprise Monitor installation. Enter ‘Y’
Setup is now ready to install MySQL Enterprise Monitor on your computer.
Do you want to continue? [Y/n]: Y

Please wait while Setup installs MySQL Enterprise Monitor on your computer.
Installing
0% ______________ 50% ______________ 100%

#######################################

--------------------------------------------------------------------------

Completed installing files
Setup has completed installing the MySQL Enterprise Monitor files on your computer
Uninstalling the MySQL Enterprise Monitor files can be done by invoking:
/opt/mysql/enterprise/monitor/uninstall
To complete the installation, launch the MySQL Enterprise Dashboard and complete the initial setup and product activation information. Refer to the readme file for additional information and a list of known issues.

Press [Enter] to continue :
Press [Enter] to continue :
----------------------------------------------------------------------------

Setup has finished installing MySQL Enterprise Monitor on your computer.
View Readme File [Y/n]: Y
. Test the manager server
The README file is locate in /opt/mysql/enterprise/monitor/README.txt

From the web browser, enter the following url:
http://hostname:8080/
where hostname is the hostname of the manager server, 8080 is the port you enter in step 4 for Tomcat Server Port [18080]:

10. Enter product Key and Advisor.jar
After connect to the Tomcat server the first time, you should have the screen like this one:

Browser and upload your product key file and adviser.jar files. Enter the password for admin user and agenuser. You can different username if you prefer.
Set the time period for remove historica data collection. Pick a long one start with.When done, click on complete setup.

11. Connect to the Service Manager from browser. In the browser, enter the following url:

http://::8080.
Where is the hostname of your manager server.

Use admin as user id to login. If you see a screen like this one, it is working. And you can start to install agent on eah of your MySql Database Servers.

12. Configuration files and log files location

Config.properties is in

/opt/mysql/enterprise/monitor/apache-tomcat/webapps/ROOT/WEB-INF

This file contains configuration information about database connection.

">

3. INSTALL MONITOR AGENT<

For each database server that you want to monitor, an agent need to be install locally.

3.1 Prepare for installation
1. Create the following directory and give ownship to mysql.

/opt/mysql/enterprise/monitor
#>cd /opt
#>chown –R mysql:mysql mysql

2. Add the agent user to the database server you want to monitor

Before setting up an agent to monitor a MySQL server you need to ensure that there is a user account for the agent on that server
Login to the MySql database server and create the user call agent
mysql> create user 'agent' identified by 'password';
mysql> GRANT SELECT, REPLICATION CLIENT, SHOW DATABASES, SUPER, PROCESS
-> ON *.*
-> TO 'agent'@'localhost' identified by 'password';

Query OK, 0 rows affected (0.00 sec)

3. Check LSB installation
You can check the existence of the LSB package using the following command in linux:
#> rpm -qa |grep -i lsb

redhat-lsb-3.1-19.fc8.x86_64

3.2 Install Agent

1. Start installer

./mysqlmonitoragent-2\[1\].1.1.1144-linux-glibc2.3-x86-32bit-installer.bin

2. Select language

Select 1 for English

Language Selection
Please select the installation language
[1] English - English
[2] Japanese - 日本語


Please choose an option [1] : 1

3. Select installation directory

The installation directory is /opt/mysql/enterprise/monitor
Installation directory
Please specify the directory where MySQL Enterprise Monitor Agent will be installed
Installation directory [/u0/mysql/mysql/enterprise/agent]: /opt/mysql/enterprise/monitor

4. Provide database connection information
Select to socket as connection methold. You can find your socket file location from the my.cnf file.
Provide the username and password for the agent user which defined in step 1 of section 3.1

How will the agent connect to the database it is monitoring?

[1] TCP/IP
[2] Socket
Please choose an option [1] : 2

MySQL Socket []: /var/lib/mysql/mysql.sock
MySQL Username []: agent
MySQL Password :
Re-enter :

5. Query Analyzer configuration information

Enable Proxy (recommended) [Y/n]: Y
Proxy Port [6446]: 6446
Backend Host: 127.0.0.1 (cannot be changed)
Backend Port: 3306 (cannot be changed)

6. Provde Service Manager Server information

In this section, you provide hostname or IP of the service manager server. The tomcat ports and the agent id and password. The agent is and password is the one that you created in step 10 in section 2.1.

MySQL Enterprise Monitor Options
Hostname or IP address []: xyx.domain.com
Tomcat Server Port [18080]: 8080
Tomcat SSL Port [18443]: 8443
Use SSL? [y/N]: y

Agent Username [agent]: agent
Agent Password :
Re-enter :

7. Review configuration setting
Review the configuration parameters which you just entered. If all is fine, start the installation.

----------------------------------------------------------------------------
Configuration Report
Here are the settings you specified:
Installation directory: /opt/mysql/enterprise/monitor
Monitored MySQL Database:

-------------------------
Socket: /var/lib/mysql/mysql.sock
MySQL username: agent
MySQL password: password
Query Analyzer Configuration

-------------------------
Proxy Enabled: yes
Proxy Port: 6446

MySQL Enterprise Monitor:
-------------------------
Hostname or IP address: monitor.domain.com
Tomcat Server Port: 8080
Tomcat SSL Port: 8443
Use SSL: 1
Press [Enter] to continue :
Agent username: agent
Press [Enter] to continue :
----------------------------------------------------------------------------
Setup is now ready to begin installing MySQL Enterprise Monitor Agent on your computer.

Do you want to continue? [Y/n]: Y
Please wait while Setup installs MySQL Enterprise Monitor Agent on your computer.

Installing
0% ______________ 50% ______________ 100%

#########################################
----------------------------------------------------------------------------

Start MySQL Enterprise Monitor Agent
Info to start MySQL Enterprise Monitor Agent
The MySQL Monitor Agent was successfully installed. To start the MySQL Agent please invoke:

/opt/mysql/enterprise/monitor/etc/init.d/mysql-monitor-agent start

You have not installed the MySQL Service Agent as the root user. Therefore it could not be configured to auto-start on reboot. See the Installation section of the MySQL Enterprise Monitor documentation for instructions on how to do this manually.

Press [Enter] to continue :
Setup has finished installing MySQL Enterprise Monitor Agent on your computer.

View Readme File [Y/n]: Y

8. Created inventory table in mysql dabase

The agent use the mysql.inventory table to track replication related activities. For some installation, the table dose not exists. If the table dose not exists, the agent will not start.

Use the following commands create the table and grant permission to the agent user.

mysql> CREATE TABLE mysql.inventory ( name VARCHAR(64) NOT NULL PRIMARY KEY, value VARCHAR(64)) ENGINE=MYISAM;

Query OK, 0 rows affected (0.02 sec)

Mysql>grant insert, update,select on mysql.inventory to 'agent'@'%' identified by 'password';

Query OK, 0 rows affected (0.01 sec)

9. Start agent

Change to directory: /opt/mysql/enterprise/monitor/etc/init.d
Start the agent with the following command:

#> ./mysql-monitor-agent start

Starting MySQL Enterprise agent service... [ OK ]
Check if the agent is started:

#> ./mysql-monitor-agent status

MySQL Enterprise agent is running

10. Log file location

The agent log is located in /opt/mysql/enterprise/monitor. The log file name is, by default, mysql-monitor-agent.log. The following log entries indicate the agent is started successfully:

2010-02-25 15:48:23: (critical) MySQL Monitor Agent 2.1.1.1144 started.
2010-02-25 15:48:23: (critical) network-io.c:317: successfully reconnected to dashboard at https://agent:password@10.48.82.240:8443/heartbeat
2010-02-25 15:48:23: (critical) agent_mysqld.c:707: successfully connected to database at /var/lib/mysql/mysql.sock as user agent (with password: YES)

11. Check agent status from Service Manager using browser

Login into the service manager from the browser. The server of the agent that you just created should show up on the left hand side panel. And the monitor should show some status of the agent.

-----------------------------------
Post History:
2009-02-26: Initial post. Draft from actual installation note.

Saturday, February 06, 2010

MySql Replication: Relay Log Corruption

MySql Replication Relay Log Corruption

 1 Problem: Disk was full in the slave. Relay log corrupted

After the checking the slave MySQL server error, I noticed that the slave was stopped with the following error message in the error log:

090925 16:39:47 [ERROR] Error in Log_event::read_log_event(): 'Event too big', data_len: 1330925129, event_type: 16
090925 16:39:47 [ERROR] Error reading relay log event: slave SQL thread aborted because of I/O error
090925 16:39:47 [ERROR] Slave: Could not parse relay log event entry. The possible reasons are: the master's binary log is corrupted (you can check this by running 'mysqlbinlog' on the binary log), the slave's relay log is corrupted (you can check this by running 'mysqlbinlog' on the relay log), a network problem, or a bug in the master's or slave's MySQL code. If you want to check the master's binary log or slave's relay log, you will be able to know their names by issuing 'SHOW SLAVE STATUS' on this slave. Error_code: 0
090925 16:39:47 [ERROR] Error running query, slave SQL thread aborted. Fix the problem, and restart the slave SQL thread with "SLAVE START". We stopped at log ‘appl-1-log-bin.000078' position 987008254

2 Use mysqlbinlog to check problem with the relay log:

To varify if the relay log was indeed corrupted, I used the mysqlbinlog utility to check the relay log file with the position that was mentioned in the error log.

  #>mysqlbinlog --position=19193011 slave-1-relay-bin.000575
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
ERROR: Error in Log_event::read_log_event(): 'read error', data_len: 542069838, event_type: 1
Could not read entry at offset 19193011:Error in log format or read error
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;


3 To fix the problem.

Following steps were taken to fix the problem and restart the slave

Step 1:  Check slave status

From the mysql client, issued show slave status command to get the current bin log file name and position as we as error message.

MySQL>show slave status\G;

******* 1. row **********
Slave_IO_State:
Master_Host: appl-1.xyz..com
Master_User: repl_dw
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: appl-1-log-bin.000078
Read_Master_Log_Pos: 987008254
Relay_Log_File: slave-1-relay-bin.000049
Relay_Log_Pos: 97173
Relay_Master_Log_File: appl-1-log-bin.000078
Slave_IO_Running: No
Slave_SQL_Running: No
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error: Could not parse relay log event entry. The possible reasons are: the master's binary log is corrupted (you can check this by running 'mysqlbinlog' on the binary log), the slave's relay log is corrupted (you can check this by running 'mysqlbinlog' on the relay log), a network problem, or a bug in the master's or slave's MySQL code. If you want to check the master's binary log or slave's relay log, you will be able to know their name issuing 'SHOW SLAVE STATUS' on this slave.
Skip_Counter: 0
Exec_Master_Log_Pos: 987008254
Relay_Log_Space: 298049181
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: NULL
1 row in set (0.00 sec)
ERROR:
No query specified
mysql>

Took note on Master_Log_File: appl-1-log-bin.000078 and Exec_Master_Log_Pos: 987008254 values.  The Master_Log_File was the master bin log file the slave was reading while it encountered the error.  The Exec_Master_Log_Pos was the postion in the master bin log file which the slave stopped at when it encountered the error.


Step 2: Stop the slave, and reset bin log file position

To make sure that we did not lost any data, we CANGE  MASTER TO to re-point replication to Relay_Master_Log_File and Exec_Master_Log_Pos which were the file and postion where the slave stopped due to the error. The CHANGE MASTER TO command also would purge existing relay logs and  re-fetched all events which have not been executed yet. Doing this command make sure your master is operational and it still has all the logs needed to re-fetch events.

MySql> stop slave;

From the mysql prompt, issue the following commond:
CHANGE master TO master_log_file=Relay_Master_Log_File, master_log_pos=Exec_Master_Log_Pos

MySqk> change master to master_log_file=appl-1-log-bin.000078',master_log_pos=987008254;
Query OK, 0 rows affected (1.22 sec)

Step 3 Re-Started the Slave

MySql> slave start;

After the slave started, checked the MySQL server error log:

090925 18:23:53 [Note] Slave SQL thread initialized, starting replication in log 'appl-1-log-bin.000078' at position 987008254, relay log '/u0/mysql/mysqlreplog/dwh-1-relay-bin.000001' position: 4
090925 18:23:53 [Note] Slave I/O thread: connected to master 'repl_user@appl-1.xyz..com:3306', replication started in log ‘app-1-log-bin.000078' at position 987008254

4 Explaination and Reference:

During replication the MySQL server creates a number of files that are used to hold the relayed binary log from the master, and record information about the current status and location within the relayed log. There are three file types used in the process:
  1.  The relay log consists of the events read from the binary log of the master. Events in this binary log are executed on the slave as part of the replication thread.  Therefore, it will be fine to reset this log file as we known what master bin log postion the slave was stopped at when the error occured. Moreover, Since the replay log was corrupted in our case, we need to regenerate the relay log file.
  2. The master.info file contains the status and current configuration information for the slave's connectivity to the master. The file holds information on the master host name, login credentials, and the current position within the master's binary log.
  3. The relay-log.info file holds the status information about the execution point within the slave's relay log files. The relationship amount the three files and the replication process is as follows:
    • The master.info file retains the point within the master binary log that has been read from the master.
    • These read events are written to the relay log.
    • The relay-log.info file records the position within the relay log of the statements that have been executed. 
 Reference:




Post Update History
----------------------
  • 2010-02-10: Initial draft from note.
  • 2010-05-06: Fixed typoes, organized note and add references.

Tuesday, January 12, 2010

Mysql Start Up Error: MySQL..Manager of pid-file quit without updating file.[FAILED]

MySql failed to start and produced this error:(version 5.1)

MySQL..Manager of pid-file quit without updating file.[FAILED]

This error was caused by one or more error entries in the my.cnf file. Check the entries to make sure that all the reference paths were entered correctly. You can check the error log to for error messages. Also, make sure all the parameters were with corrected names

Reference

MySQL Startup Error: No such process [FAILED]

Saturday, June 27, 2009

MySQL: Set Server Variables

There are more than one way to set or change paramenter values.

1.Set my.cnf file.

Parameter values are read into memory during server start up.

Parameter is entered in the form of key value pair. All the parameter should enter in the my,cnf file so that the server will apply the parameter values in start up. After any change to parameter values using Set Global option, values should also change in the parameter file.

The syntax of the paramer key value paire is:

parameter=value
key_buffer_size=1073741824;

To translate GB, MB, KG to byte, use the following formula:
1GB = 1*1024*1024*1024
1MB = 1*1024*1024
1KB = 1*1024
1.5GB = 1.5*1024*1024*1024

2.Enter in command line or in the start up script

You may find this is not as convince as using the configuration file.

shell> mysqld --key_buffer_size=64M --table_cache=256 \
--sort_buffer_size=4M --read_buffer_size=1M &

3.Use Set GLOBAL command for Dynamic Variable from mysql client

If the parameter is a dynamic varable, we can use MYSQL client to change the value in run time.

Mysql> SET GLOBAL key_buffer_size=1073741824;

To translate values to bytes, you can use the following formula to enter GB, MB, or KB.

1GB = 1*1024*1024*1024
1MB = 1*1024*1024
1KB = 1*1024
1.5GB = 1.5*1024*1024*1024

MYSQL> SET GLOBAL key_buffer_size=1*1024*1024*1024;

The parameter values are load when the sessions started. If we want to use the new values that we just changed using the SET GLOBAL command, we need to start a new session.

Saturday, March 21, 2009

MySql Replication: Skip Duplicate Key Error (Error 1062, Unique Constraint Violation)

MySQL replication will stop whenever there is a query causing an error on the slave. The error message will be written to the error log; therefore, it allows us to identify the problem and fix it,

One of the common error is error 1062, unique constraint violation, that is, when a duplicate key is being insert into a table. For example you might see an errors message in the error log or from “show slave status” output:

"1062 Error 'Duplicate entry 'abc' for key 1' on query. Default database: 'mydb'. Query: 'INSERT INTO ..."

Since, in most case, this error will need to fix in the source (master) database, we can skip the error and let the replication continue on slave.

To skip an error , from the slave, you can use the SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1 statement to skip a sql statement which caused the 1062 error.

mysql>stop slave;
mysql>SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
mysql> start slave;

For, 1062 error, during the normal replication process, you can also specify the following variable in the
my.cnf configuration file to tell the slave to skip all 1062 errors

slave-skip-errors = 1062

Of cause, please make sure that all the statements, which were skipped, will eventually be corrected in the master and will not cause any data issue.


Sunday, March 01, 2009

Mysql Replication: Use Slave Skip Counter to Skip Error Statement

To Skip an error in a replication event during replication, use:

SET GLOBAL SQL_SLAVE_SKIP_COUNTER = N

This statement skips the next N events from the master. This is useful for recovering from replication stops caused by a statement.

This statement is valid only when the slave thread is not running. Otherwise, it produces an error.

When using this statement, it is important to understand that the binary log is actually organized as a sequence of groups known as event groups. Each event group consists of a sequence of events.

· For transactional tables, an event group corresponds to a transaction.
· For nontransactional tables, an event group corresponds to a single SQL statement.

A single transaction can contain changes to both transactional and nontransactional tables.

When you use SET GLOBAL SQL_SLAVE_SKIP_COUNTER to skip events and the result is in the middle of a group, the slave continues to skip events until it reaches the end of the group. Execution then starts with the next event group.

Examples of using SET GLOBAL SQL_SLAVE_SKIP_COUNTER = N :

1. Skip statements that caused duplicates or referential integrity error.

When a referential integrity error occurred, the transaction will cause the replication thread to hang. To skip the transaction do:

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;
mysql> START SLAVE;

Use the value 1 for any SQL statement that does not use AUTO_INCREMENT or LAST_INSERT_ID(), otherwise you will need to use the value 2. Statements that use AUTO_INCREMENT or LAST_INSERT_ID() take up 2 events in the binary log.


Tuesday, August 12, 2008

MySql Replication: Set Up Master and Slave

1. INSTRUCTION

The following post contains that base installation steps for setting up MySql Replication Servers (version 5.0.x) on a new MySql database systems. It makes the assumption that the database system is a new system and there is no existing database running; therefore, there is no need to synchronizing the databases among master and slave before replication.

This document uses three nodes replication systems for demonstration purposes. Please see diagram bellow on how data flow.


The replication will go from mySql-1, the master server, to mySql-2, the first slave, slave-1. The additional slave, slave 2, will replicate from mySql-2; therefore, mySql-2 also acts as a master for mySql-3. Please note that Mysql replication server replicate data using ‘pull’ which means that data are pulled by the slaves from the master.

Note that the hostnames, user ids, passowrds, and installation directories are for demonstration purposes.

2. VARIFY SERVER INSTALLATIONS AND CONFIGURATION

The configurations demo here will replicate all databases.

2.1 Verify Master Server Installation and Configuration

Following are the minimum configuration variable setting. Please refer to MySql documentation on other configuration variable settings.

For master, add the following entries to the [mysqld] section of the my.cnf file:
#make sure that skip-networking is not enable (commented) in my.cnf

#skip-networking
server-id = 1
# log-bin is the path and file name where the binary logs are stored
log-bin=/var/lib/mysqlreplog/mySql-1-log-bin
innodb_flush_log_at_trx_commit=1
sync_binlog=1

2.2 Verify Slave Server Installation and Configuration

2.2.1 Slave Server: mySql-2
Add the following entries to the [mysqld] section of the my.cnf file. Since slave 1, server myMyMySql-2, will act as master server for slave 2, there are entries for both master and slave on the my.cnf file in this node.

[mysqld]
# Replication Configuration
#skip-networking
server-id=2
# Binary log
log-bin=/var/lib/mysqlreplog/myMySql-2-log-bin
log-slave-updates
sync_binlog=1

# Relay-logs
relay-log=/var/lib/mysqlreplog/mySql-2-relay-bin
relay-log-index=/var/lib/mysqlreplog/mySql-2-relay-bin-index
relay-log-info=/var/lib/mysqlreplog/mySql-2-relay-bin-info
master-info-file=/var/lib/mysqlreplog/mySql-2-master-info
max_relay_log_size= 100Mpid file

2.2.2 Slave Server: mySql-3

[mysqld]
# Replication Configuration
#skip-networking
server-id = 3
# Binary log
log-bin=/var/lib/mysqlreplog/mySql-3-log-bin

# Relay-logs
relay-log=/var/lib/mysqlreplog/mySql-3-relay-bin
relay-log-index=/var/lib/mysqlreplog/omySql-3-relay-bin-index
relay-log-info=/var/lib/mysqlreplog/omySql-3-relay-bin-info
master-info-file=/var/lib/mysqlreplog/omySql-3-master-info
max_relay_log_size= 100M


3. CREATE REPLICATION USERS

3.1 Create Replication User for Slave 1, mySql-2
Each master server need to have a user id for a slave to use to pull data from. On mySql-1, create a user for slave 1, server myMySql-2 to pull data from.

3.1.1 Create replication user and grant privileges: (password is a place holder only)

mysql>create user 'repsql2' identified by 'repsql2pass';

3.1.2 Grant Replication Privileges

mysql>grant replication slave on *.* to 'repsql2' @ 'hostname or ip' identified by 'repsql2pass';

Replace ”mySql-2. or ip” with the hostname or ip address of server mySql-2

3.2 Create Replication User for Slave-3, mySql-3
On mySql-2 create a user for slave 2, server mySql-3 to pull data from.

3.2.1 Create replication user and grant privileges: (password is a place holder only)
mysql>create user 'repsql3' identified by 'repsql3pass';

3.2.2 Grant Replication Privileges

mysql>grant replication slave on *.* to

Replace ”mySql-3. or ip” with the hostname or ip address of server mySql-3.

4. SET UP REPLICATION ON MASTER SERVER, mySql-1
1. Stop mysql server: mySql-1
#>/sbin/service mysqld stop

2. check that no mysqlds are running

#>ps –ef |grep mysql

3. Re-start the mysql server to reflect any change that made in section 2.1 Verify Master Server Installation and Configuration
4. Lock the tables to prepare for a backup dump.

mysql> flush tables with read lock;

Query OK, 0 rows affected (0.00 sec)

5. Record the log name and offset. The file column shows the name of the log file and the position shows the offset within the file. Record these values for setting up the slave.
mysql> show master status;

+------------------+----------+--------------+------------------+
File Position Binlog_Do_DB inlog_Ignore_DB
+------------------+----------+--------------+------------------+
mySql-1-log-bin.000001 98
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

6. Shut down mysql server again to create a back up. Make sure there is no mysqld running.

#>/sbin/service mysqld stop

#>ps –ef | grep mysql
7. create a back up of the data files in the mysql data directory: datadir=/var/lib/mysql

#> tar –cvf /u0/prod-mysql-snapshot.tar /var/lib/mysql
8. bring mysql back on line

>/sbin/service mysqld start
9. Unlock the tables
mysql> unlock tables;

Query OK, 0 rows affected (0.00 sec)


5. SETUP REPLICATION ON SLAVE SERVER 1, mySql-2

1. Stop slave server: mySql-2

#>/sbin/service mysql stop

2. Create directory /var/lib/mysql/backup
3. Backup the mysql data file in mySql-2 to the backup directory.

#>/var/lib/mysql>cp –R * backup

4. Apply the backup copy from master (from section 4, step 7.)
Scp the file over and untar it.
#/tar –xvf /u0/mySql-1-mysql-snapshot.tar
5. start the slave server and check the err log to make sure it started nomarly.
#/sbin/service mysql start

6. Update master information
Mysql> change master to master_host =’
-> master_port = 3306,
-> master_user=’repsql2’,
->master_password=’repsql2pass’,
->master_log_file=’’
->master_log_spos=;

6. Check slave status.

Mysql>show slave status\G;

Mysql>show full processlist;

7. logon the master server mySql-1 and check if slave threads are connected:

mysql>show full processlist;

6. SET UP SLAVE SERVER 2: mySql-3
6.1 Get Backup Data Dump From mySql-2
1.Logon to mysql server myMySql-2 and lock the tables.

Mysql> Flush tables with read lock;

2. Record the log name and offset;
mysql> show master status;
+----------------------+----------+--------------+------------------+
File Position Binlog_Do_DB \Binlog_Ignore_DB
+----------------------+----------+--------------+------------------+
mySql-2-log-bin.000007 159616
+----------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

3. Stop mysql server mySql-2
#>/sbin/service mysql stop

4. Make a backup of the data files

#> tar –cvf /u0/mySql-2-mysql-snapshot.tar /var/lib/mysql
5. bring myMySql-2 back online and unlock tables

#>/sbin/service mysql start
Mysql>unlock tables;

6.2 Set Up Slave Server 2, mySql-3
1. Stop mysql server mySql-3
#>/sbin/service mysql stop

2. Apply backup from mySql-2

#>/tar – xvf /u0/myMySql-2-mysql-snapshot-20080626.tar /var/lib/mysql

3. Start mysql server mySql-3

#>/sbin/service mysql start

4. Update master information

Mysql> change master to master_host =’
-> master_port = 3306,
-> master_user=’repsql3’,
->master_password=’resql3pass’,
->master_log_file=’’
->master_log_pos=

8. Check slave status.

Mysql>show slave status\G;
Mysql>show full processlist;

9. Logon the master server sq2-1 and check if slave threads are connected:

mysql>show full processlist;

7. TEST
Create a test table in mySql-1 and make sure that it get replicated to mySql-2 and mySql-3

Mysql> create table reptest (a int,b int,c varchar(100));

Mysql> insert into reptest(a,b,c) values (1,2,’relication test’);

8. STOP AND START SLAVE
To stop a slave, use:
Mysql> slave stop;

To start a slave, use:
Mysql> slave start;


Friday, February 01, 2008

MySql: Change Root Password

1. Use Mysqladmin Command To Change Root  User Password

If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. To setup root password for first time, use mysqladmin command at shell prompt as follows:

$ mysqladmin -u root password NEWPASSWORD

However, if you want to change (or update) a root password, then you need to use following command

$ mysqladmin -u root -p oldpassword newpass

Enter password:

2.  Reset /Recover MySQL Root Password

In case you can not remember the root password, following steps can be used to reset the password.
Here are commands you need to type for each step (login as the root user):

 Step # 1 : Stop mysql service

# /etc/init.d/mysql stop

Output:

Stopping MySQL database server: mysqld.

Step # 2: Start to MySQL server w/o password:

# mysqld_safe --skip-grant-tables;

Output:

[1] 5988

Starting mysqld daemon with databases from /var/lib/mysql

mysqld_safe[6025]: started

Step # 3: Connect to mysql server using mysql client:

# mysql -u root

Output:

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 1 to server version: 5.0.1

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

Step # 4: Setup new MySQL root user password

mysql> use mysql;

mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';

mysql>flush privileges;

mysql>quit

Step # 5: Stop MySQL Server:

# /etc/init.d/mysql stop

Output:

Stopping MySQL database server: mysqld

STOPPING server from pid file /var/run/mysqld/mysqld.pid

 Step # 6: Start MySQL server and test it

# /etc/init.d/mysql start

# mysql -u root -p

Enter password.