Esempio n. 1
0
        public bool Copy()
        {
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

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

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

            _sourceRootPath = _thisComServer.TftpPath + "static" +
                              Path.DirectorySeparatorChar;
            var copyResult = ServiceSetting.GetSettingValue(SettingStrings.ProxyDhcpEnabled) == "Yes"
                  ? CopyFilesForProxy()
                  : CopyFilesForNonProxy();

            return(copyResult);
        }
Esempio n. 2
0
        public DtoActionResult Add(EntityClientComServer clientServer)
        {
            var actionResult = new DtoActionResult();

            if (!clientServer.Url.EndsWith("/"))
            {
                clientServer.Url += "/";
            }
            clientServer.Url = clientServer.Url.ToLower();
            var validationResult = Validate(clientServer, true);

            if (validationResult.Success)
            {
                _uow.ClientComServerRepository.Insert(clientServer);
                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = clientServer.Id;
            }
            else
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = validationResult.ErrorMessage
                });
            }

            return(actionResult);
        }
        public DtoActionResult Post(EntityClientComServer server)
        {
            var result = _clientComService.Add(server);

            if (result == null)
            {
                return new DtoActionResult()
                       {
                           ErrorMessage = "Result Was Null"
                       }
            }
            ;
            if (result.Success)
            {
                var auditLog = new EntityAuditLog();

                auditLog.ObjectType = "ClientComServer";
                auditLog.ObjectId   = result.Id;
                auditLog.ObjectName = server.DisplayName;
                auditLog.ObjectJson = JsonConvert.SerializeObject(server);
                auditLog.UserId     = _userId;
                auditLog.AuditType  = EnumAuditEntry.AuditType.Create;
                _auditLogService.AddAuditLog(auditLog);
            }
            return(result);
        }
Esempio n. 4
0
        protected void buttonAdd_OnClick(object sender, EventArgs e)
        {
            if (txtLocalStorage.Text.Contains(" "))
            {
                EndUserMessage = "Storage Path Cannot Contain Any Spaces";
                return;
            }
            var server = new EntityClientComServer()
            {
                DisplayName      = txtName.Text,
                Url              = txtUrl.Text,
                Description      = txtDescription.Text,
                UniqueId         = Guid.NewGuid().ToString(),
                LocalStoragePath = txtLocalStorage.Text
            };

            var result = Call.ClientComServerApi.Post(server);

            if (result.Success)
            {
                EndUserMessage = "Successfully Created Server";
                Response.Redirect("~/views/admin/comservers/editcomserver.aspx?level=2&serverId=" + result.Id);
            }
            else
            {
                EndUserMessage = result.ErrorMessage;
            }
        }
Esempio n. 5
0
        public DtoActionResult Update(EntityClientComServer clientServer)
        {
            var u = GetServer(clientServer.Id);

            if (u == null)
            {
                return new DtoActionResult {
                           ErrorMessage = "Com Server Not Found", Id = 0
                }
            }
            ;
            var actionResult = new DtoActionResult();

            if (!clientServer.Url.EndsWith("/"))
            {
                clientServer.Url += "/";
            }
            clientServer.Url = clientServer.Url.ToLower();
            if (!string.IsNullOrEmpty(clientServer.LocalStoragePath))
            {
                if (!clientServer.LocalStoragePath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    clientServer.LocalStoragePath += Path.DirectorySeparatorChar.ToString();
                }
            }
            if (!string.IsNullOrEmpty(clientServer.TftpPath))
            {
                if (!clientServer.TftpPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    clientServer.TftpPath += Path.DirectorySeparatorChar.ToString();
                }
            }
            if (!string.IsNullOrEmpty(clientServer.RemoteAccessUrl))
            {
                if (!clientServer.RemoteAccessUrl.EndsWith("/"))
                {
                    clientServer.RemoteAccessUrl += "/";
                }
            }

            var validationResult = Validate(clientServer, false);

            if (validationResult.Success)
            {
                _uow.ClientComServerRepository.Update(clientServer, u.Id);
                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = clientServer.Id;
            }
            else
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = validationResult.ErrorMessage
                });
            }

            return(actionResult);
        }
