viernes, 25 de junio de 2010

Arch linux en Active Directory

Con estos dos howtos está hecho :D

Arch server to Windows domain
http://wiki.archlinux.org/index.php/Arch_server_to_Windows_domain

Unir Linux a un Dominio Active directory
http://gnulinuxcodigo.blogspot.com/2009/12/unir-linux-un-dominio-active-directory.html

Stonith ibmrsa-telnet Suse SLES11

Según el departamento de ingeniería de Novell, el patch que adjunté anteriormente ya se incluye en el Service Pack 1 de SLES11.

Entonces el script queda así:



#!/usr/bin/python

# vim: set filetype=python

#######################################################################

#

# ibmrsa-telnet - External stonith plugin for HAv2 (http://linux-ha.org/wiki)

# Connects to IBM RSA Board via telnet and switches power

# of server appropriately.

#

# Author: Andreas Mock (andreas.mock@web.de)

#

# History:

# 2007-10-19 Fixed bad commandline handling in case of stonithing

# 2007-10-11 First release.

#

# Comment: Please send bug fixes and enhancements.

# I hope the functionality of communicating via telnet is encapsulated

# enough so that someone can use it for similar purposes.

#

# Description: IBM offers Remote Supervisor Adapters II for several

# servers. These RSA boards can be accessed in different ways.

# One of that is via telnet. Once logged in you can use 'help' to

# show all available commands. With 'power' you can reset, power on and

# off the controlled server. This command is used in combination

# with python's standard library 'telnetlib' to do it automatically.

#

# cib-snippet: Please see README.ibmrsa-telnet for examples.

#

# Copyright (c) 2007 Andreas Mock (andreas.mock@web.de)

# All Rights Reserved.

#

# This program is free software; you can redistribute it and/or modify

# it under the terms of version 2 or later of the GNU General Public

# License as published by the Free Software Foundation.

#

# This program is distributed in the hope that it would be useful, but

# WITHOUT ANY WARRANTY; without even the implied warranty of

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

#

# Further, this software is distributed without any warranty that it is

# free of the rightful claim of any third person regarding infringement

# or the like. Any license provided herein, whether implied or

# otherwise, applies only to this software file. Patent licenses, if

# any, provided herein do not apply to combinations of this program with

# other software, or any other product whatsoever.

#

# You should have received a copy of the GNU General Public License

# along with this program; if not, write the Free Software Foundation,

# Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.

#

#######################################################################

import sys

import os

import time

import telnetlib

import subprocess


class TimeoutException(Exception):

def __init__(self, value=None):

Exception.__init__(self)

self.value = value



def __str__(self):

return repr(self.value)


class RSABoard(telnetlib.Telnet):

def __init__(self, *args, **kwargs):

telnetlib.Telnet.__init__(self, *args, **kwargs)

self._timeout = 10

self._loggedin = 0

self._history = []

self._appl = os.path.basename(sys.argv[0])


def _get_timestamp(self):

ct = time.time()

msecs = (ct - long(ct)) * 1000

return "%s,%03d" % (time.strftime("%Y-%m-%d %H:%M:%S",

time.localtime(ct)), msecs)



def write(self, buffer):

self._history.append(self._get_timestamp() + ': WRITE: ' + repr(buffer))

telnetlib.Telnet.write(self, buffer)



def expect(self, what, timeout=20):

line = telnetlib.Telnet.expect(self, what, timeout)

self._history.append(self._get_timestamp() + ': READ : ' + repr(line))

if not line:

raise TimeoutException("Timeout while waiting for '%s'." % (what, ))

return line



def login(self, user, passwd):

time.sleep(1)

line = self.expect(['\nlogin : ', '\nusername: '], self._timeout)

self.write(user)

self.write('\r')

line = self.expect(['\nPassword: ', '\npassword: '], self._timeout)

self.write(passwd)

self.write('\r')

line = self.expect(['\nsystem>', '> '], self._timeout)



def reset(self):

self.write('power cycle\r')

line = self.expect(['\nok'], self._timeout)

line = self.expect(['\nsystem>', '> '], self._timeout)



def on(self):

self.write('power on\r')

