jueves, 31 de octubre de 2019

Recreacion de la replica de la BD (MySQL)

Descripcion Funcional
  • Cambiar clave del usuario de replica: repl
grant replication slave on *.* to repl identified by 'XXXXX'; (cualquiera)
  • Poner el master en read only
SET GLOBAL read_only = ON;
FLUSH TABLES WITH READ LOCK;
  • Ver en el master la ultima secuencia generada
SHOW MASTER STATUS;
  • Exportar las tablas y pasarlas al slave
mysqldump -uroot -pXXXXXX > dump.sql
mysqldump -uroot -p --all-databases > alldata.sql
  • Sacar de read only el master
SET GLOBAL read_only = OFF;
UNLOCK TABLES;
  • Copiar file al server slave
scp file server_destino:
  • Importar las tablas en el slave:
mysql -uroot -p
stop slave;
reset slave;
source alldata.sql;
  • Configurar el slave para que replique desde esa secuencia
CHANGE MASTER TO MASTER_HOST='$MASTER_HOST_IP', MASTER_USER='repl', MASTER_PASSWORD='cualquieraXXXX', MASTER_LOG_FILE='$File', MASTER_LOG_POS=$Position;
  • Comenzar la replicar
START SLAVE;
  • Verificar que el slave continua aplicando
SHOW SLAVE STATUS\G

  • Tomar un backup desde el slave

Instalando MySQL Server en Ubuntu

Install MySQL

Install the MySQL server by using the Ubuntu package manager:
sudo apt-get update
sudo apt-get install mysql-server
The installer installs MySQL and all dependencies.
If the secure installation utility does not launch automatically after the installation completes, enter the following command:
sudo mysql_secure_installation utility
This utility prompts you to define the mysql root password and other security-related options, including removing remote access to the root user and setting the root password.

Allow remote access

If you have iptables enabled and want to connect to the MySQL database from another machine, you must open a port in your server’s firewall (the default port is 3306). You don’t need to do this if the application that uses MySQL is running on the same server.
Run the following command to allow remote access to the mysql server:
sudo ufw enable
sudo ufw allow mysql

Start the MySQL service

After the installation is complete, you can start the database service by running the following command. If the service is already started, a message informs you that the service is already running:
sudo systemctl start mysql

Launch at reboot

To ensure that the database server launches after a reboot, run the following command:
sudo systemctl enable mysql

Configure interfaces

MySQL, by default is no longer bound to ( listening on ) any remotely accessible interfaces. Edit the “bind-address” directive in /etc/mysql/mysql.conf.d/mysqld.cnf:
bind-address  = 127.0.0.1 ( The default. )
bind-address  = XXX.XXX.XXX.XXX ( The ip address of your Public Net interface. )
bind-address  = ZZZ.ZZZ.ZZZ.ZZZ ( The ip address of your Service Net interface. )
bind-address  = 0.0.0.0 ( All ip addresses. )
Restart the mysql service.
sudo systemctl restart mysql

Start the mysql shell

There is more than one way to work with a MySQL server, but this article focuses on the most basic and compatible approach, the mysql shell.
  1. At the command prompt, run the following command to launch the mysql shell and enter it as the root user:
    /usr/bin/mysql -u root -p
    
  2. When you’re prompted for a password, enter the one that you set at installation time, or if you haven’t set one, press Enter to submit no password.
    The following mysql shell prompt should appear:
    mysql>
    

Set the root password

If you logged in by entering a blank password, or if you want to change the root password that you set, you can create or change the password.
  1. For versions earlier than MySQL 5.7, enter the following command in the mysql shell, replace password with your new password:
    UPDATE mysql.user SET Password = PASSWORD('password') WHERE User = 'root';
    
    For version MySQL 5.7 and later, enter the following command in the mysql shell, replacing password with your new password:
    UPDATE mysql.user SET authentication_string = PASSWORD('password') WHERE User = 'root';
    
  2. To make the change take effect, reload the stored user information with the following command:
    FLUSH PRIVILEGES;
    
    Note: We’re using all-caps for SQL commands. If you type those commands in lowercase, they’ll work. By convention, the commands are written in all-caps to make them stand out from field names and other data that’s being manipulated.