Esempio n. 6
0
        public int RunOnComServer(DtoMulticastArgs mArgs, EntityClientComServer comServer)
        {
            var intercomKey  = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted);
            var decryptedKey = new EncryptionServices().DecryptText(intercomKey);


            var pid = new APICall().ClientComServerApi.StartUdpSender(comServer.Url, "", decryptedKey, mArgs);

            return(pid);
        }
        public DtoActionResult Put(int id, EntityClientComServer account)
        {
            account.Id = id;
            var result = _clientComService.Update(account);

            if (result == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            if (result.Success)
            {
                var auditLog = new EntityAuditLog();
                auditLog.ObjectType = "ClientComServer";
                auditLog.ObjectId   = result.Id;
                auditLog.ObjectName = account.DisplayName;
                auditLog.ObjectJson = JsonConvert.SerializeObject(account);
                auditLog.UserId     = _userId;
                auditLog.AuditType  = EnumAuditEntry.AuditType.Update;
                _auditLogService.AddAuditLog(auditLog);
            }
            return(result);
        }
Esempio n. 8
0
        protected void buttonAdd_OnClick(object sender, EventArgs e)
        {
            var server = new EntityClientComServer()
            {
                DisplayName      = txtName.Text,
                Url              = txtUrl.Text,
                Description      = txtDescription.Text,
                ReplicateStorage = true,
            };

            var result = Call.ClientComServerApi.Post(server);

            if (result.Success)
            {
                EndUserMessage = "Successfully Created Server";
                Response.Redirect("~/views/admin/comservers/editcomserver.aspx?level=2&serverId=" + result.Id);
            }
            else
            {
                EndUserMessage = result.ErrorMessage;
            }
        }
Esempio n. 9
0
        public DtoValidationResult Validate(EntityClientComServer comServer, bool isNew)
        {
            var validationResult = new DtoValidationResult {
                Success = true
            };

            if (string.IsNullOrEmpty(comServer.DisplayName) || !comServer.DisplayName.All(c => char.IsLetterOrDigit(c) || c == '_' || c == '-' || c == ' '))
            {
                validationResult.Success      = false;
                validationResult.ErrorMessage = "Com Server Name Is Not Valid";
                return(validationResult);
            }

            if (isNew)
            {
                if (_uow.ClientComServerRepository.Exists(h => h.DisplayName == comServer.DisplayName))
                {
                    validationResult.Success      = false;
                    validationResult.ErrorMessage = "A Com Server With This Name Already Exists";
                    return(validationResult);
                }
            }
            else
            {
                var original = _uow.ClientComServerRepository.GetById(comServer.Id);
                if (original.DisplayName != comServer.DisplayName)
                {
                    if (_uow.ClientComServerRepository.Exists(h => h.DisplayName == comServer.DisplayName))
                    {
                        validationResult.Success      = false;
                        validationResult.ErrorMessage = "A Com Server With This Name Already Exists";
                        return(validationResult);
                    }
                }
            }

            return(validationResult);
        }
Esempio n. 10
0
        public DtoActionResult Update(EntityClientComServer clientServer)
        {
            var u = GetServer(clientServer.Id);

            if (u == null)
            {
                return new DtoActionResult {
                           ErrorMessage = "Com Server Not Found", Id = 0
                }
            }
            ;
            var actionResult = new DtoActionResult();

            if (!clientServer.Url.EndsWith("/"))
            {
                clientServer.Url += "/";
            }
            clientServer.Url = clientServer.Url.ToLower();
            var validationResult = Validate(clientServer, false);

            if (validationResult.Success)
            {
                _uow.ClientComServerRepository.Update(clientServer, u.Id);
                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = clientServer.Id;
            }
            else
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = validationResult.ErrorMessage
                });
            }

            return(actionResult);
        }
