Exemplo n.º 1
0
        private static Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > InsertConfigDriveDisk(
            string configDriveIsoPath,
            TypedPsObject <VirtualMachineInfo> vmInfo,
            IPowershellEngine engine)
        {
            return
                (from dvdDrive in GetOrCreateInfoAsync(vmInfo,
                                                       l => l.DVDDrives,
                                                       drive => drive.ControllerLocation == 63 && drive.ControllerNumber == 0,
                                                       () => engine.GetObjectsAsync <DvdDriveInfo>(
                                                           PsCommandBuilder.Create().AddCommand("Add-VMDvdDrive")
                                                           .AddParameter("VM", vmInfo.PsObject)
                                                           .AddParameter("ControllerNumber", 0)
                                                           .AddParameter("ControllerLocation", 63)
                                                           .AddParameter("PassThru"))
                                                       )

                 from _ in engine.RunAsync(PsCommandBuilder.Create()

                                           .AddCommand("Set-VMDvdDrive")
                                           .AddParameter("VMDvdDrive", dvdDrive.PsObject)
                                           .AddParameter("Path", configDriveIsoPath))

                 from vmInfoRecreated in vmInfo.RecreateOrReload(engine)
                 select vmInfoRecreated);
        }
Exemplo n.º 2
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > CloudInit(
            TypedPsObject <VirtualMachineInfo> vmInfo,
            string vmConfigPath,
            VirtualMachineProvisioningConfig provisioningConfig,
            IPowershellEngine engine,
            Func <string, Task <Unit> > reportProgress
            )
        {
            var remove = await RemoveConfigDriveDisk(vmInfo, engine).BindAsync(u => vmInfo.RecreateOrReload(engine)).ConfigureAwait(false);


            if (provisioningConfig.Method == ProvisioningMethod.None || remove.IsLeft)
            {
                return(remove);
            }


            var configDriveIsoPath = Path.Combine(vmConfigPath, "configdrive.iso");

            await reportProgress("Updating configdrive disk").ConfigureAwait(false);

            await from _ in CreateConfigDriveDirectory(vmConfigPath).AsTask()
            select _;

            GenerateConfigDriveDisk(configDriveIsoPath, provisioningConfig.Hostname,
                                    provisioningConfig.UserData);

            return(await InsertConfigDriveDisk(configDriveIsoPath, vmInfo, engine));
        }
Exemplo n.º 3
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > Drives(TypedPsObject <VirtualMachineInfo> vmInfo,
                                                                                                           MachineConfig vmConfig,
                                                                                                           VMStorageSettings storageSettings,
                                                                                                           HostSettings hostSettings, IPowershellEngine engine, Func <string, Task> reportProgress)
        {
            if (storageSettings.Frozen)
            {
                return(Right <PowershellFailure, TypedPsObject <VirtualMachineInfo> >(vmInfo));
            }

            var currentCheckpointType = vmInfo.Value.CheckpointType;

            try
            {
                await(
                    //prevent snapshots creating during running disk converge
                    from _ in SetVMCheckpointType(vmInfo, CheckpointType.Disabled, engine).ToAsync()
                    //make a plan
                    from plannedDriveStorageSettings in Storage.PlanDriveStorageSettings(vmConfig, storageSettings, hostSettings, engine).ToAsync()
                    //ensure that the changes reflect the current VM settings
                    from infoReloaded in vmInfo.Reload(engine).ToAsync()
                    //detach removed disks
                    from __ in DetachUndefinedDrives(engine, infoReloaded, plannedDriveStorageSettings, hostSettings, reportProgress).ToAsync()
                    from infoRecreated in vmInfo.RecreateOrReload(engine).ToAsync()
                    from ___ in VirtualDisks(infoRecreated, plannedDriveStorageSettings, hostSettings, engine, reportProgress).ToAsync()

                    select Unit.Default).ToEither().ConfigureAwait(false);
            }
            finally
            {
                await SetVMCheckpointType(vmInfo, currentCheckpointType, engine).ConfigureAwait(false);
            }

            return(await vmInfo.Reload(engine).ConfigureAwait(false));
        }
Exemplo n.º 4
0
 public static Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > RenameVirtualMachine(
     IPowershellEngine engine,
     TypedPsObject <VirtualMachineInfo> vmInfo,
     string newName)
 {
     return(engine.RunAsync(PsCommandBuilder.Create()
                            .AddCommand("Rename-VM")
                            .AddParameter("VM", vmInfo.PsObject)
                            .AddParameter("NewName", newName)
                            ).BindAsync(u => vmInfo.RecreateOrReload(engine)));
 }
