martes, 13 de mayo de 2008

Startup

Starting your Oracle Database

One of the most common jobs of the database administrator is to startup or shutdown the Oracle database. Typically we hope that database shutdowns will be infrequent for a number of reasons:

* Inconvenience to the user community.

* Anytime you cycle the database, there is a risk that it will not restart.

* It flushes the Oracle memory areas, such as the database buffer cache.

Performance on a restarted database will generally be slow until the database memory areas are "warmed" up.

Why would you shutdown your database? Some reasons include database maintenance:

* Applying a patch or an upgrade.

* Allow for certain types of application maintenance.

* Performing a cold (offline) backup of your database. (We recommend hot backups that allow you to avoid shutting down your database)

* An existing bug in your Oracle software requires you to restart the database on a regular basis.

When the time comes to "bounce" the database (using the shutdown and startup commands), you will use SQL*Plus to issue these commands. Let's look at each of these commands in more detail.

The Oracle Startup Command

You start the Oracle database with the startup command. You must first be logged into an account that has sysdba or sysoper privileges such as the SYS account (we discussed connecting as SYSDBA earlier in this book). Here then is an example of a DBA connecting to his database and starting the instance:

C:\Documents and Settings\Robert>set oracle_sid=booktst
C:\Documents and Settings\Robert>sqlplus "sys as sysdba"
SQL*Plus: Release 10.1.0.2.0 - Production on Mon Feb 21 12:35:48
Enter password: xxxx
Connected to an idle instance.
SQL> startup
ORACLE instance started.
Total System Global Area 251658240 bytes
Fixed Size 788368 bytes
Variable Size 145750128 bytes
Database Buffers 104857600 bytes
Redo Buffers 262144 bytes
Database mounted.
Database opened.

In this example from a Windows XP server, we set the ORACLE_SID to the name of the database and we log into SQL*Plus using the "sys as sysdba" login. This gives us the privileges we need to be able to startup the database. Finally, after we enter our password, we issue the startup command to startup the database. Oracle displays its progress as it opens the database, and then returns us to the SQL*Plus prompt once the startup has been completed.

When Oracle is trying to open your database, it goes through three distinct stages, and each of these is listed in the startup output listed previously. These stages are:

* Startup (nomount)

* Mount

* Open

Let's look at these stages in a bit more detail.

The Startup (nomount) Stage

When you issue the startup command, the first thing the database will do is enter the nomount stage. During the nomount stage, Oracle first opens and reads the initialization parameter file (init.ora) to see how the database is configured. For example, the sizes of all of the memory areas in Oracle are defined within the parameter file.

After the parameter file is accessed, the memory areas associated with the database instance are allocated. Also, during the nomount stage, the Oracle background processes are started. Together, we call these processes and the associated allocated memory the Oracle instance. Once the instance has started successfully, the database is considered to be in the nomount stage. If you issue the startup command, then Oracle will automatically move onto the next stage of the startup, the mount stage.

Starting the Oracle Instance (Nomount Stage)

There are some types of Oracle recovery operations that require the database to be in nomount stage. When this is the case, you need to issue a special startup command: startup nomount, as seen in this example:

SQL> startup nomount

The Mount Stage

When the startup command enters the mount stage, it opens and reads the control file. The control file is a binary file that tracks important database information, such as the location of the database datafiles.

In the mount stage, Oracle determines the location of the datafiles, but does not yet open them. Once the datafile locations have been identified, the database is ready to be opened.

Mounting the Database

Some forms of recovery require that the database be opened in mount stage. To put the database in mount stage, use the startup mount command as seen here:

SQL> startup mount

If you have already started the database instance with the startup nomount command, you might change it from the nomount to mount startup stage using the alter database command:

SQL> alter database mount;

The Open Oracle startup Stage

The last startup step for an Oracle database is the open stage. When Oracle opens the database, it accesses all of the datafiles associated with the database. Once it has accessed the database datafiles, Oracle makes sure that all of the database datafiles are consistent.

Opening the Oracle Database

To open the database, you can just use the startup command as seen in this example

SQL> startup

If the database is mounted, you can open it with the alter database open command as seen in this example:

SQL> alter database open;

Opening the Database in Restricted Mode