line = self.expect(['\nok'], self._timeout)

line = self.expect(['\nsystem>', '> '], self._timeout)



def off(self):

self.write('power off\r')

line = self.expect(['\nok'], self._timeout)

line = self.expect(['\nsystem>', '> '], self._timeout)



def exit(self):

self.write('exit\r')



def get_history(self):

return "\n".join(self._history)



class RSAStonithPlugin:

def __init__(self):

# define the external stonith plugin api

self._required_cmds = \

'reset gethosts status getconfignames getinfo-devid ' \

'getinfo-devname getinfo-devdescr getinfo-devurl ' \

'getinfo-xml'

self._optional_cmds = 'on off'

self._required_cmds_list = self._required_cmds.split()

self._optional_cmds_list = self._optional_cmds.split()



# who am i

self._appl = os.path.basename(sys.argv[0])



# telnet connection object

self._connection = None



# the list of configuration names

self._confignames = ['nodename', 'ip_address', 'username', 'password']



# catch the parameters provided by environment

self._parameters = {}

for name in self._confignames:

try:

self._parameters[name] = os.environ.get(name, '').split()[0]

except IndexError:

self._parameters[name] = ''



def _get_timestamp(self):

ct = time.time()

msecs = (ct - long(ct)) * 1000

return "%s,%03d" % (time.strftime("%Y-%m-%d %H:%M:%S",

time.localtime(ct)), msecs)



def _echo_debug(self, *args):

self.echo_log('debug', *args)



def echo(self, *args):

what = ''.join([str(x) for x in args])

sys.stdout.write(what)

sys.stdout.write('\n')

sys.stdout.flush()

self._echo_debug("STDOUT:", what)



def echo_log(self, level, *args):

subprocess.call(('ha_log.sh', level) + args)


def _get_connection(self):

if not self._connection:

c = RSABoard()

self._echo_debug("Connect to '%s'" %

(self._parameters['ip_address'],))

c.open(self._parameters['ip_address'])

self._echo_debug("Connection established")

c.login(self._parameters['username'],

self._parameters['password'])

self._connection = c


def _end_connection(self):

if self._connection:

self._connection.exit()

self._connection.close()


def reset(self):

self._get_connection()

self._connection.reset()

self._end_connection()

self._echo_debug(self._connection.get_history())

self.echo_log("info", "Reset of node '%s' done" %

(self._parameters['nodename'],))

return(0)



def on(self):

self._get_connection()

self._connection.on()

self._end_connection()

self._echo_debug(self._connection.get_history())

self.echo_log("info", "Switched node '%s' ON" %

(self._parameters['nodename'],))

return(0)



def off(self):

self._get_connection()

self._connection.off()

self._end_connection()

self._echo_debug(self._connection.get_history())

self.echo_log("info", "Switched node '%s' OFF" %

(self._parameters['nodename'],))

return(0)



def gethosts(self):

self.echo(self._parameters['nodename'])

return(0)



def status(self):

self._get_connection()

self._end_connection()

self._echo_debug(self._connection.get_history())

return(0)



def getconfignames(self):

for name in ['nodename', 'ip_address', 'username', 'password']:

self.echo(name)

return(0)


def getinfo_devid(self):

self.echo("External Stonith Plugin for IBM RSA Boards")

return(0)



def getinfo_devname(self):

self.echo("External Stonith Plugin for IBM RSA Boards connecting "

"via Telnet")

return(0)

def getinfo_devdescr(self):

self.echo("External stonith plugin for HAv2 which connects to "

"a RSA board on IBM servers via telnet. Commands to "

"turn on/off power and to reset server are sent "

"appropriately. "

"(c) 2007 by Andreas Mock (andreas.mock@web.de)")

return(0)

def getinfo_devurl(self):

self.echo("http://www.ibm.com/Search/?q=remote+supervisor+adapter")



def getinfo_xml(self):

info = """





nodename to shoot



Name of the node which has to be stonithed in case.









hostname or ip address of RSA



Hostname or ip address of RSA board used to reset node.









username to login on RSA board



Username to login on RSA board.









password to login on RSA board



Password to login on RSA board.







"""