Exemplo n.º 5
0
 private static Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > RemoveConfigDriveDisk(
     TypedPsObject <VirtualMachineInfo> vmInfo,
     IPowershellEngine engine)
 {
     return(FindAndApply(vmInfo, l => l.DVDDrives,
                         drive => drive.ControllerLocation == 63 && drive.ControllerNumber == 0,
                         drive => engine.RunAsync(PsCommandBuilder.Create()
                                                  .AddCommand("Remove-VMDvdDrive")
                                                  .AddParameter("VMDvdDrive", drive.PsObject)))
            .Map(list => list.Lefts().HeadOrNone()).MatchAsync(
                None: () => vmInfo.RecreateOrReload(engine),
                Some: l => LeftAsync <PowershellFailure, TypedPsObject <VirtualMachineInfo> >(l).ToEither()));
 }
Exemplo n.º 6
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > Cpu(TypedPsObject <VirtualMachineInfo> vmInfo,
                                                                                                        Option <VirtualMachineCpuConfig> cpuConfig, IPowershellEngine engine, Func <string, Task> reportProgress)
        {
            return(await cpuConfig.MatchAsync(
                       None : () => vmInfo,
                       Some : async config =>
            {
                if (vmInfo.Value.ProcessorCount != config.Count)
                {
                    await reportProgress($"Configure VM Processor: Count: {config.Count}").ConfigureAwait(false);

                    await engine.RunAsync(PsCommandBuilder.Create()
                                          .AddCommand("Set-VMProcessor")
                                          .AddParameter("VM", vmInfo.PsObject)
                                          .AddParameter("Count", config.Count)).ConfigureAwait(false);

                    return await vmInfo.RecreateOrReload(engine).ConfigureAwait(false);
                }

                return vmInfo;
            }).ConfigureAwait(false));
        }
Exemplo n.º 7
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > Firmware(TypedPsObject <VirtualMachineInfo> vmInfo,
                                                                                                             MachineConfig config, IPowershellEngine engine, Func <string, Task> reportProgress)
        {
            if (vmInfo.Value.Generation < 2)
            {
                return(vmInfo);
            }

            return(await engine.GetObjectsAsync <VMFirmwareInfo>(PsCommandBuilder.Create()
                                                                 .AddCommand("Get-VMFirmware")
                                                                 .AddParameter("VM", vmInfo.PsObject))
                   .BindAsync(firmwareInfoSeq =>
                              firmwareInfoSeq.HeadOrNone()
                              .Match <Either <PowershellFailure, TypedPsObject <VMFirmwareInfo> > >(
                                  None: () => new PowershellFailure {
                Message = "Failed to get VM Firmware"
            },
                                  Some: s => s
                                  ))
                   .BindAsync(async firmwareInfo =>
            {
                if (firmwareInfo.Value.SecureBoot != OnOffState.Off)
                {
                    await reportProgress($"Configure VM Firmware - Secure Boot: {OnOffState.Off}")
                    .ConfigureAwait(false);


                    var res = await engine.RunAsync(PsCommandBuilder.Create()
                                                    .AddCommand("Set-VMFirmware")
                                                    .AddParameter("VM", vmInfo.PsObject)
                                                    .AddParameter("EnableSecureBoot", OnOffState.Off)).BindAsync(_ => vmInfo.RecreateOrReload(engine)
                                                                                                                 ).ConfigureAwait(false);
                    return res;
                }

                return await vmInfo.RecreateOrReload(engine).ConfigureAwait(false);
            }
                              ).ConfigureAwait(false));
        }
Exemplo n.º 8
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > NetworkAdapter(
            VirtualMachineNetworkAdapterConfig networkAdapterConfig,
            IPowershellEngine engine,
            TypedPsObject <VirtualMachineInfo> vmInfo,
            MachineConfig machineConfig,
            Func <string, Task> reportProgress)
        {
            var optionalAdapter = await GetOrCreateInfoAsync(vmInfo,
                                                             i => i.NetworkAdapters,
                                                             adapter => networkAdapterConfig.Name.Equals(adapter.Name, StringComparison.OrdinalIgnoreCase),
                                                             async() =>
            {
                await reportProgress($"Add Network Adapter: {networkAdapterConfig.Name}").ConfigureAwait(false);
                return(await engine.GetObjectsAsync <VMNetworkAdapter>(PsCommandBuilder.Create()
                                                                       .AddCommand("Add-VmNetworkAdapter")
                                                                       .AddParameter("Passthru")
                                                                       .AddParameter("VM", vmInfo.PsObject)
                                                                       .AddParameter("Name", networkAdapterConfig.Name)
                                                                       .AddParameter("StaticMacAddress", UseOrGenerateMacAddress(networkAdapterConfig, vmInfo))
                                                                       .AddParameter("SwitchName", networkAdapterConfig.SwitchName)).ConfigureAwait(false));
            }).ConfigureAwait(false);

            return(await optionalAdapter.BindAsync(_ => vmInfo.RecreateOrReload(engine)).ConfigureAwait(false));

            //optionalAdapter.Map(async (adapter) =>
            //{
            //    if (!adapter.Value.Connected || adapter.Value.SwitchName != networkConfig.SwitchName)
            //    {
            //        await reportProgress($"Connect Network Adapter {adapter.Value.Name} to switch {networkConfig.SwitchName}").ConfigureAwait(false);
            //        await engine.RunAsync(
            //            PsCommandBuilder.Create().AddCommand("Connect-VmNetworkAdapter")
            //                .AddParameter("VMNetworkAdapter", adapter.PsObject)
            //                .AddParameter("SwitchName", networkConfig.SwitchName)).ConfigureAwait(false);

            //    }
            //});
        }
