jueves, 28 de abril de 2016

vSphere: Lista de todos los discos asociados a una VM


En más de una ocasión hemos tenido que inventariar las VMs y los discos asociados, sobre todo en aquellas ocasiones en las que nos quedamos cortos de espacio en las cabinas y debemos realizar un estudio para "racionalizar" el consumo.

PowerCli nos puede ayudar, la capacidad de scripting de powerShell aplicada a los objetos de vSphere nos permite obtener esta información en formato csv para que podamos importar en Excel.

El script supone que las VMs están bajo el control de un virtualCenter.


connect-viserver <VirtualCenter> -User <Usuario> -Password <Password>
Get-vm | get-harddisk | select Parent,StorageFormat,CapacityGB,Filename |sort Parent,FileName|Export-Csv c:\temp\VmDisk.csv


Este post ha sido extraído de http://pipe2text.com/?page_id=2635 , a continuación se reproduce la nota completa.
-------------------

I recently received an alarm that some of the datastores in my VMware environment were getting close to full. While auditing the environment to see if there was any space to cleared, I noticed that several VMs had thick provisioned disks when they should have been thin provisioned. Since I was dealing with many virtual machines, it would have been way too time consuming to visit the settings if each Virtual Machine and check the hard disks using the vCenter client. Using PowerShell, I was able to pull the hard disk inventory I needed for the VMDK files so I could see where corrections could be made. In this article I will be using the “Get-Harddisk” and the “Export-Csv” cmdlets to gather the harddisk information and exporting it to a csv file for easy viewng. The Get-Harddisk cmdlet is used to gather information for virtual disks on your vSphere serves. To do anything with PowerShell in VMware you will need to install VMware vSphere PowerCLI. You will then need to open PowerCLI and connect to your VMWare vCenter server by typing “Connect-VIServer vCenterServerName”.

First I would like to start by showing you how to get the hard disk information for one virtual machine. Type the following command replacing virtualmachinename with the name of the virtual machine for which you would like to retrieve disk information.
Get-Vm virtualmachinename | Get-Harddisk | Format-List
When executing the command above, it will return the following properties in for each virtual disk associated with the virtual machine specified.
StorageFormat
Persistence
DiskType
Filename
CapacityKB
CapacityGB
ParentId
Parent
Uid
ConnectionState
ExtensionData
Id
Name
Client
 
Now lets say that all this information is not important and you only want to see certain properties. In the following command I will select the “Parent” property to show the virtual machine name, the storage format, and filename to see the VMDK filename. Im am also piping it to the “Export-Csv” cmdlet to send the results to a csv file named “disks.csv” located in the “c:\output” directory. Type the following command replacingvirtualmachinename with the name of the virtual machine for which you would like to retrieve disk information.
Get-vm virtualmachinename | get-harddisk | select Parent,StorageFormat,Filename | Export-Csv c:\output\disks.csv –NoTypeInformation
In this next command I get the disk information for all virtual machines with all the default properties and export it to a csv file creating a disk inventory.
get-vm | get-harddisk | Export-Csv c:\output\disks.csv –NoTypeInformation
Finally, as shown earlier, if we do not want to see all properties, we can simply select the ones we need. In the following command I will get the disk information for all virtual vachines but only select the Parent, StorageFormat and Filename properties.
get-vm | get-harddisk | select Parent,StorageFormat,Filename | Export-Csv c:\output\disks.csv –NoTypeInformation
I hope this helps. If you would like any more information about the Get-Harddisk cmdlet, you can simply type “Get-Help Get-Harddisk”. If you have any questions or feedback, please leave a comment.

lunes, 25 de abril de 2016

Oracle: Cursores abiertos

En más de una ocasión nos hemos encontrado con alguna aplicación con errores o fallos en el código que no cierran adecuadamente los cursores abiertos contra la BBDD, para determinar tanto el número como las sesiones y máquinas causantes de este problema que puede "tirarnos" la BBDD tenemos la  siguiente nota extraída de Oracle que reproducimos al final.

Es altamente recomendable monitorizar con Zabbix estos valores de forma sencilla para determinar problemas antes de que ocurran, sobre todo en las fases iniciales de producción de los proyectos.


A partir de la nota podemos obtener queries útiles como las siguientes:

Query Genérica para ver los cursores abiertos por sesión, aplicación, máquina y cuenta

select  a. USER_NAME , a.sid , a. sql_text, p.PROGRAM, s. MODULE, s.MACHINE, count( *) as "OPEN CURSORS"
from v$open_cursor a,
     v$session s,
     v$process p
where s.SID = a.SID
  and s.paddr = p.addr
Group by a. user_name, a.sid, p.PROGRAM, s. MODULE, a. sql_text,s. MACHINE

Queries y cursores abiertos por query
select sid , sql_text, count( *) as "OPEN CURSORS" , USER_NAME
from v$open_cursor
Group by sid, sql_text, user_name

Sesiones con cursores abiertos
select a.value, s. username, s.sid, s. serial#
from v$sesstat a, v$statname b, v$session s
where a. statistic# = b.statistic# 
  and s.sid=a.sid
  and b.name = 'opened cursors current'
  and s.username is not null;

