Translate

lunes, 15 de agosto de 2016

REPLICANDO CON MYSQL 5.6

ESTRUCTURA

SERVIDOR MASTER

MYSQLSERVERS
IP 10.0.4.16
REDHAT 7

SERVIDORES SLAVE

MYSQLVIRTUAL              MYSQLVIRTUAL2
IP 10.0.4.23                           IP 12.26.10.3
 UBUNTU 14.04                   REDHAT 7
-------------------------------------------------------------------------------------------------------------------------
INTRODUCCION

Demos configurar un Servidor como MASTER (MysqlServers) y otro como SLAVE (MysqlVirtual en TECO, MysqlVirtual2 en CENTRAL).

PASOS PREVIOS PARA SERVIDORES MASTER Y SLAVE:

  Antes que nada debemos chequear la variable "open_files_limit" :
 
    mysql > show global variables like 'open%';
 
    +------------------+-------+
    | Variable_name    | Value |
    +------------------+-------+
    | open_files_limit | 65536 |
    +------------------+-------+
    1 row in set (0,00 sec)

  Este valor no es el ideal pero por ahora quedara asi, para conseguirlo debemos saber que Sistema Operativo tenemos.
  Para el caso de REDHAT 7 debemos agregar en:

    [root@MysqlServers ~]# cd /usr/lib/systemd/system
    [root@MysqlServers system]# vi mysqld.service

  Y agregamos las siguientes lineas al final del archivo mysqld.service:

    LimitNOFILE = infinity
    LimitMEMLOCK = infinity

  Pero ademas debemos hacerlo para el sistema operativo:

    [root@MysqlServers ~]# cd /etc/security/
    [root@MysqlServers security]# vi limits.conf

  Aqui agregamos las siguientes lineas:

  definimos aqui tambien para el servicio de mysql

    * soft nofile 65536
    * hard nofile 65536
    * soft nproc 65536
    * hard nproc 65536

    mysql hard nofile 65536
    mysql soft nofile 65536

  Echo esto agregamos en el archivo de configuracion del mysql la variable global open_files_limit con el valor definido anteriormente:

    [root@MysqlServers ~]# cd /etc
    [root@MysqlServers etc]# vi my.cnf

  Dentro de las etiquetas [mysqld] y [mysqld_safe]

    [mysqld]
    ...
    open_files_limit = 65536
    ...

    [mysqld_safe]
    ...
    open_files_limit = 65536
    ...

  Y para evitar varios problemas chequen los permisos del my.cnf, por default tiene los permisos 600, necesitamos modificar a 644

  Default
  -rw-------. 1 root root 1793 abr 20 10:28 my.cnf

  Modificado

  -rw-r--r--. 1 root root 1793 abr 20 10:28 my.cnf

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

  CONFIGURANDO MASTER my.cnf

  [root@MysqlServers etc]# vi my.cnf

    # For advice on how to change settings please see
    # http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html

    [mysqld]
    user = mysql
    # Remove leading # and set to the amount of RAM for the most important data
    # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
    # innodb_buffer_pool_size = 128M

    # Remove leading # to turn on a very important data integrity option: logging
    # changes to the binary log between backups.
    log_bin = "/var/lib/mysql/mysql-bin"

    # These are commonly set, remove the # and set as required.
    # basedir = .....
    # datadir = .....
    # port = .....
    # server_id = .....
    # socket = .....

    # Remove leading # to set options mainly useful for reporting servers.
    # The server defaults are faster for transactions and fast SELECTs.
    # Adjust sizes as needed, experiment to find the optimal values.
    # join_buffer_size = 128M
    # sort_buffer_size = 2M
    # read_rnd_buffer_size = 2M

    server-id = 1
    skip-external-locking
    sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
    binlog_format=MIXED
    log_bin_index = "/var/lib/mysql/mysql-bin.index"
    sync_binlog=1
    general-log
    general_log_file = "/var/lib/mysql/MysqlServer.log"
    innodb_flush_log_at_trx_commit=1

  Lo importante para el mnaster

    server-id = 1
    log_bin = "/var/lib/mysql/mysql-bin"
    log_bin_index = "/var/lib/mysql/mysql-bin.index"
    sync_binlog=1
    binlog_format=MIXED

  Todos los demas parametros son necesarios, pero para el motor de base de datos, no para la replicacion en si.

  Luego chequeamos que este andando

  1.- reiniciamos el mysql: service mysqld restart
  2.- ingresamos a mysql: mysql -u root -ppassword
  3.- Ejecutamos el comando show para ver el estado del master

    mysql> SHOW MASTER STATUS;
    +------------------+-----------+--------------+------------------+-------------------+
    | File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
    +------------------+-----------+--------------+------------------+-------------------+
    | mysql-bin.000003 | 213040583 |              |                  |                   |
    +------------------+-----------+--------------+------------------+-------------------+
    1 row in set (0,00 sec)

  4.- Si queremos reiniciar el MASTER, ejecutaremos:

    mysql> reset master;

  5.- Debemos hacer dump de todas las bases de datos para deployarlas luego en el Slave, sino hacemos estos no replicara nunca.
  Este dump tiene la caracteristica siguiente:

    [root@MysqlServers root]# mysqldump -u root -p --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data=2 --all-databases > Dump-TOTAL.sql

  Luego de terminado ejecutamos el siguiente comando:

    head DumpTotal-20160420.sql -n80 | grep MASTER_LOG_POS

  Debemos tener encuenta estos valor para luego en el slave utilizarlos.

    CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

  6.- Copiamos el dump al servidor slave

    [root@MysqlServers root] scp DumpTotal-20160420.sql root@MysqlVirtual:/root/

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