Exemplo n.º 9
0
        public static async Task <Either <PowershellFailure, TypedPsObject <VirtualMachineInfo> > > VirtualDisk(
            VMDiskStorageSettings diskSettings,
            IPowershellEngine engine,
            TypedPsObject <VirtualMachineInfo> vmInfo,
            Seq <CurrentVMDiskStorageSettings> currentStorageSettings,
            Func <string, Task> reportProgress)
        {
            var currentSettings =
                currentStorageSettings.Find(x => diskSettings.Path.Equals(x.Path, StringComparison.OrdinalIgnoreCase) &&
                                            diskSettings.Name.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase));
            var frozenOptional = currentSettings.Map(x => x.Frozen);

            if (frozenOptional.IsSome && frozenOptional.ValueUnsafe())
            {
                await reportProgress($"Skipping disk '{diskSettings.Name}': storage management is disabled for this disk.").ConfigureAwait(false);

                return(vmInfo);
            }



            return(await diskSettings.AttachPath.Map(async (vhdPath) =>
            {
                if (!File.Exists(vhdPath))
                {
                    await reportProgress($"Create VHD: {diskSettings.Name}").ConfigureAwait(false);

                    var createDiskResult = await diskSettings.ParentPath.Match(Some: parentPath =>
                    {
                        return engine.RunAsync(PsCommandBuilder.Create().Script(
                                                   $"New-VHD -Path \"{vhdPath}\" -ParentPath \"{parentPath}\" -Differencing"));
                    },
                                                                               None: () =>
                    {
                        return engine.RunAsync(PsCommandBuilder.Create().Script(
                                                   $"New-VHD -Path \"{vhdPath}\" -Dynamic -SizeBytes {diskSettings.SizeBytes}"));
                    });

                    if (createDiskResult.IsLeft)
                    {
                        return Prelude.Left(createDiskResult.LeftAsEnumerable().FirstOrDefault());
                    }
                }

                var sizeResult = await engine
                                 .GetObjectsAsync <VhdInfo>(new PsCommandBuilder().AddCommand("get-vhd").AddArgument(vhdPath))
                                 .BindAsync(x => x.HeadOrLeft(new PowershellFailure())).BindAsync(async(vhdInfo) =>
                {
                    if (vhdInfo.Value.Size != diskSettings.SizeBytes && diskSettings.SizeBytes > 0)
                    {
                        var gb = Math.Round(diskSettings.SizeBytes / 1024d / 1024 / 1024, 1);
                        await reportProgress(
                            $"Resizing disk {diskSettings.Name} to {gb} GB");
                        return await engine.RunAsync(PsCommandBuilder.Create().AddCommand("Resize-VHD")
                                                     .AddArgument(vhdPath)
                                                     .AddParameter("Size", diskSettings.SizeBytes));
                    }

                    return Unit.Default;
                });

                if (sizeResult.IsLeft)
                {
                    return Prelude.Left(sizeResult.LeftAsEnumerable().FirstOrDefault());
                }


                return await GetOrCreateInfoAsync(vmInfo,
                                                  i => i.HardDrives,
                                                  disk => currentSettings.Map(x => x.AttachedVMId) == disk.Id,
                                                  async() =>
                {
                    await reportProgress($"Attaching disk {diskSettings.Name} to controller: {diskSettings.ControllerNumber}, Location: {diskSettings.ControllerLocation}").ConfigureAwait(false);
                    return (await engine.GetObjectsAsync <HardDiskDriveInfo>(PsCommandBuilder.Create()
                                                                             .AddCommand("Add-VMHardDiskDrive")
                                                                             .AddParameter("VM", vmInfo.PsObject)
                                                                             .AddParameter("Path", vhdPath)
                                                                             .AddParameter("ControllerNumber", diskSettings.ControllerNumber)
                                                                             .AddParameter("ControllerLocation", diskSettings.ControllerLocation)
                                                                             .AddParameter("PassThru")
                                                                             ).ConfigureAwait(false));
                }).BindAsync(_ => vmInfo.RecreateOrReload(engine))


                .ConfigureAwait(false);
            }).IfNone(vmInfo.RecreateOrReload(engine)));
        }