We have just published a hotfix for Windows Virtual PC that addresses a compatibility problem when trying to install on an AMD Bulldozer system.
You can download it here: http://support.microsoft.com/kb/2519949
Cheers,
Ben
We released a new hotfix for Hyper-V today.
This hotfix addresses an issue where virtual machines may crash (with a STOP 0x000000D1, DRIVER_IRQL_NOT_LESS_OR_EQUAL error) when it is being live migrated. While this problem is relatively hard to encounter – I would encourage anyone who is using live migration to plan to deploy this hotfix in the near future, as you do not want to hit this accidentally.
You can download this fix directly from here: http://support.microsoft.com/kb/2636573
Alternatively, it is also being distributed through Windows Update. Unfortunately it is only available as an optional update though – so you will need to explicitly select to install it on your servers.
Either way, this hotfix does require that you reboot the physical server so you will need to plan the deployment of the fix appropriately for your environment.
Cheers,
Ben
Today we released a fix for to resolve an issue that can lead to guest VM’s crashing after a live migration. This issue only impacted virtual machines that where utilizing virtual SCSI controllers and was only seen under some specific stress conditions however if you have VM’s with SCSI controllers and utilize live migration than I would recommend investigating and installing this hotfix.
http://support.microsoft.com/kb/2636573
Article ID: 2636573 - Last Review: January 10, 2012 - Revision: 1.0
FIX: The guest operating system may crash when you perform a live migration of Hyper-V virtual machines in a Windows Server 2008 R2 environmentSymptoms
In a Windows Server 2008 R2 environment, you perform a live migration of Hyper-V virtual machines. In this scenario, the guest operating system may crash. Additionally, you receive a Stop error message that resembles the following:
STOP 0x000000D1 (parameter1, parameter2, parameter3, parameter4)
DRIVER_IRQL_NOT_LESS_OR_EQUAL
To resolve this problem, install this update on the host computer where the Hyper-V virtual machines are located.
Update information To resolve this problem, install this update from Microsoft Windows Update (http://update.microsoft.com) .Download the update package now. (http://www.microsoft.com/downloads/details.aspx?FamilyId=06c9e6e0-26de-44dc-a2e7-6a87fe0d5e76)
Release Date: January 10, 2012
For more information about how to download Microsoft support files, click the following article number to view the article in the Microsoft Knowledge Base:
119591 (http://support.microsoft.com/kb/119591/ ) How to obtain Microsoft support files from online services
Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help prevent any unauthorized changes to the file.
Prerequisites To apply this hotfix, you must be running Windows Server 2008 R2 Service Pack 1 (SP1).976932 (http://support.microsoft.com/kb/976932/ ) Information about Service Pack 1 for Windows 7 and for Windows Server 2008 R2
Registry information To use the hotfix in this package, you do not have to make any changes to the registry. Restart informationYou must restart the computer after you apply this hotfix.
Taylor Brown
Hyper-V Enterprise Deployment Team
taylorb@microsoft.com
http://blogs.msdn.com/taylorb
My last challenge for getting all of my server virtual machines over to fixed-size virtual hard disks is moving some of my Windows Server 2008 R2 virtual machines. As a reminder, the goal here is to move a virtual machine on a large dynamically expanding virtual hard disk to a smaller fixed-size virtual hard disk. I have used the same technique as I discussed here – but for obvious reasons the process is quite different, as I cannot use any of the GUI tools. Here is the process I followed:
Once this is all complete, and once you have confirmed that the virtual machine is working properly, you can delete the dynamically expanding disk and the backup.
Cheers,
Ben
Yesterday I showed you how to easily convert a dynamically expanding virtual hard disk to a fixed size virtual hard disk. But, how do you do this if you want to keep your fixed size virtual hard disk as small as possible? Well, here is the process that I use for my Windows Server 2008 R2 virtual machines:
Once this is all complete, and once you have confirmed that the virtual machine is working properly, you can delete the dynamically expanding disk and the backup.
Cheers,
Ben
As I discussed yesterday – I have been working on converting my virtual machines from dynamic virtual hard disks to fixed virtual hard disks. There are a couple of ways that you can do this. The easiest way is to just convert the disks using Hyper-V. To do this you need to:
While this process is fairly easy to follow – it has one big drawback. The fixed virtual hard disk will take up the maximum space of the dynamically expanding virtual hard disk. For some of my virtual machines I had created small dynamically virtual hard disks, so this worked well. But for some of them I had created foolishly large dynamically expanding virtual hard disks.
Tomorrow I will document the process that I used for these virtual machines.
Cheers,
Ben
I have had a couple of days off for Christmas, and once the children were happily playing with their new presents, my mind naturally turned to some outstanding server maintenance that I needed to do.
Top of my list was completing the process of switching all of my servers over to fixed virtual hard disks.
There are two reasons why you should use fixed virtual hard disks in production environments:
Given that my servers are only used by me and my family – performance is not a big concern. And for a long time now I have been using dynamically expanding virtual hard disks for all my server virtual machines. But recently I had a big problem. One of my virtual machines started chewing up huge amounts of space. The result was that my Hyper-V server ran out of space and paused all of my virtual machines (to stop any of them from crashing). When this happened I did some emergency space management, but left most of the virtual machines still using dynamic virtual hard disks.
Converting a virtual machine from a dynamic virtual hard disk to a fixed virtual hard disk can be quite tricky. So this week I am going to blog about some of the tips-and-tricks that I have picked up in the process of switching over to fixed virtual hard disks.
Cheers,
Ben
Last week I was asked, on Twitter, if it was possible to publish a built in application (like Internet Backgammon) from Windows XP mode. The answer is: Yes, but it is a little tricky.
Most people use Windows XP mode to run specific applications that they have that will not run under Windows 7. These people do not want to have their start menus cluttered with all the applications that populate the Windows XP menu – they just want to access their applications. For this reason, we block publishing of all of the built in applications in Windows XP – but you can unblock them.
To test this out – I published Internet Backgammon on one of my systems. The process that you need to follow is this:
After doing this – the application will appear in the Windows 7 start menu:
And you can run it as an integrated application:
Cheers,
Ben
In Windows Vista we introduced “BitLocker” to Windows – a native full disk encryption technology for Windows. Most people immediately saw the potential for BitLocker on laptops. Encrypting your laptop meant that if you were ever unfortunate enough to lose your laptop (through theft or forgetfulness) you would not have to worry about someone else getting access to your data.
But today I would like to explain to you why you want to use BitLocker on your servers too. All of your servers.
Recently, I had a hard disk fail in one of my servers. This happens from time to time, and thanks to RAID it was not a big deal. I just bought a new drive, popped out the old drive, put in the new one, rebuilt the array and I was off and running.
But now I have a problem: what do I do with the old drive?
It’s broken. So broken that it is hard to delete the data that is on there – but there is data on there none the less. And despite how unlikely it is that anyone will ever look at it – I am not entirely comfortable with just dropping it in the trash. Personally, I have had the experience of connecting a broken drive that had been sitting on the shelf for a couple of months and finding that it would work for a couple of hours before failing again. It is plausible to imagine that someone might find my old drive and hook it up just to see if it worked.
So how do I get rid of that data?
Drives these days are quite hard to destroy. I have tried to pull them apart manually, I have hit them with a hammer, I have even driven a car over one. They are surprisingly rugged. You could sit magnets on them – but you won’t know how effective it has been. Microwaving the drive should be quite good – but would probably damage the microwave as well. Besides, there is a much simpler solution: use BitLocker.
Once you have enabled BitLocker on a server – your data is now protected, even if the disk fails. Especially when the disk fails. With BitLocker on you can take that failed hard disk and drop it in the bin with no concern of anyone ever getting data off of it.
Happy times.
Cheers,
Ben
Over the weekend I reconfigured one of my main servers. As part of this process – I had to make some large fixed virtual hard disks (800-1600GB in size). This took a long time…
I spent quite some a while looking at this screen…
In the past I have talked about why this takes a long time and I have also talked about a tool that is available that can make fixed virtual hard disks quickly. So you may be wondering why I would still create virtual hard disks the slow way.
Well – there are two reasons:
In my opinion – when it comes to production systems, sometimes it is just worth taking the time to do things properly.
Cheers,
Ben
Hopefully what I am about to say is not news to you – but it is worth saying: data protection systems that have not been tested are useless. Whether you are backing up computers, using RAID or replicating data – the first thing you need to do once you have everything setup is to test that you are actually getting the data protection you think you are getting, and that you can actually recover from a problem.
Too often, people setup data protection systems and believe everything is fine – until they need to recover lost data. Then they discover that:
So for this reason – I always test my data protection systems. To make sure that they are working, and that I actually know how to use them.
Ordinarily – I use a combination of Windows backup and hardware RAID1 in my home environment. I know my hardware RAID systems like the back of my hand – and have frequently tested my backups by restoring them into a handy virtual machine (just to confirm that everything is still working). However, recently I bought some new hard disks that did not approve of my older RAID controller. After some thought and investigation – I decided that the easiest (and cheapest) solution would be to setup a software mirror using Windows.
The problem with this is that it has been a long time since I used software mirroring in Windows. “Dynamic versus basic disks”, “foreign disks”, “pack IDs” are all terms that I could remember – and I could remember that it could be a little tricky. I needed more confidence than that to trust my data to this.
Virtual machines to the rescue!
It took me about an hour to:
All of this went well – and I was soon setting up my software mirror on hardware, with complete confidence in what I was doing.
Cheers,
Ben
Hola
La cantidad de novedades y funcionalidades que se van a introducir en Windows Server 8 hacen complicado resumirlas en un solo post. Para aquellos de vosotros que estéis interesados, os recomiendo empezar por el Whitepaper o por los posts que se publican en los blogs de los grupos de producto y ampliar información en las presentaciones y videos del evento Build que se hizo en Septiembre:
Como veis hay sustanciales mejoras y novedades en las capas de almacenamiento y red, diseñadas obviamente para facilitar la introducción de nuevas funcionalidades en las capas de gestión y virtualización y alta disponibilidad. Algunas de ellas ya están presentes en los binarios de la Preview, disponible para subscriptores a MSDN
Saludos
Yesterday we released a new version of the Linux Integration Services for Hyper-V. You can download them directly from here: http://www.microsoft.com/download/en/details.aspx?id=28188
Some key changes / new features to call out are:
For more details, check out the link and read the documentation.
Cheers,
Ben
Hola
Me entero por este post de Miguel que se ha actualizado este e-book a las versiones correspondientes a Windows Server 2008 R2, y que se puede descargar gratuitamente desde aquí:
Echándole un vistazo por encima se me ha ocurrido coger los capítulos del índice, y enlazarlos con algunos contenidos de la TechNet Library, TechCenters y “landing pages”, siempre más completos y actualizados:
Saludos
Hola
El proceso de exportación de una máquina virtual consiste en el “empaquetado” de todos los ficheros que conforman una máquina virtual y su copia a un cierto path dentro del host en el que se lleva a cabo la acción. El proceso, que debe llevarse a cabo con la máquina detenida, no la modifica ni la destruye, y tiene por objeto el poder trasladar la máquina, manual o automatizadamente, a otro host para recuperarla posteriormente en caso de, por ejemplo, haber querido prescindir de ella o ante la necesidad de reinstalar un host. Este mecanismo de exportación/importación que podemos llevar a cabo en el Hyper-V Manager está detrás de algunas acciones que están disponibles en System Center Virtual Machine Manager, como llevarnos la máquina virtual a la librería o mover máquinas entre hosts stand-alone (no clusterizados). En ellos, la máquina virtual se exporta, se copia a una carpeta compartida de la librería o al host destino donde se importará, y por último se borra la máquina virtual en el origen.
En la primera versión de Hyper-V existía una casilla para exportar únicamente la configuración de la máquina virtual. La idea era poder importar la VM posteriormente, asumiendo que los discos virtuales, snapshots y ficheros de estado no se han visto alterados en el almacenamiento. Esta es la alternativa purista y soportada a registrar a mano en Hyper-V una máquina virtual a partir de su fichero de configuración, y lo que debería estar detrás de cualquier estrategia de recuperación de desastres que emprendamos en base a replicas del almacenamiento (técnicas de backup/restore aparte, o mejor dicho, además)
En Hyper-V R2 e Hyper-V R2 SP1 esa opción desapareció de la interfaz gráfica, quedándonos como alternativa el hacerlo desde programación o scripting. Aquí tenéis la información más relevante al respecto:
Las APIs
Aunque esto está bastante bien explicado en los enlaces segundo y último de los mencionados arriba, vamos a hacer un pequeño resumen. Los métodos de exportación e importación están definidos en la clase Msvm_VirtualSystemManagementService como ExportVirtualSystemEx e ImportVirtualSystemEx respectivamente. ExportVirtualSystemEx utiliza como parámetro una instancia de la clase Msvm_VirtualSystemExportSettingData para representar a la máquina virtual que se quiere exportar, mientras que ImportVirtualSystemEx utiliza como parámetro una instancia de la clase Msvm_VirtualSystemImportSettingData, que se obtiene mediante una llamada al método GetVirtualSystemImportSettingData. Si miramos la definición de las clases, observaremos que la correspondiente a la importación es más rica en posibilidades de la de exportación:
class Msvm_VirtualSystemExportSettingData : CIM_SettingData
{
string Description;
string Caption;
string InstanceID;
string ElementName;
boolean CopyVmStorage;
boolean CopyVmRuntimeInformation;
boolean CreateVmExportSubdirectory;
uint8 CopySnapshotConfiguration;
string SnapshotVirtualSystem;
};
Es decir, que al exportar podemos decir si queremos copiar los VHDs, si queremos crear una subcarpeta en el path indicado para la exportación con el nombre de la VM, si queremos guardar su estado de ejecución y si queremos almacenar también la información de snapshots. Poniendo estos valores a True o False podemos controlar que parte de la VM queremos llevarnos al directorio de exportación. Exportar solo la configuración de la VM supone, de entrada, poner a CopyVmStorage = False
Sin embargo, lo anterior tiene un efecto colateral. Al generar el .exp, y pese a que almacenamos los paths originales de los VHDs, no los seguimos considerando como válidos, ya que no tenemos la certeza de que al importar sigan en el mismo sitio. Lo mismo sucede con las snapshots y con los las conexiones a los switches virtuales. Manejaremos esa situación en la clase que gobierna el proceso de importación:
class Msvm_VirtualSystemImportSettingData : CIM_SettingData
{
string Description;
string Caption;
string InstanceID;
string ElementName;
boolean GenerateNewId;
boolean CreateCopy;
string Name;
string SourceVmDataRoot;
string SourceSnapshotDataRoot;
string SourceVhdDataRoot;
string TargetVmDataRoot;
string TargetSnapshotDataRoot;
string TargetVhdDataRoot;
string SecurityScope;
string CurrentResourcePaths[];
string SourceResourcePaths[];
string TargetResourcePaths[];
string SourceNetworkConnections[];
string TargetNetworkConnections[];
};
La clave esta en manejar los parámetros CreateCopy, Current*, Source* y Target* en función del significado que tienen cada uno, que podéis encontrar en los enlaces de arriba. Como vemos, algunos de ellos son arrays, donde se almacenan todos los paths de todos los VHDs que puede tener la máquina virtual. en función de la situación a manejar y de nuestras intenciones deberemos de manejarlos de manera acorde. Pero de entrada, pensemos que los paths que dejamos en el .exp al exportar sin copiar los VHDs se encuentran almacenados en SourceResourcePaths
Hasta aquí un resumen de la teoría. Deberíamos de haber dejado claro que exportar es fácil, e importar tiene sus consideraciones, sobre todo si las letras de unidad/paths de los VHDs y los nombres de los switches van a cambiar. Aquí reside la dificultad, pero también abre un buen abanico de posibilidades
Script para Exportar solo la configuración de la máquina virtual en Powershell
Para evitar que mi compañero Ben me acuse de plagio, y porque dado que todo System Center maneja mejor Powershell que vbscript, vamos a ver un ejemplo para exportar solamente la configuración de una máquina virtual en powershell. Simplemente usamos como parámetros el nombre de la máquina virtual y el path donde crearemos una subcarpeta con dicho nombre para almacenar la información de exportación, sin los VHDs. En amarillo lo importante:
# ExportVMConfig.ps1
# Usage: ./ExportVMConfig.ps1 <VMName> <Path to store export dir>
# Example: ./ExportVMConfig.ps1 "Test" "d:\vmexports"
param([parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $VMName, [parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $expDir)
# Get VM, VMMS & Export Settings Objects
$ns = 'root\virtualization'
$vmms = gwmi -n $ns Msvm_VirtualSystemManagementService
$vm = gwmi -n $ns Msvm_ComputerSystem | ?{$_.ElementName -eq $VMName}
$exp = @($vm.GetRelated('Msvm_VirtualSystemExportSettingData'))[0]
# Don't Export VHDs & saved state data. Create a folder for VM's export data
$exp.CopyVmStorage = $false
$exp.CopyVmRuntimeInformation = $false
$exp.CreateVmExportSubdirectory = $true
#Perform Export
$out = $vmms.ExportVirtualSystemEx($vm.Path.Path, $expDir, $exp.GetText(1))
#Perform Job handling if necessary
if ($out.ReturnValue -eq 4096){
$task = [Wmi]$out.Job;
while($task.JobState -eq 3 -or $task.JobState -eq 4){
$task.Get();
sleep 1;
}
if ($task.JobState -ne 7){
"Error exporting VM " + $task.ErrorDescription;
}
else {
"Export completed successfully..."
}
}
elseif ($out.ReturnValue -ne 0) {
"Export failed with error : " + $out.ReturnValue;
}
else {
"Export completed successfully..."
}
Si estamos haciendo esto como parte de una estrategia de recuperación ante desastres, ni que decir tiene que lo siguiente es poner ese path de exportación a buen recaudo, tal y como estaremos haciendo con los datastores que almacenan los VHDs. Generalmente esto se hace en base a alguna tecnología de replicación de almacenamiento, porque para copiar los contenidos de la VM a través e la red, lo mejor será usar la vía de la copia de seguridad en base a la tecnología VSS.
Script para Importar solo la configuración de la máquina virtual en Powershell
Para importar la máquina virtual, debemos especificar lógicamente el path donde reside el fichero con la información, es decir. el .exp. Es muy importante darse cuenta de que, si no se usa el parámetro CreateCopy, y en este caso no lo podemos utilizar ya que no tenemos VHDs que copiar, la máquina virtual pasa a residir en ese mismo path, y además el .exp desaparece en favor del .xml resultante. Esto tiene dos efectos. Que no podemos volver a usar la información exportada, y que la máquina virtual se queda en un path que seguramente nosotros considerábamos temporal. La idea es copiar la información de exportación “cerca” de donde residan los VHDs, de manera que todos los componentes de la máquina virtual queden lo mas ordenados posibles
Así es que lo que vamos a usar como parámetros va a ser el nombre de la VM, el path a donde residen los ficheros de exportación y el path a donde queremos copiarlos. La importación se realizará realmente desde este último, que debería de coincidir con el path original que tenía la máquina virtual exportada. Cualquier cambio en esta lógica no debería ser un gran problema, como tampoco una manipulación más personalizada de los paths. Esto quizás merecería el desarrollo de una interfaz gráfica con un explorador de ficheros. Ahí dejo la idea)
# ImportMConfig.ps1
# Usage: ./ImportVMConfig.ps1 <VMName> <Path to export dir> <path to place VM Configuration Files>
# Example: ./ImportVMConfig.ps1 "Test" "d:\vmexports" "D:\VirtualMachines"
param([parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $VMName, [parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $expDir, [parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $VMdestdir)
# Copy export data from export dir to the path where VM's files will reside, and perform the import from there
Copy-Item $expdir"\"$VMName -Destination $VMdestdir -recurse -ea "silentlycontinue"
# Get VM, VMMS & Export Settings Objects
$ns = 'root\virtualization'
$vmms = gwmi -n $ns Msvm_VirtualSystemManagementService
$SettingData = $vmms.GetVirtualSystemImportSettingData($VMdestdir+"\"+$VMName).ImportSettingData
# Do not try to copy de VHDs, as we didn't exported them
$SettingData.CreateCopy = $False
# Copy CurrentResourcePaths to SourceResourcePaths, as we assume paths has not changed
$SettingData.SourceResourcePaths = $SettingData.CurrentResourcePaths
# Do the Import VM config Only
$out=$vmms.importVirtualSystemEx($VMdestdir+"\"+$VMName, $SettingData.PSBase.GetText("CimDtd20") )
#Perform Job handling if necessary
if ($out.ReturnValue -eq 4096){
$task = [Wmi]$out.Job;
while($task.JobState -eq 3 -or $task.JobState -eq 4){
$task.Get();
sleep 1;
}
if ($task.JobState -ne 7){
"Error Importing VM " + $task.ErrorDescription;
}
else {
"Import completed successfully..."
}
}
elseif ($out.ReturnValue -ne 0) {
"Import failed with error : " + $out.ReturnValue;
}
else {
"Import completed successfully..."
}
No me meto en el jardín de llevar a cabo estas tareas sobre sistemas remotos. Digamos que en ambos scripts simplemente tendríamos que agregar el parámetro correspondiente al nombre del host remoto y agregarlo como valor del parámetro –computer en las llamadas a Get-WMIObject (p.e. gwmi –computername $hostremoto…).
DISCLAIMER: Los presentes scripts solamente han sido probados por mi, en un entorno de pruebas, y por tanto su correcto funcionamiento en cualquier situación no está garantizado. Aunque he intentado capturar gran parte de las posibles excepciones, estoy seguro de que puede haber situaciones que no estén contempladas. Si planteáis incluir estos scripts en vuestro maletín de herramientas, por favor, probadlos bien, y enviad cualquier problema o mejora que consideréis pertinente.
NOTA 1: Ardo en deseos de ver lo que es capaz de hacer con esto mi compañero Daniel Matey en base a workflows de DR de Opalis/System Cenyter Orchestrator
NOTA 2: Algo similar a esto es lo que está detrás a soluciones del tipo Snapshot+Remotecopy a nivel de almacenamiento como SnapMirror de NetApp (OnCommand Plug-in for Microsoft)
Saludos
Hola
En este post vamos a tratar un procedimiento, que deberíamos intentar evitar tener que llevar a cabo en la medida de lo posible, pero que en ocasiones puede llegar a ser el último recurso que nos quede para recuperar el estado de una máquina virtual sin tener que volverla a montar de nuevo a partir de los discos virtuales. En abril de 2008 ya tratamos este tema para la primera versión de Hyper-V, y aunque la esencia sigue siendo la misma, aquel procedimiento ya no resulta válido para ni para Hyper-V 2008 R2 ni para Hyper-V 2008 R2 SP1. Este es el enlace al post original, y ya en los comentarios alguno de vosotros proponíais soluciones para las versiones actuales.
Anatomía de una máquina virtual
A grandes rasgos, una máquina virtual en Hyper-V se compone de:
Problema: la configuración por defecto de Hyper-V tiende a desligar los ficheros de configuración de los discos virtuales almacenándolos en diferentes carpetas, y además lo hace por intrincadas ramas del árbol de directorios de C:\. (C:\ProgramData\Microsoft\Windows\Hyper-V y C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks). A mi personalmente me suele gustar cambiar esto en el Hyper-V Manager para que toda máquina virtual que se cree por defecto en base al asistente lo haga en un punto que esta bajo control, si es posible en otra unidad que no sea la de sistema. Es decir cambiar de:
a:
Si utilizas System Center Virtual Machine Manager, o el proceso de Export/Import que veremos en el próximo post, las máquinas virtuales quedan perfectamente ordenaditas en una cierta carpeta. Algo a lo que deberíamos tender cuando las creamos con el asistente del Hyper-V Managera. Para ello basta con marcar esta casilla, que genera una subcarpeta con el nombre de la máquina virtual dentro del path especificado, y donde luego tendemos también la precaución de colocar los VHDs:
Para cerrar este capítulo, y aunque no venga mucho al caso, este asistente gasta otra pequeña broma, que a la larga seguramente pueda llegar a causar problemas. Los VHDs que se crean por defecto son dinámicos y de 127 Gb. Cuando nos damos cuenta de que los discos dinámicos penalizan el rendimiento y lo queremos pasar a fijo, se nos solicitan 127 GB de espacio libre en el datastore donde resida la máquina.
Enlaces simbólicos y permisos
Cuando se genera una máquina virtual, o cuando se llevan a cabo snapshots, sucede lo siguiente:
Todo esto es fácilmente comprobable en cualquier máquina virtual que tengáis creada sobre Hyper-V. El Hyper-V Manager, o mejor dicho el servicio de gestión de máquinas virtuales que corre en la partición padre, solo considera máquinas las máquinas virtuales que tengan dichos enlaces simbólicos creados y los ficheros sobre los cuales tenga permisos. Si algo de esto se rompe, la VM desaparece de la consola, o no puede arrancar al intentar acceder a algún rincón de la configuración.
NOTA: Para probar esto y lo que viene a continuación, obviamente sobre una máquina virtual de prueba, no hay que borrarla del Hyper-V Manager, ya que esto eliminaría los ficheros de configuración. Bastará con borrar los hardlinks, y si se quiere probar del todo eliminar de los permisos el SID que quedará huérfano.
Recuperación de una máquina virtual que nunca fue exportada
Nos encontraremos en esta situación cuando hayamos perdido el host por alguna clase de fatalidad, o cuando nos encontremos ante la necesidad de usar una máquina virtual cuyos ficheros tenemos en su totalidad disponibles en el almacenamiento (p.e, un amigo te pasa un USB lleno de máquinas virtuales que tiene en uso en su entrono y que por tanto no se ha preocupado en exportar). En un escenario de Disaster Recovery habremos perdido todos los hosts pero contaremos con una réplica del almacenamiento. Esto debería de estar planificado de otra manera (existen los clusteres, las copias de seguridad…) , pero como último recurso, y antes de ponernos a crear todas las máquinas virtuales desde cero y reconectarlas a sus discos, podemos probar algo así. El script que proponemos a continuación asume que los paths donde se almacenan las máquinas virtuales no cambian. De ser así, tendríamos que, manual o automatizadamente, cambiarlos el contenido de los ficheros XML previamente al uso del script, o modificarlo para que nos vaya preguntando el nuevo path:
# RegisterVM.ps1 - Registers a Hyper-V’s VM that was not previously exported
# Usage: ./RegisterVM.ps1 <path to VM's xml file>
# Example: ./RegisterVM.ps1 "D:\VirtualMachines\test\Virtual Machines\D73AF4BF-3F52-4DE0-85BA-ADB457E31C37.xml"
param([parameter(Mandatory=$TRUE,ValueFromPipeline=$TRUE)] $VMXMLPath)
# Adding MKLINK function as CreateSymbolicLink
$signature = @"
using System;
using System.Runtime.InteropServices;
namespace System
{
public class MkLink
{
[DllImport("kernel32.dll")]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
}
}
"@
Add-Type -TypeDefinition $Signature
# Hard-coded default Virtual Machines and Snapshots paths in Hyper-V Host
$VMsLNKS = "C:\ProgramData\Microsoft\Windows\Hyper-V\Virtual Machines"
$SnapshotsLNKS = "C:\ProgramData\Microsoft\Windows\Hyper-V\Snapshots"
# Read VM's configuration file
Trap [System.Management.Automation.ErrorRecord] {write-host("File not found, or it is invalid") -Foregroundcolor Yellow; Break}
[xml]$VMCONFIG = get-content $VMXMLPath -EA Stop
# Get VM's XML file name and Service ID from VM's configuration file name. If you are using a localized version of Windows you must translate this string
$VMFile = [io.path]::GetFileName($VMXMLPath)
$VMPath = [io.path]::GetDirectoryName($VMXMLPath)
$ServiceID = "NT VIRTUAL MACHINE\"+$VMFile.Replace(".xml", "")
# Get VM's Name. If the attribute does not exist, we assume this is not a VM's XML Configuration file
if ($vmconfig.configuration.properties.name -eq "properties"){
write-host("The file does not look like a VM's XML file") -Foregroundcolor Yellow
Throw ("Now exiting")
}
$VMname = $vmconfig.Configuration.properties.name.Get_InnerText()
# Read available VM's storage
$Disks = $vmconfig.configuration.GetElementsByTagName("pathname")
# Create VM's Hard Link and set ACLs
write-host ("Rebuilding Hardlink") -Foregroundcolor Yellow
$hardlink=[system.MkLink]::CreateSymbolicLink($VMsLNKS+"\"+$VMFile,$VMXMLPath,0)
IF (!$hardlink){
write-host("Failed to create the hard link") -Foregroundcolor Yellow
}
# Wait 10 seconds until VMMS Service creates de NT VIRTUALMACHINE\VM ID user.
write-host ("Waiting for Service ID") -Foregroundcolor Yellow
Start-Sleep 10
write-host ("Securing Hard Link and VM's State files") -Foregroundcolor Yellow
icacls $VMsLNKS"\"$VMFile /grant $ServiceID":(F)" /L
icacls $VMPath /grant $ServiceID":(F)" /T
# Check whether Snapshots exists or not, and read them. Create their Hard Links and set ACLs
Trap [System.Management.Automation.RuntimeException] {write-host("Snapshots directory is not set in VM's XML configuration file") -Foregroundcolor Yellow ; Continue}
If ($vmconfig.configuration.global_settings.snapshots.list.size.Get_InnerText() -ne "0"){
write-host ("Rebuilding Snapshots") -Foregroundcolor Yellow
$Snapshotspath = $vmconfig.configuration.global_settings.snapshots.data_root.Get_InnerText()
$Snapshots = $vmconfig.configuration.GetElementsByTagName("guid")
foreach ($_ in $snapshots) {
if ($_.Get_InnerText()){
$snap = $_.Get_InnerText()+".xml"
[system.MkLink]::CreateSymbolicLink($SnapshotsLNKS+"\"+$snap,$Snapshotspath+"\Snapshots\"+$_.Get_InnerText()+".xml",0)
icacls $SnapshotsLNKS"\"$snap /grant $ServiceID":(F)" /L
icalcs $Snapshotspath /grant $ServiceID":(F)" /T
}
}
}
# Set ACLs for every VHD (not pass-through Disks)
write-host ("Rebuilding VHD Permissions") -Foregroundcolor Yellow
foreach ($_ in $Disks) {
if ($_.Get_InnerText().ToLower().Contains("vhd")){
$Disk = $_.Get_InnerText()
icacls $disk /grant $ServiceID":(F)"
}
}
write-host ("Done: Check Hyper-V Manager for the virtual machine") -Foregroundcolor Yellow
El script simplemente necesita como parámetro el path completo al fichero de configuración de la máquina virtual. A partir de aquí:
DISCLAIMER: El presente script solamente ha sido probado por mi, en un entorno de pruebas, y por tanto su correcto funcionamiento en cualquier situación no está garantizado. Aunque he intentado capturar gran parte de las posibles excepciones, estoy seguro de que puede haber situaciones que no estén contempladas. Si llegáis aquí desesperados por haber perdido alguna máquina importante, espero que os ayude a recuperarla o que la información del port os ayude a realizar los pasos manualmente. Si por el contrario os planteáis incluir este script en vuestro maletín de herramientas, por favor, probadlo bien, y enviad cualquier problema o mejora que consideréis pertinente.
Saludos
Hola
Durante las ultimas semanas se han puesto a disponibles para descarga las ultimas Release Candidates y Betas de todos los productos de la familia de System Center, que saldrán con la denominación común de System Center 2012
Release Candidates:
Betas:
Los tres enlaces principales a tener en cuenta son:
Con esto hay como para encerrarse varias semanas en el laboratorio, y salir como nuevo.
Saludos
Mike Neil has blogged about the Hyper-V Extensible Switch in Windows Server 8 over on the Server and Cloud Platform blog (here: http://blogs.technet.com/b/server-cloud/archive/2011/11/08/windows-server-8-introducing-hyper-v-extensible-switch.aspx).
This is something that I am actually quite excited about. Specifically – I am really interested to see what ideas other people are able to come up with around extending the capabilities of virtual networking.
As Mike mentions – we talked about this at //BUILD/ and you can watch the recording of the session here: SAC-559T
The highlight of this session for me was the number of partners that we already have looking for ways to build in new functionality here. Some of the partner solutions that were presented in this session include:
And this is just the beginning of what people are going to build here.
Cheers,
Ben
I spend far too much time in meetings these days. But I try to keep my Friday afternoons free of meetings – and often use this time to update my various servers and try out new configurations. Today it is time to rebuild some of my storage:
Specifically I am throwing a bunch of disks into one of my servers and setting up a storage space to play around with (you can learn more about spaces here: http://channel9.msdn.com/events/BUILD/BUILD2011/SAC-474T).
These days I find that the most common cause of performance issues in my virtualized environments is the storage subsystem. So I try to build systems with as much parallelism in the storage as possible – as I will be running dozens of virtual machines at the same time and a single disk just will not cut it for performance.
Cheers,
Ben
On Monday I posted a script for configuring virtual machine CPU scheduler settings. This script got me to thinking about another use for the virtual machine CPU reserve.
You see, it can also be used to ensure that you do not unintentionally start too many virtual machines at once.
If you were to set the CPU reserve on each virtual machine at 20% (or at 20,000 using the underlying API) then it is not possible to start extra virtual machines once you hit a ratio of 5 virtual processors for each physical processor. This is actually what System Center Virtual Machine Manager does to enforce limits on the system.
Here is a script that will do just that:
# Function for handling WMI jobs / return values Function ProcessResult($result, $successString, $failureString) { #Return success if the return value is "0" if ($result.ReturnValue -eq 0) {write-host $successString} #If the return value is not "0" or "4096" then the operation failed ElseIf ($result.ReturnValue -ne 4096) {write-host $failureString " Error value:" $result.ReturnValue} Else {#Get the job object $job=[WMI]$result.job #Provide updates if the jobstate is "3" (starting) or "4" (running) while ($job.JobState -eq 3 -or $job.JobState -eq 4) {write-host $job.PercentComplete "% complete" start-sleep 1 #Refresh the job object $job=[WMI]$result.job} #A jobstate of "7" means success if ($job.JobState -eq 7) {write-host $successString} Else {write-host $failureString write-host "ErrorCode:" $job.ErrorCode write-host "ErrorDescription" $job.ErrorDescription} } } # Prompt for the Hyper-V Server to use $HyperVServer = Read-Host "Specify the Hyper-V Server to use (enter '.' for the local computer)" # Prompt for the new CPU reservation $NewReservation = Read-Host "Specify the CPU reservation (from 0-100000)" # Get the management service $VMMS = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService -computername $HyperVServer # Get all VSSDs for non-snapshots $VSSDs = gwmi "MSVM_VirtualSystemSettingData" -namespace "root\virtualization" -computername $HyperVServer | ? {$_.SettingType -eq 3} foreach ($VSSD in $VSSDs) { # Get the related VM $VM = $VSSD.getRelated("MSVM_ComputerSystem") | select -first 1 # Get the processor setting data $ProcSetting = $VSSD.getRelated("Msvm_ProcessorSettingData") | select -first 1 # Update ProcSetting with the new value $ProcSetting.Reservation = $NewReservation # Apply the changes to the processor setting data back to the virtual machine $result = $VMMS.ModifyVirtualSystemResources($VM, $ProcSetting.GetText(1)) # Process the result $successMessage = "Updated processor scheduling settings on '" + $VM.ElementName + "'" $failureMessage = "Failed to update processor scheduling settings on " + $VM.ElementName + "'" ProcessResult $result $successMessage $failureMessage }If you run this script and specify “20000” then you will be able to run at a ratio of 5 virtual processors for each physical processor. If you run this script and specify “25000” then you will be able to run at a ratio of 4 virtual processors for each physical processor.
Note that this will not apply to any virtual machine snapshots, or to any newly created virtual machines, so it is a little fragile as a solution.
Cheers,
Ben