Esempio n. 11
0
        public bool Download(DtoOnlineKernel onlineKernel)
        {
            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);
            }

            var baseUrl = "http://files.theopenem.com/kernels/";

            using (var wc = new WebClient())
            {
                try
                {
                    wc.DownloadFile(new Uri(baseUrl + onlineKernel.BaseVersion + "/" + onlineKernel.FileName),
                                    _thisComServer.TftpPath + "kernels" +
                                    Path.DirectorySeparatorChar + onlineKernel.FileName);
                    return(true);
                }
                catch (Exception ex)
                {
                    log.Error("Could Not Download Kernel On Com Server: " + _thisComServer.DisplayName);
                    log.Error(ex.Message);
                    return(false);
                }
            }
        }
Esempio n. 12
0
        public DtoValidationResult Validate(EntityClientComServer comServer, bool isNew)
        {
            var validationResult = new DtoValidationResult {
                Success = true
            };

            if (string.IsNullOrEmpty(comServer.DisplayName) || !comServer.DisplayName.All(c => char.IsLetterOrDigit(c) || c == '_' || c == '-' || c == ' '))
            {
                validationResult.Success      = false;
                validationResult.ErrorMessage = "Com Server Name Is Not Valid";
                return(validationResult);
            }

            if (isNew)
            {
                if (_uow.ClientComServerRepository.Exists(h => h.DisplayName == comServer.DisplayName))
                {
                    validationResult.Success      = false;
                    validationResult.ErrorMessage = "A Com Server With This Name Already Exists";
                    return(validationResult);
                }
            }
            else
            {
                var original = _uow.ClientComServerRepository.GetById(comServer.Id);
                if (original.DisplayName != comServer.DisplayName)
                {
                    if (_uow.ClientComServerRepository.Exists(h => h.DisplayName == comServer.DisplayName))
                    {
                        validationResult.Success      = false;
                        validationResult.ErrorMessage = "A Com Server With This Name Already Exists";
                        return(validationResult);
                    }
                }
            }

            //remove for now, it's possible that you might want to com servers on the same server and still wouldn't need smb

            /*
             * var comServerCount = Convert.ToInt32(TotalCount());
             * if(comServerCount > 0)
             * {
             *  //verify storage type before allowing more than one com server
             *  var storageType = ServiceSetting.GetSettingValue(SettingStrings.StorageType);
             *  if(storageType.Equals("Local"))
             *  {
             *      validationResult.Success = false;
             *      validationResult.ErrorMessage = "Could Not Add Server.  If Using More Than 1 Com Server, The Storage Type Must Be Set To SMB In Admin Settings->Storage Location";
             *      return validationResult;
             *  }
             * }*/

            if (string.IsNullOrEmpty(comServer.LocalStoragePath))
            {
                validationResult.Success      = false;
                validationResult.ErrorMessage = "Local Storage Path Must Be Populated.  If Global Storage is set to Local, verify Admin Settings-> Storage Location is populated.";
                return(validationResult);
            }

            Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
                                RegexOptions.None, TimeSpan.FromMilliseconds(150));
            Match m = r.Match(comServer.Url);

            if (m.Success)
            {
                var port = r.Match(comServer.Url).Result("${port}");
                if (string.IsNullOrEmpty(port))
                {
                    validationResult.Success      = false;
                    validationResult.ErrorMessage = "The URL Must Include The Port Number";
                    return(validationResult);
                }
            }
            else
            {
                validationResult.Success      = false;
                validationResult.ErrorMessage = "The URL Is Invalid";
                return(validationResult);
            }


            return(validationResult);
        }
