public ClientComServerController()
 {
     _clientComService = new ServiceClientComServer();
     _auditLogService  = new ServiceAuditLog();
     _userId           = Convert.ToInt32(((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type == "user_id")
                                         .Select(c => c.Value).SingleOrDefault());
 }
        public void IpxeBoot(string filename, string type)
        {
            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
            }

            if (string.IsNullOrEmpty(thisComServer.TftpPath))
            {
                Logger.Error($"Com Server With Guid {guid} Does Not Have A Valid Tftp Path");
            }
            if (type == "kernel")
            {
                var path = thisComServer.TftpPath + "kernels" +
                           Path.DirectorySeparatorChar;
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=" + filename);
                HttpContext.Current.Response.TransmitFile(path + filename);
                HttpContext.Current.Response.End();
            }
            else
            {
                var path = thisComServer.TftpPath + "images" +
                           Path.DirectorySeparatorChar;
                HttpContext.Current.Response.ContentType = "application/x-gzip";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=" + filename);
                HttpContext.Current.Response.TransmitFile(path + filename);
                HttpContext.Current.Response.End();
            }
        }
示例#3
0
        private int GenerateProcessArguments()
        {
            var multicastArgs = new DtoMulticastArgs();

            multicastArgs.schema      = new ServiceClientPartition(_imageProfile).GetImageSchema();
            multicastArgs.Environment = _imageProfile.Image.Environment;
            multicastArgs.ImageName   = _imageProfile.Image.Name;
            multicastArgs.Port        = _multicastSession.Port.ToString();

            var comServer = new ServiceClientComServer().GetServer(_multicastSession.ComServerId);

            if (_isOnDemand)
            {
                multicastArgs.ExtraArgs = string.IsNullOrEmpty(_imageProfile.SenderArguments)
                    ? comServer.MulticastSenderArguments
                    : _imageProfile.SenderArguments;
                if (!string.IsNullOrEmpty(_clientCount))
                {
                    multicastArgs.clientCount = _clientCount;
                }
            }
            else
            {
                multicastArgs.ExtraArgs = string.IsNullOrEmpty(_imageProfile.SenderArguments)
                    ? comServer.MulticastSenderArguments
                    : _imageProfile.SenderArguments;
                multicastArgs.clientCount = _computers.Count.ToString();
            }

            if (_multicastServerId == null)
            {
                return(0);
            }


            var pid = new MulticastArguments().RunOnComServer(multicastArgs, comServer);


            if (pid == 0)
            {
                return(pid);
            }

            var activeMulticastSessionServices = new ServiceActiveMulticastSession();

            if (_isOnDemand)
            {
                _multicastSession.Pid  = pid;
                _multicastSession.Name = _group.Name;
                activeMulticastSessionServices.AddActiveMulticastSession(_multicastSession);
            }
            else
            {
                _multicastSession.Pid = pid;
                activeMulticastSessionServices.UpdateActiveMulticastSession(_multicastSession);
            }

            return(pid);
        }
示例#4
0
        public static List <string> GetComServerLogs(int comServerId)
        {
            var comServer    = new ServiceClientComServer().GetServer(comServerId);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            return(new APICall().ClientComServerApi.GetComServerLogs(comServer.Url, "", decryptedKey));
        }
示例#5
0
        public bool Sync()
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var folder in new [] { "client_versions", "software_uploads" })
                    {
                        RoboCommand backup = new RoboCommand();
                        // events
                        backup.OnError += Backup_OnError;

                        // copy options
                        backup.CopyOptions.Source             = ServiceSetting.GetSettingValue(SettingStrings.StoragePath) + folder;
                        backup.CopyOptions.Destination        = thisComServer.LocalStoragePath + folder.Trim('\\');
                        backup.CopyOptions.CopySubdirectories = true;
                        backup.CopyOptions.UseUnbufferedIo    = true;
                        if (thisComServer.ReplicationRateIpg != 0)
                        {
                            backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                        }
                        else
                        {
                            backup.CopyOptions.InterPacketGap = 0;
                        }
                        // select options
                        backup.CopyOptions.Mirror = true;
                        backup.CopyOptions.Purge  = true;

                        backup.LoggingOptions.VerboseOutput = false;
                        // retry options
                        backup.RetryOptions.RetryCount    = 3;
                        backup.RetryOptions.RetryWaitTime = 10;
                        backup.Start().Wait();
                    }
                    return(true);
                }
                return(false);
            }
        }
