protected override void OnStart(string[] args) { try { _EventLog = new EventLog("Application"); _EventLog.Source = CmpCommon.Constants.CmpAzureServiceWorkerRole_EventlogSourceName; _EventLog.WriteEntry("Service Starting", EventLogEntryType.Information, 1, 1); } catch (Exception) { _EventLog = null; } try { _CS = new CmpServiceLib.CmpService(_EventLog, null, null); _CS.AsynchStart(); if (null != _EventLog) { _EventLog.WriteEntry("Service Started", EventLogEntryType.Information, 2, 1); } } catch (Exception ex) { if (null != _EventLog) { _EventLog.WriteEntry("Service not started : " + CmpCommon.Utilities.UnwindExceptionMessages(ex), EventLogEntryType.Error, 100, 100); } } //return base.OnStart(); }
private void button_RunAsService_Click(object sender, EventArgs e) { try { _EventLog = new EventLog("Application"); _EventLog.Source = CmpCommon.Constants.CmpAzureServiceWorkerRole_EventlogSourceName; _EventLog.WriteEntry("Service Starting", EventLogEntryType.Information, 1, 1); } catch (Exception) { _EventLog = null; } try { _CS = new CmpServiceLib.CmpService(_EventLog, null, null); //_CS.PerformSingleRun(); _CS.AsynchStart(); if (null != _EventLog) { _EventLog.WriteEntry("Service Started", EventLogEntryType.Information, 2, 1); } } catch (Exception ex) { if (null != _EventLog) { _EventLog.WriteEntry("Service not started : " + CmpCommon.Utilities.UnwindExceptionMessages(ex), EventLogEntryType.Error, 100, 100); } } }
public IQueryable <CmpInterfaceModel.Models.VmDeploymentRequest> VmDeployments() { try { var vdr = new List <CmpInterfaceModel.Models.VmDeploymentRequest>(); using (var cmp = new CmpServiceLib.CmpService(_EventLog, _CmpDbConnectionString, _AftsDbConnectionString)) { var vmdeploymentrequestList = cmp.FetchVmDepRequests(); foreach (var vmdeploymentrequest in vmdeploymentrequestList) { if (null != vmdeploymentrequest) { vdr.Add(ServToInt(vmdeploymentrequest)); } } } return(vdr.AsQueryable()); } catch (Exception ex) { LogThis(ex, EventLogEntryType.Error, "Exception in GetVmDeploymentRequest()", 100, 100); throw; } }
//********************************************************************* /// /// <summary> /// /// </summary> /// <returns></returns> /// //********************************************************************* public override bool OnStart() { try { _EventLog = new EventLog("Application"); _EventLog.Source = CmpCommon.Constants.CmpAzureServiceWorkerRole_EventlogSourceName; _EventLog.WriteEntry("Service Starting", EventLogEntryType.Information, 1, 1); } catch (Exception) { _EventLog = null; } try { InitDiagnostics(); if (JoinDomain()) { return(false); } // Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12; // Create the queue if it does not exist already var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var xk = new KryptoLib.X509Krypto(null); connectionString = xk.DecrpytKText(connectionString); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.QueueExists(QueueName)) { namespaceManager.CreateQueue(QueueName); } // Initialize the connection to Service Bus Queue //Client = QueueClient.CreateFromConnectionString(connectionString, QueueName); _CS = new CmpServiceLib.CmpService(_EventLog, null, null); //_CS.PerformSingleRun(); _CS.AsynchStart(); if (null != _EventLog) { _EventLog.WriteEntry("Service Started", EventLogEntryType.Information, 2, 1); } } catch (Exception ex) { if (null != _EventLog) { _EventLog.WriteEntry("Service not started : " + CmpCommon.Utilities.UnwindExceptionMessages(ex), EventLogEntryType.Error, 100, 100); } } return(base.OnStart()); }
//********************************************************************* /// /// <summary> /// /// </summary> /// <returns></returns> /// //********************************************************************* private CmpServiceLib.CmpService StartCmpServiceTest() { _eventLog.Source = CmpCommon.Constants.CmpAzureServiceWorkerRole_EventlogSourceName; _eventLog.WriteEntry("Service Starting", EventLogEntryType.Information, 1, 1); CmpServiceLib.CmpService _CS = new CmpServiceLib.CmpService(_eventLog, null, null); //if service has not started it will throw an exception and the test will fail _CS.AsynchStart(); return(_CS); }
//******************************************************************** /// /// <summary> /// Ugly code, does not belong here. Belongs in a lib. Should remove /// this when we solve the big 'method not returning' bug /// </summary> /// <param name="cmpReq"></param> /// <returns></returns> /// //******************************************************************** private VmDashboardInfo GetLocalvmDBI(Models.CmpRequest cmpReq) { string cmpDbConnectionString = GetCmpContextConnectionStringFromConfig(); CmpServiceLib.CmpService cmps = new CmpServiceLib.CmpService(eventLog, cmpDbConnectionString, null); var vmg = cmps.VmGet((int)cmpReq.CmpRequestID, CmpInterfaceModel.Constants.FetchType.AzureFull); VmDashboardInfo vmDBI = new VmDashboardInfo() { //Cores = "", DataVirtualHardDisks = ConvertDisk(vmg.DataVirtualHardDisks), DeploymentID = vmg.DeploymentID, DNSName = vmg.DNSName, InternalIP = vmg.InternalIP, MediaLocation = vmg.MediaLocation, OSVersion = vmg.OSVersion, OSVirtualHardDisk = new OsVirtualHardDisk() { DiskLabel = vmg.OSVirtualHardDisk.DiskLabel, DiskName = vmg.OSVirtualHardDisk.DiskName, HostCaching = vmg.OSVirtualHardDisk.HostCaching, MediaLink = vmg.OSVirtualHardDisk.MediaLink, OS = vmg.OSVirtualHardDisk.OS, RemoteSourceImageLink = vmg.OSVirtualHardDisk.RemoteSourceImageLink, SourceImageName = vmg.OSVirtualHardDisk.SourceImageName }, QueueStatus = "", RDPCertificateThumbprint = "", RoleName = vmg.RoleName, RoleSize = cmpReq.VmSize, Status = vmg.Status, Subscription = new SubscriptionInfo() { CurrentCoreCount = vmg.Subscription.CurrentCoreCount, MaximumCoreCount = vmg.Subscription.MaximumCoreCount, SubscriptionID = vmg.Subscription.SubscriptionID, SubscriptionName = vmg.Subscription.SubscriptionName } }; return(vmDBI); }
GetVmDeploymentRequest([FromODataUri] int key) { try { //**************************** //var testReqList = new List<VmDeploymentRequest>(); //testReqList.Add(new CmpInterfaceModel.Models.VmDeploymentRequest()); //return SingleResult.Create(testReqList.AsQueryable()); //**************************** using (var cmp = new CmpServiceLib.CmpService(_EventLog, _CmpDbConnectionString, _AftsDbConnectionString)) { var vmdeploymentrequest = cmp.FetchVmDepRequest(key); if (null == vmdeploymentrequest) { return(null); } var vdr = new List <CmpInterfaceModel.Models.VmDeploymentRequest> { ServToInt(vmdeploymentrequest) }; return(SingleResult.Create(vdr.AsQueryable())); } } catch (Exception ex) { LogThis(ex, EventLogEntryType.Error, "Exception in GetVmDeploymentRequest()", 100, 100); throw; } //return SingleResult.Create(db.VmDeploymentRequests.Where(vmdeploymentrequest => vmdeploymentrequest.ID == key)); }
//********************************************************************* /// /// <summary> /// /// </summary> /// //********************************************************************* private void FetchUserAccounts() { return; try { var cs = new CmpServiceLib.CmpService( _eventLog, _cmpDbConnectionString, _aftsDbConnectionString); var userAcountList = cs.FetchUserAccounts(); if (null == userAcountList) { userAcountList = WebHostBasicAuth.Modules.BasicAuthHttpModule.GetDefaultAccountList(); if (null != _eventLog) { _eventLog.WriteEntry("Using default service user account.", EventLogEntryType.Information, 1, 1); } } else if (0 == userAcountList.Count) { userAcountList = WebHostBasicAuth.Modules.BasicAuthHttpModule.GetDefaultAccountList(); if (null != _eventLog) { _eventLog.WriteEntry("Using default service user account.", EventLogEntryType.Information, 1, 1); } } else if (null != _eventLog) { _eventLog.WriteEntry("Using DB source service user accounts.", EventLogEntryType.Information, 1, 1); } WebHostBasicAuth.Modules.BasicAuthHttpModule.UserList = new List <WebHostBasicAuth.Modules.BasicCreds>(); foreach (var UA in userAcountList) { WebHostBasicAuth.Modules.BasicAuthHttpModule.UserList.Add( new WebHostBasicAuth.Modules.BasicCreds(UA.Name, UA.Password)); } if (null != _eventLog) { _eventLog.WriteEntry("Service user accounts set OK", EventLogEntryType.Information, 1, 1); } } catch (Exception ex) { if (null != _eventLog) { _eventLog.WriteEntry("Startup Exception: Unable to fetch CMP service user accounts : " + CmpInterfaceModel.Utilities.UnwindExceptionMessages(ex), EventLogEntryType.Error, 10, 10); } } }
//********************************************************************* /// /// <summary> /// /// </summary> /// <returns></returns> /// //********************************************************************* public object ProcessOpsProcessing() { var cdb = new CmpDb(_cmpDbConnectionString); ReadConfigValues(cdb); if (_submittedQueueBlocked) { return(0); } List <Models.OpRequest> opsReqList = null; try { opsReqList = cdb.FetchOpsRequests( Constants.StatusEnum.Processing.ToString(), true); } catch (Exception ex) { throw new Exception("Exception in ProcessOpsProcessing() " + CmpCommon.Utilities.UnwindExceptionMessages(ex)); } var cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); foreach (var opsReq in opsReqList) { try { var opSpec = CmpInterfaceModel.Utilities.DeSerialize( typeof(OpSpec), opsReq.Config) as OpSpec; if (null == opSpec) { throw new Exception("Unable to deserialize opsReq.Config"); } var resp = cmp.CheckOpsStatus(opSpec.TargetId, opsReq.ServiceProviderStatusCheckTag); if (resp.HadError) { if (resp.Body.Contains("(503)")) { continue; } if (resp.Body.Contains("retry")) { continue; } if (resp.Body.Contains("try again")) { continue; } opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); opsReq.StatusMessage = resp.Body; opsReq.ExceptionMessage = "Error in ProcessOpsProcessing() : " + resp.Body; } else { var stat = new AzureAdminClientLib.AzureAdminTaskStatus(resp.Body, opsReq.RequestType); switch (stat.Result) { case AzureAdminClientLib.AzureAdminTaskStatus.ResultEnum.Succeeded: if (stat.Status.Equals("InProgress")) { if (HasTimedOut(opsReq, OpsTtl)) { opsReq.StatusCode = Constants.StatusEnum.Agedout.ToString(); opsReq.StatusMessage = Constants.StatusEnum.Agedout.ToString(); } else { continue; } } else { opsReq.StatusCode = Constants.StatusEnum.Complete.ToString(); opsReq.StatusMessage = resp.Body; opsReq.ExceptionMessage = ""; } break; case AzureAdminClientLib.AzureAdminTaskStatus.ResultEnum.Success: if (stat.Status.Equals("InProgress")) { if (HasTimedOut(opsReq, OpsTtl)) { opsReq.StatusCode = Constants.StatusEnum.Agedout.ToString(); opsReq.StatusMessage = Constants.StatusEnum.Agedout.ToString(); } else { continue; } } else { opsReq.StatusCode = Constants.StatusEnum.Complete.ToString(); opsReq.StatusMessage = resp.Body; opsReq.ExceptionMessage = ""; } break; case AzureAdminClientLib.AzureAdminTaskStatus.ResultEnum.Failed: if (stat.ErrorMessage.ToLower().Contains("(503)")) { continue; } if (stat.ErrorMessage.ToLower().Contains("retry")) { continue; } if (stat.ErrorMessage.ToLower().Contains("try again")) { continue; } opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); opsReq.StatusMessage = resp.Body; opsReq.ExceptionMessage = "Exception in ProcessOpsProcessing() : Code: '" + stat.ErrorCode + "', Message: " + stat.ErrorMessage; break; } } opsReq.CurrentStateStartTime = DateTime.UtcNow; if (null == opsReq.CurrentStateTryCount) { opsReq.CurrentStateTryCount = 0; } cdb.SetOpsRequestStatus(opsReq, null); } catch (Exception ex) { opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); opsReq.ExceptionMessage = "Exception in ProcessOpsProcessing() " + Utilities.UnwindExceptionMessages(ex); //Utilities.SetVmReqExceptionType(opsReq, // Constants.RequestExceptionTypeCodeEnum.Admin); cdb.SetOpsRequestStatus(opsReq, null); } } return(0); }
//********************************************************************* /// /// <summary> /// /// </summary> /// <param name="opsReq"></param> /// //********************************************************************* private void ProcessOp(Models.OpRequest opsReq) { try { //LogThis(EventLogEntryType.Information, "VmOp Request Submitted", 2, 1); var opcode = CmpInterfaceModel.Constants.VmOpcodeEnum.Undefined; var opSpec = CmpInterfaceModel.Utilities.DeSerialize(typeof(OpSpec), opsReq.Config) as OpSpec; if (null == opSpec) { opsReq.StatusMessage = "Config of given Ops Request could not be deserialized"; opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); return; } try { opcode = (CmpInterfaceModel.Constants.VmOpcodeEnum)Enum.Parse( typeof(CmpInterfaceModel.Constants.VmOpcodeEnum), opsReq.RequestType); } catch (Exception) { opsReq.StatusMessage = "Unknown opcode '" + opsReq.RequestType + "'"; opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); return; } CmpServiceLib.CmpService cmp = null; switch (opcode) { case CmpInterfaceModel.Constants.VmOpcodeEnum.START: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmStart(opSpec.TargetId); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.STOP: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmStop(opSpec.TargetId); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DEALLOCATE: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmDeallocate(opSpec.TargetId); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.RESIZE: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmResize(opSpec.TargetId, opSpec.Vmsize); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.ADDISK: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmAddDisk(opSpec.TargetId, opSpec.Disks); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.RESTART: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmRestart(opSpec.TargetId); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DELETE: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmDelete(opSpec.TargetId, false, false); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DELETEFROMSTORAGE: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmDelete(opSpec.TargetId, true, false); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DELETEONEXCEPTION: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.VmDelete(opSpec.TargetId, true, false); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DETACH: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.DetachDisk(opSpec.TargetId, opSpec.Disks[0], false); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.DETACHANDDELETE: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.DetachDisk(opSpec.TargetId, opSpec.Disks[0], true); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.ATTACHEXISTING: cmp = new CmpServiceLib.CmpService(_eventLog, _cmpDbConnectionString, null); opsReq.ServiceProviderStatusCheckTag = cmp.AttachExistingDisk(opSpec.TargetId, opSpec.Disks[0]); break; case CmpInterfaceModel.Constants.VmOpcodeEnum.Undefined: break; } opsReq.StatusMessage = Constants.StatusEnum.Processing.ToString(); opsReq.StatusCode = Constants.StatusEnum.Processing.ToString(); //LogThis(EventLogEntryType.Information, "VmOp Request Submitted OK", 2, 2); } catch (Exception ex) { LogThis(ex, EventLogEntryType.Error, "CmpWapExtension.OpsController.SubmitOp()", 100, 1); //throw new Microsoft.WindowsAzurePack.CmpWapExtension.Common.PortalException(ex1.Message); opsReq.StatusMessage = Constants.StatusEnum.Exception.ToString(); opsReq.StatusCode = Constants.StatusEnum.Exception.ToString(); opsReq.ExceptionMessage = "Exception in ProcessOp(): " + CmpInterfaceModel.Utilities.UnwindExceptionMessages(ex); } }
//********************************************************************* /// // POST odata/VmDeployments /// <summary> /// /// </summary> /// <param name="vmdeploymentrequest"></param> /// <returns></returns> /// //********************************************************************* //[Authorize] public async Task <IHttpActionResult> Post( CmpInterfaceModel.Models.VmDeploymentRequest vmdeploymentrequest) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var checkForExistingVm = true; var newRequest = true; CmpServiceLib.Models.VmDeploymentRequest response = null; var cmp = new CmpServiceLib.CmpService(_EventLog, _CmpDbConnectionString, _AftsDbConnectionString); vmdeploymentrequest.LastStatusUpdate = DateTime.Now; if (0 == vmdeploymentrequest.ID) { if (cmp.IsVmDepRequestInProcess(vmdeploymentrequest.TargetVmName)) { throw new Exception(string.Format( "A request for deployment for a server with name '{0}' is currently in process. Duplicates not allowed.", vmdeploymentrequest.TargetVmName)); } var vmCfg = CmpInterfaceModel.Models.VmConfig.Deserialize(vmdeploymentrequest.Config); if (null != vmCfg) { if (null != vmCfg.Placement) { if (vmCfg.Placement.RebuildRequest) { checkForExistingVm = false; } } } if (checkForExistingVm) { if (DoesNameResolve(vmdeploymentrequest.TargetVmName)) { throw new Exception(string.Format( "A DNS record for a server with name '{0}' already exists. Duplicates not allowed.", vmdeploymentrequest.TargetVmName)); } } if (vmdeploymentrequest.WhenRequested.Year < 2013) { vmdeploymentrequest.WhenRequested = DateTime.Now; } vmdeploymentrequest.Status = CmpInterfaceModel.Constants.StatusEnum.Submitted.ToString(); } else { newRequest = false; } var vmDepReq = new CmpServiceLib.Models.VmDeploymentRequest { ID = vmdeploymentrequest.ID, ExceptionMessage = vmdeploymentrequest.ExceptionMessage, LastStatusUpdate = vmdeploymentrequest.LastStatusUpdate, ParentAppName = vmdeploymentrequest.ParentAppName, RequestDescription = vmdeploymentrequest.RequestDescription, RequestName = vmdeploymentrequest.RequestName, SourceServerName = vmdeploymentrequest.SourceServerName, SourceVhdFilesCSV = vmdeploymentrequest.SourceVhdFilesCSV, SourceServerRegion = vmdeploymentrequest.SourceServerRegion, StatusCode = vmdeploymentrequest.Status, TagData = vmdeploymentrequest.TagData, TargetLocation = vmdeploymentrequest.TargetLocation, TargetLocationType = vmdeploymentrequest.TargetLocationType, TargetVmName = vmdeploymentrequest.TargetVmName, TargetServicename = vmdeploymentrequest.TargetServiceName, VmSize = vmdeploymentrequest.VmSize, WhenRequested = vmdeploymentrequest.WhenRequested, WhoRequested = vmdeploymentrequest.WhoRequested, Active = vmdeploymentrequest.Active, AftsID = vmdeploymentrequest.AftsID, Config = vmdeploymentrequest.Config, ConfigOriginal = vmdeploymentrequest.Config, ParentAppID = vmdeploymentrequest.ParentAppID, RequestType = vmdeploymentrequest.RequestType, StatusMessage = vmdeploymentrequest.StatusMessage, TargetAccount = vmdeploymentrequest.TargetAccount, TargetAccountCreds = vmdeploymentrequest.TargetAccountCreds, TargetAccountType = vmdeploymentrequest.TargetAccountType, TargetServiceProviderType = vmdeploymentrequest.TargetServiceProviderType, ServiceProviderAccountID = 1, ServiceProviderStatusCheckTag = null, TagID = vmdeploymentrequest.TagID, OverwriteExisting = false, ValidationResults = vmdeploymentrequest.ValidationResults, ExceptionTypeCode = vmdeploymentrequest.ExceptionTypeCode, //CurrentStateStartTime = Now, //CurrentStateTryCount = 0, //LastState = null, //ServiceProviderResourceGroup = null, //Warnings = null }; if (newRequest) { response = cmp.InsertVmDepRequest(vmDepReq); } else { cmp.ResubmitVmDepRequest(vmDepReq); } if (response != null) { vmdeploymentrequest.ID = response.ID; } return(Created(vmdeploymentrequest)); } catch (Exception ex) { LogThis(ex, EventLogEntryType.Error, "Exception in Post()", 100, 100); throw; } }
private void StopCmpServiceTest(CmpServiceLib.CmpService cmpService) { cmpService.AsynchStop(); }