Показаны сообщения с ярлыком MariaDB. Показать все сообщения
Показаны сообщения с ярлыком MariaDB. Показать все сообщения

четверг, 27 июля 2017 г.

Восстановление MySQL репликации

Источник

# Остановить работу slave
mysql> stop slave;
# заставить slave забыть позицию его репликации в файле лога master'а
mysql> reset slave;
# Заставить slave читать начиная с той позиции на которой остановился
mysql> change master to master_log_file='mysql-bin.000048', master_log_pos=283932126;
# Запустить slave
mysql> start slave;

понедельник, 30 мая 2016 г.

How to Back Up and Restore a MySQL Database

Source

If you're storing anything in MySQL databases that you do not want to lose, it is very important to make regular backups of your data to protect it from loss. This tutorial will show you two easy ways to backup and restore the data in your MySQL database. You can also use this process to move your data to a new web server.
Back up From the Command Line (using mysqldump)
If you have shell or telnet access to your web server, you can backup your MySQL data by using the mysqldump command. This command connects to the MySQL server and creates an SQL dump file. The dump file contains the SQL statements necessary to re-create the database. Here is the proper syntax:
$ mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]
  • [uname] Your database username
  • [pass] The password for your database (note there is no space between -p and the password)
  • [dbname] The name of your database
  • [backupfile.sql] The filename for your database backup
  • [--opt] The mysqldump option
For example, to backup a database named 'Tutorials' with the username 'root' and with no password to a file tut_backup.sql, you should accomplish this command:
$ mysqldump -u root -p Tutorials > tut_backup.sql
This command will backup the 'Tutorials' database into a file called tut_backup.sql which will contain all the SQL statements needed to re-create the database.
With mysqldump command you can specify certain tables of your database you want to backup. For example, to back up only php_tutorials and asp_tutorials tables from the 'Tutorials' database accomplish the command below. Each table name has to be separated by space.
$ mysqldump -u root -p Tutorials php_tutorials asp_tutorials > tut_backup.sql
Sometimes it is necessary to back up more that one database at once. In this case you can use the --database option followed by the list of databases you would like to backup. Each database name has to be separated by space.
$ mysqldump -u root -p --databases Tutorials Articles Comments > content_backup.sql
If you want to back up all the databases in the server at one time you should use the --all-databases option. It tells MySQL to dump all the databases it has in storage.
$ mysqldump -u root -p --all-databases > alldb_backup.sql
The mysqldump command has also some other useful options:
--add-drop-table: Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in the dump.
--no-data: Dumps only the database structure, not the contents.
--add-locks: Adds the LOCK TABLES and UNLOCK TABLES statements you can see in the dump file.
The mysqldump command has advantages and disadvantages. The advantages of using mysqldump are that it is simple to use and it takes care of table locking issues for you. The disadvantage is that the command locks tables. If the size of your tables is very big mysqldump can lock out users for a long period of time.
Back up your MySQL Database with Compress
If your mysql database is very big, you might want to compress the output of mysqldump. Just use the mysql backup command below and pipe the output to gzip, then you will get the output as gzip file.
$ mysqldump -u [uname] -p[pass] [dbname] | gzip -9 > [backupfile.sql.gz]
If you want to extract the .gz file, use the command below:
$ gunzip [backupfile.sql.gz]
Restoring your MySQL Database
Above we backup the Tutorials database into tut_backup.sql file. To re-create the Tutorials database you should follow two steps:
  • Create an appropriately named database on the target machine
  • Load the file using the mysql command:
$ mysql -u [uname] -p[pass] [db_to_restore] < [backupfile.sql]
Have a look how you can restore your tut_backup.sql file to the Tutorials database.
$ mysql -u root -p Tutorials < tut_backup.sql
To restore compressed backup files you can do the following:
gunzip < [backupfile.sql.gz] | mysql -u [uname] -p[pass] [dbname]
If you need to restore a database that already exists, you'll need to use mysqlimport command. The syntax for mysqlimport is as follows:
mysqlimport -u [uname] -p[pass] [dbname] [backupfile.sql]
Backing Up and Restoring using PHPMyAdmin
It is assumed that you have phpMyAdmin installed since a lot of web service providers use it. To backup your MySQL database using PHPMyAdmin just follow a couple of steps:
  • Open phpMyAdmin.
  • Select your database by clicking the database name in the list on the left of the screen.
  • Click the Export link. This should bring up a new screen that says View dump of database (or something similar).
  • In the Export area, click the Select All link to choose all of the tables in your database.
  • In the SQL options area, click the right options.
  • Click on the Save as file option and the corresponding compression option and then click the 'Go' button. A dialog box should appear prompting you to save the file locally.