CONFIGURANDO SLAVE

Para que realmente pueda replicar debemos tener que restaurar un dump del master en el slave, (ste es el caso donde se replican todas las bases del Master), pero una vez que empezo a repplicar, cuando creamos una nueva base en el master, se copia en los slave, sin tener que hacer un dump del master o tener que crear por consola la base en el slave.

Restauramos el Dump:

root@MysqlVirtual:~# mysql -u root -ppassword < DumpTotal.sql

Echo la restauracion abrimos el archivo de configurarcion del mysql (my.cnf) del slave:

PARA UBUNTU 14.04

root@MysqlVirtual:~# cd /etc/mysql/
root@MysqlVirtual:/etc/mysql# vi my.cnf

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket        = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket        = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket        = /var/run/mysqld/mysqld.sock
port        = 3306
basedir        = /usr
datadir        = /var/lib/mysql
tmpdir        = /tmp
lc-messages-dir    = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address        = 127.0.0.1
#
# * Fine Tuning
#
key_buffer        = 16M
max_allowed_packet    = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit    = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
general_log_file        = /var/log/mysql/mysql.log
general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries    = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
server-id        = 2
log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M

# Agregar este parametro para solucionar este error: ERROR 2006 (HY000): MySQL server has gone away, que se produce cuando estamos restaurando el dump del master en el slave

max_allowed_packet    = 64M


#binlog_do_db        = include_database_name
#binlog_ignore_db    = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
open_files_limit = 65536


[mysqldump]
quick
quote-names
max_allowed_packet    = 16M

[mysql]
#no-auto-rehash    # faster start of mysql but no tab completition

[isamchk]
key_buffer        = 16M

[mysqld_safe]
open_files_limit = 65536

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/


Los parametros que son importantes para el servidor slave (UBUNTU 14.04)

server-id        = 2
log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M
max_allowed_packet    = 64M


PARA REDHAT 7


[root@MysqlVirtual2 ~]# cd /etc/mysql
[root@MysqlVirtual2 mysql]#

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
# basedir = .....
# datadir = .....
# port = .....
# server_id = .....
# socket = .....

# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

server-id = 3

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
max_allowed_packet = 64M

# GLOBAL VARIABLES
explicit_defaults_for_timestamp
open_files_limit = 65536

# VARIABLES RELAY

relay-log = mysqld-relay-bin
max-relay-log-size = 500M
relay_log_purge = 1

# REPLICATIONS

report-host = 10.0.48.160
report-user = replicar
report-password = r3pl1c4c10n
report-port = 3306

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

auto_increment_increment = 2
auto_increment_offset = 1

sysdate-is-now

symbolic-links

skip_external_locking = off

plugin_dir = /usr/lib64/mysql/plugin/

general-log = 1
log-error = mysqlservers.err
general_log_file = mysqlservers.log
log_slave_updates
show-slave-auth-info

sync_binlog = 1
enforce_gtid_consistency
gtid-mode = OFF
slave_allow_batching
slave-sql-verify-checksum
slave_exec_mode = STRICT
binlog-format = MIXED
relay_log_info_file = relay-log.info

Los parametros que son importantes para el servidor slave (REDHAT 7):

server-id = 3

# VARIABLES RELAY

relay-log = mysqld-relay-bin
max-relay-log-size = 500M
relay_log_purge = 1

# REPLICATIONS

report-host = 10.0.4.16
report-user = replicar
report-password = r3pl1c4c10n
report-port = 3306

general-log = 1
log-error = mysqlservers.err
general_log_file = mysqlservers.log
log_slave_updates
show-slave-auth-info

sync_binlog = 1
enforce_gtid_consistency
gtid-mode = OFF
slave_allow_batching
slave-sql-verify-checksum
slave_exec_mode = STRICT
binlog-format = MIXED
relay_log_info_file = relay-log.info

Realizado a configuracion del archivo my.cnf debemos ingresar al motor mysql

[root@MysqlVirtual2 mysql]# mysql -u root -ppassword

Debemos decirle al slave donde tiene que buscar el servidor MASTER, en este momento vamos a utilizar los datos que obtuvimos del master


MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

Y lo agregamos en el siguiente comando:

mysql> CHANGE MASTER TO MASTER_HOST='10.0.4.16', MASTER_PORT=3306, MASTER_USER='replicar', MASTER_PASSWORD='r3pl1c4cion', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

Query OK, 0 rows affected (0,03 sec)

Luego iniciamos el servidor slave:

mysql> start slave;
Query OK, 0 rows affected (0,00 sec)

Y chequeamos que todo este funcionando adecuadamente:

mysql> show slave status\G;

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.4.16
                  Master_User: replicar
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000042
          Read_Master_Log_Pos: 1963620
               Relay_Log_File: mysqld-relay-bin.000081
                Relay_Log_Pos: 493146
        Relay_Master_Log_File: mysql-bin.000042
             Slave_IO_Running: Yes                 
            Slave_SQL_Running: Yes
              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:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1963620
              Relay_Log_Space: 1964120
              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: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: f82504d7-fb73-11e5-b535-005056bb4337
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
1 row in set (0,00 sec)

ERROR:
No query specified


Esta salida del comando nos esta diciendo que todo esta normal y funcionando, sabiendo que los siguientes parametros estan incializados con el valor "YES"
 
    Slave_IO_Running: Yes                 
    Slave_SQL_Running: Yes
   
---------------------------------------------------------------------------------------------------------------------------------------------------------

PROCEDIMIENTO UNA VEZ SOLUCIONADO EL ERROR EN LA REPLICACION

Ahora bien, si se produce un error, luego de solucionarlo debemos hacer lo siguiente:

1.- Paramos el servicio de slave
mysql> stop slave;
Query OK, 0 rows affected (0,00 sec)

2.- Reseteamos el servicio de slave, osea limpiamos el error
mysql> reset slave;
Query OK, 0 rows affected (0,00 sec)

3.- Ejecutamos nuevamente el comando CHANGE MASTER TO como lo detallamos arriba

4.- Reiniciamos nuevamente el slave

mysql> start slave;
Query OK, 0 rows affected (0,00 sec)

---------------------------------------------------------------------------------------------------------------------------------------------------------
ERRORES: CASOS SOLUCIONADOS


1.- Caso: EQUAL MySQL server UUIDs;

mysql> show slave status\G
*************************** 1. row ***************************
...
                Last_IO_Errno: 1593
                Last_IO_Error: Fatal error: The slave I/O thread stops because
                               master and slave have equal MySQL server UUIDs;
                               these UUIDs must be different for replication to work.
...

Solucion
Dentro del directorio donde estan las bases de mysql /var/lib/mysql se encuentra un archivo llamado auto.cnf este se autogenera, este error nos avisa que
tenemos el mismo uuid entre el master y slave, por lo tanto borramos en el slave el archvio y reiniciamos el mysql


 

lunes, 13 de junio de 2016

MANUAL DE ADMINISTRACION DE MYSQL: VERSION 2

Comentario:
Este manual esta en su etapa de desarrollo, sepan disculpar las molestias ocacionadas, ademas hay parrafos que no son mios, y que debo reescribirlos, a mi estilo.

1.- Se agrego REPLICACION

ADMINISTRACION DE MYSQL SERVER

Recuperar contraseña root de MySQL

Paso 1: Detener cualquier proceso del servidor MySQL.
Paso 2: Iniciar el proceso del servidor MySQL (mysqld) con la opción
–skip-grant-tables por lo cual este no preguntará por la contraseña.
Paso 3: Conectar al servidor MySQL como el usuario root
Paso 4: Configurar una nueva contraseña para la nueva contraseña root
Paso 5: Salir y reiniciar el servidor MySQL

Iniciar sesión como el usuario root:
Paso # 1: Detener el servicio mysql
# /etc/init.d/mysql stop
Salida:
Stopping MySQL database server: mysqld.
Paso # 2: Iniciar el servidor MySQL sin contraseña:
# mysqld_safe --skip-grant-tables
Salida:
[1] 5988
Iniciando el motor de mysqld de las bases de datos desde /var/lib/mysql
mysqld_safe[6025]: started
Paso # 3: Conectar al servidor mysql usando el cliente mysql:
# mysql -u root
Salida:
Bienvenido al monitor de MySQL.  Comandos y con ; o \g.
Your MySQL connection id is 1 to server version: 5.0.21-log
Tipiar ‘help;’ o ‘\h’ para obtener ayuda. Tipiar ‘\c’ para en vaciar el buffer.
mysql>
Paso # 4: Configurar una nueva contraseña del servidor MySQL para el usuario root:
mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
Paso # 5: Detener el servidor MySQL:
# /etc/init.d/mysql stop
Salida:
Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6121]: ended
[1]+  Done                    mysqld_safe –skip-grant-tables
Paso # 6: Iniciar el servidor MySQL y verificar la contraseña:
# /etc/init.d/mysql start
# mysql -u root -p



Dar de alta a usuarios

Por regla se habilita al usuario para acceso pidiendole la IP asi solo desde esa pc se puede conectar al servidor de datos.

Usuario con privilegios de administrador

GRANT ALL PRIVILEGES ON *.* TO nameusart@'IP' IDENTIFIED BY 'passworduser' WITH GRANT OPTION;

Usuarios con privilegios de administrador de una determinada base de datos:

GRANT ALL PRIVILEGES ON namedatabase.* TO nameusart@'IP' IDENTIFIED BY 'passworduser';

Usuarios con privilegios de solo lectura RO para una determinada base de datos

GRANT SELECT ON namebase.* TO prueba@'IP' identified by 'passwduser';

Usuario para replicacion