If you need to reset the root password later, see Reset a MySQL root password.

View users

MySQL stores the user information in its own database. The name of the database is mysql. Inside that database the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:
SELECT User, Host, authentication_string FROM mysql.user;
The following list describes the parts of that command:
  • SELECT tells MySQL that you are asking for data.
  • UserHostauthentication_string tells MySQL what fields you want it to look in. Fields are categories for the data in a table. In this case, you are looking for the username, the host associated with the username, and the encrypted password entry.
  • FROM mysql.user “ tells MySQL to get the data from the mysql database and the user table.
  • A semicolon (;) ends the command.
Note: All SQL queries end in a semicolon. MySQL does not process a query until you type a semicolon.

User hosts

The following example is the output for the preceding query:
SELECT User, Host, authentication_string FROM mysql.user;
+------------------+-----------+-------------------------------------------+
| User             | Host      | authentication_string                     |
+------------------+-----------+-------------------------------------------+
| root             | localhost | *756FEC25AC0E1823C9838EE1A9A6730A20ACDA21 |
| mysql.session    | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys        | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| debian-sys-maint | localhost | *27E7CA2445405AB10C656AFD0F86AF76CCC57692 |
+------------------+-----------+-------------------------------------------+
Users are associated with a host, specifically, the host from which they connect. The root user in this example is defined for localhost, for the IP address of localhost, and the hostname of the server. You usually need to set a user for only one host, the one from which you typically connect.
If you’re running your application on the same computer as the MySQL server, the host that it connects to by default is localhost. Any new users that you create must have localhost in their host field.
If your application connects remotely, the host entry that MySQL looks for is the IP address or DNS hostname of the remote computer (the one from which the client is coming).

Anonymous users

In the example output, one entry has a host value but no username or password. That’s an anonymous user. When a client connects with no username specified, it’s trying to connect as an anonymous user.
You usually don’t want any anonymous users, but some MySQL installations include one by default. If you see one, you should either delete the user (refer to the username with empty quotes, like ‘ ‘) or set a password for it.

Create a database

There is a difference between a database server and a database, even though those terms are often used interchangeably. MySQL is a database server, meaning it tracks databases and controls access to them. The database stores the data, and it is the database that applications are trying to access when they interact with MySQL.
Some applications create a database as part of their setup process, but others require you to create a database yourself and tell the application about it.
To create a database, log in to the mysql shell and run the following command, replacing demodb with the name of the database that you want to create:
CREATE DATABASE demodb;
After the database is created, you can verify its creation by running a query to list all databases. The following example shows the query and example output:
SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| demodb             |
| mysql              |
+--------------------+
3 rows in set (0.00 sec)

Add a database user

When applications connect to the database using the root user, they usually have more privileges than they need. You can add users that applications can use to connect to the new database. In the following example, a user named demouser is created.
  1. To create a new user, run the following command in the mysql shell:
    INSERT INTO mysql.user (User,Host,authentication_string,ssl_cipher,x509_issuer,x509_subject)
    VALUES('demouser','localhost',PASSWORD('demopassword'),'','','');
    
  2. When you make changes to the user table in the mysql database, tell MySQL to read the changes by flushing the privileges, as follows:
    FLUSH PRIVILEGES;
    
  3. Verify that the user was created by running a SELECT query again:
    SELECT User, Host, authentication_string FROM mysql.user;
    
    +------------------+-----------+-------------------------------------------+
    | User             | Host      | Password                                  |
    +------------------+-----------+-------------------------------------------+
    | root             | localhost | *756FEC25AC0E1823C9838EE1A9A6730A20ACDA21 |
    | mysql.session    | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
    | mysql.sys        | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
    | debian-sys-maint | localhost | *27E7CA2445405AB10C656AFD0F86AF76CCC57692 |
    | demouser         | localhost | *0756A562377EDF6ED3AC45A00B356AAE6D3C6BB6 |
    +------------------+-----------+-------------------------------------------+
    

Grant database user permissions

