コード例 #1
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Stop-VM
        public static void StopVm(string ComputerName, string Name, bool PowerOff, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;
            string Flag = PowerOff ? "-PowerOff" : "";

            PSWrapper.Execute(ComputerName, $"Stop-VM -Name \"{Name}\" {Flag} -Force", out res, handlers);
        }
コード例 #2
0
 private void RefreshCollections(WorkerContext ctx = null)
 {
     try
     {
         if (ctx == null)
         {
             databaseManager.FlushCache();
         }
         else
         {
             databaseManager.FlushCache(PsStreamEventHandlers.GetUIHandlers(ctx));
             ctx.s = StatusCode.OK;
         }
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message, "Exception", MessageBoxButtons.OK);
         if (ctx != null)
         {
             ctx.s = StatusCode.FAILED;
         }
         return;
     }
     RefreshUI();
 }
コード例 #3
0
 public static bool PathExists(string host, string path, PsStreamEventHandlers handlers = null)
 {
     return((bool)PSWrapper.Execute(host, (ps) =>
     {
         ps.AddCommand("Test-Path").AddParameter("path", path);
         return ps.Invoke();
     })[0].BaseObject);
 }
コード例 #4
0
 public static void NewDirectory(string host, string path, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(host, (ps) =>
     {
         return(ps.AddCommand("New-Item")
                .AddParameter("Type", "Directory")
                .AddParameter("Path", path)
                .AddParameter("Force").Invoke());
     }, handlers);
 }
コード例 #5
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Get-VHD
        public static List <PSObject> GetVhd(string ComputerName, string Path, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            res = PSWrapper.FastExecute(ComputerName, (ps) =>
            {
                return(ps.AddCommand("Get-VHD").AddParameter("Path", Path).Invoke());
            }, handlers);
            return(res.ToList());
        }
コード例 #6
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Get-VM
        /// <exception cref="Exception">May throw exceptions</exception>
        public static VirtualMachine GetVm(string hostName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> objs = null;

            PSWrapper.FastExecute(hostName, $"Get-Vm -Name \"{Name}\"", out objs, handlers);
            if (objs == null || objs.Count == 0)
            {
                return(null);
            }
            return(VirtualMachine.FromPSObject(objs[0], hostName));
        }
コード例 #7
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Get-VMHost
        public static PSObject GetVmHost(string ComputerName, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Get-VMHost -ComputerName \"{ComputerName}\"", out res, handlers);
            if (res == null || res.Count <= 0)
            {
                return(null);
            }
            return(res[0]);
        }
コード例 #8
0
 public static string GetTopMostParent(string hostName, string path, PsStreamEventHandlers handlers = null)
 {
     while (true)
     {
         var pso = HyperV.GetVhd(hostName, path, handlers)[0];
         if (pso == null)
         {
             break;
         }
         if (string.IsNullOrWhiteSpace((string)pso?.Members["ParentPath"].Value))
         {
             break;
         }
         path = (string)pso?.Members["ParentPath"].Value;
     }
     return(path);
 }
コード例 #9
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Get-VM
        /// <exception cref="Exception">May throw exceptions</exception>
        public static List <VirtualMachine> GetVm(string hostName, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> objs = null;

            PSWrapper.FastExecute(hostName, "Get-Vm", out objs, handlers);
            if (objs == null || objs.Count == 0)
            {
                return(new List <VirtualMachine>());
            }
            List <VirtualMachine> machines = new List <VirtualMachine>();

            foreach (var m in objs)
            {
                machines.Add(VirtualMachine.FromPSObject(m, hostName));
            }
            return(machines);
        }
コード例 #10
0
ファイル: DatabaseManager.cs プロジェクト: phoenixyj/trhvmgr
        /// <summary>
        /// Exception safe cache flushing for virtual machines.
        /// </summary>
        public void FlushCache(PsStreamEventHandlers handlers = null)
        {
            foreach (var e in Directory)
            {
                e.Value.BurnChildren();
            }
            Directory.Clear();
            var hosts = GetCollection <DbHostComputer>();
            var virts = GetCollection <DbVirtualMachine>();

            // Loop through each host
            foreach (var h in hosts.FindAll())
            {
                MasterTreeNode root = null;
                HostState      st   = HostState.Unknown;
                try
                {
                    Interface.BringOnline(h.HostName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK);
                    st = HostState.Offline;
                }

                var vm = new List <VirtualMachine>();
                try
                {
                    vm = HyperV.GetVm(h.HostName, handlers);
                    st = HostState.Online;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK);
                    st = HostState.Offline;
                }

                root = this.GetRootTreeNode(h, st, vm);
                // Finally, add this host to our tree
                if (root != null)
                {
                    Directory.Add(h.HostName, root);
                }
            }
        }