GRANT REPLICATION SLAVE ON *.* TO 'replica'@'%' IDENTIFIED BY 'r3pl1cac10n';

Usuarios para ABM

GRANT SELECT, DELETE, INSERT, UPDATE ON namebase.* TO nameuser@IP IDENTIFIED BY 'passworduser';

Consulta de usuariosPara hacer alguna consulta al una base determinada debemos en primre lugar seleccionarla de la siguiente forma

use mysql;

Luego hacemos la consulta, esta en particular muestra la lista de usuarios de mysql

mysql>select user,password,host from user;

Cambiar password
mysql> use mysql;
mysql>select user,password,host from user;
mysql> update user set password=PASSWORD("NEW-PASSWORD") where User='nameuser';

LEMGUAJE SQL : CONSULTAS

Definindo Base de Datos.

La base de datos esta compuesta de tablas (MD_Clientes)y las tablas de campos (ID_Cliente,sNombreCliente,sApellidosCliente,etc...)y los campos contienen registros. Si lo pensamos como una planilla de excel, las columnas son los campos, las hojas es la tabla y los registros (tuplas) son las filas.


Elementos del lenguaje SQL

código SQL

El código SQL consta de los siguientes elementos:

  • Comandos. Las distintas instrucciones que se pueden realizar desde SQL
    • SELECT. Se trata del comando que permite realizar consultas sobre los datos de la base de datos. Obtiene datos de la base de datos. A ésta parte del lenguaje se la conoce como DQL (Data Query Language, Lenguaje de consulta de datos); pero es parte del DML del lenguaje.
    • DML, Data Manipulation Language (Lenguaje de manipulación de datos). Modifica filas (registros) de la base de datos. Lo forman las instrucciones INSERT, UPDATE, MERGE y DELETE.
    • DDL, Data Definition Language (Lenguaje de definición de datos). Permiten modificar la estructura de las tablas de la base de datos. Lo forman las instrucciones CREATE, ALTER, DROP, RENAME y TRUNCATE
    • DCL, Data Control Language (Lenguaje de control de datos). Administran los derechos y restricciones de los usuarios. Lo forman las instrucciones GRANT y REVOKE.
    • DTL, Instrucciones de control de transacciones. Administran las modificaciones creadas por las instrucciones DML. Lo forman las instrucciones ROLLBACK y COMMIT. Se las considera parte del DML.
  • Cláusulas. Son palabras especiales que permiten modificar el funcionamiento de un comando (WHERE, ORDER BY,...)
  • Operadores. Permiten crear expresiones complejas. Pueden ser aritméticos (+,-,*,/,...) lógicos (>, <, !=,<>, AND, OR,...)
  • Funciones. Para conseguir valores complejos (SUM(), DATE(),...)
  • Literales. Valores concretos para las consultas: números, textos, caracteres,... Ejemplos: 2, 12.34, 'Avda Cardenal Cisneros'
  • Metadatos. Obtenidos de la propia base de datos

Muestra listado de Bases de datos

show databases;

Muestra listado de Tablas

Crear bases de datos

create database namebase;

Borrar base de datos

drop database namebase;

Backup de todas las bases en un solo script sql (Colocar Año/Mes/Dia):

root@mysqlserver:/etc/mysql# mysqldump --single-transaction --opt --all-databases --events -u root -pmysql2011 > mysqlserver-AAAAMMDD.sql

Backup en particular de una base de datos

root@mysqlserver:/etc/mysql# mysqldump --single-transaction --opt dotproject --events -u root -pmysql2011 > dotproject-AAAAMMDD.sql

Optimizacion de bases

Estos comando se ejecuta desde el prompt de Linux, tambien pueden ejecutarse desde el prompt de mysql, pero NO LO HAGAN, hasta no estar mas seguros !!

Usage: mysqlcheck [OPTIONS] database [tables]
OR mysqlcheck [OPTIONS] --databases DB1 [DB2 DB3...]
OR mysqlcheck [OPTIONS] --all-databases

Auto Reparacion ( Usar discriminadamente )
mysqlcheck --auto-repair --all-databases -u root -pmysql2011

Repara la base de datos
mysqlcheck -r --all-databases -u root -pmysql2011

Optimiza la base:
mysqlcheck -o --all-databases -u root -pmysql2011

Chequea error en las tablas
mysqlcheck -c --all-databases -u root -pmysql2011

Reemplazar datos
Este ejemplo cambia el password de un usuario

mysql> update user set password=PASSWORD("NEW-PASSWORD") where User='nameuser';
Borrar datos
El formato basico de esta instruccion es:
DELETE FROM nombretabla WHERE condicion;
1.- EL caso mas simple es eliminar un registro cualquiera:
DELETE from nombretabla where campo = valor(puede ser numerico, alfanumerico o alfabetico);
2.- Tambien puden eliminarse un subconjunto de registros usando la clausula WHERE con un filtro o condicion de manera apropiada y bien construido como lo muestra el siguiente ejemplo.
Delete from nombretabla where campo <=valor(puede ser numerico, alfanumerico o alfabetico);


REPLICANDO DATOS

ESTRUCTURA

SERVIDOR MASTER