Right after you create a new user, it has no privileges. The user can log in, but can’t be used to make any database changes.
  1. Give the user full permissions for your new database by running the following command:
    GRANT ALL PRIVILEGES ON demodb.* to demouser@localhost;
    
  2. Flush the privileges to make the change official by running the following command:
    FLUSH PRIVILEGES;
    
  3. To verify that those privileges are set, run the following command:
    SHOW GRANTS FOR 'demouser'@'localhost';
    2 rows in set (0.00 sec)
    
    MySQL returns the commands needed to reproduce that user’s permissions if you were to rebuild the server. USAGE on \*.\* means the users gets no privileges on anything by default. That command is overridden by the second command, which is the grant you ran for the new database.
    +-----------------------------------------------------------------------------------------------------------------+
    | Grants for demouser@localhost                                                                                   |
    +-----------------------------------------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'demouser'@'localhost' IDENTIFIED BY PASSWORD '*0756A562377EDF6ED3AC45A00B356AAE6D3C6BB6' |
    | GRANT ALL PRIVILEGES ON `demodb`.* TO 'demouser'@'localhost'                                                    |
    +-----------------------------------------------------------------------------------------------------------------+
    2 rows in set (0.00 sec)
    

Espero que les sea Util.

Gracias !!! 

martes, 29 de octubre de 2019

Refrescar una vista materializada.

simplemente



Primero nos ponemos como el owner de la vista..

alter session set current_schema = <esquema>;

y luego refrescamos.


BEGIN
   dbms_mview.refresh(‘NOMBRE DE LA VISTA);
END;
/


y listo 

martes, 22 de octubre de 2019

La clave esta expirada.. Que hacer ?

Este error se debe a que la base de datos Oracle tiene por defecto expira los passwords después de 180 días (6 meses), para cambiar esta configuración solo se tiene que seguir los siguientes pasos:
*Nota: todo lo que se encuentre entre llaves({}) se debe de sustituir por los valores deseados, adicionalmente se deben de eliminar las llaves.
Entra a la terminal de la base de datos usando el usuario “dueño” del servicio de base de datos:

Ej. para Linux:
“su – oracle”
“sqlplus / as sysdba”
Verifica el tiempo de expiración usando la siguiente consulta:        

“SELECT * FROM DBA_PROFILES WHERE RESOURCE_NAME = ‘PASSWORD_LIFE_TIME’ AND PROFILE = ‘DEFAULT’;”

Ejecuta la siguiente instruccion: 

“ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;”

y listo !!!

Tema de terceros.

Dejo esta ventana abierta por si necesito algo lo pueden subir aca.
GRACIAS !!

Verificación de procesos RFS

SQL> select inst_id,process,status,thread#,sequence#,block#,blocks from gv$managed_standby;

   INST_ID PROCESS   STATUS      THREAD#  SEQUENCE#     BLOCK#     BLOCKS
---------- --------- ------------ ---------- ---------- ---------- ----------
1 ARCH      CLOSING    4   51519     163840 1106
1 ARCH      CONNECTED    0       0 0     0
1 ARCH      CLOSING    5   48955      32768   737
1 ARCH      CLOSING    1   51754    7536640   700
1 ARCH      CLOSING    2   49809     534528 1534
1 ARCH      CLOSING    5   48956      20480 1690
1 ARCH      CLOSING    3   48933      20480    14
1 ARCH      CLOSING    3   48934      28672   704
1 ARCH      CLOSING    1   51757     561152   746
1 ARCH      CLOSING    1   51756    2656256 1319
1 RFS      IDLE    0       0 0     0

   INST_ID PROCESS   STATUS      THREAD#  SEQUENCE#     BLOCK#     BLOCKS
---------- --------- ------------ ---------- ---------- ---------- ----------
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0

   INST_ID PROCESS   STATUS      THREAD#  SEQUENCE#     BLOCK#     BLOCKS
---------- --------- ------------ ---------- ---------- ---------- ----------
1 RFS      IDLE    0       0 0     0
1 MRP0      WAIT_FOR_LOG    4   51520 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    3   48935      24298     4
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      RECEIVING    1   51758    1417145    17
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0

   INST_ID PROCESS   STATUS      THREAD#  SEQUENCE#     BLOCK#     BLOCKS
