Kickstart ESXi 4.1

No me apetece cambiar todos los < y >, así que se verá regular :P

#########################################
# ESXi 4.1 Kickstart configuration #
#########################################

# Accept User Agreement
accepteula

# Root password
rootpw –iscrypted PASSWORD

# Disk autopartition
# TIP: Maybe needs some tunning
autopart –firstdisk –overwritevmfs

# Installation files
install url http://URL/4.1/

# Network configuration (install)
network –bootproto=dhcp –device=vmnic0

# Post-configuration tasks
# TIP: It runs in level 998 because is the latest level without root password
# It allow to run high privileges commands without entering the root password
%firstboot –unsupported –interpreter=busybox –level=998

# Enable remote administation
vim-cmd hostsvc/enable_remote_tsm
vim-cmd hostsvc/start_remote_tsm

# Enable local administration
vim-cmd hostsvc/enable_local_tsm
vim-cmd hostsvc/start_local_tsm

# NOTE:
# Enabling administration, shows a warning in vCenter
# In 4.1, it disappears by restarting the hostd agent:
# http://www.vcritical.com/2011/02/get-rid-of-those-esxi-tech-support-mode-warnings/
# In 5, there is an advanced parameter to ignore this:
# http://www.yellow-bricks.com/2011/07/21/esxi-5-suppressing-the-localremote-shell-warning/
# So, uncomment the next line, in 5 ;)
# esxcfg-advopt -s 1 /UserVars/SuppressShellWarning

# Syslog stuff
vim-cmd hostsvc/advopt/update Syslog.Remote.Hostname string
vim-cmd hostsvc/advopt/update Syslog.Remote.Port int 514
# Don’t know if it’s the datastore path of the server, so, disabled
#vim-cmd hostsvc/advopt/update Syslog.Remote.DatastorePath string “[datastoreName] /logfiles/hostName.log”

# Rename the local datastore
vim-cmd hostsvc/datastore/rename datastore1 “$(hostname -s)-local-storage-1″

# Configure ntp
echo “server NTPSERVER” >> /etc/ntp.conf
chkconfig ntpd on

# Configure snmpd
cat > /tmp/snmpd.xml << __SNMP__

COMMUNITIES
true
163 TARGETS

__SNMP__
cp /tmp/snmp.conf /etc/vmware/snmp.xml

# Configure DNS
cat > /etc/resolv.conf << __DNS__
search DOMAIN
nameserver DNS1
nameserver DNS2
__DNS__

# Configure depth queue
# LPFC820 (G7)
if esxcfg-module -l|grep lpfc820 ; then
/usr/sbin/esxcfg-module -s “lpfc0_lun_queue_depth=64 lpfc1_lun_queue_depth=64 lpfc2_lun_queue_depth=64 lpfc3_lun_queue_depth=64 lpfc4_lun_queue_depth=64 lpfc5_lun_queue_depth=64″ lpfc820
fi
# Qlogic
if esxcfg-module -l|grep ql2 ; then
/usr/sbin/esxcfg-module -s “ql2xmaxqdepth=64″ qla2xxx
fi
# LPFC740
if esxcfg-module -l|grep lpfc_740 ; then
/usr/sbin/esxcfg-module -s “lpfc0_lun_queue_depth=64 lpfc1_lun_queue_depth=64 lpfc2_lun_queue_depth=64 lpfc3_lun_queue_depth=64 lpfc4_lun_queue_depth=64 lpfc5_lun_queue_depth=64″ lpfc_740
fi

# Depth Queue
vim-cmd hostsvc/advopt/update Disk.SchedNumReqOutstanding long 64

# Lun Reset
/usr/sbin/esxcfg-advcfg -s 1 /Disk/UseLunReset
/usr/sbin/esxcfg-advcfg -s 0 /Disk/UseDeviceReset

#####################
# Check this in 4.1
#/usr/bin/vimsh -n -e “hostsvc/advopt/update Misc.RunningVCpuLimit int 192″
#sed -i -e ‘s!^!\t450\n\t400\n!g’ $CONFIG
#/usr/sbin/esxcfg-boot -b
#####################

# Create vSwitches
/usr/sbin/esxcfg-vswitch -L vmnic0 vSwitch0
/usr/sbin/esxcfg-vswitch -L vmnic1 vSwitch1
/usr/sbin/esxcfg-vswitch -L vmnic2 vSwitch2
/usr/sbin/esxcfg-vswitch -L vmnic3 vSwitch3
/usr/sbin/esxcfg-vswitch -L vmnic4 vSwitch4
/usr/sbin/esxcfg-vswitch -L vmnic5 vSwitch5
/usr/sbin/esxcfg-vswitch -L vmnic6 vSwitch6

