private void button_Test_Click(object sender, EventArgs e) { PowershellLib.RemotingResult RR = null; try { string Line; Output_lb.Items.Clear(); PowershellLib.Remoting Rem = new PowershellLib.Remoting(Host_t.Text, Name_t.Text, Password_t.Text); //PowershellLib.RemotingResult RR = Rem.Execute(Host_t.Text, Directory_t.Text, Command_t.Text); /*if (Impersonate_cb.Checked) * { * using (new Impersonator(Name_t.Text, Domain_t.Text, Password_t.Text)) * { * RR = Rem.Execute(Host_t.Text, Directory_t.Text, new List<string>(Command_t.Text.Split(new char[] { '\r', '\n' }))); * } * } * else * { * RR = Rem.Execute(Host_t.Text, Directory_t.Text, new List<string>(Command_t.Text.Split(new char[] { '\r', '\n' }))); * }*/ //*** RR = Rem.Execute(Host_t.Text, Directory_t.Text, new List <string>(Command_t.Text.Split(new char[] { '\r', '\n' })), "markwes", "123Mainau"); //*** if (RR.HasErrors) { foreach (object Error in RR.ErrorList) { Line = Convert.ToString(Error); Output_lb.Items.Add(Line); } MessageBox.Show("Command execution errors", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { foreach (object Thing in RR.Output) { Line = Convert.ToString(Thing); Output_lb.Items.Add(Line); } MessageBox.Show("Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
//********************************************************************* /// /// <summary> /// /// </summary> /// <param name="commandList"></param> /// <returns></returns> /// //********************************************************************* public PowershellLib.RemotingResult ExecuteCommands(List <string> commandList) { try { var psResult = _PsRem.Execute(VmProcessorDirectory, commandList); return(psResult); } catch (Exception ex) { throw new Exception("Exception in PostProvDisk.Execute() : " + Utilities.UnwindExceptionMessages(ex)); } }
public override object Execute() { if (AllQueuesBlocked) { return(0); } var remoteErrorDescriptionList = new List <string>(); var remoteResultDescriptionList = new List <string>(); PowershellLib.Remoting psRem = null; var restart = true; var appIdList = new HashSet <string>(); var cdb = new CmpDb(CmpDbConnectionString); List <Models.VmDeploymentRequest> vmReqList = null; try { vmReqList = cdb.FetchVmDepRequests( Constants.StatusEnum.MovingPagefile.ToString(), true); } catch (Exception ex) { throw new Exception("Exception in ProcessTransferedSubmissions() " + CmpCommon.Utilities.UnwindExceptionMessages(ex)); } foreach (var vmReq in vmReqList) { try { //AssertIfTimedOut(vmReq, 0, Constants.StatusEnum.MovingPagefile.ToString()); var vmCfg = CmpInterfaceModel.Models.VmConfig.Deserialize(vmReq.Config); //*** Which Azure API are we looking at here? *** if (null == vmCfg.AzureApiConfig) { vmCfg.AzureApiConfig = null == vmCfg.AzureArmConfig ? new AzureApiSpec() { Platform = Constants.AzureApiType.RDFE.ToString() } } : new AzureApiSpec() { Platform = Constants.AzureApiType.ARM.ToString() }; //*** Don't try ops on the same service twice in the same run *** if (vmCfg.AzureApiConfig.Platform.Equals(Constants.AzureApiType.RDFE.ToString())) { if (appIdList.Contains(vmReq.ParentAppID)) { continue; } appIdList.Add(vmReq.ParentAppID); } //*** Set status to 'MovingPagefile' *** vmReq.StatusCode = Constants.StatusEnum.MovingPagefile.ToString(); vmReq.ExceptionMessage = ""; vmReq.StatusMessage = "Moving Pagefile"; cdb.SetVmDepRequestStatus(vmReq, null); try { psRem = GetPowershellConnection(vmReq); } catch (Exception) { continue; } if (null == psRem) { throw new Exception("Unable to contact WinRM on target"); } //*** TODO *** Let it settle for a moment, this may get rid of the random disk move failure error Thread.Sleep(60000); var vmc = CmpInterfaceModel.Models.VmConfig.Deserialize(vmReq.Config); List <string> commandList = null; PowershellLib.RemotingResult rr = null; //*** Force DNS registration now *** commandList = new List <string>(1) { @"ipconfig /registerdns" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "DNS Registration : " + ed)); } //*** Fetch BIOS asset tag *** commandList = new List <string>(1) { @"$computerSystemProduct = gwmi -Class Win32_computerSystemproduct -computername localhost -namespace ""root\CIMV2"" $computerSystemProduct.uuid" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "Fetch BIOS asset tag : " + ed)); } if (null != rr.StringOutput) { foreach (var outLine in rr.StringOutput) { if (null == vmc.InfoFromVM) { vmc.InfoFromVM = new CmpInterfaceModel.Models.InfoFromVmSpec(); } if (null == vmc.PostInfoFromVM) { vmc.PostInfoFromVM = new CmpInterfaceModel.Models.PostInfoFromVmSpec(); } vmc.InfoFromVM.BiosAssetTag = outLine; vmc.PostInfoFromVM.BiosAssetTag = outLine; vmReq.Config = vmc.Serialize(); } } if (vmReq.RequestType.Equals(CmpInterfaceModel.Constants.RequestTypeEnum.NewVM.ToString(), StringComparison.InvariantCultureIgnoreCase)) { if (IsMsitDeployment) { //*** Set firewall *** commandList = new List <string>(9) { @"netsh advfirewall firewall set rule group=""File and Printer Sharing"" new enable=yes", @"netsh advfirewall firewall set rule group=""Remote Desktop"" new enable=yes", @"netsh advfirewall firewall set rule group=""Remote Event Log Management"" new enable=yes", @"netsh advfirewall firewall set rule group=""Windows Management Instrumentation (WMI)"" new enable=yes", @"netsh advfirewall firewall set rule group=""Remote Volume Management"" new enable=yes", @"netsh advfirewall firewall set rule group=""Remote Scheduled Tasks Management"" new enable=yess", @"netsh advfirewall firewall set rule group=""Remote Service Management"" new enable=yes", @"netsh advfirewall firewall set rule group=""Windows Firewall Remote Management"" new enable=yes", @"netsh advfirewall firewall set rule group=""Windows Remote Management"" new enable=yes" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "Setting Firewall : " + ed)); } } //*** Activate Windows *** commandList = new List <string>(1) { "slmgr.vbs /ato" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => string.Format("Windows Activation : {0}", ed))); } if (DisableSmartCardAuth) { //*** Disable smartcard task *** commandList = new List <string>(1) { @"schtasks /Create /RU ""NT AUTHORITY\SYSTEM"" /F /SC ""OnStart"" /delay ""0001:00"" /TN ""ITCU-BuildSCDisable"" /TR ""cmd.exe /c reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v scforceoption /t REG_DWORD /d 0 /f""" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "Disable smartcard task : " + ed)); } } } if (MovePagefile) { //*** Move pagefile as needed *** if (null != vmc.PageFileConfig) { //*** TODO : Fix the AMP client to set this *** if (null == vmc.PageFileConfig.DiskName) { vmc.PageFileConfig.DiskName = "X"; } if (1 != vmc.PageFileConfig.DiskName.Length) { vmc.PageFileConfig.DiskName = "X"; } if (null == vmc.PageFileConfig.DiskName) { remoteErrorDescriptionList.Add("Null DiskName in PageFileConfig"); } else if (1 != vmc.PageFileConfig.DiskName.Length) { remoteErrorDescriptionList.Add("DiskName length != 1 in PageFileConfig"); } else { restart = true; commandList = new List <string>(9) { @"$ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -EnableAllPrivileges", @"$ComputerSystem.AutomaticManagedPagefile = $false", @"$ComputerSystem.Put()", @"Start-Sleep -s 2", @"$CurrentPageFile = Get-WmiObject -Class Win32_PageFileSetting", @"$CurrentPageFile.Delete()", @"Start-Sleep -s 2", @"Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{Name=""c:\pagefile.sys""; InitialSize = 0; MaximumSize = 0}" }; rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "Moving pagefile to C drive : " + ed)); } } } } //If this is ARM, we should skip this part about Making the IP static. if (MakeIpStatic) { //*** Make IP static as needed ******************** if (vmc.Placement != null) { if (vmc.Placement.Config != null) { var pc = PlacementConfig.Deserialize(vmc.Placement.Config); if (pc.UseStaticIpAddr) { var connection = ServProvAccount.GetAzureServiceAccountConnection( Convert.ToInt32(vmReq.ServiceProviderAccountID), CmpDbConnectionString); var vmo = new AzureAdminClientLib.VmOps(connection); var ipstatic = vmo.MakeIpStatic(vmReq.TargetVmName, vmReq.TargetServicename); if (ipstatic != null) { vmc.InfoFromVM.VmAddress = ipstatic; vmc.PostInfoFromVM.VmAddress = ipstatic; vmReq.Config = vmc.Serialize(); } appIdList.Add(vmReq.ParentAppID); restart = false; } } } } //*** Reboot as needed *** if (restart) { try { commandList = new List <string>(1) { @"Restart-Computer -force" }; psRem.Execute(null, commandList); Thread.Sleep(DwellTime); } catch (Exception ex) { var message = CmpCommon.Utilities.UnwindExceptionMessages(ex); if (!message.Contains(REBOOT_EXIT_TRAP_MATCH)) { remoteErrorDescriptionList.Add("Exception during first VM restart (possibly benign) : " + message); } } } vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.ExceptionMessage = ""; vmReq.StatusMessage = "Rebooting"; vmReq.StatusCode = Constants.StatusEnum.WaitForReboot1.ToString(); cdb.SetVmDepRequestStatus(vmReq, remoteErrorDescriptionList); } catch (Exception ex) { var message = Utilities.UnwindExceptionMessages(ex); if (ex.Message.Contains("(503)")) { vmReq.StatusMessage = "Retry on '(503)' condition"; cdb.SetVmDepRequestStatus(vmReq, null); continue; } if (message.ToLower().Contains("retry")) { vmReq.StatusMessage = "Retry on 'Please retry the request' condition"; cdb.SetVmDepRequestStatus(vmReq, null); continue; } if (message.Contains("requires exclusive access")) { vmReq.StatusMessage = "Retry on 'requires exclusive access' condition"; cdb.SetVmDepRequestStatus(vmReq, null); continue; } if (message.Contains("another operation is pending")) { vmReq.StatusMessage = "Retry on 'another operation is pending' condition"; cdb.SetVmDepRequestStatus(vmReq, null); continue; } vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.StatusCode = Constants.StatusEnum.Exception.ToString(); vmReq.ExceptionMessage = "Exception in ProcessMovePagefile() " + Utilities.UnwindExceptionMessages(ex); Utilities.SetVmReqExceptionType(vmReq, CmpInterfaceModel.Constants.RequestExceptionTypeCodeEnum.Admin); cdb.SetVmDepRequestStatus(vmReq, remoteErrorDescriptionList); } finally { if (null != psRem) { try { psRem.Dispose(); } catch (Exception) { //*** TODO: markwes : now what? } } } } return(0); }
public override object Execute() { if (AllQueuesBlocked) { return(0); } var HaltSequence = false; var remoteErrorDescriptionList = new List <string>(); PowershellLib.Remoting psRem = null; var cdb = new CmpDb(CmpDbConnectionString); List <Models.VmDeploymentRequest> vmReqList = null; try { vmReqList = cdb.FetchVmDepRequests( Constants.StatusEnum.CreatingDrives.ToString(), true); } catch (Exception ex) { throw new Exception("Exception in ProcessTransferedSubmissions() " + CmpCommon.Utilities.UnwindExceptionMessages(ex)); } foreach (var vmReq in vmReqList) { try { if (null == vmReq) { continue; } //AssertIfTimedOut(vmReq, 0, Constants.StatusEnum.CreatingDrives.ToString()); //*** Experiment with dwell time *** if (null != vmReq.CurrentStateStartTime) { if (DefaultRebootDwellTimeMinutes > DateTime.UtcNow.Subtract(((DateTime)vmReq.CurrentStateStartTime)).TotalMinutes) { continue; } } //*** Set status to 'PostProcessing' *** vmReq.StatusCode = Constants.StatusEnum.CreatingDrives.ToString(); vmReq.ExceptionMessage = ""; vmReq.StatusMessage = "Creating Drives"; cdb.SetVmDepRequestStatus(vmReq, null); //*** Contact remote Powershell *** try { psRem = GetPowershellConnection(vmReq); } catch (Exception) { //*** TODO: Mark West : Try this for now continue; /*if( ex.Message.Contains("Not Found") ) * { * VmReq.CurrentStateStartTime = DateTime.UtcNow; * VmReq.StatusCode = Constants.StatusEnum.Exception.ToString(); * VmReq.ExceptionMessage = Utilities.UnwindExceptionMessages(ex); * CDB.SetVmDepRequestStatus(VmReq, null); * continue; * }*/ } if (null == psRem) { //*** It can take time to spin up WinRM, if we can't connect then break out and try again next cycle continue; } var vmc = CmpInterfaceModel.Models.VmConfig.Deserialize(vmReq.Config); List <string> commandList = null; //*** Move temp drive to specified drive *** PowershellLib.RemotingResult RR = null; if (MovePagefile && (null != vmc.PageFileConfig)) { //*** Relabel drive 'D' to drive 'X' *** if (null == vmc.PageFileConfig.DiskName) { vmc.PageFileConfig.DiskName = "X"; } if (0 == vmc.PageFileConfig.DiskName.Length) { vmc.PageFileConfig.DiskName = "X"; } commandList = new List <string>(2) { @"$drive = Get-WmiObject -Class win32_volume -Filter ""Label = 'Temporary Storage'""", "Set-WmiInstance -input $drive -Arguments @{DriveLetter=\"" + vmc.PageFileConfig.DiskName + ":\";}" }; RR = psRem.Execute(null, commandList); if (RR.HasErrors) { remoteErrorDescriptionList.AddRange(RR.ErrorDecsriptionList.Select( ed => string.Format("Moving 'Temporary Storage' drive to {0}: - {1}", vmc.PageFileConfig.DiskName, ed))); //*** Try again *** RR = psRem.Execute(null, commandList); if (RR.HasErrors) { remoteErrorDescriptionList.AddRange(RR.ErrorDecsriptionList.Select( ed => string.Format("Moving 'Temporary Storage' drive to {0}: - {1}", vmc.PageFileConfig.DiskName, ed))); } } //*** Relable DVD drive 'E' to drive 'Z' *** commandList = new List <string>(2) { @"$drive = Get-WmiObject -Class win32_volume -Filter ""DriveType = '5'""", "Set-WmiInstance -input $drive -Arguments @{DriveLetter=\"" + "Z" + ":\";}" }; RR = psRem.Execute(null, commandList); //*** Move pagefile to 'X' *** commandList = new List <string>(8) { @"$ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -EnableAllPrivileges", @"$ComputerSystem.AutomaticManagedPagefile = $false", @"$ComputerSystem.Put()", @"Start-Sleep -s 2", @"$CurrentPageFile = Get-WmiObject -Class Win32_PageFileSetting", @"$CurrentPageFile.Delete()", @"Start-Sleep -s 2", "Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{Name=\"" + vmc.PageFileConfig.DiskName + ":\\pagefile.sys\"; InitialSize = 0; MaximumSize = 0}" }; RR = psRem.Execute(null, commandList); if (RR.HasErrors) { remoteErrorDescriptionList.AddRange(RR.ErrorDecsriptionList.Select( ed => string.Format("Moving pagefile to {0}: - {1}", vmc.PageFileConfig.DiskName, ed))); } } //*** Provision disks *** if (ProvisionDisks && (null != vmc.DiskSpecList && 0 < vmc.DiskSpecList.Count)) { //*** Initialize Disks *** var diskIndex = 2; commandList = new List <string>(2) { "NEW-ITEM -Path 'diskpartscript.txt' -ItemType file -force | OUT-NULL", "ADD-CONTENT -Path 'diskpartscript.txt' -Value 'san policy=OnlineAll'", "diskpart /s 'diskpartscript.txt'" }; var rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select( ed => "Problem setting diskpart san policy=OnlineAll : " + ed)); } foreach (var ds in vmc.DiskSpecList) { try { if (!ds.IsOS) { commandList = new List <string>(5) { "NEW-ITEM -Path 'diskpartscript.txt' -ItemType file -force | OUT-NULL", "ADD-CONTENT -Path 'diskpartscript.txt' -Value 'select disk " + diskIndex++ + "'", "ADD-CONTENT -Path 'diskpartscript.txt' -Value 'attribute disk clear readonly'", "ADD-CONTENT -Path 'diskpartscript.txt' -Value 'online disk'" }; if (vmReq.RequestType.Equals(CmpInterfaceModel.Constants.RequestTypeEnum.NewVM.ToString(), StringComparison.InvariantCultureIgnoreCase)) { commandList.Add("ADD-CONTENT -Path 'diskpartscript.txt' -Value 'CONVERT GPT'"); commandList.Add("ADD-CONTENT -Path 'diskpartscript.txt' -Value 'CREATE PARTITION PRIMARY'"); if (ds.BlockSizeK == 0) { commandList.Add("ADD-CONTENT -Path 'diskpartscript.txt' -Value 'FORMAT FS=ntfs QUICK'"); } else { commandList.Add("ADD-CONTENT -Path 'diskpartscript.txt' -Value 'FORMAT FS=ntfs unit=" + ds.BlockSizeK + "K QUICK'"); } commandList.Add("ADD-CONTENT -Path 'diskpartscript.txt' -Value 'ASSIGN LETTER= " + ds.DriveLetter + "'"); } commandList.Add("diskpart /s 'diskpartscript.txt'"); rr = psRem.Execute(null, commandList); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select( ed => "Problem setting diskpart online disk : " + ed)); } } } catch (Exception ex) { remoteErrorDescriptionList.Add("Exception while assigning disk(s) : " + Utilities.UnwindExceptionMessages(ex)); } } } //*** Add entities to local groups *** if (AddUsersToGroups && (null != vmc.UserSpecList && 0 < vmc.UserSpecList.Count)) { //*** Add entities to group(s) *** commandList = new List <string>(1); foreach (var us in vmc.UserSpecList) { if (null == us) { remoteErrorDescriptionList.Add("Null UserSpec"); } else if (null == us.GroupToJoinName) { remoteErrorDescriptionList.Add("Null GroupToJoin name in UserSpec"); } else if (null == us.DomainName) { remoteErrorDescriptionList.Add("Null DomainName in UserSpec"); } else if (null == us.EntityName) { remoteErrorDescriptionList.Add("Null EntityName in UserSpec"); } else if (0 == us.GroupToJoinName.Length & 0 == us.DomainName.Length & 0 == us.EntityName.Length) { continue; } else { commandList.Add(string.Format(ADDUSERTOGROUPTEMPLATE, us.GroupToJoinName, us.DomainName, us.EntityName)); RR = psRem.Execute(null, commandList); if (RR.HasErrors) { foreach (var ED in RR.ErrorDecsriptionList) { if (!(ED.Contains("already a member"))) { remoteErrorDescriptionList.Add(string.Format( "Adding entity '{0}/{1}' to '{2}' group : {3}", us.DomainName, us.EntityName, us.GroupToJoinName, ED)); } } } } } } //*** Remove temporary local admin user profile *** //*** TODO : Fix this. Got the following error: /* * Exception in Remoting.Execute() : At line:1 char:51 + ([ADSI]"WinNT://$env:computername").delete("user",U2b7384407) + ~ + Missing expression after ','. + + At line:1 char:51 + ([ADSI]"WinNT://$env:computername").delete("user",U2b7384407) + ~~~~~~~~~~ + Unexpected token 'U2b7384407' in expression or statement. + + At line:1 char:61 + ([ADSI]"WinNT://$env:computername").delete("user",U2b7384407) + ~ + Unexpected token ')' in expression or statement. */ /*string tempAccountName = ""; * * try * { * tempAccountName = Utilities.GetXmlInnerText(vmReq.Config, "AdminUsername"); * * if (null != tempAccountName) * { * commandList = new List<string>(1); * //CommandList.Add(@"([ADSI]""WinNT://$env:computername"").delete(""user"",TheTempUserName)"); * commandList.Add(string.Format(_DELETELOCALUSERTEMPLATE, tempAccountName)); * RR = psRem.Execute(null, commandList); * * if (RR.HasErrors) * foreach (string ED in RR.ErrorDecsriptionList) * remoteErrorDescriptionList.Add(string.Format("Removing temp local admin '{0}' : {1}", * tempAccountName, ED)); * } * } * catch (Exception ex) * { * remoteErrorDescriptionList.Add(string.Format("Removing temp local admin '{0}' : {1}", * tempAccountName, Utilities.UnwindExceptionMessages(ex))); * }*/ if (!HaltSequence) { vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.ExceptionMessage = ""; vmReq.StatusMessage = NextStatusMessage; vmReq.StatusCode = NextStatusCode.ToString(); cdb.SetVmDepRequestStatus(vmReq, remoteErrorDescriptionList); } } catch (Exception ex) { if (null == vmReq) { LogThis(ex, EventLogEntryType.Error, "Exception in ProcessPostProcess()", 10, 10); } else { vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.StatusCode = Constants.StatusEnum.Exception.ToString(); vmReq.ExceptionMessage = Utilities.UnwindExceptionMessages(ex); Utilities.SetVmReqExceptionType(vmReq, CmpInterfaceModel.Constants.RequestExceptionTypeCodeEnum.Admin); cdb.SetVmDepRequestStatus(vmReq, remoteErrorDescriptionList); } } finally { if (null != psRem) { psRem.Dispose(); } } } return(0); }
public override object Execute() { if (AllQueuesBlocked) { return(0); } List <string> warninglist = null; List <string> commandList = null; PowershellLib.Remoting psRem = null; var cdb = new CmpDb(CmpDbConnectionString); List <Models.VmDeploymentRequest> vmReqList = null; try { vmReqList = cdb.FetchVmDepRequests( Constants.StatusEnum.PostProcessing1.ToString(), true); } catch (Exception ex) { throw new Exception("Exception in ProcessPostProcessStage1() " + CmpCommon.Utilities.UnwindExceptionMessages(ex)); } foreach (var vmReq in vmReqList) { var vmReq2 = vmReq; try { //*** Is it a non-Windows deployment? *** if (GetOsFamily(vmReq) != Constants.OsFamily.Windows) { CompleteVmRequest(vmReq, warninglist, cdb); continue; } //*** Obtain Powershell connection *** psRem = null; try { psRem = GetPowershellConnection(vmReq); vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.ExceptionMessage = ""; vmReq.StatusMessage = "Post Processing"; vmReq.StatusCode = Constants.StatusEnum.PostProcessing1.ToString(); try { cdb.SetVmDepRequestStatus(vmReq, warninglist); } catch (Exception ex) { LogThis(ex, System.Diagnostics.EventLogEntryType.Error, "Exception while setting req status in PostProcessing1()", 100, 100); } } catch (Exception) { continue; } if (null == psRem) { continue; } //************* /*foreach (var scriptSpec in vmc.ScriptList) * { * if (scriptSpec.ExecuteInState.Equals(Constants.StatusEnum.PostProcessing1.ToString(), * StringComparison.InvariantCultureIgnoreCase)) * scriptSpec.ExecuteInState = Constants.StatusEnum.PostProvisioningQC.ToString(); * } * * vmReq.Config = vmc.Serialize(); * * //************* * * var exSeqResult = ExecuteSequences(vmReq); * cdb.SetVmDepRequestStatus(vmReq, null);*/ //*** Final reboot *** try { commandList = new List <string>(1) { @"Restart-Computer -force" }; psRem.Execute(null, commandList); Thread.Sleep(DwellTime); } catch (Exception ex) { var message = CmpCommon.Utilities.UnwindExceptionMessages(ex); if (!message.Contains(REBOOT_EXIT_TRAP_MATCH)) { if (null == warninglist) { warninglist = new List <string>(1); } warninglist.Add("Exception during final VM restart (possibly benign) : " + message); } } CompleteVmRequest(vmReq, warninglist, cdb); } catch (Exception ex) { vmReq2.CurrentStateStartTime = DateTime.UtcNow; vmReq2.ExceptionMessage = "Exception in ProcessPostProcessStage1() : " + CmpInterfaceModel.Utilities.UnwindExceptionMessages(ex); vmReq2.StatusMessage = Constants.StatusEnum.Exception.ToString(); vmReq2.StatusCode = Constants.StatusEnum.Exception.ToString(); cdb.SetVmDepRequestStatus(vmReq2, null); LogThis(ex, System.Diagnostics.EventLogEntryType.Warning, "Exception in ProcessPostProcessStage1()", 100, 100); } finally { if (null != psRem) { try { psRem.Dispose(); } catch (Exception) { //*** Ignore *** } } } } return(0); }
public override object Execute() { if (AllQueuesBlocked) { return(0); } PowershellLib.Remoting psRem = null; var cdb = new CmpDb(CmpDbConnectionString); List <Models.VmDeploymentRequest> vmReqList = null; try { vmReqList = cdb.FetchVmDepRequests( Constants.StatusEnum.WaitForReboot1.ToString(), true); } catch (Exception ex) { throw new Exception("Exception in ProcessWaitForReboot1() " + CmpCommon.Utilities.UnwindExceptionMessages(ex)); } foreach (var vmReq in vmReqList) { try { //AssertIfTimedOut(vmReq, 0, Constants.StatusEnum.WaitForReboot1.ToString()); //*** Experiment with dwell time *** if (null != vmReq.CurrentStateStartTime) { if (2 > DateTime.UtcNow.Subtract(((DateTime)vmReq.CurrentStateStartTime)).TotalMinutes) { continue; } } //*** Contact remote Powershell *** try { psRem = GetPowershellConnection(vmReq); var vmMtuSetting = Microsoft.Azure.CloudConfigurationManager.GetSetting("VMMTUSETTING"); if (null != psRem && null != vmMtuSetting) { if (!vmMtuSetting.Equals("0")) { var commandList = new List <string>(4) { @"$a = netsh int ipv4 sho int $maxNic = $a.count for ($i=3;$i -lt $maxNic-1;$i++) { $nic = ($a[$i].split("" "") | ?{!$_ -eq """"}) if (([string]$nic[4]).contains(""Ethernet"") ) { Netsh int ipv4 set subinterface $nic[0] mtu= " + vmMtuSetting + " store=persistent } }", @"$a = netsh int ipv4 sho int $maxNic = $a.count for ($i=3;$i -lt $maxNic-1;$i++) { $nic = ($a[$i].split("" "") | ?{!$_ -eq """"}) if (([string]$nic[4]).Contains(""Local"")-and ([string]$nic[5]).contains(""Area"") -and ([string]$nic[6]).contains(""Connection"") ) { Netsh int ipv4 set subinterface $nic[0] mtu= " + vmMtuSetting + " store=persistent} }" }; var rr = psRem.Execute(null, commandList); var remoteErrorDescriptionList = new List <string>(); //remoteErrorDescriptionList.Add("Setting MTU :" + vmMtuSetting + "---" ); if (rr.HasErrors) { remoteErrorDescriptionList.AddRange(rr.ErrorDecsriptionList.Select(ed => "Setting MTU : " + ed)); } } } } catch (Exception ex) { if (CmpInterfaceModel.Utilities.UnwindExceptionMessages(ex).Contains("Access is denied")) { throw; } if (HasTimedOut(vmReq, ContactingVmMinutesTTL)) { if (vmReq.RequestType.Equals( CmpInterfaceModel.Constants.RequestTypeEnum.MigrateVm.ToString())) { throw; } DeleteVm(vmReq, DeleteDwelltimeMinutes, true, true); ResubmitRequest(vmReq, "Timeout " + Constants.StatusEnum.WaitForReboot1, cdb, false, false); } continue; } if (null == psRem) { if (HasTimedOut(vmReq, ContactingVmMinutesTTL)) { DeleteVm(vmReq, DeleteDwelltimeMinutes, true, true); ResubmitRequest(vmReq, "Timeout " + Constants.StatusEnum.WaitForReboot1, cdb, false, false); } //*** It can take time to spin up WinRM, if we can't connect then break out and try again next cycle continue; } vmReq.CurrentStateStartTime = DateTime.UtcNow; //vmReq.CurrentStateTryCount = 0; vmReq.ExceptionMessage = ""; vmReq.StatusMessage = "Contacted After Reboot"; vmReq.StatusCode = Constants.StatusEnum.CreatingDrives.ToString(); cdb.SetVmDepRequestStatus(vmReq, null); } catch (Exception ex) { if (null == vmReq) { LogThis(null, EventLogEntryType.Error, "Exception in ProcessWaitForReboot1() : vmReq == null", 1, 1); return(-1); } vmReq.CurrentStateStartTime = DateTime.UtcNow; vmReq.StatusCode = Constants.StatusEnum.Exception.ToString(); vmReq.ExceptionMessage = Utilities.UnwindExceptionMessages(ex); Utilities.SetVmReqExceptionType(vmReq, CmpInterfaceModel.Constants.RequestExceptionTypeCodeEnum.Admin); cdb.SetVmDepRequestStatus(vmReq, null); } finally { if (null != psRem) { psRem.Dispose(); } } } return(0); }