コード例 #11
0
        public InspectDiskDialog(string computer, string path)
        {
            InitializeComponent();
            var bg = new BackgroundWorkerQueueDialog("Getting information...", ProgressBarStyle.Marquee);

            bg.AppendTask("Getting information...", DummyWorker.GetWorker((ctx) =>
            {
                try
                {
                    pso   = HyperV.GetVhd(computer, path, PsStreamEventHandlers.GetUIHandlers(ctx))[0];
                    ctx.s = StatusCode.OK;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK);
                    ctx.s = StatusCode.FAILED;
                }
                return(ctx);
            }));
            bg.ShowDialog();
            this.c = computer;
        }
コード例 #12
0
        private void addbtn_Click(object sender, EventArgs e)
        {
            bool isFormValid = false;

            // Disgusting
            if (serverComboBox.SelectedIndex == -1)
            {
                serverComboBox.IsValid = tribool.FALSE;
            }
            else
            {
                serverComboBox.IsValid = tribool.TRUE;
            }
            if (baseComboBox.SelectedIndex == -1)
            {
                baseComboBox.IsValid = tribool.FALSE;
            }
            else
            {
                baseComboBox.IsValid = tribool.TRUE;
            }
            if (configComboBox.SelectedIndex == -1)
            {
                configComboBox.IsValid = tribool.FALSE;
            }
            else
            {
                configComboBox.IsValid = tribool.TRUE;
            }
            if (adapterComboBox.SelectedIndex == -1)
            {
                adapterComboBox.IsValid = tribool.FALSE;
            }
            else
            {
                adapterComboBox.IsValid = tribool.TRUE;
            }
            if (string.IsNullOrEmpty(vmTextbox.Text))
            {
                vmTextbox.IsValid = tribool.FALSE;
            }
            else
            {
                vmTextbox.IsValid = tribool.TRUE;
            }

            isFormValid = serverComboBox.IsValid == tribool.TRUE &&
                          baseComboBox.IsValid == tribool.TRUE &&
                          vmTextbox.IsValid == tribool.TRUE &&
                          configComboBox.IsValid == tribool.TRUE &&
                          adapterComboBox.IsValid == tribool.TRUE;

            if (!isFormValid)
            {
                this.DialogResult = DialogResult.None;
            }
            else
            {
                // !! IMPORTANT !!
                // We NEED these exactly here because of cross thread errors
                // (we cannot get the user inputs from the BackgroundWorker)
                var a1 = GetSelectedHost().HostName;
                var a2 = vmTextbox.Text;
                var a3 = GetSelectedVirtualMachine().Uuid;
                var a4 = GetSelectedSwitch().Name;
                var a5 = configComboBox.SelectedIndex;

                if (a1 != GetSelectedVirtualMachine().Host&&
                    MessageBox.Show(
                        "The selected target server is different from the server hosting the base image. Do you want to continue?",
                        "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    this.DialogResult = DialogResult.None;
                    return;
                }

                var backgroundWorker = new BackgroundWorkerQueueDialog("Loading servers...");
                backgroundWorker.AppendTask("Creating VM...", DummyWorker.GetWorker((ctx) => {
                    // Try to create the VM
                    try
                    {
                        Interface.NewTemplate(a1, a2, a3, a4, jsonHelper.JObject["templates"][a5], PsStreamEventHandlers.GetUIHandlers(ctx));
                        ctx.s = StatusCode.OK;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK);
                        ctx.s = StatusCode.FAILED;
                    }
                    return(ctx);
                }));
                backgroundWorker.ShowDialog();
                if (backgroundWorker.GetWorker().ReturnedObjects[0].s == StatusCode.OK)
                {
                    this.DialogResult = DialogResult.OK;
                }
            }
        }
