XenServer Commands Cheat Sheet

Here you are a XenServer Commands Cheat Sheet!

  • Configure SR-IOV
    • /opt/xensource/libexec/xen-cmdline –set-xen iommu=1
    • lspci
    • xe vm-param-set other-config:pci=0/0000:07:10.0 uuid=uuid_of_the_VM
  • Enable and Disable Open VSwitch
    • xe-switch-network-backend bridge
    • xe-switch-network-backend openvswitch
  • Setup Diagnostic Website
    • cd /opt/xensource/www
    • ln –s /opt/xensource/debug/www debug
    • http://masterserverip/debug/index.html
  • Configure Auto Start VMs
    • Pool Config : xe pool-param-set uuid=… other-config:auto_poweron=true
    • VM Config: xe vm-param-set uuid=… other-config:auto_poweron=true
  • iSCSI Commands
    • discover: iscsiadm –mode discovery –type sendtargets –portal <IP-Address of the iSCSI target>
    • login: iscsiadm –mode node –targetname <target IQN you have discovered before> –portal <IP-Address of your Target>:3260 –login
    • logout: iscsiadm –mode node –targetname <target IQN you have discovered before> –portal <IP-Address of your Target>:3260 –logout
  • View TapDisks
    • tap-ctl list
    • ls -l /var/run/sr-mount/…..
  • Compare Template Differences
    • xe template-list name-label=Citrix\ XenApp\ on\ Windows\ Server\ 2003\ \(32-bit)\) params=all >> /root/2k3-32
    • xe template-list name-label=Citrix\ XenApp\ on\ Windows\ Server\ 2008\ \(32-bit)\) params=all >> /root/2k8-32
    • diff –side-by-side –suppress-common-lines /root/2k3-32 /root/2k8-32 (to see which parameters differ)
    • or
    • diff –suppress-common-lines /root/2k3-32 /root/2k8-32 (to see the full difference)
  • Reclaim Disk Space from Deleted XenServer Snapshots (http://support.citrix.com/article/CTX123400)
    • xe host-call-plugin host-uuid=<host-UUID> plugin=coalesce-leaf fn=leaf-coalesce args:vm_uuid=<VM-UUID>
  • Emergency Master Server Failure Recovery
    • xe host-emergency-ha-disable force=true
    • xe pool-emergency-transition-to-master
    • pool-designate-new-master host-uuid=<UUID of member XenServer host to become new master>
    • cat /etc/xensource/pool.conf to reflect to the new master.
    • Restarted XAPI service and it back to the pool.
  • Remove a Lost server from a Resource Pool

xe host-list
xe -s [ip address] -u root -pw PASSWORD pool-sync-database
xe -s [ip address] -u root -pw PASSWORD host-forget uuid=[the above command will provide the UUID]
xe pool-eject host-uuid

  • Copy a VM to another XenServer

xe vm-list (note the name of the VM you wish to copy)
xe sr-list (note the name of the storage you will to copy the VM to)
xe vm-copy (needs the following parameters to complete)
xe vm-copy vm=<name of VM to copy> sr-uuid=<UUID of SR to copy VM to> new-name-label=<NewNameofVM> new-name-description=”Description of VM”

  • Force Pool master Selection

xe pool-emergency-transition-to-master
xe pool-recover-slaves
xe host-list
xe pool-sync-database
xe host-forget

  • Check if XenServer is a Pool Master

cat /etc/xensource/pool.conf
Output says “master” , slaves output “slave:<master host IP>”

  • Enable Open vSwitch

xe-switch-network-backend openvswitch
xe host-list params=software-version

  • Enter XenServer Config Menu via SSH

xsconsole

  • Configure HA Timeout
      • xe pool-ha-enable heartbeat-sr-uuids=021e7e21-1e64-a0b3-2e22-5bbfcfe559e9 ha-config:timeout=10
      • Minimum timeout is 10 seconds
      • Default is 30 Seconds
      • xe pool-ha-compute-max-host-failures-to-tolerate
  • Destroying or forgetting a SR (Storage Repository)


xe -s [host ip] -u root -pw [password] sr-list
xe -s [host ip] -u root -pw [password] pbd-list sr-uuid=
xe -s [host ip] -u root -pw [password] pbd-unplug uuid=
xe -s [host ip] -u root -pw [password] pbd-destroy uuid=
xe -s [host ip] -u root -pw [password] sr-forget uuid=

  • xentop

displays real-time information about Xen system.

  • xen-bugtool –yestoall
  • Set HA Timeouot

xe pool-ha-enable heartbeat-sr-uuids=##### ha-config:timeout=however many seconds you want.

  • VM Operations

xe task-list
xe task-cancle uuid=xe
vm-shutdown –force vm=

  • Overload CPU for testing Workload Balancing

while true ; do true ; donewhile true ; do true ; done &while true ; do `ls –lR /` ; done

  • How to Create a Local Storage Repository (CTX121313)

# cat /proc/partitions
# ll /dev/disk/by-id
Find the disk ID of the “sdb” or “cciss/c0d1”disk. The “scsi-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” or “cciss-xxxxxxxxxxxxxxxxxxxxxxxxxx”format is what you need.
Create a Storage Repository (SR):
# xe sr-create content-type=user device-config:device=/dev/disk/by-id/<scsi-xxxxxxxxxxxxxxxxxxxxxxxxx> host-uuid=<host-uuid> name-label=”Local Storage 2” shared=false type=lvm-
Or –
# xe sr-create content-type=user device-config:device=/dev/disk/by-id/<cciss-xxxxxxxxxxxxxxxxxxxxxxxxx> host-uuid=<host-uuid> name-label=”Local Storage 2” shared=false type=lvm

  • Cancel XenServer Tasks

xe task-list
xe task-cancel uuid=<task uuid>

  • Install XenTools on Linux

mount /dev/xvdd /mnt
cd /mnt/Linux
./install.sh

QLogic, run scli
Emulex, run hbanywhere
Emulex: /bin/sbin/ocmanager
QLogic FC: /opt/QLogic_Corporation/SANsurferCLI
QLogic iSCSI: /opt/QLogic_Corporation/SANsurferiCLI
Enable HA

  • xe vm-param-set uuid=<vm_uuid> ha-restart-priority=<1> ha-always-run=true
  • xe pool-ha-enable heartbeat-sr-uuids=<sr_uuid>

Reboot Host in HA

  • host-disable host=<hostname>
  • host-evacuate uuid=<host uuid>
  • host-shutdown host=<hostname>

Designate new master

  • Xe pool-designate-new-master host-uuid=<UUID of member XenServer host to become new master>

Pool Emergency Actions

  • host-emergency-ha-disable –force
  • pool-recovery-slaves
  • pool-eject host-uuid=<host UUID>
  • pool-emergency-reset-master master-address=<ip address of pool master>
  • pool-emergency-transition-to-master uuid=<host uuid>
  • xe pool-join master-address=<host1> master-username=<administrators_username> master-password=<password>

Snapshot Copy (Fast Clone)

  • xe snapshot-list snapshot-of=<vm uuid>
  • xe snapshot-copy new-name-label=<vm-template-name> snapshot-uuid=<uuid of the snapshot>
  • xe template-list
  • xe snapshot-export-to-template snapshot-uuid=<uuid of snapshot> filename=<template filename> (.XVA)
  • other-config snapmanager=true
  • xe vm-snapshot-with-quiesce vm=<vm uuid> ne-name-lablel=<name of new vm> (install-XenProvider.cmd)

Memory Consistent Snapshots

  • xe vm-checkpoint vm=<vm uuid> new-name-lable=<name of the snapshot>

Role Based Administration

  • xe subject-add subject-name=[active directory account name]
  • xe subject-role-add uuid=<subject uuid> role-name=<role_name>

Configure Management Interface

  • xe pif-scan, xe pif-list, xe pif-reconfigure-ip, xe host-management-reconfigure

Create NFS ISO Repository

  • xe sr-create host-uuid=<mast uuid> content-type=iso name-lable=<”name”> location=\\10.1.1.1:cds

Create a shared NFS SR on 192.168.1.10:/export1

  • xe sr-create host-uuid=<host_uuid> content-type=user name-label=<”Example shared NFS SR”> shared=true device-config:server=<192.168.1.10> device-config:serverpath=</export1> type=nfs

Physic NIC configuration

  • xe pif-scan
  • xe pif-plug
  • xe pif-introduce

VM in libo

  • xe vm-list
  • xe vm-reset-powerstate uuid=<uuid of VM> force=true

XAPI stack

  • service xapi status
  • service xapi restart
  • xe-toolstack-restart

XenServer Log Files

  • /var/log – XenServer Log Files
  • /etc/logrotate.conf – XenServer Log Rotation Configuration File

Search SR to locate metadata

  • xe sr-probe type=lvmoiscsi device-config:target=IP device-config:targetIQN=IQN device-config:SCSIid=SCSIID sm-config:metadata=true

Check VDI database

  • xe vm-list database:vdi-uuid=$my_vdi

Check inventory

  • . /etc/xensource-inventory
  • xe host-list uuid=$INSTALLATION_UUID

Exporting and Importing VMs via API – http://docs.vmd.citrix.com/XenServer/5.6.0fp1/1.0/en_gb/sdk.html#vm_import_and_export

  • curl http://root:foo@myxenserver1/export?uuid=<vm_uuid> -o <exportfile>
  • curl -T <exportfile> http://root:foo@myxenserver2/import?sr_uuid=<uuid_of_sr>
  • curl -T <exportfile> http://root:foo@myxenserver2/import
  • http://server/import_metadata
  • http://server/export_metadata.

MySQL Tips

Aqui os dejo una pequeña Cheat Sheet con muchos MySQL Tips (Spaninglish owned :D)

MySQL : Crear una base de datos

Crear una base de datos:

$ mysql
mysql > show databases;
mysql > create database joomla;
mysql > use database joomla;

o bien:

$ mysqladmin create joomla

Si es necesario un encoding en particular se necesitan definir el character set y el collate:

  • En ISO:
    mysql > create database joomla character set latin1 collate
    latin1_spanish_ci;
  • En UTF8:
    mysql > create database joomla character set utf8 collate
    utf8_general_ci;

MySQL: Borrar una base de datos

Borrar bases de datos:

$ mysql
mysql > show databases;
mysql > drop database joomla;

o bien:

$ mysqladmin drop joomla

MySQL: Hacer un dump de la base de datos

$ mysqldump -h localhost -u root -p joomla > joomla.sql

donde joomla es la base de datos, root es el usuario de la base datos y localhost el servidor de la base de datos.

MySQL: Importar una base de datos

$ mysql
mysql> create database joomla;
mysql> use joomla
mysql> source joomla.sql

o bien:

$ mysql -u root -p --database=joomla < joomla.sql

MySQL: Importar tablas de una base de datos

$ mysqldump --user=root joomla jos_core_acl_aro jos_core_acl_groups_aro_map jos_users > jos_users.sql

MySQL: Importar la estructura de base de datos

$ mysqldump --no-data --user=root joomla > joomla.sql

MySQL: Vaciar una tabla

$ mysql
> use joomla;
> truncate table jos_users;

MySQL: Cómo generar los scripts individuales para las tablas de una base de datos

El script generate-mysql-tables-scripts.sh

Nota: el usuario es root y no tiene contraseña.

 ~/tmp $ cat generate-mysql-tables-scripts.sh
DATABASE=$1
for i in `echo "use $DATABASE; show tables;" | mysql -u root|grep -v "Tables_in"`
        do
                echo "Dumping $i"
                mysqldump -u root $DATABASE $i > $i.sql
        done

De este modo:

 ~/tmp $ generate-mysql-tables-scripts.sh zyf
Dumping ...
Dumping
.
.
.

MySQL: Importar una base de datos desde un fichero CSV

$ mysql
> load data local infile 'users.csv' into table `jos_users`
> fields terminated by ','
> optionally enclosed by '"'
> lines terminated by '\n\r';

Especificamos que el contenido se encuentra en el servidor, en un fichero llamado users.csv

> local infile 'users.csv'

que los campos se separan mediante comas:

> fields terminated by ','

que el contenido puede estar entrecomillado, y de ser así el contenido se pasará a la BD sin comillas (o en su defecto sin el símbolo especificado en el comando). Si quisiéramos pasar el contenido a la BD con comillas y todo, no especificaríamos esta opción.

> optionally enclosed by '"'

especificando cual es el carácter que señaliza el final de una línea, de no tener nada que marque el fin de una línea omitiríamos esta opción.

> lines terminated by '\n\r'

MySQL: Exportar a CSV una select

Desde la consola de mysql:

> select * from joomla.jos_users into outfile '/tmp/filename.csv'
fields terminated by ',' lines terminated by '\n';

o desde la terminal:

$ mysql -u root joomla -B -e \
"select \* from users " | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > filename.csv

MySQL: Cambiar la contraseña de root en mysql

A todos nos ha pasado alguna vez ir a modificar algo en nuestro servidor MySQL y encontrarnos con:

ERROR 1045: Access denied for user: 'root@localhost' (Using password: YES)

Aquí está la receta:

$ killall mysqld
$ /usr/sbin/mysqld --skip-grant-tables &
$ mysql -u root mysql
mysql> UPDATE mysql.user SET Password=PASSWORD('') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> EXIT
$ killall mysqld
$ /usr/sbin/mysqld &

Si se conoce la contraseña anterior sólo sería necesario:

mysql> set password for 'root'@'localhost' = password('');

o en su defecto:

$ mysql -u root mysql
mysql> UPDATE mysql.user SET Password=PASSWORD('') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> EXIT

MySQL: Listado de privilegios de MySQL

En la siguiente http://dev.mysql.com/doc/refman/5.0/es/privileges-provided.html página de documentación de MySQL se listan y explican en castellano todos los privilegios de MySQL.

MySQL: Dar privilegios a usuario en una base de datos

Para dar privilegios a un usuario sobre una base de datos ejecutaremos el siguiente comando, en el ejemplo le damos todos los permisos que una base de datos tiene, la sintaxis queda debajo:

$ mysql -u root -p
mysql> grant all on joomla.* to joomla identified by 'joomla';

Donde el primer joomla.* es la base de datos, el segundo el nombre de usuario y por ultimo la contraseña:

mysql> grant all on nombre_de_la_basededatos.* to nombre_usuario identified by ‘contraseña’;

Por último, actualizamos los privilegios:

mysql> flush privileges;

Ya podremos entrar en la base de datos usando el usuario y la contraseña asignada;

$ mysql -u joomla -p

Mostrar privilegios de un usuario de MySQL

mysql> show grants for usuario;

Quitar privilegios a un usuario de MySQL

mysql> revoke privilegio on basededatos.table from usuario;

Mostrar host y usuarios de MySQL

mysql> use mysql;
mysql> select host,user from user;

Eliminar un usuario de MySQL

mysql> drop user usuario;

Permitir acceso remoto a MySQL

Editar el fichero /etc/mysql/my.cnf y comentar la línea: bind-address = 127.0.0.1

vi /etc/mysql/my.cnf
# bind-address          = 127.0.0.1

Después tendríamos que crear usuarios utilizando la siguiente sentencia:

> grant all on basededatos.tabla to usuario@'dirección_ip' identified by 'contraseña';

Ejemplos

Sentencia para establecer permisos en la tabla table de la base da datos database para el usuario user desde el host de la dirección IP 192.168.10.10 con la contraseña password:

> grant all on database.table to user@'192.168.10.10' identified by 'password';

Sentencia para establecer permisos en todas las tablas de la base de datos database para el usuario user desde un host que tiene cualquier dirección IP y sin contraseña:

> grant all on database.* to user@'%';

Modificar codificación del servidor MySQL

Podemos ver la codificación de MySQL mediante el comando:

> show variables;

En este ejemplo vamos a cambiar la codificación a UTF-8. Para ello haremos lo siguiente:

$ vi /etc/mysql/my.cnf

Buscaremos la sección mysqld y después añadiremos las siguientes líneas.

And add these lines under it:

# utf8
init-connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_general_ci

Una vez hecho esto sólo nos queda reiniciar el servicio.

/etc/init.d/mysql stop
/etc/init.d/mysql start

Comprobar codificación de una tabla

mysql> SHOW CREATE DATABASE `prueba`;
+----------+-------------------------------------------------------------------+
| Database | Create Database                                                   |
+----------+-------------------------------------------------------------------+
| prueba   | CREATE DATABASE `prueba` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-------------------------------------------------------------------+
1 row in set (0.00 sec)

Modificar codificación de una tabla

> ALTER TABLE tabla CONVERT TO CHARSET charset COLLATE collation;

Por ejemplo:

> ALTER TABLE tabla CONVERT TO CHARSET latin1 COLLATE latin1_spanish_ci;

Variables de mysql

$ mysqladmin variables
$ mysqladmin variables | grep datadir
| datadir                         | /var/lib/mysql/             |

Errores comunes

ERROR 1005 (HY000) at line 1: Can’t create table ‘./joomla/jos_users.frm’ (errno: 150)

‘Explicación:

Es un error que puede surgir al importar una base de datos.

Debe de haber algún error en la comprobación de Foreign Keys.

‘Solución:

Añadir la siguiente línea al principio del fichero .sql:

> SET FOREIGN_KEY_CHECKS = 0;

Y después la siguiente línea al final del fichero .sql:

> SET FOREIGN_KEY_CHECKS = 1;

Si sabéis o quereis saber mas pequeños tips de mysql y quereis que los añada aqui hacer un comentario y lo añado 😀