Jugando con las estadisticas de un esquema

Hoy vamos a ver algunas consultas practicas de las estadisticas de sistema

Esquemas o objetos de un esquema con las estadisticas bloqueadas

Veamos algunas consultas utiles para comprobar cuales son las tablas que estan bloqueadas o para trabajar con las estadistias del esquema APPSCHEMA

Tablas conlas estadisticas bloqueadas para un esquema


select owner, table_name, stattype_locked
from dba_tab_statistics
where
stattype_locked is not null and OWNER=’APPSCHEMA’;

Cuando fueron bloqueadas las estadisticas en estas tablas?


set linesize 200
set pagesize 0
col owner format a20;
col table_name format a30;
Select table_name,last_analyzed from dba_tables
where table_name in
(select table_name from dba_tab_statistics where stattype_locked is not null and OWNER=’APPSCHEMA’)
order by last_analyzed asc ;

Tenemos una metaconsulta para desbloquearlas todas?

  select 'exec dbms_stats.unlock_table_stats('||chr(39)||'APPSCHEMA'||chr(39)||','||chr(39)||TABLE_NAME||chr(39)||' );'
       from dba_tab_statistics where stattype_locked is not null and OWNER='APPSCHEMA';

Ver las fechas de las estadisticas que han sido analizadas en los ultimos 2 dias

set pagesize 9000;
column owner format a20;
column TABLE_NAME format a30;
column PARTITION_NAME format a30;
select owner,table_name,partition_name,to_char(LAST_ANALYZED,'dd-mm-yy hh:mi'),NUM_ROWS,STATTYPE_LOCKED from dba_TAB_STATISTICS
where OWNER='APPSCHEMA' 
and LAST_ANALYZED  < sysdate-2
order by LAST_ANALYZED asc ;

Ver la fecha en la que fueron obtenidas las estadisticas de una tabla en concreto

set pagesize 9000;
column owner format a20;
column TABLE_NAME format a30;
column PARTITION_NAME format a30;
select owner,table_name,partition_name,to_char(LAST_ANALYZED,'dd-mm-yy hh:mi'),NUM_ROWS,STATTYPE_LOCKED from dba_TAB_STATISTICS
where TABLE_NAME='APPSCHEMA' 
order by LAST_ANALYZED asc ;

Como salvamos las estadisticas de un determinado esquema

Creamos una tabla de estadisticas llamada «MISTATS bajo el esquema APPSCHEMA

exec dbms_stats.create_stat_table(ownname => 'APPSCHEMA', stattab => 'MISTATS');

Si quisiesemos guardar solo las estadisticas de una tabla

  
exec dbms_stats.export_table_stats(ownname=>'APPSCHEMA', tabname=>'MISTATS', statown=>'APPSCHEMA', stattab=>'MISTATS', cascade=>true);

Si queremos salvar los de un esquema

EXEC DBMS_STATS.export_schema_stats('APPSCHEMA','MISTATS',NULL,'APPSCHEMA');

Mas informacion en

Bucle sleep en codigo PL-SQL

Vamos a ver una entrada rapidisima y sencillisima para dummies.

Como introducimos una espera en codigo PL-SQL

La respuesta es sencillisima, con la funcion DBMS_LOCK.SLEEP
Veamos por ejemplo como forzar dos esperas de 1 minuto para obtener un hang analyzer

$ORACLE_HOME/bin/sqlplus -s "/as sysdba" << EOF
oradebug setmypid;
oradebug unlimit;
oradebug hanganalyze 3;
exec dbms_lock.sleep(60);
-- Wait upto 1 minute before getting the second hanganalyze
oradebug hanganalyze 3;
-- Wait upto 1 minute before getting the second hanganalyze
exec dbms_lock.sleep(60);
oradebug hanganalyze 3;
oradebug tracefile_name;
EOF

Formatear el prompt del SQLplus