コード例 #13
0
        private void AddTemplateDialog_Load(object sender, EventArgs e)
        {
            // Get server information
            BackgroundWorkerQueueDialog backgroundWorker = new BackgroundWorkerQueueDialog("Retrieving Network Information");

            foreach (var host in SessionManager.GetDatabase().GetServerDb())
            {
                backgroundWorker.AppendTask("Validating " + host.HostName, NetworkWorkers.GetStarterWorker(
                                                new NetworkWorkerObject {
                    HostName = host.HostName
                }
                                                ));
                backgroundWorker.AppendTask("Getting IP address of " + host.HostName + "...", NetworkWorkers.GetIpWorker());
            }
            backgroundWorker.ShowDialog();
            var bw = backgroundWorker.GetWorker();

            for (int i = 0; i < SessionManager.GetDatabase().GetServerDb().Count; i++)
            {
                if (bw.ReturnedObjects[i * 2 + 1].s == StatusCode.OK)
                {
                    hostComputers.Add(new HostComputer
                    {
                        HostName  = ((NetworkWorkerObject)bw.ReturnedObjects[i * 2 + 1].o).HostName,
                        IpAddress = ((NetworkWorkerObject)bw.ReturnedObjects[i * 2 + 1].o).IpAddress,
                    });
                }
            }

            // Get configurations
            for (int i = 0; i < jsonHelper.JObject["templates"]?.Count(); i++)
            {
                configComboBox.ComboBox.Items.Add(jsonHelper.JObject["templates"][i]["name"]);
            }

            // Add options to host combobox
            hostComputers.ForEach(x =>
            {
                if (!string.IsNullOrEmpty(x.HostName) && !string.IsNullOrEmpty(x.IpAddress))
                {
                    serverComboBox.ComboBox.Items.Add(x.HostName + " [" + x.IpAddress + "]");
                }
            });

            // Get virtual machines
            backgroundWorker = new BackgroundWorkerQueueDialog("Scanning for Virtual Machines...", ProgressBarStyle.Marquee);
            backgroundWorker.AppendTask("Getting machines...", DummyWorker.GetWorker((ctx) =>
            {
                SessionManager.GetDatabase().FlushCache(PsStreamEventHandlers.GetUIHandlers(ctx));
                try
                {
                    foreach (var vm in SessionManager.GetDatabase().GetVm(VirtualMachineType.BASE))
                    {
                        virtualMachines.Add(vm);
                    }
                    virtualMachines.ForEach(x =>
                    {
                        ThreadManager.Invoke(this, baseComboBox, () =>
                                             baseComboBox.ComboBox.Items.Add(x.Name + " [" + x.Host + "]")
                                             );
                    });
                    ctx.s = StatusCode.OK;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK);
                    ctx.s = StatusCode.FAILED;
                }
                return(ctx);
            }));
            backgroundWorker.ShowDialog();
        }
コード例 #14
0
        public ServerPropertyGrid(string hostName)
        {
            this.HostName = hostName;
            // Populate all
            PSObject psObj = null;

            new BackgroundWorkerQueueDialog("Getting server information...", ProgressBarStyle.Marquee)
            .AppendTask("", DummyWorker.GetWorker((ctx) => psObj = HyperV.GetVmHost(hostName, PsStreamEventHandlers.GetUIHandlers(ctx))))
            .ShowDialog();
            if (psObj == null)
            {
                return;
            }

            this.VirtualHardDiskPath       = (string)psObj.Members["VirtualHardDiskPath"].Value;
            this.VirtualMachinePath        = (string)psObj.Members["VirtualMachinePath"].Value;
            this.MacAddressMaximum         = (string)psObj.Members["MacAddressMaximum"].Value;
            this.MacAddressMinimum         = (string)psObj.Members["MacAddressMinimum"].Value;
            this.EnableEnhancedSessionMode = (bool)psObj.Members["EnableEnhancedSessionMode"].Value;
            this.MemoryCapacity            = (long)psObj.Members["MemoryCapacity"].Value;
            this.LogicalProcessorCount     = (int)psObj.Members["LogicalProcessorCount"].Value;
        }