Esempio n. 13
0
        public string Upload(int taskId, string fileName, int profileId, int userId, string hdNumber)
        {
            //no need to find and call com server, client should already be directly communicating with the correct imaging server
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

            _thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

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

            var appPath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "private", "apps");

            var task = new ServiceActiveImagingTask().GetTask(taskId);

            if (task == null)
            {
                return("0");
            }

            var imageProfile = new ServiceImageProfile().ReadProfile(profileId);

            var uploadPort = new ServicePort().GetNextPort(task.ComServerId);

            var path = _thisComServer.LocalStoragePath;


            try
            {
                var dir = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{ hdNumber}");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                log.Error("Could Not Create Directory");
                log.Error(ex.Message);
                return("0");
            }

            path = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{hdNumber}", fileName);
            string arguments    = " /c \"";
            var    receiverPath = Path.Combine(appPath, "udp-receiver.exe");

            arguments += $"{receiverPath}\" --portbase {uploadPort}";
            arguments += $" --interface {_thisComServer.ImagingIp} --file {path}";

            var pid = StartReceiver(arguments, imageProfile.Image.Name);
            //use multicast session even though it's not a multicast, uploads still use udpcast
            var activeMulticast = new EntityActiveMulticastSession();

            if (pid != 0)
            {
                activeMulticast.ImageProfileId = imageProfile.Id;
                activeMulticast.Name           = imageProfile.Image.Name;
                activeMulticast.Pid            = pid;
                activeMulticast.Port           = uploadPort;
                activeMulticast.ComServerId    = _thisComServer.Id;
                activeMulticast.UserId         = userId;
                activeMulticast.UploadTaskId   = task.Id;

                var result = new ServiceActiveMulticastSession().AddActiveMulticastSession(activeMulticast);
                if (result)
                {
                    return(uploadPort.ToString());
                }
            }
            return("0");
        }
Esempio n. 14
0
        public bool Execute(EntityComputer computer)
        {
            _computer   = computer;
            _listOfMacs = new List <string>();
            if (!string.IsNullOrEmpty(_computer.ImagingMac))
            {
                _listOfMacs.Add(StringManipulationServices.MacToPxeMac(_computer.ImagingMac));
            }
            else
            {
                var computerMacs = new UnitOfWork().NicInventoryRepository.Get(x => x.ComputerId == computer.Id && x.Type.Equals("Ethernet")).Select(x => x.Mac).ToList();
                foreach (var mac in computerMacs)
                {
                    _listOfMacs.Add(StringManipulationServices.MacToPxeMac(mac));
                }
            }

            _computerServices = new ServiceComputer();

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

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

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

            if (ServiceSetting.GetSettingValue(SettingStrings.ProxyDhcpEnabled) == "Yes")
            {
                DeleteProxyFile("bios");
                DeleteProxyFile("bios", ".ipxe");
                DeleteProxyFile("efi32");
                DeleteProxyFile("efi32", ".ipxe");
                DeleteProxyFile("efi64");
                DeleteProxyFile("efi64", ".ipxe");
                DeleteProxyFile("efi64", ".cfg");
            }
            else
            {
                var mode = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader);
                if (mode.Contains("ipxe"))
                {
                    DeleteStandardFile(".ipxe");
                }
                else if (mode.Contains("grub"))
                {
                    DeleteStandardFile(".cfg");
                }
                else
                {
                    DeleteStandardFile();
                }
            }
            return(true);
        }
Esempio n. 15
0
        public DtoActionResult Add(EntityClientComServer clientServer)
        {
            var actionResult = new DtoActionResult();

            if (!clientServer.Url.EndsWith("/"))
            {
                clientServer.Url += "/";
            }
            clientServer.Url = clientServer.Url.ToLower();
            if (!string.IsNullOrEmpty(clientServer.LocalStoragePath))
            {
                if (!clientServer.LocalStoragePath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    clientServer.LocalStoragePath += Path.DirectorySeparatorChar.ToString();
                }
            }
            if (!string.IsNullOrEmpty(clientServer.TftpPath))
            {
                if (!clientServer.TftpPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    clientServer.TftpPath += Path.DirectorySeparatorChar.ToString();
                }
            }
            if (!string.IsNullOrEmpty(clientServer.RemoteAccessUrl))
            {
                if (!clientServer.RemoteAccessUrl.EndsWith("/"))
                {
                    clientServer.RemoteAccessUrl += "/";
                }
            }


            clientServer.DecompressImageOn          = "client";
            clientServer.EmMaxBps                   = 0;
            clientServer.EmMaxClients               = 0;
            clientServer.ImagingMaxBps              = 0;
            clientServer.ImagingMaxClients          = 5;
            clientServer.IsEndpointManagementServer = true;
            clientServer.IsImagingServer            = true;
            clientServer.IsMulticastServer          = true;
            clientServer.IsTftpServer               = true;
            clientServer.MulticastEndPort           = 10000;
            clientServer.MulticastStartPort         = 9000;
            clientServer.ReplicateStorage           = true;
            clientServer.ReplicationRateIpg         = 0;
            clientServer.TftpPath                   = @"C:\Program Files\Theopenem\tftpboot\";
            clientServer.IsTftpInfoServer           = true;
            clientServer.UniqueId                   = Guid.NewGuid().ToString();

            var validationResult = Validate(clientServer, true);

            if (validationResult.Success)
            {
                _uow.ClientComServerRepository.Insert(clientServer);
                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = clientServer.Id;
            }
            else
            {
                return(new DtoActionResult()
                {
                    ErrorMessage = validationResult.ErrorMessage
                });
            }

            return(actionResult);
        }
