Beispiel #1
0
        public string Start()
        {
            if (string.IsNullOrEmpty(SettingServices.GetSettingValue(SettingStrings.ServerIdentifier)))
            {
                return("The Server Identifier Must Be Set Before Tasks Can Be Started");
            }

            if (_computer == null)
            {
                return("The Computer Does Not Exist");
            }

            _imageProfile = new ImageProfileServices().ReadProfile(_computer.ImageProfileId);
            if (_imageProfile == null)
            {
                return("The Image Profile Does Not Exist");
            }

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

            if (_direction == "deploy" || _direction == "permanentdeploy")
            {
                var validation = new ImageServices().CheckApprovalAndChecksum(_imageProfile.Image, _userId);
                if (!validation.Success)
                {
                    return(validation.ErrorMessage);
                }
            }

            var dp = new DistributionPointServices().GetPrimaryDistributionPoint();

            if (dp == null)
            {
                return("Could Not Find A Primary Distribution Point");
            }

            if (SettingServices.ServerIsClusterPrimary)
            {
                var clusterGroup = new ComputerServices().GetClusterGroup(_computer.Id);
                if (clusterGroup == null)
                {
                    return("Could Not Find A Cluster Group For This Computer");
                }
            }

            if (new ComputerServices().IsComputerActive(_computer.Id))
            {
                return("This Computer Is Already Part Of An Active Task");
            }

            _activeTask = new ActiveImagingTaskEntity
            {
                ComputerId = _computer.Id,
                Direction  = _direction,
                UserId     = _userId
            };

            _activeTask.Type = _direction;

            var activeImagingTaskServices = new ActiveImagingTaskServices();

            if (!activeImagingTaskServices.AddActiveImagingTask(_activeTask))
            {
                return("Could Not Create The Database Entry For This Task");
            }

            if (!new TaskBootMenu(_computer, _imageProfile).CreatePxeBootFiles())
            {
                activeImagingTaskServices.DeleteActiveImagingTask(_activeTask.Id);
                return("Could Not Create PXE Boot File");
            }

            _activeTask.Arguments = new CreateTaskArguments(_computer, _imageProfile, _direction).Execute();
            if (!activeImagingTaskServices.UpdateActiveImagingTask(_activeTask))
            {
                activeImagingTaskServices.DeleteActiveImagingTask(_activeTask.Id);
                return("Could Not Create Task Arguments");
            }

            IpServices.WakeUp(_computer.Mac);

            var auditLog = new AuditLogEntity();

            switch (_direction)
            {
            case "deploy":
                auditLog.AuditType = AuditEntry.Type.Deploy;
                break;

            case "permanentdeploy":
                auditLog.AuditType = AuditEntry.Type.PermanentPush;
                break;

            default:
                auditLog.AuditType = AuditEntry.Type.Upload;
                break;
            }

            auditLog.ObjectId = _computer.Id;
            var user = new UserServices().GetUser(_userId);

            if (user != null)
            {
                auditLog.UserName = user.Name;
            }
            auditLog.ObjectName = _computer.Name;
            auditLog.Ip         = _ipAddress;
            auditLog.UserId     = _userId;
            auditLog.ObjectType = "Computer";
            auditLog.ObjectJson = JsonConvert.SerializeObject(_activeTask);
            new AuditLogServices().AddAuditLog(auditLog);

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

            return("Successfully Started Task For " + _computer.Name);
        }