コード例 #15
0
 public static void CopyFile(string srcHost, string dstHost, string src, string dst, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(dstHost, (ps) =>
     {
         ps.AddCommand("Set-Variable").AddParameter("Name", "cred").AddParameter("Value", SessionManager.GetCredential());
         ps.AddScript($"Copy-Item \"{src}\" \"{dst}\" -Force –FromSession (New-PSSession –ComputerName {srcHost} -Credential $cred)");
         ps.Invoke();
         return(null);
     }, handlers);
 }
コード例 #16
0
 /// <exception cref="Exception">May throw exceptions</exception>
 public static void RestartService(string hostName, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(hostName, (ps) => ps.AddCommand("Restart-Service").AddParameter("Name", "vmms").Invoke(), handlers);
 }
コード例 #17
0
        public static void NewDeployment(string hostName, string name, Guid tmplUid, string switchName, JToken config, PsStreamEventHandlers handlers = null)
        {
            var tmplVm = SessionManager.GetDatabase().GetVm(tmplUid);
            var baseVm = SessionManager.GetDatabase().GetVm(tmplVm.ParentUuid);

            if (baseVm == null)
            {
                throw new Exception("Template VM without parent.");
            }

            var    bsrcHost = baseVm.Host;
            string bdstDir  = Path.Combine(Settings.Default.vhdPath, bsrcHost);
            string bdstPath = Path.Combine(bdstDir, baseVm.Uuid.ToString() + ".vhdx");
            string bsrcPath = GetTopMostParent(baseVm.Host, baseVm.VhdPath[0]);

            var    tsrcHost = tmplVm.Host;
            string tsrcPath = tmplVm.VhdPath[0];
            string dstHost  = hostName;
            string vhdPath  = Path.Combine(Settings.Default.vhdPath, name + ".vhdx");

            if (bsrcHost != hostName)
            {
                if (!PathExists(dstHost, bdstPath))
                {
                    NewDirectory(dstHost, bdstDir, handlers);
                    CopyFile(bsrcHost, dstHost, bsrcPath, bdstPath, handlers);
                }
            }
            else
            {
                bdstPath = bsrcPath;
            }

            if (!PathExists(dstHost, vhdPath))
            {
                NewDirectory(dstHost, bdstDir, handlers);
                CopyFile(tsrcHost, dstHost, tsrcPath, vhdPath, handlers);
            }
            HyperV.SetVHD(dstHost, bdstPath, vhdPath, true, handlers);
            PSWrapper.Execute(dstHost, config, handlers, name, vhdPath, switchName);

            var vm = HyperV.GetVm(hostName, name, handlers).GetDbObject();

            vm.ParentHost = bsrcHost;
            vm.ParentUuid = baseVm.Uuid;
            vm.VmType     = (int)VirtualMachineType.DEPLOY;
            SessionManager.GetDatabase().SetVm(vm);
        }
コード例 #18
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
 // Alias: New-VHD
 public static PSObject NewVHD(string ComputerName, string ParentPath, string Path, PsStreamEventHandlers handlers = null)
 {
     return(PSWrapper.Execute(ComputerName, (ps) =>
     {
         ps.AddStatement().AddScript($"New-VHD -ParentPath \"{ParentPath}\" -Path \"{Path}\" -Differencing");
         return ps.Invoke();
     }, handlers)[0]);
 }
コード例 #19
0
 private void StopVmms(string host)
 {
     SetStatus("Busy.");
     new BackgroundWorkerQueueDialog("Stopping service...")
     .AppendTask("Stopping vmms...", DummyWorker.GetWorker((ctx) =>
                                                           Interface.StopService(host, "vmms", PsStreamEventHandlers.GetUIHandlers(ctx))
                                                           )).ShowDialog();
     Thread.Sleep(1000);
     SetStatus("Ready.");
 }