Restoring your database is easy as well as backing it up. Make the following:
  • Open phpMyAdmin.
  • Create an appropriately named database and select it by clicking the database name in the list on the left of the screen. If you would like to rewrite the backup over an existing database then click on the database name, select all the check boxes next to the table names and select Drop to delete all existing tables in the database.
  • Click the SQL link. This should bring up a new screen where you can either type in SQL commands, or upload your SQL file.
  • Use the browse button to find the database file.
  • Click Go button. This will upload the backup, execute the SQL commands and re-create your database.

четверг, 28 апреля 2016 г.

MySQL Remove bin-log by the variable expire_log_days

2, Remove bin-log by the variable expire_log_days
An alternative option is to set “expire_log_days” as MySQL server parameter. The default values for expire_log_days is not to purge logs. You can either set it in MySQL’s configuration file or in a command terminal like below:
mysql> SET GLOBAL expire_logs_days = 7;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'expire_%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| expire_logs_days |  7    |
+------------------+-------+
1 row in set (0.00 sec)
When this vavirable takes effect, the log files will be removed automatically on a weekly basis.

UPDATE:

You can remove binlog files by "PURGE BINARY LOGS"  command.

examples:
 
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';
 
The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value 
(a value in 'YYYY-MM-DD hh:mm:ss' format).

How to fix MySql Replication Error 1236

Source

We have some websites that use two database servers in master-master replication. Recently one of the servers died and had to be resurrected. (They are cloud based and SoftLayer doesn't seem to have their cloud-based offering thing nailed down, yet. Every week one of them will go down and be unresponsive until tech support does some magic.)

After one of the servers was brought back up the other server would not connect. It "Slave_IO_Running: No" and "Seconds_Behind_Master: null" which means it was not playing nicely.

First, I went to the MySql log files, which for this server is found at /var/log/mysql.log and looked at the last few messages here by running "tail /var/log/mysql.log" from the command prompt. This revealed the error number (server_errno=1236). It also had the following info:

Got fatal error 1236: 'Client requested master to start replication from impossible position' from master when reading data from binary log

Just before this entry in the mysql.log it indicates the file and position that it is trying to read. So, with this data in hand, I headed over to the master server and took a look at the bin logs. They are located in /var/lib/mysql/. Here I took a look at the file in question using the mysqlbinlog utility. I used the following command to check out the bin log. Obviously, you'll have to replace the position and file name with the position and file indicated in your mysql.log.
mysqlbinlog --offset=128694 mysql-bin.000013

And, this is what I saw here, among other things:
Warning: this binlog was not closed properly. Most probably mysqld crashed writing it.

Well, that explains things! When the server crashed the bin log was not closed properly. This is easy to fix. Going back to the slave server, I stopped the slave, reset the bin log position and started the server.
?
1
2
3
4
STOP SLAVE;
CHANGE MASTER TO MASTER_LOG_POS = 0;
CHANGE MASTER TO MASTER_LOG_FILE = 'mysql-bin.000014';
START SLAVE;

I simply pointed the slave to the start of the next bin log. It started right up with no problem.

Update 5/21/13 - An anonymous commentor made a good point about potentially losing data using the above technique. If you are in a situation like I am (master-master replication with 100's of gigs of non-critical data) this is really the only way of getting back up without significant down time. But if you are in a master-slave configuration with a manageable data set or its critical you slave doesn't miss any data, you should probably dump the master database and re-create the slave database to make sure you didn't miss anything.

MySQL: Cannot load from mysql.proc. The table is probably corrupted

Источник

Когда получаешь какую то ошибку от mysql, например, ту что указана в заголовке: "MySQL: Cannot load from mysql.proc. The table is probably corrupted", то немного пугаешься. Жутковато, однако ничего архи страшного в этом нет. Вы наверное только установили новую версию mysql, причем сами базы данных при этом находились на сервере. Такое случается, ну ничего страшного - все поправимо.

Прежде всего заходим в командную строку, например через Putty и делаем следующую команду:

mysql_upgrade -u root -p

После ввода у вас попросит ввести пароль для root пользователя. Вводите его, нажимаем Enter и дожидаемся выполнения операции.

Обращаю ваше внимание на то, что выполнение данной операции может затянуться, особенно, если у вас много Баз Данных и таблиц с данными. Однако другого выбора то нет. Ждем пока не напишет: "OK".

Рекомендуется всегда делать бекап всех баз данных перед тем как инсталлировать устанавливать новую версию Mysql, учтите это на будущее!

понедельник, 21 декабря 2015 г.

MySQL Replication issues.

1) MySQL Skip Duplicate Replication Errors


Normally MySQL replication will stop whenever there is an error running a query on the slave. This happens in order for us to be able to identify the problem and fix it, and keep the data consistent with the mater that has sent the query. You can skip such errors, even if this is not recommended, as long as you know really well what are those queries and why they are failing, etc.
For example you can skip just one query that is hanging the slave using:
1
mysql>SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; START SLAVE;
There might be cases where you will want to skip more queries. For example you might want to skip all duplicate errors you might be getting (output from show slave status;):
1
"1062 | Error 'Duplicate entry 'xyz' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO ..."
If you are sure that skipping those errors will not bring your slave inconsistent and you want to skip them ALL, you would add to your my.cnf:
1
slave-skip-errors = 1062
As shown above in my example 1062 is the error you would want to skip, and from here we have: _ Error: 1062 SQLSTATE: 23000 (ER_DUP_ENTRY) Message: Duplicate entry ‘%s’ for key %d_
You can skip also other type of errors, but again don’t do this unless you understand very well what those queries are and what impact they have on your data:
1
slave-skip-errors=[err_code1,err_code2,...|all]
and for the error codes you can see them all here … (you will see them in your _show slave statu_s; also).
 
2)  Binlog has bad magic number (mysql error) 