Beispiel #2
0
        public string Create()
        {
            _imageProfile = new ImageProfileServices().ReadProfile(_group.ImageProfileId);
            if (_imageProfile == null)
            {
                return("The Image Profile Does Not Exist");
            }

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

            var validation = new ImageServices().CheckApprovalAndChecksum(_imageProfile.Image, _userId);

            if (!validation.Success)
            {
                return(validation.ErrorMessage);
            }

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

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

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

            _multicastSession.ServerId = _multicastServerId;
            _multicastSession.UserId   = _userId;
            //End of the road for starting an on demand multicast
            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 AuditLogEntity();
                ondAuditLog.AuditType = AuditEntry.Type.OndMulticast;
                ondAuditLog.ObjectId  = _imageProfile.ImageId;
                var ondUser = new UserServices().GetUser(_userId);
                if (ondUser != null)
                {
                    ondAuditLog.UserName = ondUser.Name;
                }
                ondAuditLog.ObjectName = _imageProfile.Image.Name;
                ondAuditLog.Ip         = _ipAddress;
                ondAuditLog.UserId     = _userId;
                ondAuditLog.ObjectType = "Image";
                ondAuditLog.ObjectJson = JsonConvert.SerializeObject(_multicastSession);
                new AuditLogServices().AddAuditLog(ondAuditLog);
                return("Successfully Started Multicast " + _group.Name);
            }

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

            var activeMulticastSessionServices = new ActiveMulticastSessionServices();

            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)
            {
                IpServices.WakeUp(computer.Mac);
            }

            var auditLog = new AuditLogEntity();

            auditLog.AuditType = AuditEntry.Type.Multicast;
            auditLog.ObjectId  = _group.Id;
            var user = new UserServices().GetUser(_userId);

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

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

            return("Successfully Started Multicast " + _group.Name);
        }
