コード例 #1
0
ファイル: Program.cs プロジェクト: SpotLabsNET/VMFactory
 static void Main(string[] args)
 {
     Console.WriteLine(string.Format("{0}: VM Factory Orchestration Simulator", DateTime.UtcNow)); Console.WriteLine(string.Format("{0}: Hit CRT+C to exit.", DateTime.UtcNow));  bool isCriticalException = false;  while (true)
     {
         using (VMFSupportContext db = new VMFSupportContext()) { try { Console.WriteLine(string.Format("\n{0}: Checking request queue.", DateTime.UtcNow)); var queuedVms = db.VMRequests.Where(c => (c.RequestStatus == null || c.RequestStatus == (int)RequestStatus.None || c.RequestStatus == (int)RequestStatus.InstallationCompleted)); if (queuedVms.Count() > 0)
                                                                        {
                                                                            Console.WriteLine(string.Format("{1}: Found {0} VMs queued.", queuedVms.Count(), DateTime.UtcNow)); VMRequest vmToProcess = queuedVms.First(); if (vmToProcess.RequestStatus == (int)RequestStatus.None)
                                                                            {
                                                                                CreateVM.CreateVirtualMachine(vmToProcess, db);
                                                                            }
                                                                            if (vmToProcess.RequestStatus == (int)RequestStatus.InstallationCompleted)
                                                                            {
                                                                                Console.WriteLine(string.Format("{2}: VM [{1}]({0}) ready for finalization", vmToProcess.Id, vmToProcess.DisplayName, DateTime.UtcNow)); DeployVM.DeployVirtualMachineForDownload(vmToProcess, db);
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            Console.WriteLine(string.Format("{0}: No VMs on the queue!", DateTime.UtcNow)); Thread.Sleep(DefaultConfigurationStore.Current.WaitTimeBetweenCicles * 1000);
                                                                        } }                     catch (InvalidOperationException ioe) { Console.WriteLine(string.Format("{0}: Failed! Exception detail bellow.", DateTime.UtcNow));  Console.WriteLine(string.Format("{2}: Processing Error \n {0} \n {1}", ioe.Message, ioe.StackTrace, DateTime.UtcNow)); isCriticalException = true; }                     catch (Exception ex) { Console.WriteLine(string.Format("{2}: Processing Error \n {0} \n {1}", ex.Message, ex.StackTrace, DateTime.UtcNow)); } finally { } if (isCriticalException)
                                                                  {
                                                                      Console.WriteLine(string.Format("{0}: Critical error found. Operation stopped. Press <RETURN> to exit.", DateTime.UtcNow)); if (DefaultConfigurationStore.Current.RequestUserConfirmation)
                                                                      {
                                                                          Console.ReadLine();
                                                                      }
                                                                      return;
                                                                  }
                                                                  Thread.Sleep(10000); }
     }
 }
コード例 #2
0
 public VirtualMachineRequest(long Id)
 {
     using (var db = new VMFSupportContext()) { var x = db.VMRequests;  var requests = from r in db.VMRequests where r.Id == Id select r;  if (requests.Count() == 0)
                                                {
                                                    throw new ArgumentException("Virtual machine couldn't be found!");
                                                }
                                                else
                                                {
                                                    Populate(requests.First());
                                                } }
 }
コード例 #3
0
 /// <summary>
 /// Saves this instance.
 /// The only properties saved/updated will be the: request status and last udpdated date.
 /// </summary>
 /// <returns></returns>
 public bool Save()
 {
     bool result = false; try { using (var db = new VMFSupportContext()) { VMRequest request = (from v in db.VMRequests where v.Id == this.Id select v).First();  if (request == null)
                                                                           {
                                                                               throw new TechnicalException("Virtual machine request not found!");
                                                                           }
                                                                           if (request.RequestStatus != (int)this.Status)
                                                                           {
                                                                               request.RequestStatus = (int)this.Status; request.LastUpdated = DateTime.UtcNow;
                                                                           }
                                                                           if (request.ProcessLog != this.ProcessLog)
                                                                           {
                                                                               request.ProcessLog = this.ProcessLog; request.LastUpdated = DateTime.UtcNow;
                                                                           }
                                                                           db.SaveChanges();  result = true; } } catch (Exception e) { ExceptionManager.HandleException(e); throw; }  return(result);
 }
コード例 #4
0
        public static void CreateVirtualMachine(VMRequest vmToProcess, VMFSupportContext db)
        {
            #region Start VM Creation process

            #region Lauch conditions
            // Check for launch conditions
            Console.WriteLine("Checking for launch conditions.");

            // Call the lauunch checker module
            bool           readyToLounch   = false;
            ValidateLaunch launchValidator = new ValidateLaunch();
            readyToLounch = launchValidator.VerifyLaunchConditions();
            Console.WriteLine("Completed with the result [{0}]", readyToLounch.ToString());

            // dump the screen info
            Console.WriteLine("Checking lounch conditions: {0}", "<TBD> Lounch conditions status");

            #endregion

            if (readyToLounch)
            {
                Console.WriteLine(String.Format("Reserving VM request : {0} ({1})", vmToProcess.MachineName, vmToProcess.Id));  vmToProcess.RequestStatus = (int)RequestStatus.Queued; vmToProcess.ProcessLog = "";  var valErrors = db.GetValidationErrors();  if (valErrors.Count() > 0)
                {
                    foreach (var valErr in valErrors)
                    {
                        foreach (var valerrCol in valErr.ValidationErrors)
                        {
                            Console.WriteLine(String.Format("Validation errors on update: {0} - {1}", valerrCol.PropertyName, valerrCol.ErrorMessage));
                        }
                    }
                }
                else
                {
                    db.SaveChanges();
                } Console.WriteLine(String.Format("Calling the StartProcess for VM : {0} ({1})", vmToProcess.MachineName, vmToProcess.Id)); vmToProcess.RequestStatus = (int)RequestStatus.InProgress; vmToProcess.ProcessLog = "Copying and importing base VM."; db.SaveChanges();   string baseVmSourcePath = DefaultConfigurationStore.Current.BaseVmSourcePath; string destinationFolder = vmToProcess.DestinationFolder;  string baseVmConfigFile = DefaultConfigurationStore.Current.BaseVmConfigFilePath.Replace(baseVmSourcePath, destinationFolder); string newVmName = vmToProcess.DisplayName; string baseVmName = DefaultConfigurationStore.Current.BaseVmName; HyperVHelper.CopyAndImportVM(baseVmName, baseVmSourcePath, destinationFolder, baseVmConfigFile, newVmName);  vmToProcess.ProcessLog = "Preloading boot data."; db.SaveChanges();  string driveLetter = DefaultConfigurationStore.Current.TemporaryDriveLetter; string dismPath = DefaultConfigurationStore.Current.DismPath; string vmId = vmToProcess.Id.ToString(); string vmStatusSvcUrl = DefaultConfigurationStore.Current.VmfStatusServiceUrl; string cfgFileName = DefaultConfigurationStore.Current.VmfConfigFile;  HyperVHelper.PreLoadVHDBootData(driveLetter, dismPath, vmToProcess.DisplayName, vmId, vmStatusSvcUrl, cfgFileName);  vmToProcess.ProcessLog = "Starting VM."; db.SaveChanges();  HyperVHelper.StartVM(vmToProcess.DisplayName);  Console.WriteLine(String.Format("Transferred control for MDT for VM: {0} ({1})", vmToProcess.MachineName, vmToProcess.Id));
            }
            else
            {
                Console.WriteLine("No resources available at the moment. Skipping cycle");  Thread.Sleep(DefaultConfigurationStore.Current.WaitTimeBetweenCicles * 1000);
            }
            #endregion
        }
コード例 #5
0
 public static void DeployVirtualMachineForDownload(VMRequest vmToProcess, VMFSupportContext db)
 {
     Debug.WriteLine("VM [{1}]({0}) Shutting down.", vmToProcess.Id, vmToProcess.DisplayName); if (HyperVHelper.StopVM(vmToProcess.DisplayName))
     {
         Debug.WriteLine("VM [{1}]({0}) Compressing", vmToProcess.Id, vmToProcess.DisplayName);  vmToProcess.RequestStatus = (int)RequestStatus.Packaging; vmToProcess.ProcessLog = "Compressing VHD file."; db.SaveChanges();  VMFinalization finalization = new VMFinalization();  Guid internalId = Guid.NewGuid();  string dropFolder = string.Format(DefaultConfigurationStore.Current.VhdSplitDropLocationTemplate, internalId);  if (finalization.FinalizeVM(vmToProcess.DisplayName, dropFolder, DefaultConfigurationStore.Current.VhdSplitBlockSize, null, null))
         {
             Debug.WriteLine("VM [{1}]({0}) Updating request information", vmToProcess.Id, vmToProcess.DisplayName);  vmToProcess.RequestStatus = (int)RequestStatus.Deploying; vmToProcess.ProcessLog = "Deploying result."; db.SaveChanges(); vmToProcess.VMOutputs.Clear(); DirectoryInfo dirInfo = new DirectoryInfo(dropFolder);                     foreach (FileInfo file in dirInfo.GetFiles())
             {
                 VMOutput vmOut = new VMOutput(); vmOut.FileName = file.Name; vmOut.DownloadUrl = string.Concat(DefaultConfigurationStore.Current.BaseVmDownloadUrl, "/", internalId, "/", file.Name);  vmOut.VMRequest = vmToProcess; vmOut.VMRequestId = vmToProcess.Id; vmOut.VMTemplate = vmToProcess.VMTemplate; vmOut.VMTemplateId = vmToProcess.VMTemplate.Id; vmOut.CreatedOn = file.CreationTime.ToUniversalTime(); vmOut.LastModified = file.LastWriteTime;  vmOut.Log += "File added to the VM Output file list.";  vmToProcess.VMOutputs.Add(vmOut);
             }
             Debug.WriteLine("VM [{1}]({0}) Sending email to the user", vmToProcess.Id, vmToProcess.DisplayName); try { EmailHelper.SendConfirmationEmail(vmToProcess.DisplayName, vmToProcess.CreatedBy, vmToProcess.VMOutputs); } catch (Exception ex) { Console.WriteLine("Processing Error (unable to send email alert) \n {0} \n {1}\n\n", ex.Message, ex.StackTrace); } vmToProcess.RequestStatus = (int)RequestStatus.ReadyForPickup; vmToProcess.ProcessLog = "Done.";  var valErrors = db.GetValidationErrors();                     if (valErrors.Count() > 0)
             {
                 foreach (var valErr in valErrors)
                 {
                     foreach (var valerrCol in valErr.ValidationErrors)
                     {
                         Console.WriteLine("Validation errors on update: {0} - {1}", valerrCol.PropertyName, valerrCol.ErrorMessage);
                     }
                 }
             }
             else
             {
                 db.SaveChanges();
             } if (HyperVHelper.RemoveVM(vmToProcess.DisplayName))
             {
                 try { DirectoryInfo dir = new DirectoryInfo(vmToProcess.DestinationFolder); dir.Delete(true); } catch (Exception ex) { Console.WriteLine("Processing Error (unable to delete VM info) \n {0} \n {1}\n\npath: ", ex.Message, ex.StackTrace, vmToProcess.DestinationFolder); }
             }
             else
             {
                 Console.WriteLine("Processing Error (unable to remove VM from Hyper-V)");
             }
         }
     }
     else
     {
         Console.WriteLine("Unable to stop machine: {0}", vmToProcess.DisplayName);
     }
 }
コード例 #6
0
 /// <summary>
 /// Gets the next virtual machine request.
 /// </summary>
 /// <returns></returns>
 public static VirtualMachineRequest GetNextVirtualMachineRequest()
 {
     VirtualMachineRequest result = null;  try { using (var db = new VMFSupportContext()) { var x = db.VMRequests;  var dbRequests = from r in db.VMRequests where r.RequestStatus == (int)RequestStatus.None orderby r.CreatedOn select r;  result = new VirtualMachineRequest(dbRequests.First <VMRequest>()); } } catch (Exception e) {  }  return(result);
 }