示例#6
0
        public DtoFreeSpace GetComServerFreeSpace()
        {
            var    dpFreeSpace = new DtoFreeSpace();
            string path        = string.Empty;

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return(null);
            }

            path             = thisComServer.LocalStoragePath;
            dpFreeSpace.name = thisComServer.DisplayName;


            dpFreeSpace.dPPath = path;

            if (Directory.Exists(path))
            {
                ulong freespace = 0;
                ulong total     = 0;


                bool success;

                success = DriveFreeBytes(path, out freespace, out total);



                if (!success)
                {
                    return(null);
                }

                var freePercent = 0;
                var usedPercent = 0;

                if (total > 0 && freespace > 0)
                {
                    freePercent = (int)(0.5f + 100f * Convert.ToInt64(freespace) / Convert.ToInt64(total));
                    usedPercent =
                        (int)(0.5f + 100f * Convert.ToInt64(total - freespace) / Convert.ToInt64(total));
                }
                dpFreeSpace.freespace   = freespace;
                dpFreeSpace.total       = total;
                dpFreeSpace.freePercent = freePercent;
                dpFreeSpace.usedPercent = usedPercent;
            }
            return(dpFreeSpace);
        }
        public HttpResponseMessage GetImagingFile(DtoImageFileRequest fileRequest)
        {
            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            var profile = new ServiceImageProfile().ReadProfile(fileRequest.profileId);

            if (profile == null)
            {
                Logger.Error($"Image Profile Not Found: {fileRequest.profileId}");
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            var maxBitRate = thisComServer.ImagingMaxBps;
            var basePath   = thisComServer.LocalStoragePath;

            var fullPath = Path.Combine(basePath, "images", profile.Image.Name, $"hd{fileRequest.hdNumber}",
                                        fileRequest.fileName);

            if (File.Exists(fullPath))
            {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                try
                {
                    var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
                    if (maxBitRate == 0)
                    {
                        result.Content = new StreamContent(stream);
                    }
                    else
                    {
                        Stream throttledStream = new ThrottledStream(stream, maxBitRate);
                        result.Content = new StreamContent(throttledStream);
                    }

                    result.Content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("inline");
                    result.Content.Headers.ContentDisposition.FileName = fileRequest.fileName;
                    return(result);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
示例#8
0
        public bool CheckImageExists(int imageId)
        {
            //storage type is set to smb, get this current com server's storage
            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }

            var image = new ServiceImage().GetImage(imageId);

            var basePath = thisComServer.LocalStoragePath;

            if (string.IsNullOrEmpty(image.Name))
            {
                return(false);
            }


            var imagePath = Path.Combine(basePath, "images", image.Name);

            if (!Directory.Exists(imagePath))
            {
                return(false);
            }
            var guidPath = Path.Combine(imagePath, "guid");

            if (!File.Exists(guidPath))
            {
                return(false);
            }
            using (StreamReader reader = new StreamReader(guidPath))
            {
                var fileGuid = reader.ReadLine() ?? "";
                if (fileGuid.Equals(image.LastUploadGuid))
                {
                    return(true);
                }
            }


            return(false);
        }
示例#9
0
        public HttpResponseMessage GetFile(DtoClientFileRequest fileRequest)
        {
            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            var maxBitRate = thisComServer.EmMaxBps;
            var basePath   = thisComServer.LocalStoragePath;

            var fullPath = Path.Combine(basePath, "software_uploads", fileRequest.ModuleGuid,
                                        fileRequest.FileName);

            if (File.Exists(fullPath))
            {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                try
                {
                    var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
                    if (maxBitRate == 0)
                    {
                        result.Content = new StreamContent(stream);
                    }
                    else
                    {
                        Stream throttledStream = new ThrottledStream(stream, maxBitRate);
                        result.Content = new StreamContent(throttledStream);
                    }
                    result.Content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                    result.Content.Headers.ContentDisposition.FileName = fileRequest.FileName;
                    return(result);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                }
            }
            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
示例#10
0
        public static List <string> GetKernels()
        {
            var result = new List <string>();

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return(result);
            }

            if (string.IsNullOrEmpty(thisComServer.TftpPath))
            {
                log.Error($"Com Server With Guid {guid} Does Not Have A Valid Tftp Path");
                return(result);
            }

            var kernelPath = Path.Combine(thisComServer.TftpPath, "kernels");

            try
            {
                var kernelFiles = Directory.GetFiles(kernelPath, "*.*");

                for (var x = 0; x < kernelFiles.Length; x++)
                {
                    result.Add(Path.GetFileName(kernelFiles[x]));
                }
            }

            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            return(result);
        }
示例#11
0
        public string IpxeLogin(string username, string password, string kernel, string bootImage, string task)
        {
            //no reason to look at other com  servers, just continue to use the currently connected one.
            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                return(null);
            }

            string userToken;
            var    webRequiresLogin     = ServiceSetting.GetSettingValue(SettingStrings.WebTasksRequireLogin);
            var    consoleRequiresLogin = ServiceSetting.GetSettingValue(SettingStrings.ConsoleTasksRequireLogin);
            var    globalToken          = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingToken);

            if (webRequiresLogin.Equals("False") || consoleRequiresLogin.Equals("False"))
            {
                userToken = globalToken;
            }
            else
            {
                userToken = "";
            }

            var webPath            = thisComServer.Url + "clientimaging/,";
            var globalComputerArgs = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingArguments);


            var iPxePath = webPath;

            if (iPxePath.Contains("https://"))
            {
                if (ServiceSetting.GetSettingValue(SettingStrings.IpxeSSL).Equals("False"))
                {
                    iPxePath = iPxePath.ToLower().Replace("https://", "http://");
                    var currentPort = iPxePath.Split(':').Last();
                    iPxePath = iPxePath.Replace(currentPort, ServiceSetting.GetSettingValue(SettingStrings.IpxeHttpPort)) + "/clientimaging/";
                }
                else
                {
                    iPxePath += "clientimaging/";
                }
            }
            else
            {
                iPxePath += "clientimaging/";
            }

            var newLineChar = "\n";

            var validationResult = GlobalLogin(username, password, "iPXE");

            if (!validationResult.Success)
            {
                return("goto Menu");
            }
            var lines = "#!ipxe" + newLineChar;

            lines += "kernel " + iPxePath + "IpxeBoot?filename=" + kernel +
                     "&type=kernel" +
                     " initrd=" + bootImage + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" +
                     webPath + " USER_TOKEN=" + userToken + " consoleblank=0 " +
                     globalComputerArgs + newLineChar;
            lines += "imgfetch --name " + bootImage + " " + iPxePath +
                     "IpxeBoot?filename=" +
                     bootImage + "&type=bootimage" + newLineChar;
            lines += "boot";

            return(lines);
        }
示例#12
0
        public DtoDownloadConnectionResult CreateDownloadConnection(DtoDownloadConRequest conRequest)
        {
            var result = new DtoDownloadConnectionResult();

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                result.ErrorMessage = $"Com Server With Guid {guid} Not Found";
                return(result);
            }


            if (!int.TryParse(thisComServer.EmMaxClients.ToString(), out var maxClientConnections))
            {
                result.ErrorMessage = "Could Not Determine The MaxClientConnections For The Com Server: " +
                                      conRequest.ComServer;
                return(result);
            }

            if (maxClientConnections == 0) // zero is unlimited
            {
                result.Success     = true;
                result.QueueIsFull = false;
                return(result);
            }

            var client = new ServiceComputer().GetByGuid(conRequest.ComputerGuid);

            if (client == null)
            {
                result.ErrorMessage = "Could Not Find Computer With Guid: " + RequestContext.Principal.Identity.Name;
                return(result);
            }



            var serviceCurrentDownloads = new ServiceCurrentDownload();
            var currentConnections      = serviceCurrentDownloads.TotalCount(conRequest.ComServer);
            var activeClient            = serviceCurrentDownloads.GetByClientId(client.Id, conRequest.ComServer);

            if (activeClient == null && (currentConnections >= maxClientConnections))
            {
                var activeCountAfterExpire = serviceCurrentDownloads.ExpireOldConnections();
                if (activeCountAfterExpire >= maxClientConnections)
                {
                    result.Success     = true;
                    result.QueueIsFull = true;
                    return(result);
                }
            }

            //add new download connection for this client
            if (activeClient == null)
            {
                var currentDownload = new EntityCurrentDownload();
                currentDownload.ComputerId = client.Id;
                currentDownload.ComServer  = conRequest.ComServer;
                serviceCurrentDownloads.Add(currentDownload);
                result.Success     = true;
                result.QueueIsFull = false;
            }
            //update time for existing download connection
            else
            {
                activeClient.LastRequestTimeLocal = DateTime.Now;
                serviceCurrentDownloads.Update(activeClient);
                result.Success     = true;
                result.QueueIsFull = false;
            }

            return(result);
        }