Beispiel #3
0
        public DtoTriggerResponse Execute(DtoPolicyRequest policyRequest)
        {
            var triggerResponse = new DtoTriggerResponse();

            var list     = new List <DtoClientPolicy>();
            var computer = _uow.ComputerRepository.GetFirstOrDefault(x => x.Guid == policyRequest.ClientIdentity.Guid);

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

            if (string.IsNullOrEmpty(policyRequest.CurrentComServer))
            {
                Logger.Debug("Could Not Determine The Client's Policy.  A Com Server Was Not Provided.");
                return(null);
            }

            //without this, viewing the computer's effective policy, clears these values
            if (!string.IsNullOrEmpty(policyRequest.ClientVersion) && !string.IsNullOrEmpty(policyRequest.PushURL))
            {
                computer.LastCheckinTime = DateTime.Now;
                computer.ClientVersion   = policyRequest.ClientVersion;
                computer.PushUrl         = policyRequest.PushURL;
                computer.LastIp          = IpServices.GetIPAddress();
                new ServiceComputer().UpdateComputer(computer);
            }

            var groupMemberships = _uow.GroupRepository.GetMembershipsForClientPolicy(computer.Id);

            if (policyRequest.UserLogins != null)
            {
                var userLoginsResult = new ServiceUserLogins().AddOrUpdate(policyRequest.UserLogins, computer.Id);
                if (userLoginsResult != null)
                {
                    triggerResponse.UserLoginsSubmitted = userLoginsResult.Success;
                }
            }

            if (policyRequest.AppMonitors != null)
            {
                var appMonitorResult = new ServiceAppMonitor().AddOrUpdate(policyRequest.AppMonitors, computer.Id);
                if (appMonitorResult != null)
                {
                    triggerResponse.AppMonitorSubmitted = appMonitorResult.Success;
                }
            }

            foreach (var membership in groupMemberships)
            {
                var clientPoliciesJson = new ServiceGroup().GetActiveGroupPolicy(membership.GroupId);
                if (clientPoliciesJson == null)
                {
                    continue;
                }
                if (policyRequest.Trigger == EnumPolicy.Trigger.Startup)
                {
                    list.AddRange(JsonConvert.DeserializeObject <List <DtoClientPolicy> >(clientPoliciesJson.PolicyJson).Where(x => x.StartDate <= DateTime.UtcNow && (x.Trigger == EnumPolicy.Trigger.Startup || x.Trigger == EnumPolicy.Trigger.StartupOrCheckin)));
                }
                else if (policyRequest.Trigger == EnumPolicy.Trigger.Checkin)
                {
                    list.AddRange(JsonConvert.DeserializeObject <List <DtoClientPolicy> >(clientPoliciesJson.PolicyJson).Where(x => x.StartDate <= DateTime.UtcNow && (x.Trigger == EnumPolicy.Trigger.Checkin || x.Trigger == EnumPolicy.Trigger.StartupOrCheckin)));
                }
                else
                {
                    list.AddRange(JsonConvert.DeserializeObject <List <DtoClientPolicy> >(clientPoliciesJson.PolicyJson).Where(x => x.StartDate <= DateTime.UtcNow && x.Trigger == policyRequest.Trigger));
                }
            }

            var distinctList        = list.GroupBy(dto => dto.Guid).Select(y => y.First()).ToList();
            var toRemoveByComServer = new List <DtoClientPolicy>();

            //refine list to only designated com servers
            foreach (var p in distinctList)
            {
                if (p.PolicyComCondition == EnumPolicy.PolicyComCondition.Any)
                {
                    continue;
                }

                var policyComServers = _uow.PolicyRepository.GetPolicyComServerUrls(p.Id);
                if (!policyComServers.Contains(policyRequest.CurrentComServer.ToLower()))
                {
                    toRemoveByComServer.Add(p);
                }
            }

            foreach (var p in toRemoveByComServer)
            {
                distinctList.Remove(p);
            }

            //refine list to designated schedules
            var currentDayOfWeek = (int)DateTime.Now.DayOfWeek;
            var currentTimeOfDay = DateTime.Now.TimeOfDay;
            var serviceSchedule  = new ServiceSchedule();

            var toRemoveBySchedule = new List <DtoClientPolicy>();

            foreach (var p in distinctList.Where(x => x.StartWindowScheduleId != -1 && x.EndWindowScheduleId != -1 && x.Trigger != EnumPolicy.Trigger.Login))
            {
                //items in here have a more refined schedule.  Check if they should be removed from the current run list.
                var start = serviceSchedule.GetSchedule(p.StartWindowScheduleId);
                var end   = serviceSchedule.GetSchedule(p.EndWindowScheduleId);
                if (start == null || end == null)
                {
                    continue;
                }
                if (!start.IsActive || !end.IsActive)
                {
                    continue;
                }

                if (p.Frequency != EnumPolicy.Frequency.OncePerWeek && p.Frequency != EnumPolicy.Frequency.OncePerMonth) //day of week is already defined in weekly frequency and day of month is already defined
                {
                    if (currentDayOfWeek == 0 && !start.Sunday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 1 && !start.Monday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 2 && !start.Tuesday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 3 && !start.Wednesday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 4 && !start.Thursday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 5 && !start.Friday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                    else if (currentDayOfWeek == 6 && !start.Saturday)
                    {
                        toRemoveBySchedule.Add(p);
                    }
                }

                try
                {
                    var startMinute    = start.Minute == 0 ? "00" : start.Minute.ToString();
                    var endMinute      = end.Minute == 0 ? "00" : end.Minute.ToString();
                    var startTimeOfDay = DateTime.ParseExact(start.Hour + " " + startMinute, "H mm", CultureInfo.InvariantCulture).TimeOfDay;
                    var endTimeOfDay   = DateTime.ParseExact(end.Hour + " " + endMinute, "H mm", CultureInfo.InvariantCulture).TimeOfDay;
                    if (currentTimeOfDay >= startTimeOfDay && currentTimeOfDay <= endTimeOfDay)
                    {
                        //ignored
                    }
                    else
                    {
                        toRemoveBySchedule.Add(p);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Could Not Parse Schedule Times For " + start.Name + " " + end.Name);
                    Logger.Error(ex.Message);
                    continue;
                }
            }

            foreach (var p in toRemoveBySchedule)
            {
                distinctList.Remove(p);
            }

            triggerResponse.Policies      = distinctList;
            triggerResponse.CheckinTime   = Convert.ToInt32(ServiceSetting.GetSettingValue(SettingStrings.CheckinInterval));
            triggerResponse.ShutdownDelay = Convert.ToInt32(ServiceSetting.GetSettingValue(SettingStrings.ShutdownDelay));
            return(triggerResponse);
        }