MYSQLSERVERS
IP 10.0.4.16
REDHAT 7

SERVIDORES SLAVE

MYSQLVIRTUAL              MYSQLVIRTUAL2
IP 10.0.4.23                           IP 12.26.10.3
 UBUNTU 14.04                   REDHAT 7
-------------------------------------------------------------------------------------------------------------------------
INTRODUCCION

Demos configurar un Servidor como MASTER (MysqlServers) y otro como SLAVE (MysqlVirtual en TECO, MysqlVirtual2 en CENTRAL).

PASOS PREVIOS PARA SERVIDORES MASTER Y SLAVE:

  Antes que nada debemos chequear la variable "open_files_limit" :
 
    mysql > show global variables like 'open%';
 
    +------------------+-------+
    | Variable_name    | Value |
    +------------------+-------+
    | open_files_limit | 65536 |
    +------------------+-------+
    1 row in set (0,00 sec)

  Este valor no es el ideal pero por ahora quedara asi, para conseguirlo debemos saber que Sistema Operativo tenemos.
  Para el caso de REDHAT 7 debemos agregar en:

    [root@MysqlServers ~]# cd /usr/lib/systemd/system
    [root@MysqlServers system]# vi mysqld.service

  Y agregamos las siguientes lineas al final del archivo mysqld.service:

    LimitNOFILE = infinity
    LimitMEMLOCK = infinity

  Pero ademas debemos hacerlo para el sistema operativo:

    [root@MysqlServers ~]# cd /etc/security/
    [root@MysqlServers security]# vi limits.conf

  Aqui agregamos las siguientes lineas:

  definimos aqui tambien para el servicio de mysql

    * soft nofile 65536
    * hard nofile 65536
    * soft nproc 65536
    * hard nproc 65536

    mysql hard nofile 65536
    mysql soft nofile 65536

  Echo esto agregamos en el archivo de configuracion del mysql la variable global open_files_limit con el valor definido anteriormente:

    [root@MysqlServers ~]# cd /etc
    [root@MysqlServers etc]# vi my.cnf

  Dentro de las etiquetas [mysqld] y [mysqld_safe]

    [mysqld]
    ...
    open_files_limit = 65536
    ...

    [mysqld_safe]
    ...
    open_files_limit = 65536
    ...

  Y para evitar varios problemas chequen los permisos del my.cnf, por default tiene los permisos 600, necesitamos modificar a 644

  Default
  -rw-------. 1 root root 1793 abr 20 10:28 my.cnf

  Modificado

  -rw-r--r--. 1 root root 1793 abr 20 10:28 my.cnf

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

  CONFIGURANDO MASTER my.cnf

  [root@MysqlServers etc]# vi my.cnf

    # For advice on how to change settings please see
    # http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html

    [mysqld]
    user = mysql
    # Remove leading # and set to the amount of RAM for the most important data
    # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
    # innodb_buffer_pool_size = 128M

    # Remove leading # to turn on a very important data integrity option: logging
    # changes to the binary log between backups.
    log_bin = "/var/lib/mysql/mysql-bin"

    # These are commonly set, remove the # and set as required.
    # basedir = .....
    # datadir = .....
    # port = .....
    # server_id = .....
    # socket = .....

    # Remove leading # to set options mainly useful for reporting servers.
    # The server defaults are faster for transactions and fast SELECTs.
    # Adjust sizes as needed, experiment to find the optimal values.
    # join_buffer_size = 128M
    # sort_buffer_size = 2M
    # read_rnd_buffer_size = 2M

    server-id = 1
    skip-external-locking
    sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
    binlog_format=MIXED
    log_bin_index = "/var/lib/mysql/mysql-bin.index"
    sync_binlog=1
    general-log
    general_log_file = "/var/lib/mysql/MysqlServer.log"
    innodb_flush_log_at_trx_commit=1

  Lo importante para el mnaster

    server-id = 1
    log_bin = "/var/lib/mysql/mysql-bin"
    log_bin_index = "/var/lib/mysql/mysql-bin.index"
    sync_binlog=1
    binlog_format=MIXED

  Todos los demas parametros son necesarios, pero para el motor de base de datos, no para la replicacion en si.

  Luego chequeamos que este andando

  1.- reiniciamos el mysql: service mysqld restart
  2.- ingresamos a mysql: mysql -u root -ppassword
  3.- Ejecutamos el comando show para ver el estado del master

    mysql> SHOW MASTER STATUS;
    +------------------+-----------+--------------+------------------+-------------------+
    | File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
    +------------------+-----------+--------------+------------------+-------------------+
    | mysql-bin.000003 | 213040583 |              |                  |                   |
    +------------------+-----------+--------------+------------------+-------------------+
    1 row in set (0,00 sec)

  4.- Si queremos reiniciar el MASTER, ejecutaremos:

    mysql> reset master;

  5.- Debemos hacer dump de todas las bases de datos para deployarlas luego en el Slave, sino hacemos estos no replicara nunca.
  Este dump tiene la caracteristica siguiente:

    [root@MysqlServers root]# mysqldump -u root -p --skip-lock-tables --single-transaction --flush-logs --hex-blob --master-data=2 --all-databases > Dump-TOTAL.sql

  Luego de terminado ejecutamos el siguiente comando:

    head DumpTotal-20160420.sql -n80 | grep MASTER_LOG_POS

  Debemos tener encuenta estos valor para luego en el slave utilizarlos.

    CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

  6.- Copiamos el dump al servidor slave

    [root@MysqlServers root] scp DumpTotal-20160420.sql root@MysqlVirtual:/root/

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