Cursores abiertos y máximo definido en parámetro de BBDD
SELECT  max(a.value) as highest_open_cur, p.value as max_open_cur
FROM v$sesstat a, v$statname b, v$parameter p
WHERE  a. statistic# = b.statistic# 
and b.name = 'opened cursors current'
and p.name= 'open_cursors'
group by p.value;




Similar to any application that uses Oracle Database as backend repository, Oracle Identity Manager runs several SQL statements. For every SQL statement execution in Oracle Database, certain area in the memory is allocated. Oracle PL/SQL allows you to name this area. This private SQL area is called context area or cursor. These cursors take up space in the shared pool, which is essential memory component of Oracle Database, specifically in the library cache. To keep a renegade session from filling up the library cache or clogging the CPU with millions of parse requests, the OPEN_CURSORS database parameter must be set to limit the cursors.
The OPEN_CURSORS parameter sets the maximum number of cursors that each session can have open, per session. For example, if the value of OPEN_CURSORS is set to 1000, then each session can have up to 1000 cursors open at one time.
Sometimes, the number of cursors in the database exceeds the maximum limit, and as a result, the following error is thrown:
java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01000: maximum open cursors exceeded ORA-00604: error occurred at recursive SQL level 1
To troubleshoot the open cursors issue:
  1. Login to the SYS schema (or any schema with DBA privilege) of the database.
  2. Find out the session that is causing the error by using the following SQL statement:
    select a.value, s. username, s.sid, s. serial# 
    from v$sesstat a, v$statname b, v$session s 
    where a. statistic# = b.statistic#  
      and s.sid=a.sid 
      and b.name = 'opened cursors current' 
      and s.username is not null;

    ct a.value, s.username, s.sid, s.serial# from v$sesstat a, v$statname b, v$session s where a.statistic# = b.statistic#  and s.sid=a.sid and b.name = 'opened cursors current' and s.username is not null;
    The output displays the details of all sessions. You can see the maxed out session IDs.
  3. To display which queries are causing maxing out of open cursors, run the following SQL statement:
    select  sid ,sql_text, count(*) as "OPEN CURSORS", USER_NAME from v$open_cursor where sid in ($);
    
    The top queries that are opening maximum cursors and are not closing subsequent cursors gracefully are displayed.
    If some code is running above SQL queries, then check that Java Statement, Resultset, or connection are closing properly or not if they have access to the code. If the code is not closing the connections, then close all the open connections properly so that you can save memory leaks in the code and save database memory.
  4. To verify if you have set the value of the OPEN_CURSORS parameter high enough, monitor v$sesstat for the maximum opened cursors current, as shown:
    SELECT  max(a.value) as highest_open_cur, p.value as max_open_cur FROM v$sesstat a, v$statname b, v$parameter p WHERE  a.statistic# = b.statistic#  and b.name = 'opened cursors current' and p.name= 'open_cursors' group by p.value;
    
    If your sessions are running close to the limit, then increase the value of the OPEN_CURSORS parameter.

Veeam Backup : PowerShell para determinar los jobs de backup con error y éxito


Determinar el estado de las copias de las máquinas virtuales en nuestro sistema puede ser importante en los checklists de comprobación diaria de toda organización. Tratar de automatizar esta gestión puede ahorrar bastante tiempo.
Realizamos una pShell para determinar los Jobs de copia/replicación realizados con Veeam Backup & Replication v9 del día anterior con y sin error, estos scripts devuelven el número de trabajos satisfactorios y no satisfactorios lanzados a partir del día de ayer
Los scripts pueden tomar este aspecto:
vbSuccedYest.ps1
add-PsSnapin VeeamPSSnapin
@(Get-VBRBackupSession | Where-Object {$_.JobType -eq "Backup" -or $_.JobType -eq "Replica" -and $_.EndTime -ge (Get-Date).adddays(-1) -and $_.Result -eq "Success"}|select jobName,jobType,Result,CreationTime,EndTime).count

vbUnSuccedYest.ps1
add-PsSnapin VeeamPSSnapin
@(Get-VBRBackupSession | Where-Object {$_.JobType -eq "Backup" -or $_.JobType -eq "Replica" -and $_.EndTime -ge (Get-Date).adddays(-1) -and $_.Result -ne "Success"}|select jobName,jobType,Result,CreationTime,EndTime).count


En el caso de monitorización vía Zabbix estos scripts pueden ser extremadamente lentos para devolver un resultado por lo que se pueden incluir una tarea programada que ejecute la tarea y genere un fichero de salida con el resultado, que el agente local al equipo se encargaría de realizar la lectura de este fichero (VBScript, ...) y devolver el valor obtenido mediante un UserParameter  :

UserParameter=VBSuccess, cscript C:\zabbix\scripts\imprimeFicheroNumber.vbs c:\zabbix\scripts\logs\vbSuccedYest.txt //nologo
UserParameter=VBUnSuccess,cscript C:\zabbix\scripts\imprimeFicheroNumber.vbs c:\zabbix\scripts\logs\vbUnSuccedYest.txt //nologo