self.echo(info)

return(0)

def not_implemented(self, cmd):

self.echo_log("err", "Command '%s' not implemented." % (cmd,))

return(1)


def usage(self):

usage = "Call me with one of the allowed commands: %s, %s" % (

', '.join(self._required_cmds_list),

', '.join(self._optional_cmds_list))

return usage


def process(self, argv):

self._echo_debug("========== Start =============")

if len(argv) < 1:

self.echo_log("err", 'At least one commandline argument required.')

return(1)

cmd = argv[0]

self._echo_debug("cmd:", cmd)

if cmd not in self._required_cmds_list and \

cmd not in self._optional_cmds_list:

self.echo_log("err", "Command '%s' not supported." % (cmd,))

return(1)

try:

cmd = cmd.lower().replace('-', '_')

func = getattr(self, cmd, self.not_implemented)

rc = func()

return(rc)

except Exception, args:

self.echo_log("err", 'Exception raised:', str(args))

if self._connection:

self.echo_log("err", self._connection.get_history())

self._connection.close()

return(1)


if __name__ == '__main__':

stonith = RSAStonithPlugin()

rc = stonith.process(sys.argv[1:])

sys.exit(rc)


jueves, 17 de junio de 2010

Crear eth0 alias ifconfig

Por si necesitas crearte un alias temporal

ifconfig eth0:0 192.168.18.8 netmask 255.255.255.0 up

eth0:0 Link encap:Ethernet direcciónHW 00:21:9b:6c:d6:5a
Direc. inet:192.168.18.8 Difus.:192.168.18.255 Másc:255.255.255.0
ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST MTU:1500 Métrica:1
Memoria:fe9e0000-fea00000

martes, 15 de junio de 2010

VMWARE ESX 4.0 VSphere Update Crash

Tras el último update, dos de los servidores vsphere han fallado al arrancar. El error aparece justo en el momento en que arranca udev. Al parecer esta actualización ha provocado que el UUID de la partición /var/log cambie.

SOLUCIÓN
Entrar con el passwd de root y remontar el filesystem / con rescritura
m
ount -o remount,rw /

Miramos que UUID tiene /var/log en el fichero /etc/fstab
UUID=315f724f-637f-4118-b755-2511f4ff04 /var/log ext3 defaults,errors=panic 1 2
Miramos el nuevo UUID
blkid

Veremos que uno de los UUIDs ha cambiado
/dev/sdv1: UUID="e2ac6711-87c4-45a8-8f2a-fe2e47f6fd3" SEC_TYPE="ext2" TYPE="ext3"
/dev/sdz1: TYPE="ntfs"
/dev/sdab1: TYPE="swap" UUID="a0e811ca-e8dd-4e28-b4b-cabdbe54936f"
/dev/sdab2: UUID="415f724f-637f-4118-b755-251f4ff0b14" SEC_TYPE="ext2" TYPE="ext3"
/dev/sdab5: LABEL="esx-root" UUID="7b52ed6d-c48-4c12-969f-68b66a0550c" SEC_TYPE="ext2" TYPE="ext3"

modificamos la línia del fichero /etc/fstab que hace referencia al montaje de /var/log con el nuevo UUID (si se esta editando con vi, se puede traer la salida del comando blkid haciendo en modo consola [ESC] :.!blkid )

UUID=415f724f-637f-4118-b755-251f4ff0b14 /var/log ext3 defaults,errors=panic 1 2

Guardamos :wq!

Reiniciamos el servidor y ya ha funcionado.



-Después de escribir este post hemos recibido un correo electrónico de vmware con las mismas instrucciones para solucionarlo de forma oficial :)

lunes, 14 de junio de 2010

ionice - modificar prioridad de IO de disco

Este programa establece la clase de planificación io y la prioridad de un programa a la hora de escribir en disco. Linux soporta las siguienes 3 clases:

Idle: Un programa que se ejecuta con prioridad io inactivo, no va a escribir en disco si hay otro programa ha pedido io para un período de gracia definido. El impacto de los procesos de E / S de inactividad en la actividad normal del sistema debe ser cero. Esta clase de planificación, no hace falta ser un argumento de prioridad.