Esempio n. 16
0
        public int GenerateProcessArguments(DtoMulticastArgs mArgs)
        {
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

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

            var    schemaCounter      = -1;
            var    multicastHdCounter = 0;
            string processArguments   = null;

            foreach (var hd in mArgs.schema.HardDrives)
            {
                schemaCounter++;
                if (!hd.Active)
                {
                    continue;
                }
                multicastHdCounter++;

                var x = 0;
                foreach (var part in mArgs.schema.HardDrives[schemaCounter].Partitions)
                {
                    if (!part.Active)
                    {
                        continue;
                    }
                    string imageFile = null;
                    foreach (var ext in new[] { "ntfs", "fat", "extfs", "hfsp", "imager", "winpe", "xfs" })
                    {
                        imageFile = new FilesystemServices().GetMulticastFileNameWithFullPath(mArgs.ImageName,
                                                                                              schemaCounter.ToString(), part.Number, ext, _thisComServer.LocalStoragePath);

                        if (!string.IsNullOrEmpty(imageFile))
                        {
                            break;
                        }

                        //Look for lvm
                        if (part.VolumeGroup == null)
                        {
                            continue;
                        }
                        if (part.VolumeGroup.LogicalVolumes == null)
                        {
                            continue;
                        }
                        foreach (var lv in part.VolumeGroup.LogicalVolumes.Where(lv => lv.Active))
                        {
                            imageFile = new FilesystemServices().GetMulticastLVMFileNameWithFullPath(mArgs.ImageName,
                                                                                                     schemaCounter.ToString(), lv.VolumeGroup, lv.Name, ext, _thisComServer.LocalStoragePath);
                        }
                    }

                    if (string.IsNullOrEmpty(imageFile))
                    {
                        continue;
                    }
                    if (mArgs.Environment == "winpe" &&
                        mArgs.schema.HardDrives[schemaCounter].Table.ToLower() == "gpt")
                    {
                        if (part.Type.ToLower() == "system" || part.Type.ToLower() == "recovery" ||
                            part.Type.ToLower() == "reserved")
                        {
                            continue;
                        }
                    }
                    if (mArgs.Environment == "winpe" &&
                        mArgs.schema.HardDrives[schemaCounter].Table.ToLower() == "mbr")
                    {
                        if (part.Number == mArgs.schema.HardDrives[schemaCounter].Boot &&
                            mArgs.schema.HardDrives[schemaCounter].Partitions.Length > 1)
                        {
                            continue;
                        }
                    }
                    x++;

                    var minReceivers = "";

                    if (!string.IsNullOrEmpty(mArgs.clientCount))
                    {
                        minReceivers = " --min-receivers " + mArgs.clientCount;
                    }

                    var isUnix = Environment.OSVersion.ToString().Contains("Unix");

                    string compAlg;
                    var    stdout = "";
                    switch (Path.GetExtension(imageFile))
                    {
                    case ".lz4":
                        compAlg = isUnix ? "lz4 -d " : "lz4.exe\" -d ";
                        stdout  = " - ";
                        break;

                    case ".gz":
                        if (isUnix)
                        {
                            compAlg = "gzip -c -d ";
                            stdout  = "";
                        }
                        else
                        {
                            compAlg = "7za.exe\" x ";
                            stdout  = " -so ";
                        }
                        break;

                    case ".uncp":
                        compAlg = "none";
                        break;

                    case ".wim":
                        compAlg = "none";
                        break;

                    default:
                        return(0);
                    }

                    if (isUnix)
                    {
                        string prefix = null;
                        if (multicastHdCounter == 1)
                        {
                            prefix = x == 1 ? " -c \"" : " ; ";
                        }
                        else
                        {
                            prefix = " ; ";
                        }

                        if (compAlg == "none" ||
                            _thisComServer.DecompressImageOn == "client")
                        {
                            processArguments += prefix + "cat " + "\"" + imageFile + "\"" + " | udp-sender" +
                                                " --portbase " + mArgs.Port + minReceivers + " " +
                                                " --ttl 32 --interface " + _thisComServer.MulticastInterfaceIp + " --mcast-rdv-address " + _thisComServer.MulticastInterfaceIp +
                                                mArgs.ExtraArgs;
                        }

                        else
                        {
                            processArguments += prefix + compAlg + "\"" + imageFile + "\"" + stdout + " | udp-sender" +
                                                " --portbase " + mArgs.Port + minReceivers + " " +
                                                " --ttl 32 --interface " + _thisComServer.MulticastInterfaceIp + " --mcast-rdv-address " + _thisComServer.MulticastInterfaceIp +
                                                mArgs.ExtraArgs;
                        }
                    }
                    else
                    {
                        var appPath = HttpContext.Current.Server.MapPath("~") + Path.DirectorySeparatorChar + "private" +
                                      Path.DirectorySeparatorChar + "apps" + Path.DirectorySeparatorChar;

                        string prefix = null;
                        if (multicastHdCounter == 1)
                        {
                            prefix = x == 1 ? " /c \"" : " & ";
                        }
                        else
                        {
                            prefix = " & ";
                        }

                        if (compAlg == "none" ||
                            _thisComServer.DecompressImageOn == "client")
                        {
                            processArguments += prefix + "\"" + appPath +
                                                "udp-sender.exe" + "\"" + " --file " + "\"" + imageFile + "\"" +
                                                " --portbase " + mArgs.Port + minReceivers + " " +
                                                " --ttl 32 --interface " + _thisComServer.MulticastInterfaceIp + " --mcast-rdv-address " + _thisComServer.MulticastInterfaceIp +
                                                mArgs.ExtraArgs;
                        }
                        else
                        {
                            processArguments += prefix + "\"" + appPath + compAlg + "\"" + imageFile + "\"" + stdout +
                                                " | " + "\"" + appPath +
                                                "udp-sender.exe" + "\"" +
                                                " --portbase " + mArgs.Port + minReceivers + " " +
                                                " --ttl 32 --interface " + _thisComServer.MulticastInterfaceIp + " --mcast-rdv-address " + _thisComServer.MulticastInterfaceIp +
                                                mArgs.ExtraArgs;
                        }
                    }
                }
            }

            processArguments += "\"";

            return(StartMulticastSender(processArguments, mArgs.groupName));
        }