コード例 #20
0
        private void startToolButton_Click(object sender, EventArgs e)
        {
            var node = treeListView.SelectedObject as MasterTreeNode;

            if (node == null)
            {
                return;
            }
            BackgroundWorkerQueueDialog bg = new BackgroundWorkerQueueDialog("Setting machine state...");

            if (node.State?.vs == VirtualMachineState.Paused)
            {
                bg.AppendTask("", DummyWorker.GetWorker((ctx) => HyperV.ResumeVm(node.Host, node.Name, PsStreamEventHandlers.GetUIHandlers(ctx))));
            }
            else
            {
                bg.AppendTask("", DummyWorker.GetWorker((ctx) => HyperV.StartVm(node.Host, node.Name, PsStreamEventHandlers.GetUIHandlers(ctx))));
            }
            bg.ShowDialog();
            RefreshBackground();
        }
コード例 #21
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Remove-VMSnapshot
        public static void RemoveVmSnapshot(string ComputerName, string VMName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Remove-VMSnapshot -Name \"{Name}\" -VMName \"{VMName}\" -IncludeAllChildSnapshots -Confirm:$false", out res, handlers);
        }
コード例 #22
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Checkpoint-VM
        public static void CheckpointVm(string ComputerName, string VMName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Checkpoint-VM -SnapshotName \"{Name}\" -Name \"{VMName}\" -Confirm:$false", out res, handlers);
        }
コード例 #23
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
 // Alias: Set-VHD
 public static void SetVHD(string ComputerName, string ParentPath, string Path, bool IgnoreMismatchId, PsStreamEventHandlers handlers = null)
 {
     PSWrapper.Execute(ComputerName, (ps) =>
     {
         string Flag = /*IgnoreMismatchId ? "-IgnoreMismatchId" :*/ "";
         ps.AddStatement().AddScript($"Set-VHD -Path \"{Path}\" -ParentPath \"{ParentPath}\" {Flag}");
         return(ps.Invoke());
     }, handlers);
 }
コード例 #24
0
        public static void StartService(string host, string svc, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res = null;

            PSWrapper.Execute(host, $"net start \"{svc}\" | Write-Verbose -Verbose", out res, handlers);
        }
コード例 #25
0
        public static void NewTemplate(string hostName, string name, Guid baseUid, string switchName, JToken config, PsStreamEventHandlers handlers = null)
        {
            var    baseVm  = SessionManager.GetDatabase().GetVm(baseUid);
            var    srcHost = baseVm.Host;
            var    dstHost = hostName;
            string dstDir  = Path.Combine(Settings.Default.vhdPath, srcHost);
            string srcPath = GetTopMostParent(baseVm.Host, baseVm.VhdPath[0]);
            string dstPath = Path.Combine(dstDir, baseUid.ToString() + ".vhdx");
            string vhdPath = Path.Combine(Settings.Default.vhdPath, name + ".vhdx");

            if (srcHost != hostName)
            {
                if (!PathExists(dstHost, dstPath))
                {
                    NewDirectory(dstHost, dstDir, handlers);
                    CopyFile(srcHost, dstHost, srcPath, dstPath, handlers);
                }
            }
            else
            {
                dstPath = srcPath;
            }
            HyperV.NewVHD(dstHost, dstPath, vhdPath, handlers);
            PSWrapper.Execute(dstHost, config, handlers, name, vhdPath, switchName);

            var vm = HyperV.GetVm(hostName, name, handlers).GetDbObject();

            vm.ParentHost = srcHost;
            vm.ParentUuid = baseUid;
            vm.VmType     = (int)VirtualMachineType.TEMPLATE;
            SessionManager.GetDatabase().SetVm(vm);
        }
コード例 #26
0
        private void suspendToolButton_Click(object sender, EventArgs e)
        {
            var node = treeListView.SelectedObject as MasterTreeNode;

            if (node == null)
            {
                return;
            }
            new BackgroundWorkerQueueDialog("Setting machine state...")
            .AppendTask("", DummyWorker.GetWorker((ctx) =>
                                                  HyperV.SuspendVm(node.Host, node.Name, PsStreamEventHandlers.GetUIHandlers(ctx))
                                                  )).ShowDialog();
            RefreshBackground();
        }
コード例 #27
0
ファイル: HyperV.cs プロジェクト: phoenixyj/trhvmgr
        // Alias: Save-VM
        public static void SaveVm(string ComputerName, string Name, PsStreamEventHandlers handlers = null)
        {
            Collection <PSObject> res;

            PSWrapper.Execute(ComputerName, $"Save-VM -Name \"{Name}\"", out res, handlers);
        }