Best effort: Esta es la clase de planificación predeterminada para cualquier proceso que no ha pedido una prioridad io específica. Esta clase tiene un argumento de prioridad de 0-7 (menor número = máxima prioridad). Los programas que se ejecutan en la misma prioridad "Best effort" se sirven en un round-robin.

RealTime: La clase de planificación RT se da acceso por primera vez al disco, independientemente de lo que está ocurriendo en el sistema. Así, la clase RT necesita ser utilizado con cierto cuidado, ya que otros procesos pueden "morir de hambre".

-c
La clase de planificación. 1 para tiempo real, 2 para "mejor esfuerzo", 3 de inactividad.
-n
Los datos de clase de planificación. Esto define la clase de datos, si la clase acepta un argumento. Por tiempo real y mejor esfuerzo, 0-7 es un dato válido.
-p
Ir a un proceso pid para cambiar un proceso ya se está ejecutando. Si este argumento no se da, ionice ejecutará el programa en la lista con los parámetros especificados.

Ejemplos:
# ionice -c3 -p89
Sets process with PID 89 as an idle io process.
# ionice -c2 -n0 bash
Runs 'bash' as a best-effort program with highest priority.
# ionice -p89
Returns the class and priority of the process with PID 89.
Ejemplo practico para backups de discos de xen sobre particion ocsf2
sudo ionice -c 3 cp -r /xenstore/maquina1.raw /backup/xenstore

de esta forma que sólo se procesará la entrada y salida cuando el sistema esté libre y no tendremos problemas en entornos cluster.

nrpe vmware 4.0

rpm -ivh http://www.mand4la.info/stuff/nagios/rh7x/fping-2.4-1.b2.0.rh7.rf.i386.rpm
rpm -ivh http://www.mand4la.info/stuff/nagios/rh7x/perl-Net-SNMP-5.2.0-1.0.rh7.rf.noarch.rpm
rpm -ivh http://www.mand4la.info/stuff/nagios/rh7x/nagios-plugins-1.4-2.0.rh7.rf.i386.rpm

jueves, 10 de junio de 2010

Xen Cluster DomU constraints

Es necesaria una política para hacer que este recurso domU sea dependiente del recurso clon de filesystem (partición ocfs2), ya que son verdaderamente dependientes: no se puede arrancar una maquina virtual si la partición ocfs2 no esta montada.

No tiene influencia alguna sobre otros recursos (p.ej. DomU) del cluster que este funcionando, y es inocuo cargarlo en el cluster mientras funciona.

La razón por la cual se utiliza un score de 0 esta explicitada es básicamente para evitar un reinicio automatico de algunos recursos http://www.gossamer-threads.com/lists/linuxha/users/52913.

Tambien se aplica a SLES11 HAE: ver http://forums.novell.com/novell-product-support-forums/suse-linux-enterprise-server-sles/sles-configure-administer/390708-pacemaker-problem.html y http://developerbugs.linux-foundation.org/show_bug.cgi?id=2153.

En resumen: “hay una diferencia entre order="0" y order="infinity" para los recursos primitives dependiendo de los clones.

Con order="infinity", el recurso primitive se reinicia si cualquier instancia de clone se reinicia.
Con order="0", el recurso primitive se reinicia solamente si la instancia local se reinicia. (asumiendo que las reglas de collocation estan definidas tambien.)

Consideraba que esto era un bug, pero quizas alguien tiene una situación donde este comportamiento es deseable y necesitabamos alguna forma de expresar esto en la configuración.” Lars Marowsky-Brée

Saludos Philippe, muy útil tu documentación :)

Stonith ibmrsa-telnet Suse SLES11

Tras probar a fondo la anterior entrada, descubrí que Stohith seguia sin funcionar correctamente. Los filesystem compartidos seguían bloqueados hasta el join del nodo caido. Buscando, mucho, encontré un patch que al parecer me esta dando buenos resultados, por fin. A la espera aun de la respuesta oficial de Novell ya que este parche no es "oficial". El parche es el siguiente:

--- /usr/lib64/stonith/plugins/external/ibmrsa-telnet 2010-03-25 22:26:21.476805235 +0100
+++ /tmp/ibmrsa-telnet.new 2010-03-25 22:26:08.597800250 +0100
@@ -88,29 +88,29 @@
return line

def login(self, user, passwd):
- self.write("\r")
- line = self.expect(['^login : ', '^username: '], self._timeout)
+ time.sleep(1)
+ line = self.expect(['\nlogin : ', '\nusername: '], self._timeout)
self.write(user)
self.write('\r')
- line = self.expect(['^Password: ', '^password: '], self._timeout)
+ line = self.expect(['\nPassword: ', '\npassword: '], self._timeout)
self.write(passwd)
self.write('\r')
- line = self.expect(['^system>', '^> '], self._timeout)
+ line = self.expect(['\nsystem>', '> '], self._timeout)

def reset(self):
self.write('power cycle\r')
- line = self.expect(['^ok'], self._timeout)
- line = self.expect(['^system>', '^> '], self._timeout)
+ line = self.expect(['\nok'], self._timeout)
+ line = self.expect(['\nsystem>', '> '], self._timeout)

def on(self):
self.write('power on\r')
- line = self.expect(['^ok'], self._timeout)
- line = self.expect(['^system>', '^> '], self._timeout)
+ line = self.expect(['\nok'], self._timeout)
+ line = self.expect(['\nsystem>', '> '], self._timeout)

def off(self):
self.write('power off\r')
- line = self.expect(['^ok'], self._timeout)
- line = self.expect(['^system>', '^> '], self._timeout)
+ line = self.expect(['\nok'], self._timeout)
+ line = self.expect(['\nsystem>', '> '], self._timeout)

def exit(self):
self.write('exit\r')
@@ -154,7 +154,7 @@
time.localtime(ct)), msecs)

def _echo_debug(self, *args):
- subprocess.call("ha_log.sh debug '%s'" % ' '.join(args), shell=True)
+ self.echo_log('debug', *args)

def echo(self, *args):
what = ''.join([str(x) for x in args])
@@ -164,7 +164,7 @@
self._echo_debug("STDOUT:", what)

def echo_log(self, level, *args):
- subprocess.call("ha_log.sh %s '%s'" % (level,' '.join(args)), shell=True)
+ subprocess.call(('ha_log.sh', level) + args)

def _get_connection(self):
if not self._connection:
@@ -172,6 +172,7 @@
self._echo_debug("Connect to '%s'" %
(self._parameters['ip_address'],))
c.open(self._parameters['ip_address'])
+ self._echo_debug("Connection established")
c.login(self._parameters['username'],
self._parameters['password'])
self._connection = c

Parchearlo contra el ibmrsa-telnet original de sles11 (/usr/lib64/stonith/plugins/external/
ibmrsa-telnet)

Extraido de: http://www.gossamer-threads.com/lists/engine?do=post_attachment;postatt_id=4604;list=linuxha

http://www.gossamer-threads.com/lists/linuxha/pacemaker/62991

martes, 8 de junio de 2010

Oracle BD: Añadir espacio a un Tablespace

Nos conectamos al servidor Oracle por ssh con el usuario oracle y ejecutamos:
 $ sqlplus "/ as sysdba"
Vemos el estado actual de los datafiles de dicho tablespace que queremos ampliar

select t.name "TABLESPACE" , d.status, d.bytes, d.name "DATAFILE" from v$tablespace t, v$datafile d
where t.ts#=d.ts# and t.name='NombreTablespace'
;

 TABLESPACE STATUS BYTES      DATAFILE
---------- ------ ---------- --------------------------------------------------
EXEMPLE ONLINE 524288000 /opt/local/oradata/prova/campus01.dbf
EXEMPLE ONLINE 1048576000 /opt/local/oradata/prova/campus02.dbf
EXEMPLE ONLINE 524288000 /opt/local/oradata/prova/campus02.dbf
EXEMPLE ONLINE 524288000 /opt/local/oradata/prova/campus03.dbf
EXEMPLE ONLINE 1048576000 /opt/local/oradata/prova/campus05.dbf
EXEMPLE ONLINE 1048576000 /opt/local/oradata/prova/campus04.dbf
Tenemos dos opciones ampliar el tablespace con un resize o añadiendo un datafile