Esempio n. 17
0
        public bool Execute()
        {
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

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

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

            if (_thisComServer.IsTftpServer)
            {
                var tftpPath = _thisComServer.TftpPath;
                var pxePaths = new List <string>
                {
                    tftpPath + "pxelinux.cfg" + Path.DirectorySeparatorChar,
                    tftpPath + "proxy" + Path.DirectorySeparatorChar + "bios" +
                    Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar,
                    tftpPath + "proxy" + Path.DirectorySeparatorChar + "efi32" +
                    Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar,
                    tftpPath + "proxy" + Path.DirectorySeparatorChar + "efi64" +
                    Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar
                };

                foreach (var pxePath in pxePaths)
                {
                    var pxeFiles = Directory.GetFiles(pxePath, "01*");
                    try
                    {
                        foreach (var pxeFile in pxeFiles)
                        {
                            File.Delete(pxeFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex.ToString());
                        return(false);
                    }
                }
            }

            if (_thisComServer.IsMulticastServer)
            {
                if (Environment.OSVersion.ToString().Contains("Unix"))
                {
                    for (var x = 1; x <= 10; x++)
                    {
                        try
                        {
                            var killProcInfo = new ProcessStartInfo
                            {
                                FileName  = "killall",
                                Arguments = " -s SIGKILL udp-sender"
                            };
                            Process.Start(killProcInfo);
                        }
                        catch
                        {
                            // ignored
                        }
                        try
                        {
                            var killProcInfo = new ProcessStartInfo
                            {
                                FileName  = "killall",
                                Arguments = " -s SIGKILL udp-receiver"
                            };
                            Process.Start(killProcInfo);
                        }
                        catch
                        {
                            // ignored
                        }

                        Thread.Sleep(200);
                    }
                }

                else
                {
                    for (var x = 1; x <= 10; x++)
                    {
                        foreach (var p in Process.GetProcessesByName("udp-sender"))
                        {
                            try
                            {
                                p.Kill();
                                p.WaitForExit();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex.ToString());
                            }
                        }
                        foreach (var p in Process.GetProcessesByName("udp-receiver"))
                        {
                            try
                            {
                                p.Kill();
                                p.WaitForExit();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex.ToString());
                            }
                        }
                        Thread.Sleep(200);
                    }
                }
            }

            new ServiceActiveImagingTask().DeleteAll();
            new ServiceActiveMulticastSession().DeleteAll();
            return(true);
        }
