Ejemplo n.º 1
0
        public DtoBoolResponse RemoveDownloadConnection(DtoDownloadConRequest downloadConRequest)
        {
            var result = new APICall().PolicyApi.RemoveDownloadConnection(downloadConRequest);

            return(new DtoBoolResponse()
            {
                Value = result
            });
        }
Ejemplo n.º 2
0
 public DtoBoolResponse RemoveDownloadConnection(DtoDownloadConRequest conRequest)
 {
     Request.Method = Method.POST;
     Request.AddJsonBody(conRequest);
     Request.Resource = string.Format("api/{0}/RemoveDownloadConnection/", Resource);
     return
         (new ApiRequest("http://localhost:" + DtoGobalSettings.LocalApiPort + "/").Execute <DtoBoolResponse>(
              Request));
 }
Ejemplo n.º 3
0
        public DtoDownloadConnectionResult CreateDownloadConnection(DtoDownloadConRequest conRequest)
        {
            Request.Method = Method.POST;
            Request.AddJsonBody(conRequest);
            Request.Resource = string.Format("{0}/CreateDownloadConnection/", Resource);
            //this needs to use hmac or an endpoint that hasn't provisioned yet and needs an upgrade first, won't be able to upgrade
            var result = new ApiRequest().ExecuteHMAC <DtoDownloadConnectionResult>(Request, conRequest.ComputerName);

            return(result ?? new DtoDownloadConnectionResult());
        }