Hoy vamos a ver una entrada muuy sencilla de como formatear el prompt de SQLPLUS
Bajo nuestro oracle home tenemos un fichero llamado glogin.sql donde podemos definir las variables del sqlplus, entre ellas el prompt.
Supongaamos que queremos saber cual es el usuario con el que nos conectamos, seria tan sencillo como aniadir la linea

dbserver01:vi /u01/app/oracle/product/19c/dbhome_1/sqlplus/admin/glogin.sql
--
-- Copyright (c) 1988, 2005, Oracle.  All Rights Reserved.
--
-- NAME
--   glogin.sql
--
-- DESCRIPTION
--   SQL*Plus global login "site profile" file
--
--   Add any SQL*Plus commands here that are to be executed when a
--   user starts SQL*Plus, or uses the SQL*Plus CONNECT command.
--
-- USAGE
--   This script is automatically run
--
def _editor=vi
set timing on
set feedback on
set sqlprompt "_user  _connect_identifier > "

Ms informacion, en:

  • https://www.youtube.com/watch?v=Ax4s39KfcZ8
  • https://www.oreilly.com/library/view/oracle-sqlplus-the/0596007469/re95.html

Comandos basicos del Trace File Analyzer

Hoy vamos a ver los comandos y acciones basicas del tafcl
El tafcl es el comando de ejecucion del Trace File Analyzer (TFA), este pequeño script esta incluido dentro de la suite Autonomous Health Framework (AHF) , y sera o primero que nos solicite Oracle support una vez abramos un SR

Instalacion