示例#13
0
        public bool Create(DtoBootMenuGenOptions bootOptions)
        {
            _defaultBoot = bootOptions;
            var mode = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader);

            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

            _thisComServer = new ServiceClientComServer().GetServerByGuid(guid);
            if (_thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }

            if (string.IsNullOrEmpty(_thisComServer.TftpPath))
            {
                log.Error($"Com Server With Guid {guid} Does Not Have A Valid Tftp Path");
                return(false);
            }

            _bootEntryServices  = new ServiceCustomBootMenu();
            _globalComputerArgs = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingArguments);

            var defaultCluster        = new UnitOfWork().ComServerClusterRepository.Get(x => x.IsDefault).FirstOrDefault();
            var defaultImagingServers = new UnitOfWork().ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id);

            _webPath = "\"";

            //the global default menu doesn't really have a way of knowing which imaging server to connect to since it's not related to a computer /group with
            // the com server assigned.  Instead use this server if it's an imaging server, otherwise use the default cluster.
            if (_thisComServer.IsImagingServer)
            {
                _webPath += _thisComServer.Url + "clientimaging/ ";
            }
            else
            {
                foreach (var imageServer in defaultImagingServers)
                {
                    var url = new ServiceClientComServer().GetServer(imageServer.ComServerId).Url;
                    _webPath += url + "clientimaging/ "; //adds a space delimiter
                }
            }
            _webPath  = _webPath.Trim(' ');
            _webPath += "\"";

            var webRequiresLogin     = ServiceSetting.GetSettingValue(SettingStrings.WebTasksRequireLogin);
            var consoleRequiresLogin = ServiceSetting.GetSettingValue(SettingStrings.ConsoleTasksRequireLogin);
            var globalToken          = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingToken);

            if (webRequiresLogin.Equals("False") || consoleRequiresLogin.Equals("False"))
            {
                _userToken = globalToken;
            }
            else
            {
                _userToken = "";
            }

            if (_defaultBoot.Type == "standard")
            {
                if (mode.Contains("ipxe"))
                {
                    CreateIpxeMenu(defaultCluster.Id);
                }
                else if (mode.Contains("grub"))
                {
                    CreateGrubMenu();
                }
                else
                {
                    CreateSyslinuxMenu();
                }
            }
            else
            {
                foreach (var proxyMode in new[] { "bios", "efi32", "efi64" })
                {
                    bootOptions.Type = proxyMode;
                    if (proxyMode.Equals("bios"))
                    {
                        bootOptions.Kernel    = bootOptions.BiosKernel;
                        bootOptions.BootImage = bootOptions.BiosBootImage;
                    }
                    else if (proxyMode.Equals("efi32"))
                    {
                        bootOptions.Kernel    = bootOptions.Efi32Kernel;
                        bootOptions.BootImage = bootOptions.Efi32BootImage;
                    }
                    else
                    {
                        bootOptions.Kernel    = bootOptions.Efi64Kernel;
                        bootOptions.BootImage = bootOptions.Efi64BootImage;
                    }
                    CreateIpxeMenu(defaultCluster.Id);
                    CreateSyslinuxMenu();
                    CreateGrubMenu();
                }
            }

            return(true);
        }
示例#14
0
        public string GetDefaultBootMenuPath(string type, int comServerId)
        {
            string path      = null;
            var    comServer = new ServiceClientComServer().GetServer(comServerId);
            var    tftpPath  = comServer.TftpPath;
            var    mode      = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader);
            var    proxyDhcp = ServiceSetting.GetSettingValue(SettingStrings.ProxyDhcpEnabled);

            if (proxyDhcp == "Yes")
            {
                var biosFile  = ServiceSetting.GetSettingValue(SettingStrings.ProxyBiosBootloader);
                var efi32File = ServiceSetting.GetSettingValue(SettingStrings.ProxyEfi32Bootloader);
                var efi64File = ServiceSetting.GetSettingValue(SettingStrings.ProxyEfi64Bootloader);

                if (type == "bios")
                {
                    if (biosFile.Contains("ipxe"))
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default.ipxe";
                    }
                    else
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default";
                    }
                }

                if (type == "efi32")
                {
                    if (efi32File.Contains("ipxe"))
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default.ipxe";
                    }
                    else
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default";
                    }
                }

                if (type == "efi64")
                {
                    if (efi64File.Contains("ipxe"))
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default.ipxe";
                    }
                    else if (efi64File.Contains("grub"))
                    {
                        path = tftpPath + "grub" + Path.DirectorySeparatorChar + "grub.cfg";
                    }
                    else
                    {
                        path = tftpPath + "proxy" + Path.DirectorySeparatorChar +
                               type + Path.DirectorySeparatorChar + "pxelinux.cfg" +
                               Path.DirectorySeparatorChar + "default";
                    }
                }
            }
            else
            {
                if (mode.Contains("ipxe"))
                {
                    path = tftpPath + "pxelinux.cfg" + Path.DirectorySeparatorChar +
                           "default.ipxe";
                }
                else if (mode.Contains("grub"))
                {
                    path = tftpPath + "grub" + Path.DirectorySeparatorChar + "grub.cfg";
                }
                else
                {
                    path = tftpPath + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default";
                }
            }
            return(path);
        }