CONFIGURANDO SLAVE

Para que realmente pueda replicar debemos tener que restaurar un dump del master en el slave, (ste es el caso donde se replican todas las bases del Master), pero una vez que empezo a repplicar, cuando creamos una nueva base en el master, se copia en los slave, sin tener que hacer un dump del master o tener que crear por consola la base en el slave.

Restauramos el Dump:

root@MysqlVirtual:~# mysql -u root -ppassword < DumpTotal.sql

Echo la restauracion abrimos el archivo de configurarcion del mysql (my.cnf) del slave:

PARA UBUNTU 14.04

root@MysqlVirtual:~# cd /etc/mysql/
root@MysqlVirtual:/etc/mysql# vi my.cnf

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket        = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket        = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket        = /var/run/mysqld/mysqld.sock
port        = 3306
basedir        = /usr
datadir        = /var/lib/mysql
tmpdir        = /tmp
lc-messages-dir    = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address        = 127.0.0.1
#
# * Fine Tuning
#
key_buffer        = 16M
max_allowed_packet    = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit    = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
general_log_file        = /var/log/mysql/mysql.log
general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries    = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
server-id        = 2
log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M

# Agregar este parametro para solucionar este error: ERROR 2006 (HY000): MySQL server has gone away, que se produce cuando estamos restaurando el dump del master en el slave

max_allowed_packet    = 64M


#binlog_do_db        = include_database_name
#binlog_ignore_db    = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
open_files_limit = 65536


[mysqldump]
quick
quote-names
max_allowed_packet    = 16M

[mysql]
#no-auto-rehash    # faster start of mysql but no tab completition

[isamchk]
key_buffer        = 16M

[mysqld_safe]
open_files_limit = 65536

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/


Los parametros que son importantes para el servidor slave (UBUNTU 14.04)

server-id        = 2
log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M
max_allowed_packet    = 64M


PARA REDHAT 7


[root@MysqlVirtual2 ~]# cd /etc/mysql
[root@MysqlVirtual2 mysql]#

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
# basedir = .....
# datadir = .....
# port = .....
# server_id = .....
# socket = .....

# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

server-id = 3

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
max_allowed_packet = 64M

# GLOBAL VARIABLES
explicit_defaults_for_timestamp
open_files_limit = 65536

# VARIABLES RELAY

relay-log = mysqld-relay-bin
max-relay-log-size = 500M
relay_log_purge = 1

# REPLICATIONS

report-host = 10.0.48.160
report-user = replicar
report-password = r3pl1c4c10n
report-port = 3306

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

auto_increment_increment = 2
auto_increment_offset = 1

sysdate-is-now

symbolic-links

skip_external_locking = off

plugin_dir = /usr/lib64/mysql/plugin/

general-log = 1
log-error = mysqlservers.err
general_log_file = mysqlservers.log
log_slave_updates
show-slave-auth-info

sync_binlog = 1
enforce_gtid_consistency
gtid-mode = OFF
slave_allow_batching
slave-sql-verify-checksum
slave_exec_mode = STRICT
binlog-format = MIXED
relay_log_info_file = relay-log.info

Los parametros que son importantes para el servidor slave (REDHAT 7):

server-id = 3

# VARIABLES RELAY

relay-log = mysqld-relay-bin
max-relay-log-size = 500M
relay_log_purge = 1

# REPLICATIONS

report-host = 10.0.4.16
report-user = replicar
report-password = r3pl1c4c10n
report-port = 3306

general-log = 1
log-error = mysqlservers.err
general_log_file = mysqlservers.log
log_slave_updates
show-slave-auth-info

sync_binlog = 1
enforce_gtid_consistency
gtid-mode = OFF
slave_allow_batching
slave-sql-verify-checksum
slave_exec_mode = STRICT
binlog-format = MIXED
relay_log_info_file = relay-log.info

Realizado a configuracion del archivo my.cnf debemos ingresar al motor mysql

[root@MysqlVirtual2 mysql]# mysql -u root -ppassword

Debemos decirle al slave donde tiene que buscar el servidor MASTER, en este momento vamos a utilizar los datos que obtuvimos del master


MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

Y lo agregamos en el siguiente comando:

mysql> CHANGE MASTER TO MASTER_HOST='10.0.4.16', MASTER_PORT=3306, MASTER_USER='replicar', MASTER_PASSWORD='r3pl1c4cion', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=120;

Query OK, 0 rows affected (0,03 sec)

Luego iniciamos el servidor slave:

mysql> start slave;
Query OK, 0 rows affected (0,00 sec)

Y chequeamos que todo este funcionando adecuadamente:

mysql> show slave status\G;

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.4.16
                  Master_User: replicar
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000042
          Read_Master_Log_Pos: 1963620
               Relay_Log_File: mysqld-relay-bin.000081
                Relay_Log_Pos: 493146
        Relay_Master_Log_File: mysql-bin.000042
             Slave_IO_Running: Yes                 
            Slave_SQL_Running: Yes
              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:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1963620
              Relay_Log_Space: 1964120
              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: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: f82504d7-fb73-11e5-b535-005056bb4337
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
1 row in set (0,00 sec)

ERROR:
No query specified


Esta salida del comando nos esta diciendo que todo esta normal y funcionando, sabiendo que los siguientes parametros estan incializados con el valor "YES"
 
    Slave_IO_Running: Yes                 
    Slave_SQL_Running: Yes
   
---------------------------------------------------------------------------------------------------------------------------------------------------------

PROCEDIMIENTO UNA VEZ SOLUCIONADO EL ERROR EN LA REPLICACION

Ahora bien, si se produce un error, luego de solucionarlo debemos hacer lo siguiente:

1.- Paramos el servicio de slave
mysql> stop slave;
Query OK, 0 rows affected (0,00 sec)

2.- Reseteamos el servicio de slave, osea limpiamos el error
mysql> reset slave;
Query OK, 0 rows affected (0,00 sec)

3.- Ejecutamos nuevamente el comando CHANGE MASTER TO como lo detallamos arriba

4.- Reiniciamos nuevamente el slave

mysql> start slave;
Query OK, 0 rows affected (0,00 sec)

-----------------------------------------------------------------------------------------------------------------------------
ESTADO Y SISTEMA DE VARIABLES

Para saber cuantas tablas tiene una base de datos

SELECT Count(*) FROM information_schema.tables;

mysql> SELECT Count(*) FROM information_schema.tables;
+----------+
| Count(*) |
+----------+
|      300 |
+----------+
1 row in set (0.00 sec)

Para saber el tamaño de una base de datos

mysql> SELECT table_schema "senasa", sum( data_length + index_length ) / 1024 /1024 /1024 "Data Base Size in GB",sum( data_free )/ 1024 / 1024 /1024"Free Space in GB" FROM information_schema.TABLES GROUP BY table_schema ;
+-------------------------+---------------------------+--------------------------+
| senasa                        | Data Base Size in GB |     Free Space in GB  |
+-------------------------+--------------------------+--------------------------+
| information_schema |         0.000008583069 |       0.000000000000 |
| senasa                       |          2.101470947266 | 1115.917968750000 |
+------------------------+----------------------------+-------------------------+



Si lo que buscas es la cantidad de octetos recibidos y enviados por la base de datos, las variables de estado (SHOW GLOBAL STATUS) Bytes_received y Bytes_sent te lo darán







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

Errores y Soluciones
Archivo socket
Este error se produce cuando el archivo mysql.socket (que es el archivo que maneja el proceso que indica que el motor del servidor mysql esta iniciado) no se destruye por haberse parado mal el servicio de mysql.
[root@Libreria-RHN init.d]# service mysqld start
Another MySQL daemon already running with the same unix socket.
Iniciando mysqld: [FALLÓ]
Solucion:
Borrar el archivo mysql.socket que se encuentra en /var/lib/mysql/ y reiniciar el servicio de mysql



ERROR: REPLICACION


1.- Last_IO_Errno: 1593

ERROR:1593 EQUAL MySQL server UUIDs;

mysql> show slave status\G
*************************** 1. row ***************************
...
                Last_IO_Errno: 1593
                Last_IO_Error: Fatal error: The slave I/O thread stops because
                               master and slave have equal MySQL server UUIDs;
                               these UUIDs must be different for replication to work.
...

Solucion
Dentro del directorio donde estan las bases de mysql /var/lib/mysql se encuentra un archivo llamado auto.cnf este se autogenera, este error nos avisa que
tenemos el mismo uuid entre el master y slave, por lo tanto borramos en el slave el archvio y reiniciamos el mysql

2.- Last_SQL_Errno: 1062

               Last_SQL_Error: Error 'Duplicate entry '3716-INBOX.msg-3418' for key 'uniqueness'' on query. Default database: 'roundcubemail'. Query: 'INSERT INTO messages (user_id, del, cache_key, created, idx, uid, subject, `from`, `to`, cc, date, size, headers, structure) VALUES ('3716', 0, 'INBOX.msg', now(), '212', '3418', 'Fwd: Memo DCF NÃ?º 426 Requisitos Fitosanitarios para exportacion de  madera a Brasil', 'mventura@senasa.gob.ar', 'aanasco@senasa.gob.ar, cgoya@senasa.gob.ar, cnadal@senasa.gob.ar, fmango@senasa.gob.ar, ifinardi@senasa.gob.ar, jpcaceres@senasa', '', FROM_UNIXTIME(1447430459), 4960536, 'O:17:\"rcube_mail_header\":35:{s:2:\"id\";s:3:\"212\";s:3:\"uid\";s:4:\"3418\";s:7:\"subject\";s:105:\"Fwd: Memo DCF =?iso-8859-1?Q?N=C2=BA_426_Requisitos_Fitosanitarios_para_exportacion_de_?= madera a Brasil\";s:4:\"from\";s:22:\"mventura@senasa.gob.ar\";s:2:\"to\";s:205:\"aanasco@senasa.gob.ar, cgoya@senasa.gob.ar, cnadal@senasa.gob.ar, fmango@senasa.gob.ar, ifinardi@senasa.gob.ar, jpcaceres@senasa.gob.ar, jrabuffe@senasa.gob