# Interactive network configuration
chvt 1
exec < /dev/tty1 > /dev/tty1
clear

# Check if the hostname ends in
DOMAIN=”.”
nombre_host=”"

echo $nombre_host | grep -q $DOMAIN
RETVAL=$?

echo “”
while [ $RETVAL -ne 0 ]
do
read -p “Introduzca el nombre de host con FQDN: ” nombre_host
echo $nombre_host | grep -q $DOMAIN
RETVAL=$?
done

# Function to check if the IP is valid
valid_dotted_quad()
{
ERROR=0
oldIFS=$IFS
IFS=.
set -f
set — $1
if [ $# -eq 4 ]
then
for seg
do
case $seg in
“”|*[!0-9]*) ERROR=1;break ;; ## Segment empty or non-numeric char
*) [ $seg -gt 255 ] && ERROR=2 ;;
esac
done
else
ERROR=3 ## Not 4 segments
fi
IFS=$oldIFS
set +f
return $ERROR
}
# END

direccion_ip=”"

valid_dotted_quad $direccion_ip
RETVAL=$?

while [ $RETVAL -ne 0 ]
do
read -p “Introduzca la IP: ” direccion_ip
valid_dotted_quad $direccion_ip
RETVAL=$?
done

direccion_gateway=”"

valid_dotted_quad $direccion_gateway
RETVAL=$?

while [ $RETVAL -ne 0 ]
do
read -p “Introduzca el gateway: ” direccion_gateway
valid_dotted_quad $direccion_gateway
RETVAL=$?
done

unset sw

chvt 1
exec < /dev/tty1 > /dev/tty1

# Set IP, hostname, gateway with the interactive parameters
esxcfg-vmknic -i $direccion_ip -n 255.255.255.0 “Management Network”
esxcfg-advcfg -s $nombre_host /Misc/HostName
esxcfg-route -a default $direccion_gateway

# Configure /etc/hosts
echo “$direccion_ip $nombre_host $nombre_host” >> /etc/hosts

# Configure hostsvc to allow vmotion
# TIP: Don’t know if doesn’t needed anymore
cat << EOF > /etc/vmware/hostd/hostsvc.xml

normal

Vmotion

EOF

/usr/sbin/esxcfg-advcfg -s 1 /Migrate/Enabled

# 800 Mb Service Console
# TIP: Don’t needed in ESXi?
#sed -i -e ‘s/\/boot\/memSize\ =\ “[0-9][0-9][0-9]“/\/boot\/memSize\ =\ “800″/1′ /etc/vmware/esx.conf
#esxcfg-boot -g
#esxcfg-boot -b
#sed -i -e ‘s/^.*uppermem.*/uppermem 819200/g’ -e ‘s/mem=.*M/mem=800M/g’ /boot/grub/grub.conf

# VMimages and some other network file shares stuff
#mkdir -p /vmimages/isos

#echo “:/isos /vmimages/isos nfs soft,timeo=20,rsize=8192,wsize=8192 0 0″ >> /etc/fstab

# MOTD
MOTD=”Esta maquina es propiedad de PEPITO y cualquier uso debe estar autorizado por el departamento correspondiente. Cualquier otro uso sera perseguido y castigado de acuerdo a la legislacion vigente. Cualquier actividad realizada en, desde o hacia este sistema esta sujeta a monitorizacion sin previo aviso.”
echo $MOTD > /etc/motd
chmod 644 /etc/motd