示例#15
0
        private bool FromCom()
        {
            var uow = new UnitOfWork();
            var imagesToReplicate = new List <EntityImage>();

            Logger.Info("Starting Image Replication From Com Servers");
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }
            if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True"))
            {
                Logger.Info("Image replication is not used when direct smb imaging is enabled.");
                return(true); //Don't need to sync images when direct to smb is used.
            }
            //find all images that need copied from com servers to the SMB share
            var completedImages = uow.ImageRepository.Get(x => !string.IsNullOrEmpty(x.LastUploadGuid));

            if (completedImages == null)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            if (completedImages.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //check if images already exist on smb share
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    if (!Directory.Exists(Path.Combine(basePath, "images")))
                    {
                        try
                        {
                            Directory.CreateDirectory(Path.Combine(basePath, "images"));
                        }
                        catch
                        {
                            Logger.Error("Could Not Sync Images.  The images folder could not be created on smb share");
                            return(false);
                        }
                    }
                    foreach (var image in completedImages)
                    {
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue; //should never happen, but could potential erase all images if so, when syncing
                        }
                        var imagePath = Path.Combine(basePath, "images", image.Name);
                        if (!Directory.Exists(imagePath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        var guidPath = Path.Combine(imagePath, "guid");
                        if (!File.Exists(guidPath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        using (StreamReader reader = new StreamReader(guidPath))
                        {
                            var fileGuid = reader.ReadLine() ?? "";
                            if (!fileGuid.Equals(image.LastUploadGuid))
                            {
                                //image on smb is older than what database says
                                imagesToReplicate.Add(image);
                                continue;
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (imagesToReplicate.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //find com servers with the image to replicate

            var comServers   = uow.ClientComServerRepository.Get(x => x.IsImagingServer);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            var comImageDict = new Dictionary <int, int>();

            foreach (var image in imagesToReplicate)
            {
                foreach (var com in comServers)
                {
                    var hasImage = new APICall().ClientComServerApi.CheckImageExists(com.Url, "", decryptedKey, image.Id);
                    if (hasImage)
                    {
                        if (!comImageDict.ContainsKey(image.Id))
                        {
                            comImageDict.Add(image.Id, com.Id);
                            break; //only add image to a single com server, don't want to replicate image multiple times if multiple coms have it
                        }
                    }
                }
            }

            var groupedByServer = comImageDict.GroupBy(x => x.Value).ToDictionary(y => y.Key, y => y.Select(x => x.Key).ToList());

            foreach (var c in groupedByServer)
            {
                var comServerId      = c.Key;
                var thisComImageList = new List <int>();
                foreach (var imageId in c.Value)
                {
                    thisComImageList.Add(imageId);
                }

                var comServer = new ServiceClientComServer().GetServer(comServerId);
                new APICall().ClientComServerApi.SyncComToSmb(comServer.Url, "", decryptedKey, thisComImageList);
            }
            return(true);
        }
示例#16
0
        public string Create()
        {
            _imageProfile = new ServiceImageProfile().ReadProfile(_group.ImageProfileId);
            if (_imageProfile == null)
            {
                return("The Image Profile Does Not Exist");
            }

            if (_imageProfile.Image == null)
            {
                return("The Image Does Not Exist");
            }

            _multicastServerId = _isOnDemand
                ? _comServerId
                : new GetMulticastServer(_group).Run();

            if (_multicastServerId == null)
            {
                return("Could Not Find Any Available Multicast Servers");
            }


            var comServer = new ServiceClientComServer().GetServer(Convert.ToInt32(_multicastServerId));

            if (string.IsNullOrEmpty(comServer.MulticastInterfaceIp))
            {
                return("The Com Server's Multicast Interface IP Address Is Not Populated");
            }


            _multicastSession.Port = new ServicePort().GetNextPort(_multicastServerId);
            if (_multicastSession.Port == 0)
            {
                return("Could Not Determine Current Port Base");
            }

            _multicastSession.ComServerId = Convert.ToInt32(_multicastServerId);
            _multicastSession.UserId      = _userId;

            if (_isOnDemand)
            {
                if (string.IsNullOrEmpty(_multicastSession.Name))
                {
                    _multicastSession.Name = _multicastSession.Port.ToString();
                }

                if (string.IsNullOrEmpty(_multicastSession.Name) || !_multicastSession.Name.All(c => char.IsLetterOrDigit(c) || c == '_' || c == '-'))
                {
                    return("Multicast Session Name Is Not Valid");
                }

                _group.Name = _multicastSession.Name;
                var onDemandprocessArguments = GenerateProcessArguments();
                if (onDemandprocessArguments == 0)
                {
                    return("Could Not Start The Multicast Application");
                }

                var ondAuditLog = new EntityAuditLog();
                ondAuditLog.AuditType = EnumAuditEntry.AuditType.OnDemandMulticast;
                ondAuditLog.ObjectId  = _imageProfile.ImageId;
                var ondUser = new ServiceUser().GetUser(_userId);
                if (ondUser != null)
                {
                    ondAuditLog.UserName = ondUser.Name;
                }
                ondAuditLog.ObjectName = _imageProfile.Image.Name;
                ondAuditLog.UserId     = _userId;
                ondAuditLog.ObjectType = "Image";
                ondAuditLog.ObjectJson = JsonConvert.SerializeObject(_multicastSession);
                new ServiceAuditLog().AddAuditLog(ondAuditLog);
                return("Successfully Started Multicast " + _group.Name);
            }
            //End of the road for starting an on demand multicast


            //Continue On If multicast is for a group
            _multicastSession.Name = _group.Name;
            _computers             = new ServiceGroup().GetGroupMembers(_group.Id);
            if (_computers.Count < 1)
            {
                return("The Group Does Not Have Any Members");
            }

            var activeMulticastSessionServices = new ServiceActiveMulticastSession();

            if (!activeMulticastSessionServices.AddActiveMulticastSession(_multicastSession))
            {
                return("Could Not Create Multicast Database Task.  An Existing Task May Be Running.");
            }

            if (!CreateComputerTasks())
            {
                activeMulticastSessionServices.Delete(_multicastSession.Id);
                return("Could Not Create Computer Database Tasks.  A Computer May Have An Existing Task.");
            }

            if (!CreatePxeFiles())
            {
                activeMulticastSessionServices.Delete(_multicastSession.Id);
                return("Could Not Create Computer Boot Files");
            }

            if (!CreateTaskArguments())
            {
                activeMulticastSessionServices.Delete(_multicastSession.Id);
                return("Could Not Create Computer Task Arguments");
            }

            var processArguments = GenerateProcessArguments();

            if (processArguments == 0)
            {
                activeMulticastSessionServices.Delete(_multicastSession.Id);
                return("Could Not Start The Multicast Application");
            }

            foreach (var computer in _computers)
            {
                _computerServices.Wakeup(computer.Id);
            }

            var auditLog = new EntityAuditLog();

            auditLog.AuditType = EnumAuditEntry.AuditType.Multicast;
            auditLog.ObjectId  = _group.Id;
            var user = new ServiceUser().GetUser(_userId);

            if (user != null)
            {
                auditLog.UserName = user.Name;
            }
            auditLog.ObjectName = _group.Name;
            auditLog.UserId     = _userId;
            auditLog.ObjectType = "Group";
            auditLog.ObjectJson = JsonConvert.SerializeObject(_multicastSession);
            new ServiceAuditLog().AddAuditLog(auditLog);

            auditLog.ObjectId   = _imageProfile.ImageId;
            auditLog.ObjectName = _imageProfile.Image.Name;
            auditLog.ObjectType = "Image";
            new ServiceAuditLog().AddAuditLog(auditLog);

            return("Successfully Started Multicast " + _group.Name);
        }
示例#17
0
        private bool ToCom()
        {
            var uow = new UnitOfWork();
            var imagesToReplicate = new List <EntityImage>();

            Logger.Info("Starting Image Replication To Com Servers");
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                Logger.Info("Image replication is not used when storage type is set to local.");
                return(true);
            }
            if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True"))
            {
                Logger.Info("Image replication is not used when direct smb imaging is enabled.");
                return(true); //Don't need to sync images when direct to smb is used.
            }

            //find all images that need copied from SMB share to com servers
            var completedImages = uow.ImageRepository.Get(x => !string.IsNullOrEmpty(x.LastUploadGuid));

            if (completedImages == null)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            if (completedImages.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //check if images already exist on smb share
            var basePath = ServiceSetting.GetSettingValue(SettingStrings.StoragePath);

            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var image in completedImages)
                    {
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue; //should never happen, but could potential erase all images if so, when syncing
                        }
                        var imagePath = Path.Combine(basePath, "images", image.Name);
                        if (!Directory.Exists(imagePath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        var guidPath = Path.Combine(imagePath, "guid");
                        if (!File.Exists(guidPath))
                        {
                            imagesToReplicate.Add(image);
                            continue;
                        }
                        using (StreamReader reader = new StreamReader(guidPath))
                        {
                            var fileGuid = reader.ReadLine() ?? "";
                            if (fileGuid.Equals(image.LastUploadGuid))
                            {
                                //image on smb share matches what database says, this is the master and should be replicated to com servers
                                imagesToReplicate.Add(image);
                                continue;
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (imagesToReplicate.Count == 0)
            {
                Logger.Info("No Images Found To Replicate");
                return(true);
            }

            //find com servers that need this image

            var comServers   = uow.ClientComServerRepository.Get(x => x.IsImagingServer);
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);

            var comImageList = new List <DtoRepImageCom>();

            foreach (var com in comServers)
            {
                foreach (var image in imagesToReplicate)
                {
                    var hasImage = new APICall().ClientComServerApi.CheckImageExists(com.Url, "", decryptedKey, image.Id);
                    if (hasImage)
                    {
                        continue; //already has image move to next com server
                    }
                    else
                    {
                        var comImage = new DtoRepImageCom();
                        comImage.ComServerId = com.Id;
                        comImage.ImageId     = image.Id;
                        comImageList.Add(comImage);
                    }
                }
            }

            if (comImageList.Count == 0)
            {
                Logger.Info("Com Server Images Are All Up To Date.  Skipping Replication.");
                return(true);
            }

            foreach (var c in comImageList.GroupBy(x => x.ComServerId))
            {
                var comServerId      = c.First().ComServerId;
                var thisComImageList = new List <int>();
                foreach (var imageId in c)
                {
                    thisComImageList.Add(imageId.ImageId);
                }

                var comServer = new ServiceClientComServer().GetServer(comServerId);
                new APICall().ClientComServerApi.SyncSmbToCom(comServer.Url, "", decryptedKey, thisComImageList);
            }
            return(true);
        }
示例#18
0
        private string VerifyPolicy()
        {
            if (string.IsNullOrEmpty(_policy.Name))
            {
                return("The Policy's Name Is Not Valid.");
            }
            if (string.IsNullOrEmpty(_policy.Guid))
            {
                return("The Policy's Guid Is Not Valid.");
            }

            if (_policy.Frequency != EnumPolicy.Frequency.OncePerComputer &&
                _policy.Frequency != EnumPolicy.Frequency.OncePerDay &&
                _policy.Frequency != EnumPolicy.Frequency.OncePerMonth &&
                _policy.Frequency != EnumPolicy.Frequency.OncePerUserPerComputer &&
                _policy.Frequency != EnumPolicy.Frequency.OncePerWeek &&
                _policy.Frequency != EnumPolicy.Frequency.Ongoing &&
                _policy.Frequency != EnumPolicy.Frequency.EveryXdays &&
                _policy.Frequency != EnumPolicy.Frequency.EveryXhours)
            {
                return("The Policy's Frequency Is Not Valid.");
            }
            if (_policy.Trigger != EnumPolicy.Trigger.Checkin && _policy.Trigger != EnumPolicy.Trigger.Login &&
                _policy.Trigger != EnumPolicy.Trigger.Startup &&
                _policy.Trigger != EnumPolicy.Trigger.StartupOrCheckin)
            {
                return("The Policy's Trigger Is Not Valid.");
            }
            if (_policy.RunInventory != EnumPolicy.InventoryAction.After &&
                _policy.RunInventory != EnumPolicy.InventoryAction.Before &&
                _policy.RunInventory != EnumPolicy.InventoryAction.Both &&
                _policy.RunInventory != EnumPolicy.InventoryAction.Disabled)
            {
                return("The Policy's Run Inventory Is Not Valid.");
            }
            int value;

            if (!int.TryParse(_policy.SubFrequency.ToString(), out value))
            {
                return("The Policy's Sub Frequency Is Not Valid.");
            }
            if (_policy.CompletedAction != EnumPolicy.CompletedAction.DoNothing &&
                _policy.CompletedAction != EnumPolicy.CompletedAction.Reboot && _policy.CompletedAction != EnumPolicy.CompletedAction.RebootIfNoLogins)
            {
                return("The Policy's Completed Action Is Not Valid.");
            }
            if (_policy.ExecutionType != EnumPolicy.ExecutionType.Cache &&
                _policy.ExecutionType != EnumPolicy.ExecutionType.Install)
            {
                return("The Policy's Execution Type Is Not Valid.");
            }
            if (_policy.ErrorAction != EnumPolicy.ErrorAction.AbortCurrentPolicy &&
                _policy.ErrorAction != EnumPolicy.ErrorAction.AbortRemainingPolicies &&
                _policy.ErrorAction != EnumPolicy.ErrorAction.Continue)
            {
                return("The Policy's Error Action Is Not Valid");
            }
            if (_policy.MissedAction != EnumPolicy.FrequencyMissedAction.NextOpportunity &&
                _policy.MissedAction != EnumPolicy.FrequencyMissedAction.ScheduleDayOnly)
            {
                return("The Policy's Frequency Missed Action Is Not Valid.");
            }
            if (_policy.LogLevel != EnumPolicy.LogLevel.Full &&
                _policy.LogLevel != EnumPolicy.LogLevel.HiddenArguments &&
                _policy.LogLevel != EnumPolicy.LogLevel.None)
            {
                return("The Policy's Log Level Is Not Valid.");
            }
            if (_policy.WuType != EnumPolicy.WuType.Disabled && _policy.WuType != EnumPolicy.WuType.Microsoft &&
                _policy.WuType != EnumPolicy.WuType.MicrosoftSkipUpgrades &&
                _policy.WuType != EnumPolicy.WuType.Wsus && _policy.WuType != EnumPolicy.WuType.WsusSkipUpgrades)
            {
                return("The Policy's Windows Update Type Is Not Valid.");
            }
            if (_policy.AutoArchiveType != EnumPolicy.AutoArchiveType.AfterXdays &&
                _policy.AutoArchiveType != EnumPolicy.AutoArchiveType.None &&
                _policy.AutoArchiveType != EnumPolicy.AutoArchiveType.WhenComplete)
            {
                return("The Policy's Auto Archive Type Is Not Valid.");
            }

            if (_policy.AutoArchiveType == EnumPolicy.AutoArchiveType.AfterXdays)
            {
                int autoArchiveSub;
                if (!int.TryParse(_policy.AutoArchiveSub, out autoArchiveSub))
                {
                    return("The Policy's Auto Archive Sub Is Not Valid.");
                }
            }

            if (_policy.WindowStartScheduleId != -1)
            {
                var schedule = new ServiceSchedule().GetSchedule(_policy.WindowStartScheduleId);
                if (schedule == null)
                {
                    return("The Policy's Start Schedule Id Is Not Valid.");
                }
            }
            if (_policy.WindowEndScheduleId != -1)
            {
                var schedule = new ServiceSchedule().GetSchedule(_policy.WindowEndScheduleId);
                if (schedule == null)
                {
                    return("The Policy's End Schedule Id Is Not Valid.");
                }
            }

            if (_policy.PolicyComCondition != EnumPolicy.PolicyComCondition.Any &&
                _policy.PolicyComCondition != EnumPolicy.PolicyComCondition.Selective)
            {
                return("The Policy's Com Server Condition Is Not Valid");
            }
            if (_policy.PolicyComCondition == EnumPolicy.PolicyComCondition.Selective)
            {
                var policyComServers = _policyService.GetPolicyComServers(_policy.Id);
                if (policyComServers == null)
                {
                    return("The Policy's Selected Com Servers Are Not Valid");
                }
                if (policyComServers.Count == 0)
                {
                    return("The Policy's Selected Com Servers Are Not Valid.  At Least One Server Must Be Selected.");
                }
                foreach (var policyComServer in policyComServers)
                {
                    var comServer = new ServiceClientComServer().GetServer(policyComServer.ComServerId);
                    if (comServer == null)
                    {
                        return("The Policy's Selected Com Servers Are Not Valid.  A Specified Com Server Does Not Exist");
                    }
                }
            }
            if (_policy.ConditionId != -1) // -1 = disabled
            {
                var conditionScript = new ServiceScriptModule().GetModule(_policy.ConditionId);
                if (conditionScript == null)
                {
                    return($"Condition Script For {_policy.Name} Does Not Exist");
                }

                if (!conditionScript.IsCondition)
                {
                    return($"The Condition Script For {_policy.Name} Is Not Currently Set As A Condition");
                }

                if (string.IsNullOrEmpty(conditionScript.Name))
                {
                    return($"A Condition Script For {_policy.Name} Has An Invalid Name");
                }

                if (conditionScript.Archived)
                {
                    return($"A Condition Script For {_policy.Name} Is Archived");
                }

                if (string.IsNullOrEmpty(conditionScript.ScriptContents))
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid Script.  It Cannot Be Empty.");
                }

                if (string.IsNullOrEmpty(conditionScript.Guid))
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid GUID");
                }

                if (conditionScript.ScriptType != EnumScriptModule.ScriptType.Batch &&
                    conditionScript.ScriptType != EnumScriptModule.ScriptType.Powershell &&
                    conditionScript.ScriptType != EnumScriptModule.ScriptType.VbScript)
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid Type");
                }

                if (!int.TryParse(conditionScript.Timeout.ToString(), out value))
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid Timeout");
                }

                List <string> successCodes = new List <string>();
                foreach (var successCode in conditionScript.SuccessCodes.Split(','))
                {
                    successCodes.Add(successCode);
                }

                if (successCodes.Count == 0)
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid Success Code");
                }

                if (successCodes.Any(code => !int.TryParse(code, out value)))
                {
                    return("Condition Script: " + conditionScript.Name + " Has An Invalid Success Code");
                }

                if (!string.IsNullOrEmpty(conditionScript.WorkingDirectory))
                {
                    try
                    {
                        Path.GetFullPath(conditionScript.WorkingDirectory);
                    }
                    catch
                    {
                        return("Condition Script: " + conditionScript.Name + " Has An Invalid Working Directory");
                    }
                }

                if (conditionScript.ImpersonationId != -1)
                {
                    var impAccount = new ServiceImpersonationAccount().GetAccount(conditionScript.ImpersonationId);
                    if (impAccount == null)
                    {
                        return("Condition Script: " + conditionScript.Name + " Has An Invalid Impersonation Account");
                    }
                }


                if (_policy.ConditionFailedAction != EnumCondition.FailedAction.MarkFailed &&
                    _policy.ConditionFailedAction != EnumCondition.FailedAction.MarkNotApplicable && _policy.ConditionFailedAction != EnumCondition.FailedAction.MarkSkipped &&
                    _policy.ConditionFailedAction != EnumCondition.FailedAction.MarkSuccess)
                {
                    return($"The Condition Failed Action For {_policy.Name} Is Not Valid");
                }
            }

            return(null);
        }
示例#19
0
        public bool SyncToCom(List <int> imageIds)
        {
            if (!ServiceSetting.GetSettingValue(SettingStrings.StorageType).Equals("SMB"))
            {
                return(true);
            }

            var guid          = ConfigurationManager.AppSettings["ComServerUniqueId"];
            var thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(false);
            }


            using (var unc = new UncServices())
            {
                if (unc.NetUseWithCredentials() || unc.LastError == 1219)
                {
                    foreach (var imageId in imageIds)
                    {
                        var image = new ServiceImage().GetImage(imageId);
                        if (string.IsNullOrEmpty(image.Name))
                        {
                            continue;
                        }
                        var sourcePath = Path.Combine(ServiceSetting.GetSettingValue(SettingStrings.StoragePath), "images", image.Name);
                        var destPath   = Path.Combine(thisComServer.LocalStoragePath, "images", image.Name).TrimEnd('\\');

                        using (RoboCommand backup = new RoboCommand())
                        {
                            // events

                            /*backup.OnFileProcessed += backup_OnFileProcessed;
                             * backup.OnCommandCompleted += backup_OnCommandCompleted;
                             * backup.OnCopyProgressChanged += Backup_OnCopyProgressChanged;
                             */
                            backup.OnError += Backup_OnError;
                            // copy options
                            backup.CopyOptions.Source             = sourcePath;
                            backup.CopyOptions.Destination        = destPath;
                            backup.CopyOptions.CopySubdirectories = true;
                            backup.SelectionOptions.IncludeSame   = true;
                            backup.CopyOptions.UseUnbufferedIo    = true;
                            if (thisComServer.ReplicationRateIpg != 0)
                            {
                                backup.CopyOptions.InterPacketGap = thisComServer.ReplicationRateIpg;
                            }
                            else
                            {
                                backup.CopyOptions.InterPacketGap = 0;
                            }
                            // select options
                            backup.CopyOptions.Mirror           = true;
                            backup.CopyOptions.Purge            = true;
                            backup.LoggingOptions.VerboseOutput = false;

                            backup.SelectionOptions.ExcludeFiles = "guid";
                            // retry options
                            backup.RetryOptions.RetryCount    = 3;
                            backup.RetryOptions.RetryWaitTime = 60;

                            backup.Start().Wait();
                            if (backup.Results.Status.ExitCodeValue == 0 || backup.Results.Status.ExitCodeValue == 1)
                            {
                                //backup succesful, copy the guid now
                                try
                                {
                                    var guidPath = Path.Combine(sourcePath, "guid");
                                    File.Copy(guidPath, destPath + Path.DirectorySeparatorChar + "guid");
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex.Message);
                                    Logger.Error("Could Not Replicate Image " + image.Name);
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
示例#20
0
        public byte[] Create(DtoIsoGenOptions isoOptions)
        {
            var uow = new UnitOfWork();

            _isoOptions = isoOptions;
            var mode           = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader);
            var imageServers   = new List <DtoClientComServers>();
            var defaultCluster = uow.ComServerClusterRepository.GetFirstOrDefault(x => x.IsDefault);

            if (isoOptions.clusterId == -1)
            {
                imageServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id);
            }
            else
            {
                imageServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(isoOptions.clusterId);
            }

            if (imageServers == null)
            {
                Logger.Error($"No Image Servers Found For This Cluster");
                return(null);
            }

            if (imageServers.Count == 0)
            {
                Logger.Error($"No Image Servers Found For This Cluster");
                return(null);
            }

            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

            _thisComServer = new ServiceClientComServer().GetServerByGuid(guid);
            if (_thisComServer == null)
            {
                Logger.Error($"Com Server With Guid {guid} Not Found");
                return(null);
            }

            var webRequiresLogin     = ServiceSetting.GetSettingValue(SettingStrings.WebTasksRequireLogin);
            var consoleRequiresLogin = ServiceSetting.GetSettingValue(SettingStrings.ConsoleTasksRequireLogin);
            var globalToken          = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingToken);

            if (webRequiresLogin.Equals("False") || consoleRequiresLogin.Equals("False"))
            {
                _userToken = globalToken;
            }
            else
            {
                _userToken = "";
            }

            _globalComputerArgs = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingArguments);

            _webPath = "\"";
            foreach (var imageServer in imageServers)
            {
                var url = new ServiceClientComServer().GetServer(imageServer.ComServerId).Url;
                _webPath += url + "clientimaging/ "; //adds a space delimiter
            }
            _webPath  = _webPath.Trim(' ');
            _webPath += "\"";

            _basePath = HttpContext.Current.Server.MapPath("~") + "private" +
                        Path.DirectorySeparatorChar;
            _rootfsPath = _basePath + "client_iso" + Path.DirectorySeparatorChar + "rootfs" +
                          Path.DirectorySeparatorChar;
            if (isoOptions.useSecureBoot)
            {
                _grubPath = _basePath + "client_iso" + Path.DirectorySeparatorChar + "grub_binaries" +
                            Path.DirectorySeparatorChar + "signed" + Path.DirectorySeparatorChar;
            }
            else
            {
                _grubPath = _basePath + "client_iso" + Path.DirectorySeparatorChar + "grub_binaries" +
                            Path.DirectorySeparatorChar + "unsigned" + Path.DirectorySeparatorChar;
            }
            _buildPath     = _basePath + "client_iso" + Path.DirectorySeparatorChar + "build-tmp";
            _outputPath    = _basePath + "client_iso" + Path.DirectorySeparatorChar;
            _configOutPath = _basePath + "client_iso" + Path.DirectorySeparatorChar + "config" +
                             Path.DirectorySeparatorChar;

            Generate();

            var file = File.ReadAllBytes(_basePath + "client_iso" + Path.DirectorySeparatorChar + "clientboot.iso");

            return(file);
        }
示例#21
0
        public string Execute(string multicastPort = "")
        {
            var preScripts        = "\"";
            var beforeFileScripts = "\"";
            var afterFileScripts  = "\"";

            foreach (var script in _imageProfileServices.GetImageProfileScripts(_imageProfile.Id))
            {
                if (script.RunWhen == EnumProfileScript.RunWhen.BeforeImaging)
                {
                    preScripts += script.ScriptModuleId + " ";
                }
                else if (script.RunWhen == EnumProfileScript.RunWhen.BeforeFileCopy)
                {
                    beforeFileScripts += script.ScriptModuleId + " ";
                }
                else if (script.RunWhen == EnumProfileScript.RunWhen.AfterFileCopy)
                {
                    afterFileScripts += script.ScriptModuleId + " ";
                }
            }
            beforeFileScripts += "\"";
            afterFileScripts  += "\"";
            preScripts        += "\"";

            var sysprepTags = "\"";

            foreach (var sysprepTag in _imageProfileServices.GetImageProfileSysprep(_imageProfile.Id))
            {
                sysprepTags += sysprepTag.SysprepModuleId + " ";
            }

            sysprepTags  = sysprepTags.Trim();
            sysprepTags += "\"";

            var areFilesToCopy = _imageProfileServices.GetImageProfileFileCopy(_imageProfile.Id).Any();

            //On demand computer may be null if not registered
            if (_computer != null)
            {
                AppendString("computer_name=" + _computer.Name.Split(':').First());
                //AppendString("computer_id=" + _computer.Id);
            }

            AppendString("image_name=" + _imageProfile.Image.Name);
            AppendString("profile_id=" + _imageProfile.Id);
            AppendString("pre_scripts=" + preScripts);
            AppendString("before_file_scripts=" + beforeFileScripts);
            AppendString("after_file_scripts=" + afterFileScripts);
            AppendString("file_copy=" + areFilesToCopy);
            AppendString("sysprep_tags=" + sysprepTags);


            if (Convert.ToBoolean(_imageProfile.WebCancel))
            {
                AppendString("web_cancel=true");
            }
            AppendString("task_completed_action=" + "\"" + _imageProfile.TaskCompletedAction + "\"");

            if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True"))
            {
                AppendString("direct_smb=true");
            }

            if (_direction.Contains("upload"))
            {
                AppendString("image_type=" + _imageProfile.Image.Type);
                if (Convert.ToBoolean(_imageProfile.RemoveGPT))
                {
                    AppendString("remove_gpt_structures=true");
                }
                if (Convert.ToBoolean(_imageProfile.SkipShrinkVolumes))
                {
                    AppendString("skip_shrink_volumes=true");
                }
                if (Convert.ToBoolean(_imageProfile.SkipShrinkLvm))
                {
                    AppendString("skip_shrink_lvm=true");
                }
                AppendString("compression_algorithm=" + _imageProfile.Compression);
                AppendString("compression_level=-" + _imageProfile.CompressionLevel);
                if (Convert.ToBoolean(_imageProfile.UploadSchemaOnly))
                {
                    AppendString("upload_schema_only=true");
                }
                if (Convert.ToBoolean(_imageProfile.SimpleUploadSchema))
                {
                    AppendString("simple_upload_schema=true");
                }

                if (!string.IsNullOrEmpty(_imageProfile.CustomUploadSchema))
                {
                    AppendString("custom_upload_schema=true");
                    SetCustomSchemaUpload();
                }
                if (Convert.ToBoolean(_imageProfile.SkipBitlockerCheck))
                {
                    AppendString("skip_bitlocker_check=true");
                }
                if (Convert.ToBoolean(_imageProfile.SkipHibernationCheck))
                {
                    AppendString("skip_hibernation_check=true");
                }
            }
            else // push or multicast
            {
                //check for null in case of on demand
                if (_computer != null)
                {
                    var computerAttributes = new ServiceComputer().GetCustomAttributes(_computer.Id);
                    var serviceAttribute   = new ServiceCustomAttribute();
                    foreach (var attribute in computerAttributes)
                    {
                        var compAttrib = serviceAttribute.GetCustomAttribute(attribute.CustomAttributeId);
                        if (!string.IsNullOrEmpty(attribute.Value))
                        {
                            if (compAttrib.ClientImagingAvailable)
                            {
                                AppendString(compAttrib.Name + "=" + "\"" + attribute.Value + "\"");
                            }
                        }
                    }
                }


                if (Convert.ToBoolean(_imageProfile.ChangeName))
                {
                    AppendString("change_computer_name=true");
                }
                if (Convert.ToBoolean(_imageProfile.SkipExpandVolumes))
                {
                    AppendString("skip_expand_volumes=true");
                }
                if (Convert.ToBoolean(_imageProfile.FixBcd))
                {
                    AppendString("fix_bcd=true");
                }
                if (Convert.ToBoolean(_imageProfile.RandomizeGuids))
                {
                    AppendString("randomize_guids=true");
                }
                if (Convert.ToBoolean(_imageProfile.ForceStandardLegacy))
                {
                    AppendString("force_legacy_layout=true");
                }
                if (Convert.ToBoolean(_imageProfile.ForceStandardEfi))
                {
                    AppendString("force_efi_layout=true");
                }
                if (Convert.ToBoolean(_imageProfile.SkipNvramUpdate))
                {
                    AppendString("skip_nvram=true");
                }
                if (Convert.ToBoolean(_imageProfile.FixBootloader))
                {
                    AppendString("fix_bootloader=true");
                }

                if (Convert.ToBoolean(_imageProfile.ForceDynamicPartitions))
                {
                    AppendString("force_dynamic_partitions=true");
                }
                AppendString(SetPartitionMethod());
                if (!string.IsNullOrEmpty(_imageProfile.CustomSchema))
                {
                    AppendString("custom_deploy_schema=true");
                    SetCustomSchemaDeploy();
                }
                if (_direction.Contains("multicast"))
                {
                    var comServer = new ServiceClientComServer().GetServer(_comServerId);
                    if (comServer.DecompressImageOn == "client")
                    {
                        AppendString("decompress_multicast_on_client=true");
                    }
                    if (string.IsNullOrEmpty(_imageProfile.ReceiverArguments))
                    {
                        AppendString("client_receiver_args=" + "\"" + comServer.MulticastReceiverArguments + "\"");
                    }
                    else
                    {
                        AppendString("client_receiver_args=" + "\"" + _imageProfile.ReceiverArguments + "\"");
                    }

                    AppendString("multicast_port=" + multicastPort);
                    AppendString("multicast_server_ip=" + comServer.MulticastInterfaceIp);
                }
            }

            return(_activeTaskArguments.ToString());
        }