Ejemplo n.º 4
0
        public DtoApiBoolResponse RemoveDownloadConnection(DtoDownloadConRequest conRequest)
        {
            var client = new ServiceComputer().GetByGuid(conRequest.ComputerGuid);

            if (client == null)
            {
                return new DtoApiBoolResponse()
                       {
                           Value = false
                       }
            }
            ;
            var result = new ServiceCurrentDownload().DeleteByClientId(client.Id, conRequest.ComServer);

            return(new DtoApiBoolResponse()
            {
                Value = result
            });
        }
    }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        public bool Run(DtoClientPolicy singleModulePolicy = null)
        {
            if (singleModulePolicy == null)
            {
                _policiesToRun = _trigger == EnumPolicy.Trigger.Login
                    ? new APICall().LocalApi.GetLoginPolicies(Environment.UserDomainName + "\\" + Environment.UserName)
                    : new PolicySelector(_trigger, Environment.UserDomainName + "\\" + Environment.UserName).GetPoliciesToExecute();
            }
            else
            {
                _policiesToRun = new DtoTriggerResponse();
                _policiesToRun.Policies.Add(singleModulePolicy);
            }

            if (_policiesToRun == null)
            {
                Logger.Error("Error Trying To Parse Policies. Aborting Trigger: " + _trigger);
                return(false);
            }

            if (_policiesToRun.Policies.Count == 0)
            {
                Logger.Info(string.Format("No Policies For Trigger {0} Were Found For This Computer", _trigger));
                return(true);
            }

            DtoGobalSettings.PolicyIsRunning = true;
            bool cacheFailedWithTriggerStop = false;

            //Check for any conditions that will need cached
            var conditionNeedsCached = false;

            if (_policiesToRun.Policies.Any(x => x.MessageModules.Any()))
            {
                foreach (var messageModule in _policiesToRun.Policies.Select(x => x.MessageModules))
                {
                    if (messageModule.Any(x => x.Condition.Guid != null))
                    {
                        conditionNeedsCached = true;
                        break;
                    }
                }
            }
            if (_policiesToRun.Policies.Any(x => x.PrinterModules.Any()) && !conditionNeedsCached)
            {
                foreach (var printerModule in _policiesToRun.Policies.Select(x => x.PrinterModules))
                {
                    if (printerModule.Any(x => x.Condition.Guid != null))
                    {
                        conditionNeedsCached = true;
                        break;
                    }
                }
            }

            //Check if install of remote access needs cached
            var remotelyNeedsCached = false;

            if (_policiesToRun.Policies.Any(x => x.RemoteAccess == EnumPolicy.RemoteAccess.ForceReinstall))
            {
                remotelyNeedsCached = true;
            }
            else if (new ServiceSystemService().IsRemotelyInstalled())
            {
                remotelyNeedsCached = false;
            }
            else if (_policiesToRun.Policies.Any(x => x.RemoteAccess == EnumPolicy.RemoteAccess.Enabled))
            {
                remotelyNeedsCached = true;
            }

            //cache all policies first if any need cached
            if (_policiesToRun.Policies.Any(x =>
                                            x.SoftwareModules.Any() || x.FileCopyModules.Any() || x.WuModules.Any() || x.ScriptModules.Any() || x.CommandModules.Any()) || conditionNeedsCached || _policiesToRun.Policies.Any(x => x.Condition.Guid != null) || remotelyNeedsCached)
            {
                //grab a download slot
                Logger.Debug("Obtaining A Download Connection.");
                var downloadConRequest = new DtoDownloadConRequest();
                downloadConRequest.ComputerGuid = DtoGobalSettings.ClientIdentity.Guid;
                downloadConRequest.ComputerName = DtoGobalSettings.ClientIdentity.Name;
                downloadConRequest.ComServer    = DtoGobalSettings.ComServer;

                var downloadConnection = new DtoDownloadConnectionResult();
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    downloadConnection = new APICall().LocalApi.CreateDownloadConnection(downloadConRequest);
                }
                else
                {
                    downloadConnection = new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest);
                }
                var conAttempCounter = 0;
                while (downloadConnection.QueueIsFull || !downloadConnection.Success)
                {
                    if (!downloadConnection.Success)
                    {
                        Logger.Error("Could Not Obtain Download Connection. " + downloadConnection.ErrorMessage);
                        DtoGobalSettings.PolicyIsRunning = false;
                        return(true);
                    }
                    if (downloadConnection.QueueIsFull && conAttempCounter == 0)
                    {
                        Logger.Debug("Download Connections Are Full.  Will Retry Continuously Every 1 Minute For The Next 10 Minutes.");
                    }

                    Task.Delay(60 * 1000).Wait();
                    conAttempCounter++;
                    if (conAttempCounter == 10)
                    {
                        Logger.Debug("Download Connections Remain Filled.  Giving Up.  Will Retry At Next Checkin.");
                        return(true);
                    }
                    if (_trigger == EnumPolicy.Trigger.Login)
                    {
                        downloadConnection = new APICall().LocalApi.CreateDownloadConnection(downloadConRequest);
                    }
                    else
                    {
                        downloadConnection = new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest);
                    }
                }

                foreach (var policy in _policiesToRun.Policies)
                {
                    SetPolicyLogLevel(policy);

                    var cacheResult = new PolicyCacher(policy).Cache();
                    if (policy.SkipServerResult)
                    {
                        cacheResult.SkipServerResult = true;
                    }

                    if (policy.ExecutionType == EnumPolicy.ExecutionType.Cache)
                    {
                        _policyResults.Add(cacheResult);
                    }
                    if (cacheResult.PolicyResult != EnumPolicy.Result.Success)
                    {
                        if (IsTriggerStopError(policy))
                        {
                            cacheFailedWithTriggerStop = true;
                            break;
                        }
                    }
                }
                //release the download slot
                Logger.Debug("Releasing The Download Connection.");
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    new APICall().LocalApi.RemoveDownloadConnection(downloadConRequest);
                }
                else
                {
                    new APICall().PolicyApi.RemoveDownloadConnection(downloadConRequest);
                }
            }

            if (!cacheFailedWithTriggerStop)
            {
                foreach (var policy in _policiesToRun.Policies)
                {
                    SetPolicyLogLevel(policy);

                    if (policy.ExecutionType == EnumPolicy.ExecutionType.Cache)
                    {
                        Logger.Debug("Policy's Execution Type Is Cache Only And Will Not Install");
                        continue;
                    }

                    var policyResult = new PolicyExecutor(policy).Execute();
                    if (policy.SkipServerResult)
                    {
                        policyResult.SkipServerResult = true;
                    }
                    _policyResults.Add(policyResult);

                    if (policyResult.PolicyResult == EnumPolicy.Result.Failed)
                    {
                        if (IsTriggerStopError(policy))
                        {
                            break;
                        }
                    }

                    else if (policyResult.PolicyResult == EnumPolicy.Result.Success &&
                             policy.CompletedAction == EnumPolicy.CompletedAction.Reboot)
                    {
                        _reboot = true;
                        break;
                    }
                    else if (policyResult.PolicyResult == EnumPolicy.Result.Success &&
                             policy.CompletedAction == EnumPolicy.CompletedAction.RebootIfNoLogins)
                    {
                        _rebootNoLogins = true;
                        break;
                    }
                }
            }

            Logger.Info("Policies Complete.  Starting Policy Cleanup.");
            DtoGobalSettings.PolicyIsRunning = false;
            RecordResults();

            CleanupCache();

            //restore global log level
            ((Hierarchy)LogManager.GetRepository()).Root.Level = DtoGobalSettings.LogLevel;
            ((Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(
                EventArgs.Empty);

            if (_reboot)
            {
                Logger.Info("Policy Initiated Reboot.  Rebooting Now.");
                if (_trigger == EnumPolicy.Trigger.Login)
                {
                    new APICall().LocalApi.LogoutAllUsers();
                }
                else
                {
                    new ServiceUserTracker().LogoutAllUsers();
                }
                Process.Start("shutdown.exe", "/r /t " + DtoGobalSettings.ShutdownDelay);
            }

            if (_rebootNoLogins)
            {
                Logger.Info("Policy Initiated Reboot If No Users Are Logged In.");
                Logger.Info("Checking For Any Logged In Users.");
                if (_trigger != EnumPolicy.Trigger.Login)
                {
                    var users = new ServiceUserLogins().GetUsersLoggedIn();
                    if (users.Count > 0)
                    {
                        Logger.Info("User Found, Reboot Skipped.");
                    }
                    else
                    {
                        Logger.Info("No Users Found, Issuing Reboot Command.");
                        Process.Start("shutdown.exe", "/r /t " + DtoGobalSettings.ShutdownDelay);
                    }
                }
                else
                {
                    Logger.Info("User Found, Policy Is A Login Policy, Reboot Skipped.");
                }
            }
            return(true);
        }
Ejemplo n.º 7
0
        private bool UpdateClient(string msiFile)
        {
            Logger.Info("Updating Toec To: " + msiFile);


            try
            {
                Directory.CreateDirectory(DtoGobalSettings.BaseCachePath + "ClientUpgrades\\");
            }
            catch
            {
                //ignored
            }

            Logger.Debug($"Obtaining A Download Connection To {DtoGobalSettings.ComServer}");
            var downloadConRequest = new DtoDownloadConRequest();

            downloadConRequest.ComputerGuid = DtoGobalSettings.ClientIdentity.Guid;
            downloadConRequest.ComputerName = DtoGobalSettings.ClientIdentity.Name;
            downloadConRequest.ComServer    = DtoGobalSettings.ComServer;
            var downloadConnection = new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest);

            if (downloadConnection == null)
            {
                Logger.Error("Could Not Obtain Download Connection. Response was null.");
                return(false);
            }

            if (!downloadConnection.Success)
            {
                Logger.Error("Could Not Obtain Download Connection. " + downloadConnection.ErrorMessage);
                return(false);
            }

            if (downloadConnection.QueueIsFull)
            {
                Logger.Debug("Download Connections Are Full");
                return(false);
            }

            Logger.Debug("Downloading Files");

            var msiRequest = new DtoClientFileRequest();

            msiRequest.FileName = msiFile;
            Logger.Debug($"Downloading {msiRequest.FileName}");
            if (!new APICall().PolicyApi.GetClientUpgrade(msiRequest, DtoGobalSettings.ClientIdentity.Name))
            {
                Logger.Debug("Releasing The Download Connection.");
                new APICall().PolicyApi.RemoveDownloadConnection(downloadConRequest);
                return(false);
            }

            Logger.Debug("Releasing The Download Connection.");
            new APICall().PolicyApi.RemoveDownloadConnection(downloadConRequest);

            if (new FileInfo(DtoGobalSettings.BaseCachePath + "ClientUpgrades\\" + msiFile).Length < 1)
            {
                Logger.Debug("MSI File was invalid.");
                return(false);
            }

            var pArgs = new DtoProcessArgs();

            pArgs.RunWith          = "msiexec.exe";
            pArgs.RunWithArgs      = " /i ";
            pArgs.Command          = "\"" + DtoGobalSettings.BaseCachePath + "ClientUpgrades\\" + msiFile + "\"" + $" /q /norestart";
            pArgs.Timeout          = 5;
            pArgs.WorkingDirectory = DtoGobalSettings.BaseCachePath + "ClientUpgrades\\";
            var result = new ServiceProcess(pArgs).RunProcess();

            //Nothing from here on should execute. Updating msi should kill this process.
            Logger.Info(JsonConvert.SerializeObject(result));
            return(true);
        }
Ejemplo n.º 8
0
 public DtoDownloadConnectionResult CreateDownloadConnection(DtoDownloadConRequest downloadConRequest)
 {
     return(new APICall().PolicyApi.CreateDownloadConnection(downloadConRequest));
 }