Nos descargaremos el paquete de la AHF de la nota de soporte Autonomous Health Framework (AHF) – Including TFA and ORAchk/EXAchk (Doc ID 2550798.1 Y lo ejecutaremos como superusuario el comando ahf_setup.
Este comando tiene varias opciones

   Usage for ./ahf_setup

   ./ahf_setup [[-ahf_loc ][-data_dir ][-nodes ][-extract[orachk|exachk|-notfasetup] [-local][-silent][-tmp_loc ][-force][-debug [-level <1-6>]]]

        -ahf_loc          -    Install into the directory supplied. (Default /opt/oracle.ahf)
        -data_dir         -    AHF Data Directory where all the collections, metadata, etc. will be stored
        -nodes            -    Comma separated Remote Node List
        -extract          -    Extract only files from Installer. (Default for non-root users)
        -nosymlink        -    Do not create symlinks on Exadata DOM0. (Default for non-root users)
        -notfasetup       -    Do not Configure TFA when used with -extract
        -local            -    Only install on the local node
        -silent           -    Do not ask any install questions
        -tmp_loc          -    Temporary location directory for AHF to extract the install archive to (must exist) (Default /tmp)
        -perlhome         -    Custom location of perl binaries
        -force            -    Force AHF Install
        -debug            -    Debug AHF Install Script
        -level            -    AHF Instal Debug Level 1-6 (Default 4 with option -debug)
                               [FATAL - 1, ERROR - 2, WARNING - 3, INFO - 4, DEBUG - 5, TRACE - 6]

Si la instalacionn se hizo de manera estandard, el mismo TFA detectara la instalacion anterior y se actualizara.
Veamos un ejemplo de actualizacion.

[oracle@rac1 tmp]$ sudo ./ahf_setup 

AHF Installer for Platform Linux Architecture x86_64

AHF Installation Log : /tmp/ahf_install_211000_21804_2021_04_01-09_22_26.log

Starting Autonomous Health Framework (AHF) Installation

AHF Version: 21.1.0 Build Date: 202104131158

AHF is already installed at /opt/oracle.ahf

Installed AHF Version: 20.2.3 Build Date: 202010132201

Do you want to upgrade AHF [Y]|N : Y

Upgrading /opt/oracle.ahf

Shutting down AHF Services
Shutting down TFA
Removed symlink /etc/systemd/system/multi-user.target.wants/oracle-tfa.service.
Removed symlink /etc/systemd/system/graphical.target.wants/oracle-tfa.service.
. . . . .
. . .
Successfully shutdown TFA..


Starting AHF Services
Starting TFA..
Created symlink from /etc/systemd/system/multi-user.target.wants/oracle-tfa.service to /etc/systemd/system/oracle-tfa.service.
Created symlink from /etc/systemd/system/graphical.target.wants/oracle-tfa.service to /etc/systemd/system/oracle-tfa.service.
Waiting up to 100 seconds for TFA to be started..
. . . . .
. . . . .
. . . . .
Successfully started TFA Process..
. . . . .
TFA Started and listening for commands
No new directories were added to TFA


INFO: Starting orachk scheduler in background. Details for the process can be found at /opt/app/oracle/oracle.ahf/data/rac1/diag/orachk/compliance_start_230421_093124.log


AHF is successfully upgraded to latest version

.------------------------------------------------------------------.
| Host       | TFA Version | TFA Build ID         | Upgrade Status |
+------------+-------------+----------------------+----------------+
| rac1 |  21.1.0.0.0 | 21100020210413115827 | UPGRADED       |
| rac2 |  20.2.3.0.0 | 20230020201013220107 | NOT UPGRADED   |
'------------+-------------+----------------------+----------------'

Moving /tmp/ahf_install_211000_21804_2021_04_01-09_22_26.log to /opt/app/oracle/oracle.ahf/data/rac1/diag/ahf/

Usos comunes

Obtener informacion de las trazas en un determninado tiempo

Si quremos recabar informacion del sistema entre unas determinadas fechas usaremos los fags -from  -to
./tfactl diagcollect -from "2021-04-07 08:00:00" -to "2021-04-07 10:00:00"

Obtener informacion ded un determinado error

Si quremos obtener informacion del sistema sobre un determinado error, usaremos el flag srdc

./tfactl diagcollect -srdc ORA-07445

Gestion del repositorio

Ver la configuration

 
tfactl> print config
.---------------------------------------------------------------------------------------------------------------------.
|                                                      wiracdev02                                                     |
+--------------------------------------------------------------------------------------------------------+------------+
| Configuration Parameter                                                                                | Value      |
+--------------------------------------------------------------------------------------------------------+------------+
| TFA Version ( tfaversion )                                                                             | 21.1.0.0.0 |
| Java Version ( javaVersion )                                                                           | 1.8        |
| Public IP Network ( publicIp )                                                                         | true       |
| Repository current size (MB) ( currentsizemegabytes )                                                  | 293        |
| Repository maximum size (MB) ( maxsizemegabytes )                                                      | 10240      |
| Cluster Event Monitor ( clustereventmonitor )                                                          | ON         |
| scandiskmon                                                                                            | OFF        |
| scanacfslog                                                                                            | OFF        |
| File Data Collection ( inventory )                                                                     | ON         |
| Automatic Purging ( autoPurge )                                                                        | ON         |
| Internal Search String ( internalSearchString )                                                        | ON         |
| ISA Data Gathering ( collection.isa )                                                                  | ON         |
| Trim Files ( trimfiles )                                                                               | ON         |
| collectTrm                                                                                             | OFF        |
| chmdataapi                                                                                             | ON         |
| chanotification ( chanotification )                                                                    | ON         |
| Managelogs Auto Purge ( manageLogsAutoPurge )                                                          | OFF        |
| scanacfseventlog                                                                                       | OFF        |
| Alert Log Scan ( rtscan )                                                                              | ON         |
| debugips                                                                                               | OFF        |
| generateZipMetadataJson                                                                                | ON         |
| collectAllDirsByFile                                                                                   | ON         |
| scanvarlog                                                                                             | OFF        |
| Auto Diagcollection ( autodiagcollect )                                                                | ON         |
| Public IP Network ( publicIp )                                                                         | ON         |
| Flood Control ( floodcontrol )                                                                         | ON         |
| Generation of Mini Collections ( minicollection )                                                      | ON         |
| odscan                                                                                                 | ON         |
| Disk Usage Monitor ( diskUsageMon )                                                                    | ON         |
| Discovery ( discovery )                                                                                | ON         |
| analyze                                                                                                | OFF        |
| indexInventory                                                                                         | ON         |
| Generation of Telemetry Data ( telemetry )                                                             | OFF        |
| chaautocollect                                                                                         | ON         |
| Granular Tracing ( granulartracing )                                                                   | OFF        |
| minPossibleSpaceForPurge                                                                               | 1024       |
| disk.threshold                                                                                         | 90         |
| mem.swapfree                                                                                           | 5120       |
| mem.util.samples                                                                                       | 4          |
| inventoryThreadPoolSize                                                                                | 1          |
| mem.swaptotal.samples                                                                                  | 2          |
| maxFileAgeToPurge                                                                                      | 1440       |
| mem.free                                                                                               | 20480      |
| actionrestartlimit                                                                                     | 30         |
| Minimum Free Space to enable Alert Log Scan (MB) ( minSpaceForRTScan )                                 | 500        |
| cpu.io.samples                                                                                         | 30         |
| mem.util                                                                                               | 80         |
| Maximum single Zip File Size (MB) ( maxZipSize )                                                       | 2048       |
| Time interval between consecutive Disk Usage Snapshot(minutes) ( diskUsageMonInterval )                | 60         |
| TFA ISA Purge Thread Delay (minutes) ( tfaDbUtlPurgeThreadDelay )                                      | 60         |
| firstDiscovery                                                                                         | 0          |
| TFA IPS Pool Size ( tfaIpsPoolSize )                                                                   | 5          |
| Maximum File Collection Size (MB) ( maxFileCollectionSize )                                            | 5120       |
| Time interval between consecutive Managelogs Auto Purge(minutes) ( manageLogsAutoPurgeInterval )       | 60         |
| arc.backupmissing.samples                                                                              | 2          |
| cpu.util.samples                                                                                       | 2          |
| cpu.usr.samples                                                                                        | 2          |
| cpu.sys                                                                                                | 50         |
| Flood Control Limit Count ( fc.limit )                                                                 | 3          |
| Flood Control Pause Time (minutes) ( fc.pauseTime )                                                    | 120        |
| Maximum Number of TFA Logs ( maxLogCount )                                                             | 10         |
| DB Backup Delay Hours ( dbbackupdelayhours )                                                           | 27         |
| cdb.backup.samples                                                                                     | 1          |
| arc.backupstatus                                                                                       | 1          |
| purgeFrequency                                                                                         | 4          |
| TFA ISA Purge Age (seconds) ( tfaDbUtlPurgeAge )                                                       | 2592000    |
| Maximum Collection Size of Core Files (MB) ( maxCoreCollectionSize )                                   | 200        |
| cpu.util                                                                                               | 80         |
| mem.swapfree.samples                                                                                   | 2          |
| cdb.backupstatus                                                                                       | 1          |
| mem.swaputl.samples                                                                                    | 2          |
| arc.backup.samples                                                                                     | 3          |
| unreachablenodeTimeOut                                                                                 | 3600       |
| Flood Control Limit Time (minutes) ( fc.limitTime )                                                    | 60         |
| mem.swaputl                                                                                            | 10         |
| mem.free.samples                                                                                       | 2          |
| Maximum Size of Core File (MB) ( maxCoreFileSize )                                                     | 20         |
| disk.samples                                                                                           | 2          |
| cpu.sys.samples                                                                                        | 30         |
| cpu.usr                                                                                                | 98         |
| arc.backupmissing                                                                                      | 1          |
| cpu.io                                                                                                 | 20         |
| Archive Backup Delay Minutes ( archbackupdelaymins )                                                   | 40         |
| inventoryPurgeThreadInterval                                                                           | 720        |
| Age of Purging Collections (Hours) ( minFileAgeToPurge )                                               | 12         |
| cpu.idle.samples                                                                                       | 2          |
| unreachablenodeSleepTime                                                                               | 300        |
| cpu.idle                                                                                               | 20         |
| mem.swaptotal                                                                                          | 24         |
| TFA ISA CRS Profile Delay (minutes) ( tfaDbUtlCrsProfileDelay )                                        | 720        |
| cdb.backupmissing                                                                                      | 1          |
| cdb.backupmissing.samples                                                                              | 2          |
| Trim Size ( trimsize )                                                                                 | 500000     |
| Maximum Size of TFA Log (MB) ( maxLogSize )                                                            | 52428800   |
| minTimeForAutoDiagCollection                                                                           | 300        |
| skipScanThreshold                                                                                      | 100        |
| fileCountInventorySwitch                                                                               | 5000       |
| TFA ISA Purge Mode ( tfaDbUtlPurgeMode )                                                               | profile    |
| country                                                                                                | US         |
| Debug Mask (Hex) ( debugmask )                                                                         | 0x000000   |
| Setting for ACR redaction (none|SANITIZE|MASK) ( redact )                                              | none       |
| language                                                                                               | en         |
| AlertLogLevel                                                                                          | ALL        |
| BaseLogPath                                                                                            | ERROR      |
| encoding                                                                                               | UTF-8      |
| UserLogLevel                                                                                           | ALL        |
| Logs older than the time period will be auto purged(days[d]|hours[h]) ( manageLogsAutoPurgePolicyAge ) | 30d        |
| isaMode                                                                                                | enabled    |
'--------------------------------------------------------------------------------------------------------+------------'


cambio de ubicacion

Supongamos que queremos mover la ubicacion a un directorio compartido.
La ultima rama del repositorio debe de llamarse repository

tfactl set repositorydir=/mnt/tfa/repository 

Desinstalacion

Para su desinstalacion simplemente tenemos que ejecutarlo con el flag uninstall

[root@rac1 ~]$ which tfactl
/opt/app/12.1/grid/bin/tfactl
[root@rac1 ~]$  /opt/app/12.1/grid/bin/tfactl uninstall

Como siempre, mas infrmacion en oracle support:

Comandos basicos del RAC II añadir bases de datos

Hoy vamos a seguir con la serie de entradas de comandos basicos de administracion de RAC.
Hoy vamos a centrarnos en añadir bases de datos y mover los recursos del cluster

Añadir una base de datos

Para anadir una base de datos esta tendra que tener en el init.ora los parametros

  • CLUSTER_DATABASE=TRUE
  • CLUSTER_DATABASE_INSTANCES=2
  • TEST1.INSTANCE_NUMBER=1
  • TEST2.INSTANCE_NUMBER=2
  • TEST1.THREAD=1
  • TEST2.THREAD=2
  • TEST1.UNDO_TABLESPACE=’UNDOTBS1′
  • TEST2.UNDO_TABLESPACE=’UNDOTBS2′

    or supuesto,deberemos de contar con tantos grupos de UNDO y threads de REDO como nodos vayamos a tener.
    Una vez tenemos esto, la registraremos en el crs con los comandos

    srvctl add database  -db TEST-instance IBTEST1 -spfile +DATA/TEST/spfileTEST.ora -diskgroup "DATA,FRA,REDO1,REDO2"-oraclehome $ORACLE_HOME
    srvctl add instance -d TEST-i TEST1 -n rac1.pamplona.name
    srvctl start database -db TEST
    srvctl add instance -d TEST-i TEST2 -n rac2.pamplona.name
    srvctl start  instance -db IBTES -i IBTEST2 
    

    Mas entradas para dummies sobre RAC:
    Comandos basicos en Orace RAC
    Comandos basicos del RAC II
    Eliminar un nodo del rac