SQL>alter database datafile '/opt/local/oradata/prova/campus01.dbf' resize 4096 M; 

O bien:

SQL>alter tablespace CAMPUS add datafile '/opt/local/
oradata/prova/campus06.dbf' size 4096 M;

viernes, 4 de junio de 2010

Stonith ibmrsa-telnet Suse SLES11

Después de actualizar los nodos del cluster a la última con el repositorio de Novell, los recursos STONITH por ILO de los servers IBM me han dejado de funcionar. El error era:

Jun 2 15:56:13 solsones crmd: [18334]: info: do_lrm_rsc_op: Performing key=81:39:0:09220bbe-7fe2-43ac-84df-6aec5643fdb8 op=STONITH_iLO_RSA_cerdanya_start_0 )
Jun 2 15:56:13 solsones lrmd: [18331]: info: rsc:STONITH_iLO_RSA_cerdanya:35: start
Jun 2 15:56:13 solsones lrmd: [11794]: info: Try to start STONITH resource : Device=external/ibmrsa-telnet
Jun 2 15:56:13 solsones external/ibmrsa-telnet[11795]: debug: ========== Start =============
Jun 2 15:56:13 solsones external/ibmrsa-telnet[11795]: debug: cmd: getconfignames
Jun 2 15:56:13 solsones external/ibmrsa-telnet[11795]: debug: STDOUT: nodename
Jun 2 15:56:13 solsones external/ibmrsa-telnet[11795]: debug: STDOUT: ip_address
Jun 2 15:56:13 solsones external/ibmrsa-telnet[11795]: debug: STDOUT: username
Jun 2 15:56:14 solsones external/ibmrsa-telnet[11795]: debug: STDOUT: password
Jun 2 15:56:14 solsones external/ibmrsa-telnet[11843]: debug: ========== Start =============
Jun 2 15:56:14 solsones external/ibmrsa-telnet[11843]: debug: cmd: status
Jun 2 15:56:14 solsones external/ibmrsa-telnet[11843]: debug: Connect to 192.168.138.30
Jun 2 15:56:34 solsones stonithd: [18329]: WARN: external_STONITH_iLO_RSA_cerdanya_star process (PID 11842) timed out (try 1). Killing with signal SIGTERM (15).
Jun 2 15:56:35 solsones stonithd: [11842]: info: external_run_cmd: Calling '/usr/lib64/stonith/plugins/external/ibmrsa-telnet status' returned 15
Jun 2 15:56:35 solsones stonithd: [11842]: CRIT: external_status: 'ibmrsa-telnet status' failed with rc 15
Jun 2 15:56:35 solsones stonithd: [18329]: WARN: start STONITH_iLO_RSA_cerdanya failed, because its hostlist is empty
Jun 2 15:56:35 solsones lrmd: [18331]: debug: stonithRA plugin: provider attribute is not needed and will be ignored.
Jun 2 15:56:35 solsones external/ibmrsa-telnet[11950]: debug: ========== Start =====


Tras reportarlo a Novell, he probado con el paquete heartbeat de centos heartbeat-stonith-2.1.3-3.el5.centos.x86_64.rpm he sacado el script ibmrsa-telnet de este rpm y ha funcionado correctamente.
(ver el la siguiente entrada ya que luego da problemas...
http://ferranserafini.blogspot.com/2010/06/stonith-ibmrsa-telnet-suse-sles11_10.html )

martes, 1 de junio de 2010

Xen - Crear nuevo disco dd

Desde el Dom0:

dd if=/dev/zero of=disco.disk.xm bs=1 conv=notrunc count=1 seek=12G

Así si hacemos ls -l veremos que ocupa 12G pero en realidad si hacemos du -shx veremos que ocupa lo que realmente hay dentro de ese disco.

Este método tiene pros/contras. La ventaja que ofrece es que permite una mejor optimización del espacio del disco y la desventaja es el control, ya que puedes hacer overbooking si no calculas bien el espacio.

Ahora ya es solo añadirlo al DomU que haga falta.