You can also start the database in restricted mode. Restricted mode will only allow users with special privileges (we will discuss user privileges in a later chapter) to access the database (typically DBA's), even though the database is technically open. We use the startup restrict command to open the database in restricted mode as seen in this example.

SQL> startup restrict

You can take the database in and out of restricted mode with the alter database command as seen in this example:

-- Put the database in restricted session mode.

SQL> alter database enable restricted session;

-- Take the database out of restricted session mode.

SQL> alter database disable restricted session;

Note: Any users connected to the Oracle instance when going into restricted mode will remain connected; they must be manually disconnected from the database by exiting gracefully or by the DBA with the "alter system kill session" command.

Problems during Oracle Startup

The typical DBA life is like that of an airline pilot, "Long moments of boredom followed by small moments of sheer terror", and one place for sheer terror is an error during a database startup.

¿Soy un DBA? - El catálogo del sistema en ORACLE

¿Cómo saber si estoy dentro del ROL de DBAs?

Hace un par de días tuve que verificar si mi nuevo usuario tenía permisos de DBA sobre algunas de las bases de datos. Ahora ¿Cómo podría hacer esta verificación?

La respuesta es fácil, necesito consultar las tablas con prefijo 'DBA_'. Si tengo granteado el acceso a las mismas entonces tengo acceso al catalogo del sistema y por ende los derechos de un DBA. Estas no son las únicas tablas que componen el catalogo, pero para el ejemplo y para descubrir si somos o no DBAs son más que suficientes.

El Catálogo de Oracle

Oracle cuenta con una serie de tabla y vistas que conforman una estructura denominada catálogo. La principal función del catálogo de Oracle es almacenar toda la información de la estructura lógica y física de la base de datos, desde los objetos existentes, la situación de los datafiles, la configuración de los usuarios, etc.

El catálogo sigue un estándar de nomenclatura para que su memorización sea más fácil:

Prefijo/Descripción
DBA_ Objetos con información de administrador. Sólo accesibles por con permisos DBA.
  • USER_ Objetos con información propia del usuario al que estamos conectado. Accesible desde todos los usuarios. Proporcionan menos información que los objetos DBA_
  • ALL_ Objetos con información de todos los objetos en base de datos.
  • V_$ ó V$ Vistas dinámicas sobre datos de rendimiento
  • Existe un pseudo-usuario llamado PUBLIC el cual tiene acceso a todas las tablas del catálogo público. Si se quiere que todos los usuarios tengan algún tipo de acceso a un objeto, debe darse ese privilegio a PUBLIC y todo el mundo dispondrá de los permisos correspondientes.

    El catálogo público son aquellas tablas (USER_ y ALL_) que son accesibles por todos los usuarios. Normalmente dan información sobre los objetos creados en la base de datos.

    El catálogo de sistema (DBA_ y V_$) es accesible sólo desde usuarios DBA y contiene tanto información de objetos en base de datos, como información específica de la base de datos en sí (versión, parámetros, procesos ejecutándose…)

    Ciertos datos del catálogo de Oracle están continuamente actualizados, como por ejemplo las columnas de una tabla o las vistas dinámicas (V$). De hecho, en las vistas dinámicas, sus datos no se almacenan en disco, sino que son tablas sobre datos contenidos en la memoria del servidor, por lo que almacenan datos actualizados en tiempo real. Algunas de las principales son:

    • V$DB_OBJECT_CACHE: contiene información sobre los objetos que están en el caché del SGA.
    • V$FILESTAT: contiene el total de lecturas y escrituras físicas sobre un data file de la base de datos.
    • V$ROLLSTAT: contienen información acerca de los segmentos de rollback.

    Sin embargo hay otros datos que no pueden actualizarse en tiempo real porque penalizarían mucho el rendimiento general de la base de datos, como por ejemplo el número de registros de una tabla, el tamaño de los objetos, etc. Para actualizar el catálogo de este tipo de datos es necesario ejecutar una sentencia especial que se encarga de volcar la información recopilada al catálogo:

    ANALYZE [TABLEINDEX] nombre [COMPUTEESTIMATEDELETE] STATISTICS;

    La cláusula COMPUTE hace un cálculo exacto de la estadísticas (tarda más en realizarse en ANALYZE), la cláusula ESTIMATE hace una estimación partiendo del anterior valor calculado y de un posible factor de variación y la cláusula DELETE borra las anteriores estadísticas.

    viernes, 9 de mayo de 2008

    Mi primer Script

    Hoy escribí mi primer script para el nuevo laburo, me conecté a las bases de datos cambié passwords y empece a "producir" casi 14 días después de haber venido por primera vez como empleado.
    SELECT FS.tablespace_name AS TSNAME,
    (DF.total_space - FS.free_space) AS MB_USED,
    FS.free_space AS MB_FREE,
    DF.total_space AS MB_TOTAL,
    to_char(round(100 * (FS.free_space / DF.total_space))) '%' AS PCT_FREE
    FROM
    (SELECT tablespace_name,
    round(sum(bytes) / 1048576) "TOTAL_SPACE" -- Puede cambiarse 1048576 x POWER(1024,2) --MB
    FROM dba_data_files
    GROUP BY tablespace_name) DF,
    (SELECT tablespace_name,
    round(sum(bytes) / 1048576) "FREE_SPACE"
    FROM dba_free_space
    GROUP BY tablespace_name) FS
    WHERE DF.tablespace_name = FS.tablespace_name
    ORDER BY round(100 * (FS.free_space / DF.total_space)) DESC;

    ALTER TABLESPACE ADD DATAFILE '/var/adm/SeOS/oracle/DataFileName.DBF' SIZE 5.5G;

    /

    También cometí mi primer error!
    Fue no considerar en mi script que los datafiles tienen una "property" de autoextend y eso hace que a pesar de que el tablespace este al 99% ocupado, no se lo categoricoe como un hecho critico ya que todavia es posible que el datafile tenga mucho espacio para "auto-extenderse". En todo caso deberia revisar que todavia que de espacio para extenderse.

    lunes, 28 de abril de 2008

    Configurar DNS en SUN SOLARIS 10

    Se me presento el problema que despues de instalar solaris 10 en mi VMWARE no podia navegar por internet. No estar rolviendo nombres porque por IPs si podia acceder a las paginas.
    ¿Cómo solucionarlo?
    Veamos el contenido del siguiente articulo:
    1) You need to create or edit the file /etc/resolv.conf

    # cat resolv.conf
    domainname corp.petrobras.biz
    nameserver 10.26.42.1
    nameserver 10.2.56.33
    nameserver 10.2.56.34
    search corp.petrobras.biz,engenharia.petrobras.com.br,petrobras.com.br
    #
    Where :
    a) domainname => name of domain
    b) nameserver => you can put until 3 DNS servers (IP)
    c) search (optional) => used to complete a host name, when you use just the first name to resolve hosts.
    Ex: When you put test, the system will search test.corp.petrobras.biz, test.engenharia.petrobras.com.br and so on.

    2) You must edit the file /etc/nsswitch.conf and include the word "dns" after "files" in the line shown below . So the system will resolve host using the file /etc/hosts and /etc/resolv.conf in this order.

    ...
    hosts: files dns
    ...

    Good luck

    domingo, 20 de abril de 2008

    TKPROF y Tracefile

    Es necesario usar dos parametros de la base de datos, para realizar el trace de las sesiones:

    • TIMED_STATISTICS : que debe ser TRUE para usar estadisticas.

    • USER_DUMP_DEST : donde se establece el directorio donde el server escribirá los tracefiles.
    Existe un parámetro relacionado a este último:
    • MAX_DUMP_FILE_SIZE : que permite establecer el tamaño máximo del tracefile, lo valores válidos para este parámetro son UNLIMITED, o un número seguido de una M o K para establecer el tamaño en Megabytes o KBytes como tamaño máximo a ocupar. De solo tener un número (sin la letra M o K) se considera que está especificándose el número máximo de bloques del SO que el archivo puede ocupar.


    ¿Cómo habilitarlo?



    Puede habilitarse de las siguientes maneras:

    1. SQL*Plus: SQL> alter session set sql_trace true;

    2. PL/SQL: dbms_session.set_sql_trace(TRUE);

    3. DBA: SQL> execute sys.dbms_system.set_sql_trace_in_session(sid,serial#,TRUE); donde sid y serial# provienen de la consulta Select username, sid, serial#, machine from v$session;

    4. PRO*C: EXEC SQL ALTER SESSION SET SQL_TRACE TRUE;


    ¿Cómo leo los tracefiles?



    Usando TKPROF puedo leer los tracefiles generando a partir de ellos un archivo de texto con el detalle. La sintaxis del comando es la siguiente



    TKPROF tracefile exportfile [explain=username/password] [table= …] [print= ] [insert= ] [sys= ] [record=..] [sort= ]



    Y un ejemplo,

    tkprof ora_12345.trc output.txt explain=scott/tiger

    Fuentes:

    martes, 15 de abril de 2008

    Aplicaciones J2EE - iSQLPlus

    He instalado el dbms Oracle 11g en la maquina virtual y estas son las direcciones desde las que se puede acceder al iSqlPlus.

    Se han desplegado las siguientes aplicaciones J2EE y se puede acceder a ellas en las siguientes direcciones URL.

    URL de iSQL*Plus:
    http://VMWARE-ORACLE:5560/isqlplus

    URL de DBA de iSQL*Plus:
    http://VMWARE-ORACLE:5560/isqlplus/dba

    URL Enterprise Manager 10g Database Control

    lunes, 14 de abril de 2008

    EXCELENTE BLOG con las tareas de un DBA

    http://delfinonunez.wordpress.com/page/4/


    Monitoreo de espacio en tablespace


    20 Julio, 2006 by delfinonunez

    Una de las tareas de un DBA es monitorear el espacio de la base de datos, debido a que esto consume mucho tiempo cuando se tienen varias DB’s es bueno automatizar tareas repetitivas y tediosas. Una manera de realizar la automatización del monitoreo de DB’s en UNIX es por medio del crontab, el siguiente es un ejemplo de como usar el crontab para monitorear los tablespaces.



    • Los siguientes scripts permiten obtener el espacio utilizado y libre de los tablespaces, uno lo obtiene en base el porcentaje libre de espacio y el otro obtiene el espacio en base a los MB libres. Estos scripts reciben dos parametros: &1 .- es el directorio y archivo donde se va a crear el reporte(spool) y &2 que es el limite ya sea porcentaje (99) o Mb(99999).


    tablespace_size_pct.sql



    SET line 132
    SET pages 50
    SET pause OFF
    SET feedback OFF
    SET echo OFF
    SET verify OFF

    COLUMN c1 heading "Tablespace|Name"
    COLUMN c2 heading "File|Count"
    COLUMN c3 heading "Allocated|in MB"
    COLUMN c4 heading "Used|in MB"
    COLUMN c5 heading "%|free" format 99.99
    COLUMN c6 heading "Free|in MB"
    COLUMN c7 heading "%|used" format 99.99

    spool &1;

    SELECT c1,ROUND(c3,2) c3,ROUND(c4,2) c4,ROUND(c6,2) c6,ROUND(c7,2) c7,ROUND(c5,2) c5,c2
    FROM(
    SELECT NVL (b.tablespace_name, NVL (a.tablespace_name, 'UNKOWN')) c1,
    mbytes_alloc c3, mbytes_alloc - NVL (mbytes_free, 0) c4,
    NVL (mbytes_free, 0) c6,
    ((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100 c7,
    100
    - (((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100) c5,
    b.files c2
    FROM (SELECT SUM (BYTES) / 1024 / 1024 mbytes_free, tablespace_name
    FROM SYS.dba_free_space
    GROUP BY tablespace_name) a,
    (SELECT SUM (BYTES) / 1024 / 1024 mbytes_alloc, tablespace_name,
    COUNT (file_name) files
    FROM SYS.dba_data_files
    GROUP BY tablespace_name) b
    WHERE a.tablespace_name(+) = b.tablespace_name
    UNION ALL
    SELECT f.tablespace_name,
    SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2)
    ) "total MB",
    SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) "Used MB",
    SUM (ROUND ( ((f.bytes_free + f.bytes_used) - NVL (p.bytes_used, 0)
    )
    / 1024
    / 1024,
    2
    )
    ) "Free MB",
    (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    100
    - (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    COUNT (d.file_name)
    FROM SYS.v_$temp_space_header f,
    dba_temp_files d,
    SYS.v_$temp_extent_pool p
    WHERE f.tablespace_name(+) = d.tablespace_name AND f.file_id(+) = d.file_id
    AND p.file_id(+) = d.file_id
    GROUP BY f.tablespace_name)
    WHERE C1 NOT IN('USERS')
    AND C7 >= &2
    ORDER BY c6 ASC;

    spool off;
    exit;

    tablespace_size_spc.sql



    SET line 132
    SET pages 50
    SET pause OFF
    SET feedback OFF
    SET echo OFF
    SET verify OFF

    COLUMN c1 heading "Tablespace|Name"
    COLUMN c2 heading "File|Count"
    COLUMN c3 heading "Allocated|in MB"
    COLUMN c4 heading "Used|in MB"
    COLUMN c5 heading "%|free" format 99.99
    COLUMN c6 heading "Free|in MB"
    COLUMN c7 heading "%|used" format 99.99

    spool &1;

    SELECT c1,ROUND(c3,2) c3,ROUND(c4,2) c4,ROUND(c6,2) c6,ROUND(c7,2) c7,ROUND(c5,2) c5,c2
    FROM(
    SELECT NVL (b.tablespace_name, NVL (a.tablespace_name, 'UNKOWN')) c1,
    mbytes_alloc c3, mbytes_alloc - NVL (mbytes_free, 0) c4,
    NVL (mbytes_free, 0) c6,
    ((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100 c7,
    100
    - (((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100) c5,
    b.files c2
    FROM (SELECT SUM (BYTES) / 1024 / 1024 mbytes_free, tablespace_name
    FROM SYS.dba_free_space
    GROUP BY tablespace_name) a,
    (SELECT SUM (BYTES) / 1024 / 1024 mbytes_alloc, tablespace_name,
    COUNT (file_name) files
    FROM SYS.dba_data_files
    GROUP BY tablespace_name) b
    WHERE a.tablespace_name(+) = b.tablespace_name
    UNION ALL
    SELECT f.tablespace_name,
    SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2)
    ) "total MB",
    SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) "Used MB",
    SUM (ROUND ( ((f.bytes_free + f.bytes_used) - NVL (p.bytes_used, 0)
    )
    / 1024
    / 1024,
    2
    )
    ) "Free MB",
    (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    100
    - (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    COUNT (d.file_name)
    FROM SYS.v_$temp_space_header f,
    dba_temp_files d,
    SYS.v_$temp_extent_pool p
    WHERE f.tablespace_name(+) = d.tablespace_name AND f.file_id(+) = d.file_id
    AND p.file_id(+) = d.file_id
    GROUP BY f.tablespace_name)
    WHERE C1 NOT IN('USERS')
    AND C6 <= &2
    ORDER BY c6 ASC;

    SPOOL OFF;
    exit;


    • Con el siguiente script podemos ejecutar los SQL scripts anteriores dependiendo los parametros que le enviemos. La forma de ejecutar el script es la siguiente:

      • Para reportar en base al espacio, despues del parametro -d debe seguir el nombre de la instancia (SID), despues del parametro -s sigue la cantidad minima que puede tener libre un tablespace:

        • tbs_monitor.ksh -d DEVELOPMENT -s 500

          Connected.
          Instance: DEVELOPMENT
          Tablespaces with usage < 500 MB.

          Tablespace Allocated Used Free % % File
          Name in MB in MB in MB used free Count
          ------------------------------ ---------- ---------- ---------- ------ ------ ----------
          SYSTEM 600 403.13 196.88 67.19 32.81 1
          IDX1 11741 11363 378 96.78 3.22 3




      • Para reportar en base al porcentaje, en lugar de utilizar el parametro -s se utiliza el parametro -p seguido del porcentaje maximo que puede tener un tablespace:

        • tbs_monitor.ksh -d DEVELOPMENT -p 80




      • Connected.
        Instance: DEVELOPMENT
        Tablespaces with usage >= 80%.

        Tablespace Allocated Used Free % % File
        Name in MB in MB in MB used free Count
        ------------------------------ ---------- ---------- ---------- ------ ------ ----------
        IDX1 11741 11363 378 96.78 3.22 3
        IDX2 3201 2696 505 84.22 15.78 2
        IDX5 18385 17394 991 94.61 5.39 3
        DATA02 13312 11520.13 1791.88 86.54 13.46 2
        DATA03 33797 31709.13 2087.88 93.82 6.18 4
        DATA01 56629 46606.38 10022.63 82.30 17.70 7