# Enhace the prompt to show hostname in red
echo “export PS1=\”[\u@\e[31;1m\h\e[0m:\w]\\\\\$ \”" >> /etc/profile

# Some cron stuff
# TIP: Test it!
# http://www.jules.fm/Logbook/files/add_cron_job_vmware.html

cat << EOF >/tmp/crontab.root
# Run “X” script
30 5 3 * * /root/X
EOF

# Add cron stuff to crontab
crontab /tmp/crontab.root
rm /tmp/crontab.root

# Reboot/shutdown confirmation
# It doesn’t work, find some other solution
#cat << EOF >/usr/local/bin/confirm
##!/bin/bash
#prompt()
#{
# while true
# do
# echo -n “\$* s/n? ”
# read reply
# if [ "\$reply" = s -o "\$reply" = S ]
# then
# return 0
# elif [ "\$reply" = n -o "\$reply" = N ]
# then
# echo “Accion cancelada”
# exit 1
# else
# echo “Por favor, introduce ‘s’ o ‘n’”
# fi
# done
#}
#
#echo “Se va a realizar \$1″
#if prompt “Esta seguro de continuar”
#then
# prompt “Confirmelo por favor”
# \$@
#fi
#EOF
#
#chmod 755 /usr/local/bin/confirm
#
#echo “alias reboot=\”/usr/local/bin/confirm reboot\”" >> /etc/bashrc
#echo “alias shutdown=\”/usr/local/bin/confirm shutdown\”" >> /etc/bashrc
#echo “alias init=\”/usr/local/bin/confirm init\”" >> /etc/bashrc
#echo “alias halt=\”/usr/local/bin/confirm halt\”" >> /etc/bashrc

# Shell timeout after 5 min. inactivity
esxcfg-advcfg -s 300 /UserVars/TSMTimeOut

# Remove unused Port Groups
esxcfg-vswitch -D “VM Network” vSwitch0
esxcfg-vswitch -D “Service Console” vSwitch0

echo “ssh stream tcp nowait root /sbin/dropbearmulti dropbear ++min=0,swap,group=shell -i -K60″ >> /etc/inetd.conf
echo “ssh stream tcp6 nowait root /sbin/dropbearmulti dropbear ++min=0,swap,group=shell -i -K60″ >> /etc/inetd.conf

# Reboot
reboot

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on diciembre 1st 2011 in sysadmin, VMware

Kickstart RHEL6

No se ven bien los < y > :P
# Instalacion modo texto
text
install
skipx

# URL de instalacion
url –url http:///RedHat/6/Server
# Repositorio
repo –name=RHEL-6 –baseurl=http:///RedHat/6/Server
repo –name=Extras –baseurl=http:///extras

# Configuracion general
firstboot –disable
lang es_ES.UTF-8
keyboard es
rootpw –iscrypted firewall –disabled
authconfig –enableshadow –enablemd5
key –skip
selinux –disabled
timezone –utc Europe/Madrid

# Particionamiento con LVM
clearpart –all –initlabel
#zerombr yes
bootloader –location=mbr –md5pass=$1$glLthZeF$u9wREDqB6/O0WYOcZqvnJ.
part /boot –fstype ext3 –size=100 –asprimary
part pv.00 –size=1 –grow –asprimary
volgroup vg00 pv.00
logvol / –fstype ext3 –name=lvroot –vgname=vg00 –size=1024 –grow
logvol swap –fstype swap –name=lvswap –vgname=vg00 –size=512 –grow –maxsize=2048
reboot

# Paquetes
#%packages –resolvedeps
%packages

@core
@base
ntp
kernel-devel
gcc
#dkms-open-vm-tools

%pre
#!/bin/sh
chvt 3
exec < /dev/tty3 > /dev/tty3
clear
echo “- – - – Configuracion de red – - – - ”
echo -en “Introduzca direccion IP: ”
read ip

echo -en “Introduzca hostname: ”
read hostname

chvt 1
exec < /dev/tty1 > /dev/tty1

gateway=`echo $ip | cut -d. -f1,2,3`.254
netmask=
nameserver=

line=”network –bootproto static –ip $ip –netmask $netmask –hostname $hostname –gateway $gateway –nameserver $nameserver”
ks=”/tmp/ks.cfg”
sed -e “/^network/s/^network.*/$line/” $ks > ${ks}.tmp && mv ${ks}.tmp $ks
sed -e “s/ip_tag/$ip/g” $ks > ${ks}.tmp && mv ${ks}.tmp $ks
sed -e “s/gw_tag/$gateway/g” $ks > ${ks}.tmp && mv ${ks}.tmp $ks
sed -e “s/hostname_tag/$hostname/g” $ks > ${ks}.tmp && mv ${ks}.tmp $ks

%post
#!/bin/bash
chvt 3
exec < /dev/tty3 > /dev/tty3
# Banner y motd
MOTD=”Esta maquina es propiedad de y cualquier uso debe estar autorizado por el departamento de correspondiente. Cualquier otro uso sera perseguido y castigado de acuerdo a la legislacion vigente. Cualquier actividad realizada en, desde o hacia este sistema esta sujeta a monitorizacion sin previo aviso.”
echo $MOTD > /etc/motd
chmod 644 /etc/motd

chvt 1
exec < /dev/tty1 > /dev/tty1

IFACE=eth0
IFCFG_ETH0=/etc/sysconfig/network-scripts/ifcfg-eth0
NETWORK=/etc/sysconfig/network
DNS1=
DNS2=
DOMAIN=
NETMASK=
GATEWAY=gw_tag
IP=ip_tag
HOSTNAME=hostname_tag

echo “DEVICE=$IFACE” > $IFCFG_ETH0
echo “BOOTPROTO=static” >> $IFCFG_ETH0
echo “IPADDR=$IP” >> $IFCFG_ETH0
echo “NETMASK=$NETMASK” >> $IFCFG_ETH0
echo “GATEWAY=$GATEWAY” >> $IFCFG_ETH0
echo “ONBOOT=yes” >> $IFCFG_ETH0

echo “NETWORKING=yes”> $NETWORK
echo “HOSTNAME=$HOSTNAME.$DOMAIN” >> $NETWORK

echo “search $DOMAIN” > /etc/resolv.conf
echo “nameserver $DNS1″ >> /etc/resolv.conf
echo “nameserver $DNS2″ >> /etc/resolv.conf

echo “127.0.0.1 localhost.localdomain localhost” > /etc/hosts
echo “127.0.0.1 $HOSTNAME.$DOMAIN $HOSTNAME” >> /etc/hosts

# Script de sincronizacion de ntp
NTPSERVER=
echo “tinker panic 0″ > /etc/ntp.conf
echo “restrict 127.0.0.1″ >> /etc/ntp.conf
echo “restrict default kod nomodify notrap” >> /etc/ntp.conf
echo “server $NTPSERVER” >> /etc/ntp.conf
echo “driftfile /var/lib/ntp/drift” >> /etc/ntp.conf

echo “$NTPSERVER” > /etc/ntp/step-tickers

chkconfig ntpd on

# Comprimir los logs de logrotate
echo “compress” >> /etc/logrotate.conf

# Repositorios locales
BASE=http:///RedHat/repos/RHEL-6.repo
EXTRAS=http:///RedHat/repos/Extras.repo

rm -f /etc/yum.repos.d/*.repo
wget $BASE -P /etc/yum.repos.d/
wget $EXTRAS -P /etc/yum.repos.d/

RPMKEY=http:///centos/RPM-GPG-KEY-CentOS-5
wget $RPMKEY -P /etc/pki/rpm-gpg/

# Deshabilitar servicios innecesarios al arranque
SERVICIOS=”bluetooth cups gpm ip6tables iptables sendmail smartd”
for i in $SERVICIOS
do
chkconfig $i off
done

# Activar el timeout de la shell despues de 5 minutos de inactividad
echo “TMOUT=300″ >> /etc/bashrc
echo “readonly TMOUT” >> /etc/bashrc
echo “export TMOUT” >> /etc/bashrc

# Instalar VMTools
# Q&D
wget http:///vmtools/vmtools.tar.gz
tar xzvf vmtools.tar.gz
vmware-tools-distrib/vmware-install.pl –default
rm -f vmtools.tar.gz
rm -Rf vmware-tools-distrib/

# Actualizar paquetes
#yum -y update
#yum clean packages

# Confirmacion para reiniciar/apagar el equipo

cat << EOF >/usr/local/bin/confirm
#!/bin/bash
prompt()
{
while true
do
echo -n “\$* s/n? ”
read reply
if [ "\$reply" = s -o "\$reply" = S ]
then
return 0
elif [ "\$reply" = n -o "\$reply" = N ]
then
echo “Accion cancelada”
exit 1
else
echo “Por favor, introduce ‘s’ o ‘n’”
fi
done
}

echo “Se va a realizar \$1″
prompt “Esta seguro?”
\$@
EOF

chmod 755 /usr/local/bin/confirm

echo “alias reboot=\”/usr/local/bin/confirm reboot\”" >> /etc/bashrc
echo “alias shutdown=\”/usr/local/bin/confirm shutdown\”" >> /etc/bashrc
echo “alias init=\”/usr/local/bin/confirm init\”" >> /etc/bashrc
echo “alias halt=\”/usr/local/bin/confirm halt\”" >> /etc/bashrc

# Prevenir reinicios accidentales por pulsar ctrl+alt+supr
#sed -i ‘s!^ca::.*!ca::ctrlaltdel:/bin/echo “CTRL + ALT + SUPR is disabled”!g’ /etc/inittab

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on diciembre 1st 2011 in CentOS, sysadmin

Script para crear isos de ESX con kickstart personalizado


#!/bin/bash
#
# This script creates an esx iso using a custom kickstart
# Usage:
# createiso [kickstart file] [iso file]
# Parameters:
# kickstart file = Kickstart to embed
# iso file = Iso to modify

# Save the program name into PROGNAME using basename command
PROGNAME=$(basename $0)

# Exit the script if something goes wrong, using a descriptive text and an error code
function error_exit() {

echo "Error $1"
exit $2
}

# Show the usage if parameters are incorrect
function usage() {
echo "Usage: ${PROGNAME} [kickstart file] [iso file]"
error_exit "checking parameters" 1
}

# Check if the parameters are ok
function check_parms() {
# Check if there are only 2 parameters
[ $# -ne 2 ] && usage

# Check if kickstart file is a text file
[ -f $1 ] || error_exit "$1 is not a valid file" "1"

# Check if the iso is really an iso (using file command)
file $2 | grep -q "CD-ROM"
RES=$?

[ $RES -eq 0 ] || error_exit "$2 is not a valid iso" "1"
}

# Clean up
function remove_temp() {
rm -Rf temp
rm -f $1
rm -f ks_`date +%Y%m%d`
umount mountpoint
rm -Rf newiso
rmdir mountpoint
}

# Main

check_parms $1 $2

POSTINSTALL=./resources/postinstall
BACK=./resources/back.jpg

# Check if mkisofs is available
[ -x /usr/bin/mkisofs ] || error_exit "mkisofs not found" 1

# Create a kickstart file copying the original
KICKSTART=ks_`date +%Y%m%d`

cp $1 $KICKSTART

# Create directory structure
mkdir -p {temp/init,mountpoint,newiso}

# Copy the iso to another temp, just in case
echo -n "Copying iso to temp..."
cp $2 $2.new || error_exit "copying $2" 1
echo "Done"

# Mount loopback temp iso file
echo -n "Mounting temp iso..."
mount -o loop $2.new mountpoint || error_exit "mounting $2" 1
echo "Done"

# Copy the initrd (the iso file is read-only)
echo -n "Copying initrd..."
cp mountpoint/isolinux/initrd.img temp/init || error_exit "copying initrd.img" 1
echo "Done"

# Copy the isolinux.cfg to a temp
echo -n "Copying isolinux.cfg..."
cp mountpoint/isolinux/isolinux.cfg temp/ || error_exit "copying isolinux.cfg" 1
echo "Done"

# Use cm as default boot option
echo -n "Setting cm to default boot option..."
sed -i 's/default esx/default cm/g' temp/isolinux.cfg || error_exit "setting cm to default boot option" 1
echo "Done"

# Initrd.img is a compressed file, so, uncompress it
echo -n "Uncompressing initrd..."
cd temp/init
`zcat initrd.img | cpio --extract` || error_exit "uncompressing initrd" 1
echo "Done"
cd -

# Remove the old initrd.img
echo -n "Removing old initrd..."
rm -f temp/init/initrd.img || error_exit "removing old initrd" 1
echo "Done"

# Embed the kickstart into the initrd
echo -n "Copying kickstart to initrd..."
cp $KICKSTART temp/init/ks.cfg || error_exit "copying kickstart to initrd" 1
echo "Done"

# Copy the postinstall script
echo -n "Copying postinstall to initrd..."
cp $POSTINSTALL temp/init/postinstall || error_exit "copying postinstall to initrd" 1
echo "Done"

# Recreate the initrd image
echo -n "Recreating initrd..."
cd temp/init/
find ./ | cpio -H newc -o > ../initrd || error_exit "recreating initrd" 1
gzip ../initrd --suffix .img || error_exit "recreating initrd" 1
cd -
echo "Done"

# Create the boot entry in isolinux.cfg
echo -n "Creating isolinux.cfg entry..."
echo "LABEL auto" >> temp/isolinux.cfg
echo "menu label ESX automatic installation" >> temp/isolinux.cfg
echo "kernel vmlinuz" >> temp/isolinux.cfg
echo "append initrd=initrd.img vmkopts=debugLogToSerial:1 mem=512M ks=file:///ks.cfg quiet" >> temp/isolinux.cfg
echo "Done"

# Copy the back image
echo -n "Copying back image to initrd..."
cp $BACK temp/back.jpg || error_exit "copying back.jpg to initrd" 1
echo "Done"

# Create the custom iso file
echo -n "Creating new iso file..."
# Copy all iso files
cp -pr mountpoint/* newiso/ || error_exit "copying files" 1
# Sync filesystem, just in case
sync
# Sleep for 5 secs., just in case too
sleep 5
# Overwrite the two modified files
cp -f temp/{isolinux.cfg,initrd.img,back.jpg} newiso/isolinux/
cd newiso
# Create the iso into esx-XXXXYYZZ.iso
mkisofs -l -J -R -r -T -o ../esx-vsphere-`date +%Y%m%d`.iso -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table ./ || error_exit "creating iso" 1
cd -
echo "Done"

# Clean environment
echo -n "Cleaning..."
remove_temp $2.new
echo "Done"

# Finish!
echo "All done!"
echo "Now burn your new iso (esx-vsphere-`date +%Y%m%d`.iso) to a blank cd and boot the auto option"

# Exit with no errors :)
exit 0

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on noviembre 8th 2011 in bash, VMware

Reinicio forzado de VMs VMware automáticamente cuando no responden con los “Event handlers” de Nagios

Debido a un bug de Microsoft Windows o VMware, nos surge que determinados PCs virtuales se quedan “congelados”, o bien con un pantallazo azul (BSOD).

Cuando esto ocurre, aparte de quedar inaccesibles, consumen recursos y pueden surgir problemas (usuario no se puede conectar, swapeo del ESX,…)

Lo ideal en este caso sería solucionar el bug (se ha abierto caso a VMware), pero mientras VMware y Microsoft se echan la culpa unos a otros, hemos buscado un “workaround” temporal.

Aprovechando la disponibilidad de la herramienta “Nagios”, se puede aprovechar una de sus múltiples características, llamada “Event Handlers”.

Esta característica permite realizar una acción, cumpliendo ciertas condiciones.

En este caso en particular, se ha procedido de la siguiente manera:

  • Chequeo de conectividad por red (ping) cada 10 minutos
  • Si al 3er intento (pasados 30 minutos), no responde
  • Reinicio forzado de la máquina virtual

Esta operativa necesita la integración de Nagios con la API de VMware, y aprovechando que ambas herramientas utilizan perl, realizarlo en perl.

Para activar los event handlers en Nagios, hay que añadir la siguiente directiva en el fichero /etc/nagios/nagios.cfg:

enable_event_handlers=1
event_handler_timeout=60

Con el segundo paramtero, aumentamos el timeout del script a 60 segundos, puesto que la API de VMware no es todo lo rápida que debería…

Lo primero de todo, es crear la definición del PC a monitorizar en Nagios.

Para ello, creamos el fichero /etc/nagios/hosts/pcs/pcsXXXXX.cfg, cuyo contenido es:

define host{
    use pcs
    host_name HOSTNAME
    alias ALIAS
    address IP
}
define service{
    use pcs-ping-service ; Name of service template to use
    host_name HOSTNAME
    service_description PING
    check_command check_ping!100.0,20%!500.0,60%
    max_check_attempts 4
    event_handler reboot-vm
}

Este fichero indica el nombre e ip del host, así como los servicios (en este caso, un solo servicio, ping), asociados a ese host.

Esta organización de la configuración es propia, puesto que la configuración inicial de nagios, así como los hosts, servicios, etc. en principio se encuentra en /etc/nagios/nagios.cfg, pero debido a la complejidad que esto entraña, se ha dividido en directorios dentro de /etc/nagios.

También es necesario modificar los ficheros de definición (templates), para adaptarlos a la situación: /etc/nagios/templates/hosts_templates.cfg:

define host{
    name pcs
    use generic-host
    check_period workhours
    max_check_attempts 5
    check_command check_dummy!0
    notification_period workhours
    notification_interval 120
    notification_options d,u,r
    contact_groups admins
    register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
}

El chequeo a nivel de host se hace vía ping, sin embargo, en este caso no se ha hecho así, puesto que la monitorización de Nagios funciona de tal manera que si un host no responde (cualquiera que sea el tipo de chequeo que realiza, en este caso ping), no chequea los servicios asociados a ese host, y el event handler de reinicio de la máquina virtual está asociado al servicio, por lo tanto, cuando el PC se quedaba sin red, el event handler no funcionaba, puesto que el chequeo del host fallaba, y no utilizaba el chequeo de servicio.

Por eso, el chequeo del host, utiliza un script “check_dummy”, que no hace nada, siempre da ok, con lo cual, el servicio que provoca el event handler, es un servicio aparte (en este caso ping), solucionando el problema de la dependencia del chequeo de host al chequeo de los servicios. /etc/nagios/templates/services_templates.cfg:

define service{
    name pcs-ping-service
    use local-service
    normal_check_interval 10
    active_checks_enabled 1
    passive_checks_enabled 0
    check_freshness 0
    freshness_threshold 600
    retry_check_interval 10
    max_check_attempts 4
    register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE! 
}

Esta es la definición del servicio de chequeo de los pings de los pcs. No es la estándar que utilizamos, porque la estándar es más agresiva (cada minuto, en lugar de cada 10)

NOTA: Los “register 0″ indican que son plantillas, que luego se utilizan en la definición del host y sus servicios.

El comando asociado al event handler se encuentra en /etc/nagios/commands/reboot-vm.cfg, y su contenido es:

define command{
    command_name reboot-vm 
    command_line /usr/lib/nagios/plugins/eventhandlers/reboot-vm $HOSTNAME$ $SERVICESTATE$ $SERVICESTATETYPE$ $SERVICEATTEMPT$
}

Normalmente a un event handler, no se le pasa el host, pero en este caso, para hacerlo “genérico”, y que pueda valer para cualquier host (simplificando mucho las cosas…), se le pasa como parametro el nombre del host. El script que trata el event handler es el siguiente:

#!/bin/sh 
# # Event handler script for rebooting a VMware virtual machine if it doesn't reply ping 
# # Note: This script will only reboot the virtual machine if the ping is 
# retried 3 times (in a "soft" state) or if the ping somehow 
# manages to fall into a "hard" error state. 

HOSTNAME=$1 
URL="URL_VCENTER" 
USER="USER_VCENTER" 
PASS="PASS_VCENTER"
# # What state is the ping in?
case "$2" in 
OK)
    # The ping just came back up, so don't do anything... 
    ;; 
CRITICAL) 
    # Is this a "soft" or a "hard" state? 
    case "$3" in 
    # We're in a "soft" state, meaning that Nagios is in the middle of retrying the 
    # check before it turns into a "hard" state and contacts get notified... 
        SOFT) 
        # What check attempt are we on? We don't want to restart the virtual machine on the first 
        # check, because it may just be a fluke! 
        case "$4" in 
        # Wait until the check has been tried 3 times before rebooting the virtual machine. 
        # If the check fails on the 4th time (after we reboot the vm), the state 
        # type will turn to "hard" and contacts will be notified of the problem. 
        # Hopefully this will reboot the vm successfully, so the 4th check will 
        # result in a "soft" recovery. If that happens no one gets notified because we 
        # fixed the problem! 
            3) echo -n "Rebooting VM (3rd soft critical state)..." 
            # Call the script to reboot the vm
            /usr/lib/nagios/plugins/eventhandlers/resetvm.pl --url $URL --username $USER --password $PASS --vmname $HOSTNAME 
            ;; 
        esac 
        ;;
        # The virtual machine somehow managed to turn into a hard error without getting fixed. 
        # It should have been rebooted by the code above, but for some reason it didn't. 
        # Let's give it one last try, shall we?
        # Note: Contacts have already been notified of a problem with the virtual machine at this 
        # point (unless you disabled notifications for this service) 
        HARD)
            echo -n "Rebooting VM..." 
            # Call the script to reboot the vm
            /usr/lib/nagios/plugins/eventhandlers/resetvm.pl --url $URL --username $USER --password $PASS --vmname $HOSTNAME 
            ;;
        esac
        ;;
esac
exit

La lógica del script es:

  • Si la respuesta del chequeo es OK, no hacer nada
  • Si es CRITICAL (no ha devuelto el ping)
  • Si es SOFT y es la tercera vez del chequeo en SOFT
    • Reiniciar la VM
  • Si es HARD (no debería de llegar aquí nunca, pero…)
    • Reiniciar la VM

El siguiente paso sería procesar esta información y utilizar la API de VMware para resetear la máquina virtual que está causando los problemas… sin embargo, dado que los nombres de las máquinas virtuales no coinciden con el hostname, si no que llevan una descripción asociada en el nombre, hay que tratar esta información antes de mandar la orden (no todo iba a ser fácil ;) )

Por ejemplo, pcsXXXXX, en realidad es “PCSXXXXX – Pruebas piloto YYYY”.

El script de perl que realiza el reinicio es:

#!/usr/bin/perl -w 
# VMware and perl related stuff 
use strict; 
use warnings; 
use VMware::VIRuntime; 
# Add the vmname parameter to the arguments 
my %opts = ( 'vmname' => { 
    # String
    type => "=s", 
    help => "The name of the virtual machine", 
    # Required 
    required => 1,
    },
); 
# Perl stuff to add the vmname parameter and process themselves 
Opts::add_options(%opts); 
Opts::parse(); 
Opts::validate(); 
# Connect vcenter 
Util::connect(); 
# Add some regexp magic 
my $vmname = ".*" . Opts::get_option('vmname') . ".*"; 
# get the vm objects matching the criteria 
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine', 
    filter => {
        # regexp magic used here 
        'config.name' => qr/${vmname}/i, 
        # check that the vm is on 
        'runtime.powerState' => 'poweredOn'
        }); 

# this loop should be run once, because it should be only one vm... 
foreach my $vm(@$vm_views) { 
    # print "Name: " . $vm->name . "\n"; 
    $vm->ResetVM(); 
} 
# Disconnect vcenter 
Util::disconnect();

El script está comentado, con lo cual, no debería haber problema en entenderlo ;)

Se ha probado, y funciona correctamente, pero ocurre lo siguiente: Al estar en dominio, hay veces que la máquina virtual levanta el servicio de firewall, impidiendo el ping a la misma, por lo tanto, esto no sería válido… se están evaluando alternativas a esto.

NOTA: Faltan cosas, como integrarlo con las notificaciones, etc.

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on octubre 14th 2011 in General, Nagios, VMware

ownCloud 2.0

http://owncloud.org/announcement

Según su web:

ownCloud gives you universal access to your files through a web interface or WebDAV. It also provides a platform to easily view & sync your contacts, calendars and bookmarks across all your devices and enables basic editing right on the web.

Probé la versión 1 y estaba en pañales, pero esta parece que tiene muy buena pinta!

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on octubre 13th 2011 in cloud

Concentración de coches clásicos, Ávila, Octubre 2011

Aparte de los ordenadores, gadgets, y todo aquello que lleve chips :P una de las cosas que más me gustan, son los coches, y los coches clásicos últimamente mucho más.

Aquí pongo unas fotos que he hecho esta mañana aprovechando una concentración de coches clásicos en el lienzo norte de Ávila.

Están hechas con el móvil, así que perdón por la calidad de las mismas :)

Concentración coches clásicos, Ávila, Octubre 2011

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on octubre 9th 2011 in Motor, Personal

Añadir drivers al instalador de ESXi

Presupongo que perderás soporte, pero puede ser útil para entornos de lab:

http://www.ntpro.nl/blog/archives/1602-Injecting-drivers-into-the-ESXI-installer.html

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on septiembre 28th 2011 in sysadmin, VMware

Parches de VMware

En esta página -> http://www.vmware.com/patchmgr/findPatch.portal se encuentran todos los parches de los productos de VMware.

Además permite buscar por versiones y/o grado de “severidad”, con lo cual viene bastante bien tenerla “a mano”.

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on septiembre 28th 2011 in sysadmin, VMware

Solución a “ambiguous target” en scp

Cuando alguna de las rutas (origen o destino) del comando scp contiene espacios en blanco (aun “escapandolos” con la barra invertida \), falla mostrando el error “ambiguous target”.

scp <ruta_fichero_origen> <usuario>@<host_destino>:<ruta_con_espacios\ escapados>
scp: ambiguous target

La solución es entrecomillar:

scp <ruta_fichero_origen> <usuario>@<host_destino>:"<ruta_con_espacios\ escapados>"

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

2 Comments »

minWi on septiembre 27th 2011 in Linux, sysadmin

Eliminar snapshots fantasmas en VMware ESX

Puede ocurrir que por diversas causas (fallo de conectividad en el momento exacto, falta de espacio en disco,…) queden snapshots “fantasmas” de máquinas virtuales.

El procedimiento oficial de VMware es el que aparece relatado en esta KB:

http://kb.vmware.com/kb/1002310

Post to Twitter Post to Facebook Send Gmail Post to LinkedIn

No Comments »

minWi on septiembre 27th 2011 in VMware

  • RSS
  • Facebook
  • Google+
  • LinkedIn
  • Twitter
  • Picasa
  • Flickr
  • YouTube