My MySql server had the following lines in the error log:
 
121119 22:50:57  mysqld started
121119 22:50:57  InnoDB: Started; log sequence number 0 43655
121119 22:50:57 [ERROR] Binlog has bad magic number;  It's not a binary log file that can be used by this version of MySQL
121119 22:50:57 [ERROR] Can't init tc log
121119 22:50:57 [ERROR] Aborting

I fixed the problem by renaming the mysql-bin.index file:
 
mv mysql-bin.index mysql-bin.index-corrupt

This essentially takes the corrupt mysql-bin.index file out of service, causing mysql to create new one. All I can figure is that the original one got corrupted somehow. I really don’t have time to poke around and find out why today. Hope this helps somebody.
 

понедельник, 27 октября 2014 г.

Mysql: обновление timezone

Источник, как всегда авторам благодарность.

Чтобы проверить текущую временную зону, нужно выполнить команду:

SHOW VARIABLES LIKE '%zone%';
SELECT @@global.time_zone, @@session.time_zone;

Чтобы посмотреть текущее время сервера MySQL:



select current_timestamp();

Прописать в конфигурационном файле timezone можно следующим способом (в таком случае потребуется перезагрузка):

/etc/my.cnf
default-time-zone = "Europe/Moscow"

Можно поменять время и без перезагрузки, для этого сначала перенесем системные тайм зоны в MySQL следующим способом:

mysql_tzinfo_to_sql /usr/share/zoneinfo |mysql -u root mysql -p

Далее, мы уже можем обновить временную зону без появления ошибок типа:

ERROR 1298 (HY000): Unknown or incorrect time zone:

Выполним обновление time_zone:

SET GLOBAL time_zone = 'Europe/Moscow';
SET time_zone = 'Europe/Moscow';

В MySQL также можно использовать системное время, это наверное даже лучше. Чтобы изменить текущее системное время на сервере, нужно сделать:

cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
Чтобы использовалось системное время, в MySQL нужно выполнить

SET GLOBAL time_zone = 'SYSTEM';
SET time_zone = 'SYSTEM';