---------- --------- ------------ ---------- ---------- ---------- ----------
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0
1 RFS      IDLE    0       0 0     0

37 rows selected.

Loqueos en Oracle

En Oracle hay una vista v$lock que nos indica los objetos que se encuentran en bloqueo, el identificador de usuario y sesion y el tipo de bloqueo.
Un join con la tabla dba_objects nos proporciona ademas el nombre y tipo de los objetos bloqueados:

SELECT
decode(L.TYPE,'TM','TABLE','TX','Record(s)') TYPE_LOCK,
decode(L.REQUEST,0,'NO','YES') WAIT,
S.OSUSER OSUSER_LOCKER,
S.PROCESS PROCESS_LOCKER,
S.USERNAME DBUSER_LOCKER,
O.OBJECT_NAME OBJECT_NAME,
O.OBJECT_TYPE OBJECT_TYPE,
concat(' ',s.PROGRAM) PROGRAM,
O.OWNER OWNER
FROM v$lock l,dba_objects o,v$session s
WHERE l.ID1 = o.OBJECT_ID
AND s.SID =l.SID
AND l.TYPE in ('TM','TX');

Existen principalmente dos tipos de bloqueo:
bloqueos de tablas (TM) y
bloqueos a nivel de fila (TX)
Los bloqueos a nivel de tabla son creados cuando se ejecuta una sentencia DML del tipo: update, insert, delete, select ..for update sobre la tabla entera. 


miércoles, 16 de octubre de 2019

Borrar archivos con mas de XX dias de antigüedad

El comando find en Linux tiene muchas opciones y argumentos que se pueden utilizar, y entre ellos está poder ejecutar otro comando para cada archivo. Partiendo de esta base, es posible encontrar que archivos tienen más de un cierto número de días, y por ejemplo, utilizar el comando rm para eliminarlos.
La sintaxis para encontrar y eliminar, por ejemplo, archivos que tengan más de 5 días:
find /ruta/de/los/archivos* -mtime +5 -type f -exec rm {} \;

Explicación de código:

  • El primer argumento “/ruta/de/los/archivos*” es la ruta de acceso a los archivos. Nosotros recomendamos usar la ruta absoluta, y antes de utilizar el comando probarlo sin el comando rm para asegurarte de que estás obteniendo los resultados deseados.
  • El segundo argumento “-mtime“, se utiliza para especificar el número de días que debe tener el archivo para que se ejecute la segunda parte. En este caso, con el “+5” estarías indicando que quieres encontrar archivos que tengan más de 5 días.
  • El tercer argumento “-type“, se utiliza para especificar lo que estamos buscando, en este caso “f” indica que buscamos solo archivos (Files en inglés).
  • El cuarto argumento “-exec“, te permite lanzar un comando sobre los resultados, como por ejemplo “rm“.
  • Por último, para cerrar el comando se especifica “{} \;“.

miércoles, 9 de octubre de 2019

CREATE SEQUENCE

Desde un esquema crear todas las secuencias antes de borrarlas.

Select 'create sequence <schema>."'||SEQUENCE_NAME||'" START WITH 1 '||' MAXVALUE '||MAX_VALUE||' MINVALUE '||MIN_VALUE||' '||DECODE(CYCLE_FLAG,'N','NOCYCLE')||' CACHE '||CACHE_SIZE||' '||DECODE(ORDER_FLAG,'N','NOORDER')||' '||DECODE(KEEP_VALUE,'N','NOKEEP')||' GLOBAL; '
from dba_sequences where SEQUENCE_OWNER ='schema';

DROP SEQUENCE

Como hacer un listado de todas las secuencias a borrar de un esquema.

select 'drop sequence '||sequence_OWNER ||'.'||'"'||SEQUENCE_NAME||'"'||';' 
from dba_sequences where SEQUENCE_OWNER='<esquema>';

RMAN - Cuando no se encuentra un archive log --- RMAN-06726: could not locate archived log

  Lo importante en todo esto, es estar dentro del catalogo correspondiente, sino el crosscheck NO FNCIONA !!   oracle backup of logfiles is ...