SOLUCION:

1.- Generar en el master nuevamente el dump eccho como se detalla al principio de este documento
2.- Hacer la restauracion del dump sobre el SLAVE en cuestion.
3.- Resetear el Slave, STOP SLAVE; RESET SLAVE;
4.- CHANGE MASTER TO MASTER_HOST='10.0.48.160', MASTER_PORT=3306, MASTER_USER='replicar', MASTER_PASSWORD='r3pl1c4c10n', MASTER_LOG_FILE='mysql-bin.000002', MASTER_LOG_POS=120; ( tal cual esta escrito)
5.- START SLAVE;
6.- SHOW STATUS SLAVE\G;

3.- No directory, logging in with HOME=/

SOLUCION:

Este error se soluciona en tres pasos;

a.- service mysql stop
b.- usermod -d /var/lib/mysql/ mysql
c.- service mysql start


4.- Last_SQL_Errno: 1133

Error 'Can't find any matching row in the user table' on query.

mysql> SHOW SLAVE STATUS  \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.48.160
                  Master_User: replicar
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.002590
          Read_Master_Log_Pos: 556219230
               Relay_Log_File: mysqld-relay-bin.003669
                Relay_Log_Pos: 1223558
        Relay_Master_Log_File: mysql-bin.001835
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
                    ...
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1133
                   Last_Error: Error 'Can't find any matching row in the user table' on query. Default database: 'mysql'. Query: 'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, GRANT OPTION, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, EVENT, TRIGGER ON `%`.* TO 'claudio'@'10.0.48.160''
               

ERROR:
No query specified

SOLUCION

mysql> stop slave;
Query OK, 0 rows affected (0,01 sec)

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;
Query OK, 0 rows affected (0,00 sec)

mysql> START SLAVE;
Query OK, 0 rows affected (0,00 sec)


5.- ERROR EN SLAVE log_bin y log-slave-updates

You need to use --log-bin to make --log-slave-updates work.
You need to use --log-bin to make --binlog-format work.

Solo habilite log_bin sin valor, ya que log-slave-updates estaba y tiro el siguiente error:

No argument was provided to --log-bin, and --log-bin-index was not used; so replication may break when this MySQL server acts as a master and has his hostname changed!! Please use '--log-bin=MysqlVirtual2-bin' to avoid this problem.


SOLUCION

Agregarle el valor que indica a la variable log_bin


6.- ERROR de MEMCACHED

InnoDB MEMCACHED: Memcached uses atomic increment
bind(): Permission denied
failed to listen on TCP port 11211: Permission denied


7.- Last_SQL_Errno: 1114


ERROR 1114 (HY000) at line 44463: The table 'messages' is full   

You need to modify the limit cap set in my.cnf for the INNO_DB tables. This memory limit is not set for individual tables, it is set for all the tables combined.

If you want the memory to autoextend to 512MB

innodb_data_file_path = ibdata1:10M:autoextend:max:512M

If you don't know the limit or don't want to put a limit cap, you can modify it like this

innodb_data_file_path = ibdata1:10M:autoextend

This is the MySQL official doc http://dev.mysql.com/doc/refman/4.1/en/adding-and-removing.ht


8.- Last_SQL_Errno: 1452

ERROR

Last_SQL_Error: Error 'Cannot add or update a child row: a foreign key constraint fails (`roundcubemail`.`cache`, CONSTRAINT `user_id_fk_cache` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE)' on query. Default database: 'roundcubemail'. Query: 'INSERT INTO cache (created, user_id, cache_key, data) VALUES (now(), '14377', 'IMAP.mailboxes', 'a:3:{i:0;s:11:\"INBOX.Trash\";i:1;s:10:\"INBOX.Sent\";i:2;s:12:\"INBOX.Drafts\";}')'


SOLUCION:

1.- Reiniciar la base cuando da el fallo
2.- Ejecutar la sentencia : SET foreign_key_checks = 1;
3.- Chequear que ande SHOW SLAVE STATUS \G;


9.- Last_SQL_Errno: 1396
   
    Last_SQL_Error: Error 'Operation DROP USER failed for 'replicar'@'172.26.160.33'' on query. Default database: 'mysql'. Query: 'DROP USER 'replicar'@'172.26.160.33''


10.- Slave is not configured or failed to initialize properly

ERROR 1794 (HY000): Slave is not configured or failed to initialize properly. You must at least set --server-id to enable either a master or a slave. Additional error messages can be found in the MySQL error log.


En my.cnf hay que agregar

server_id = 3 (El numero server_id = 1 -> Master y los demas son server_id = 3 -> Slave, significa que hay dos Slave.

Para que surta efecto, no restartear !! Sino que parar el servicio y levantarlo de nuevo