Esempio n. 18
0
        public bool CreatePxeBootFiles(EntityComputer computer, EntityImageProfile imageProfile)
        {
            _uow = new UnitOfWork();
            const string newLineChar = "\n";

            _computer     = computer;
            _imageProfile = imageProfile;

            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);
            }

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

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

            var listOfMacs = new List <string>();

            if (!string.IsNullOrEmpty(_computer.ImagingMac))
            {
                log.Debug("Computer Task PXE Mac: " + _computer.ImagingMac);
                listOfMacs.Add(StringManipulationServices.MacToPxeMac(_computer.ImagingMac));
            }
            else
            {
                var computerMacs = _uow.NicInventoryRepository.Get(x => x.ComputerId == computer.Id && x.Type.Equals("Ethernet")).Select(x => x.Mac).ToList();
                foreach (var mac in computerMacs)
                {
                    listOfMacs.Add(StringManipulationServices.MacToPxeMac(mac));
                }
            }
            var imageComServers = new Workflows.GetCompImagingServers().Run(computer.Id);

            if (imageComServers == null)
            {
                log.Error("Could Not Determine Imaging Com Servers For Computer: " + computer.Name);
                return(false);
            }
            if (imageComServers.Count == 0)
            {
                log.Error("Could Not Determine Imaging Com Servers For Computer: " + computer.Name);
                return(false);
            }

            var webPath = "\"";

            foreach (var imageServer in imageComServers)
            {
                webPath += imageServer.Url + "clientimaging/ "; //adds a space delimiter
            }

            webPath  = webPath.Trim(' ');
            webPath += "\"";

            var globalComputerArgs = ServiceSetting.GetSettingValue(SettingStrings.GlobalImagingArguments);

            var compTftpServers = new Workflows.GetCompTftpServers().Run(computer.Id);

            if (compTftpServers == null)
            {
                log.Error("Could Not Determine Tftp Com Servers For Computer: " + computer.Name);
                return(false);
            }
            if (compTftpServers.Count == 0)
            {
                log.Error("Could Not Determine Tftp Com Servers For Computer: " + computer.Name);
                return(false);
            }

            var iPxePath = _thisComServer.Url;

            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 ipxe = new StringBuilder();

            ipxe.Append("#!ipxe" + newLineChar);
            ipxe.Append("kernel " + iPxePath + "IpxeBoot?filename=" + _imageProfile.Kernel +
                        "&type=kernel" + " initrd=" + _imageProfile.BootImage +
                        " root=/dev/ram0 rw ramdisk_size=156000" +
                        " consoleblank=0" + " web=" + webPath + " USER_TOKEN=" + _userToken + " " + globalComputerArgs +
                        " " + _imageProfile.KernelArguments + newLineChar);
            ipxe.Append("imgfetch --name " + _imageProfile.BootImage + " " + iPxePath +
                        "IpxeBoot?filename=" + _imageProfile.BootImage + "&type=bootimage" + newLineChar);
            ipxe.Append("boot" + newLineChar);

            var sysLinux = new StringBuilder();

            sysLinux.Append("DEFAULT theopenem" + newLineChar);
            sysLinux.Append("LABEL theopenem" + newLineChar);
            sysLinux.Append("KERNEL kernels" + Path.DirectorySeparatorChar + _imageProfile.Kernel + newLineChar);
            sysLinux.Append("APPEND initrd=images" + Path.DirectorySeparatorChar + _imageProfile.BootImage +
                            " root=/dev/ram0 rw ramdisk_size=156000" +
                            " consoleblank=0" + " web=" + webPath + " USER_TOKEN=" + _userToken + " " +
                            globalComputerArgs +
                            " " + _imageProfile.KernelArguments + newLineChar);

            var grub = new StringBuilder();

            grub.Append("set default=0" + newLineChar);
            grub.Append("set timeout=0" + newLineChar);
            grub.Append("menuentry Theopenem --unrestricted {" + newLineChar);
            grub.Append("echo Please Wait While The Boot Image Is Transferred.  This May Take A Few Minutes." +
                        newLineChar);
            grub.Append("linux /kernels/" + _imageProfile.Kernel +
                        " root=/dev/ram0 rw ramdisk_size=156000" + " consoleblank=0" + " web=" + webPath + " USER_TOKEN=" + _userToken +
                        " " +
                        globalComputerArgs + " " + _imageProfile.KernelArguments + newLineChar);
            grub.Append("initrd /images/" + _imageProfile.BootImage + newLineChar);
            grub.Append("}" + newLineChar);

            var list = new List <Tuple <string, string, string> >
            {
                Tuple.Create("bios", "", sysLinux.ToString()),
                Tuple.Create("bios", ".ipxe", ipxe.ToString()),
                Tuple.Create("efi32", "", sysLinux.ToString()),
                Tuple.Create("efi32", ".ipxe", ipxe.ToString()),
                Tuple.Create("efi64", "", sysLinux.ToString()),
                Tuple.Create("efi64", ".ipxe", ipxe.ToString()),
                Tuple.Create("efi64", ".cfg", grub.ToString())
            };

            //In proxy mode all boot files are created regardless of the pxe mode, this way computers can be customized
            //to use a specific boot file without affecting all others, using the proxydhcp reservations file.
            if (ServiceSetting.GetSettingValue(SettingStrings.ProxyDhcpEnabled) == "Yes")
            {
                foreach (var mac in listOfMacs)
                {
                    foreach (var bootMenu in list)
                    {
                        var path = _thisComServer.TftpPath + "proxy" +
                                   Path.DirectorySeparatorChar + bootMenu.Item1 +
                                   Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar +
                                   mac +
                                   bootMenu.Item2;

                        if (!new FilesystemServices().WritePath(path, bootMenu.Item3))
                        {
                            return(false);
                        }
                    }
                }
            }
            //When not using proxy dhcp, only one boot file is created
            else
            {
                var mode = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader);
                foreach (var mac in listOfMacs)
                {
                    var path = "";

                    path = _thisComServer.TftpPath + "pxelinux.cfg" +
                           Path.DirectorySeparatorChar + mac;

                    string fileContents = null;
                    if (mode == "pxelinux" || mode == "syslinux_32_efi" || mode == "syslinux_64_efi")
                    {
                        fileContents = sysLinux.ToString();
                    }

                    else if (mode.Contains("ipxe"))
                    {
                        path        += ".ipxe";
                        fileContents = ipxe.ToString();
                    }
                    else if (mode.Contains("grub"))
                    {
                        path        += ".cfg";
                        fileContents = grub.ToString();
                    }

                    if (!new FilesystemServices().WritePath(path, fileContents))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 19
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);
        }
Esempio n. 20
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);
        }