protected void btnCreate_Click(object sender, EventArgs e)
        {
            IAction <PlanModel> actionobj = new PlanAction();
            var model = new PlanModel();

            model.PlanName = txtPlanName.Text;
            model.Descr    = txtDescr.Text;

            if (txtDetuc.Text == string.Empty)
            {
                txtDetuc.Text = "";
            }

            int val;
            var result = int.TryParse(txtDetuc.Text, out val);

            if (!result)
            {
                return;
            }

            model.Deductable = Convert.ToDouble(txtDetuc.Text);

            if (actionobj.Insert(model) == true)
            {
                lblResult.Text = "Plan Has Been Added Successfully! ";
            }
            else
            {
                lblResult.Text = "Plan Is Not Added ";
            }
        }
Example #2
0
 internal static PlanResult FromAction(PlanAction action)
 {
     return(new PlanResult()
     {
         Action = action
     });
 }
Example #3
0
        private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            var actionsWorker = sender as BackgroundWorker;

            Program.Invoke(Program.MainWindow, () =>
            {
                if (!actionsWorker.CancellationPending)
                {
                    PlanAction action = (PlanAction)e.UserState;
                    if (action != null)
                    {
                        if (e.ProgressPercentage == 0)
                        {
                            inProgressActions.Add(action);
                        }
                        else
                        {
                            doneActions.Add(action);
                            inProgressActions.Remove(action);

                            progressBar.Value += (int)((float)e.ProgressPercentage / (float)backgroundWorkers.Count);     //extend with error handling related numbers
                        }
                    }

                    UpdateStatusTextBox();
                }
            });
        }
 protected void OnReportException(Exception ex, PlanAction planAction, Host host)
 {
     if (ReportException != null)
     {
         ReportException(ex, planAction, host);
     }
 }
Example #5
0
        private void ReportException(Exception exception, PlanAction planAction, Host host)
        {
            Program.Invoke(this, () =>
            {
                if (host != null && !host.enabled && host.Connection != null && host.Connection.Session != null)
                {
                    try
                    {
                        new EnableHostAction(host, false,
                                             AddHostToPoolCommand.EnableNtolDialog).RunExternal(host.Connection.Session);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception while trying to re-enable the host", e);
                    }
                }
            });
            Program.BeginInvoke(this, () =>
            {
                var row = planAction is UnwindProblemsAction
                                                        ? FindRow(null)
                                                        : FindRow(host);

                row.UpdateStatus(HostUpgradeState.Error, exception.Message);

                UpgradeProgress(row.Index + 1);
            });
        }
Example #6
0
        public void RunPlanAction(PlanAction action, ref DoWorkEventArgs e, bool skip = false)
        {
            if (CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            // if this action is completed successfully, do not run it again
            if (DoneActions.Contains(action) && action.Error == null)
            {
                return;
            }

            // if we retry a failed action, we need to firstly remove it from DoneActions and reset its Error
            DoneActions.Remove(action);
            action.Error = null;

            if (skip)
            {
                //skip running it, but still need to report progress, mainly for the progress bar
                PercentComplete += ProgressIncrement * 100;
                ReportProgress((int)PercentComplete, action);
            }
            else
            {
                action.OnProgressChange += action_OnProgressChange;
                action.Run();
                action.OnProgressChange -= action_OnProgressChange;
            }
        }
Example #7
0
 private void actionsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     if (!actionsWorker.CancellationPending)
     {
         PlanAction action = (PlanAction)e.UserState;
         if (e.ProgressPercentage == 0)
         {
             textBoxLog.Text = completedActionsLog.ToString();
             if (action.Visible)
             {
                 textBoxLog.Text += action.ProgressDescription ?? action.ToString();
             }
         }
         else
         {
             if (action.Visible)
             {
                 completedActionsLog.Append(action.ProgressDescription ?? action.ToString());
                 completedActionsLog.AppendLine(Messages.DONE);
             }
             textBoxLog.Text    = completedActionsLog.ToString();
             progressBar.Value += e.ProgressPercentage;
         }
     }
 }
 protected void OnReportRunning(PlanAction planAction, Host host)
 {
     if (ReportRunning != null)
     {
         ReportRunning(planAction, host);
     }
 }
        public void RunPlanAction(PlanAction action, ref DoWorkEventArgs e)
        {
            if (CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            // if this action is completed successfully, do not run it again
            if (DoneActions.Contains(action) && action.Error == null)
            {
                return;
            }

            // if we retry a failed action, we need to firstly remove it from DoneActions and reset its Error
            DoneActions.Remove(action);
            action.Error = null;

            if (action == FirstFailedSkippableAction)
            {
                FirstFailedSkippableAction = null;
                action.Skipping            = true;
            }

            action.OnProgressChange += action_OnProgressChange;
            action.Run();
            action.OnProgressChange -= action_OnProgressChange;
        }
Example #10
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            var obj = new PlanModel();


            obj.Descr      = descr.Text;
            obj.Deductable = Convert.ToDouble(dectVal.Text);

            obj.PlanName = ddlPlan.SelectedItem.Text;
            obj.PlanId   = Convert.ToInt32(ViewState["Plan_id"]);

            var result = new PlanAction().Update(obj);

            if (result)
            {
                Label1.Text = "Plan Has Been Updated Successfully!";
            }
            else
            {
                Label1.Text = "Error to delete -> " + result;
            }

            BindData();
            udp.Update();
        }
        private void action_statusUpdated(object sender, PlanActionStatusChangedEventArgs e)
        {
            Host senderHost = e.XenObject as Host;

            if (senderHost == null)
            {
                return;
            }

            PlanAction plan = sender as PlanAction;

            if (plan == null)
            {
                return;
            }

            List <DataGridViewRowUpgrade> rowsForHost = (from DataGridViewRowUpgrade row in dataGridView1.Rows
                                                         where row.RowIsForHost(senderHost)
                                                         select row).ToList();

            foreach (DataGridViewRowUpgrade row in rowsForHost)
            {
                DataGridViewRowUpgrade closureRow = row;
                Program.Invoke(this, () => closureRow.UpdateStatus(HostUpgradeState.Upgrading, plan.Status));
            }
        }
Example #12
0
 private static void InitializePlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action)
 {
     if (action is IAvoidRestartHostsAware)
     {
         var avoidRestartAction = action as IAvoidRestartHostsAware;
         avoidRestartAction.AvoidRestartHosts = bgw.AvoidRestartHosts;
     }
 }
 public UpdateProgressBackgroundWorker(Pool pool, List <HostPlan> planActions, List <PlanAction> finalActions)
 {
     Pool                       = pool;
     Name                       = pool.Name();
     HostPlans                  = planActions ?? new List <HostPlan>();
     FinalActions               = finalActions ?? new List <PlanAction>();
     CleanupActions             = FinalActions.Where(a => a is RemoveUpdateFileFromMasterPlanAction).ToList();
     FirstFailedSkippableAction = null;
 }
 public SemiAutomaticBackgroundThread(IEnumerable <Host> mastersToUpgrade, IDictionary <Host, List <PlanAction> > planActions, PlanAction revertAction)
 {
     _planActions      = planActions;
     _mastersToUpgrade = mastersToUpgrade;
     _revertAction     = revertAction;
     _bw = new Thread(BworkerDoWork)
     {
         IsBackground = true
     };
 }
        private void RunPlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action)
        {
            action.OnProgressChange += action_OnProgressChange;

            bgw.ReportProgress(0, action);
            action.Run();

            Thread.Sleep(1000);

            action.OnProgressChange -= action_OnProgressChange;
            bgw.ReportProgress(100 / bgw.ActionsCount, action);
        }
Example #16
0
        private static void RunPlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action)
        {
            InitializePlanAction(bgw, action);

            bgw.ReportProgress(0, action);
            action.Run();

            Thread.Sleep(1000);

            bgw.doneActions.Add(action);
            bgw.ReportProgress((int)((1.0 / (double)bgw.ActionsCount) * 100), action);
        }
        public ComponentDeploymentVertex(string id, string name, SemVer version, PlanAction action, TimeSpan?deploymentDuration, bool exists = true)
        {
            Id               = id;
            Name             = name;
            Version          = version;
            DeploymentAction = action;

            DeploymentDuration = deploymentDuration;
            Exists             = exists;

            ComponentGroup = -1;
            ProductGroup   = -1;
            ExecutionOrder = -1;
        }
Example #18
0
 private void ReportRunning(PlanAction planAction, Host host)
 {
     Program.BeginInvoke(this, () =>
     {
         progressBar1.Value = progressBar1.Value < 100
                                                                ? progressBar1.Value + 2
                                                                : progressBar1.Value;
         var row = planAction is UnwindProblemsAction
                                                 ? FindRow(null)
                                                 : FindRow(host);
         if (row != null)
         {
             row.UpdateStatus(HostUpgradeState.Upgrading, planAction.TitlePlan);
         }
     });
 }
Example #19
0
 private void actionsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     if (!actionsWorker.CancellationPending)
     {
         PlanAction action = (PlanAction)e.UserState;
         if (e.ProgressPercentage == 0)
         {
             textBoxLog.Text += action;
         }
         else
         {
             textBoxLog.Text   += string.Format("{0}\r\n", Messages.DONE);
             progressBar.Value += e.ProgressPercentage;
         }
     }
 }
Example #20
0
        private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            var bgw = sender as UpdateProgressBackgroundWorker;

            if (bgw == null)
            {
                return;
            }

            if (!bgw.CancellationPending)
            {
                PlanAction action = (PlanAction)e.UserState;
                if (action != null)
                {
                    if (!action.IsComplete)
                    {
                        if (!bgw.InProgressActions.Contains(action))
                        {
                            bgw.InProgressActions.Add(action);
                        }
                    }
                    else
                    {
                        if (!bgw.DoneActions.Contains(action))
                        {
                            bgw.DoneActions.Add(action);
                        }
                        bgw.InProgressActions.Remove(action);

                        if (action.Error == null)
                        {
                            // remove the successful action from the cleanup actions (we are running the cleanup actions in case of failures or if the user cancelled the process, but we shouldn't re-run the actions that have already been run)
                            bgw.CleanupActions.Remove(action);
                        }
                        else
                        {
                            if (!failedWorkers.Contains(bgw))
                            {
                                failedWorkers.Add(bgw);
                            }
                        }
                    }
                }

                UpdateStatus();
            }
        }
Example #21
0
        private void planAction_StatusChanged(PlanAction plan, Host senderHost)
        {
            if (senderHost == null || plan == null)
            {
                return;
            }

            List <DataGridViewRowUpgrade> rowsForHost = (from DataGridViewRowUpgrade row in dataGridView1.Rows
                                                         where row.RowIsForHost(senderHost)
                                                         select row).ToList();

            foreach (DataGridViewRowUpgrade row in rowsForHost)
            {
                DataGridViewRowUpgrade closureRow = row;
                Program.Invoke(this, () => closureRow.UpdateStatus(HostUpgradeState.Upgrading, plan.Status));
            }
        }
 private void actionsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     if (!actionsWorker.CancellationPending)
     {
         PlanAction action = (PlanAction)e.UserState;
         if (e.ProgressPercentage == 0)
         {
             textBoxLog.Text  = completedActionsLog.ToString();
             textBoxLog.Text += action.CurrentProgressStep;
         }
         else
         {
             completedActionsLog.AppendLine(action.CurrentProgressStep);
             textBoxLog.Text = completedActionsLog.ToString();
             int newVal = progressBar.Value + e.ProgressPercentage;
             progressBar.Value = newVal > 100 ? 100 : newVal;
         }
     }
 }
Example #23
0
        public static void UpdateDatacentreSuffix(Domain.Profile Profile, string ParametersString, string MaxRetries, string ContinueOnError, string Order)
        {
#if DEBUG_ME
            System.Diagnostics.Debug.WriteLine(
                string.Format("UpdateDatacentreSuffix(ps:{0}, mr:{1}, coe:{2}, o:{3})", ParametersString, MaxRetries, ContinueOnError, Order),
                DEBUG_CATEGORY);
#endif

            int maxRetries = 0;
            try
            {
                maxRetries = Convert.ToInt32(MaxRetries);
            }
            catch
            {
                return;
            }

            int order = 0;
            try
            {
                order = Convert.ToInt32(Order);
            }
            catch
            {
                return;
            }

            List <PlanAction> planActions = Profile.ActiveProvisioningPlan.PlanActions;
            PlanAction        action      = planActions.First((i) => i.ParametersString == ParametersString);
            action.MaxRetries      = maxRetries;
            action.ContinueOnError = ContinueOnError;
            action.Order           = order;

            planActions.Sort(PlanAction.CompareByOrder);
            Profile.ActiveProvisioningPlan.PlanActions = planActions;
        }
Example #24
0
 public static bool IsRestartRelatedPlanAction(this PlanAction a)
 {
     return
         (a is EvacuateHostPlanAction || a is RebootHostPlanAction || a is BringBabiesBackAction);
 }
    //bool help_request;
    void Awake()
    {
        navMeshAgent = this.GetComponent<NavMeshAgent> ();
        endOfWorld = false;
        foodAhead = false;
        hasFood = false;
        atBase = false;
        enemyAhead = false;
        agentAhead = false;
        isFoodOnSight = false;
        isEnemyOnSight = false;
        isObstacleOnSight = false;
        isSpecFoodOnSight = false;
        currentPlan = null;
        currentActionHasEnded = false;
        //help_request = false;
        currentAction = null;
        //myColor = transform.GetChild (0).GetChild (0).gameObject.GetComponent<Renderer> ().material.color;
        myDesires = new Dictionary<Desire,float> ();
        InitializeDesires ();

        commModule = GetComponent<ComunicationModule>();

        Vector3 moveRand = MoveRandomly ();
        myCurrentIntention = new IntentionDetails(Intention.SEARCH_FOOD, 1f, moveRand);
        myBeliefs = new Dictionary<Vector3,string> (new Vector3Comparer());
    }
Example #26
0
        private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var bgw = sender as UpdateProgressBackgroundWorker;

            if (bgw == null)
            {
                return;
            }

            PlanAction action = null;

            try
            {
                foreach (var hp in bgw.HostPlans)
                {
                    var host = hp.Host;

                    // Step 1: InitialPlanActions  (e.g. upgrade the host in the RPU case)
                    bgw.ProgressIncrement = bgw.InitialActionsIncrement(hp);
                    if (!SkipInitialPlanActions(host))
                    {
                        var initialActions = hp.InitialPlanActions;

                        foreach (var a in initialActions)
                        {
                            action = a;
                            bgw.RunPlanAction(action, ref doWorkEventArgs);
                        }
                    }

                    DoAfterInitialPlanActions(bgw, host, bgw.HostPlans.Select(h => h.Host).ToList());

                    // Step 2: UpdatesPlanActions  (priority update action)
                    bgw.ProgressIncrement = bgw.UpdatesActionsIncrement(hp);
                    var planActions = hp.UpdatesPlanActions;
                    foreach (var a in planActions)
                    {
                        action = a;
                        bgw.RunPlanAction(action, ref doWorkEventArgs);
                    }

                    // Step 3: DelayedActions
                    bgw.ProgressIncrement = bgw.DelayedActionsIncrement(hp);
                    // running delayed actions, but skipping the ones that should be skipped
                    var delayedActions = hp.DelayedPlanActions;
                    var restartActions = delayedActions.Where(a => a is RestartHostPlanAction).ToList();

                    foreach (var a in restartActions)
                    {
                        action = a;
                        bgw.RunPlanAction(action, ref doWorkEventArgs);
                    }

                    var otherActions = delayedActions.Where(a => !(a is RestartHostPlanAction)).ToList();

                    foreach (var a in otherActions)
                    {
                        action = a;

                        // any non-restart-alike delayed action needs to be run if:
                        // - this host is pre-Ely and there isn't any delayed restart plan action, or
                        // - this host is Ely or above and live patching must have succeeded or there isn't any delayed restart plan action
                        if (restartActions.Count <= 0 ||
                            (Helpers.ElyOrGreater(host) && host.Connection.TryResolveWithTimeout(new XenRef <Host>(host.opaque_ref)).updates_requiring_reboot.Count <= 0))
                        {
                            bgw.RunPlanAction(action, ref doWorkEventArgs);
                        }
                        else
                        {
                            //skip running it, but still need to report progress, mainly for the progress bar
                            bgw.RunPlanAction(action, ref doWorkEventArgs, true);
                        }
                    }
                }

                // Step 4: FinalActions (eg. revert pre-checks)
                bgw.ProgressIncrement = bgw.FinalActionsIncrement;
                foreach (var a in bgw.FinalActions)
                {
                    action = a;
                    bgw.RunPlanAction(action, ref doWorkEventArgs);
                }
            }
            catch (Exception e)
            {
                if (action.Error == null)
                {
                    action.Error = new Exception(Messages.ERROR_UNKNOWN);
                }

                log.ErrorFormat("Failed to carry out plan. {0} {1}", action.CurrentProgressStep, e);
                doWorkEventArgs.Result = new Exception(action.CurrentProgressStep, e);
            }
        }
    /*
     * Agent main loop
     * BDI Agent
     * The commitment is single-minded
     */
    void Update()
    {
        // Decreases Agent life over time
        // Value can be a public variable
        DecreaseLife(0.5f);

        //The Hybrid approach is a vertical one pass layered one, first see if
        //the percepts in reactive approach and then pass to deliberative the control.
        //The reactive layer is the one innerently connected to the sensors, although
        //with the approach of using unity the deliberative one is also connected to the
        //sensors. However, the lower one takes the decision (analgously with Subsumption)

        if (UseReactiveLayer ()) {
            currentPlan = null;
            currentAction = null;
            currentActionHasEnded = false;
            if (EnemyAhead ()) {
                HitEnemy ();
                Queue<PlanAction> plan = new Queue<PlanAction> ();
                plan.Enqueue(new PlanAction(Action.FIGHT_MONSTER));
                currentPlan = plan;
                //myCurrentIntention = new IntentionDetails(Intention.ATTACK_MONSTER_AT, 1.0f, enemy.transform.position);
            } else if (FoodAhead ()) {
                if(!HasFood ()) {
                    PickFood ();
                    Queue<PlanAction> plan = new Queue<PlanAction> ();
                    plan.Enqueue(new PlanAction(Action.MOVE_TO, myColonyPosition));
                    plan.Enqueue(new PlanAction(Action.DROP_FOOD, myColonyPosition));
                    currentPlan = plan;
                }
            }
        } else {
            if (currentPlan == null) {
                Brf ();
                Options ();
                Filter ();
                Planner planner = CreateNewPlan ();
                currentPlan = planner.Plan ();
            } else {
                ChooseAction ();

                bool impossible = Impossible ();
                if (PlanIsEmpty () || Succeeded () || impossible) {
                    if (currentAction != null && impossible) {
                        bool removeBelief = (myBeliefs.ContainsKey (myCurrentIntention.Position ()) && myBeliefs [myCurrentIntention.Position ()] != "MyCol");
                        if (removeBelief) {
                            myBeliefs.Remove (myCurrentIntention.Position ());
                        }
                    }
                    currentPlan = null;
                    currentAction = null;
                    currentActionHasEnded = false;
                    return;
                }
                ExecuteAction ();
                Brf ();
                if (Reconsider ()) {
                    Options ();
                    Filter ();
                }
            }
        }
    }
        private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var bgw = sender as UpdateProgressBackgroundWorker;

            if (bgw == null)
            {
                return;
            }

            PlanAction action = null;

            try
            {
                //running actions (non-delayed)
                foreach (var a in bgw.PlanActions)
                {
                    action = a;

                    if (bgw.CancellationPending)
                    {
                        doWorkEventArgs.Cancel = true;
                        return;
                    }

                    RunPlanAction(bgw, action);
                }

                // running delayed actions, but skipping the ones that should be skipped
                // iterating through hosts, master first
                var hostsOrdered = bgw.DelayedActionsByHost.Keys.ToList();
                hostsOrdered.Sort(); //master first

                foreach (var h in hostsOrdered)
                {
                    var actions        = bgw.DelayedActionsByHost[h];
                    var restartActions = actions.Where(a => a is RestartHostPlanAction).ToList();

                    //run all restart-alike plan actions
                    foreach (var a in restartActions)
                    {
                        action = a;

                        if (bgw.CancellationPending)
                        {
                            doWorkEventArgs.Cancel = true;
                            return;
                        }

                        RunPlanAction(bgw, action);
                    }

                    var otherActions = actions.Where(a => !(a is RestartHostPlanAction)).ToList();

                    //run the rest
                    foreach (var a in otherActions)
                    {
                        action = a;

                        if (bgw.CancellationPending)
                        {
                            doWorkEventArgs.Cancel = true;
                            return;
                        }

                        // any non-restart-alike delayed action needs to be run if:
                        // - this host is pre-Ely and there isn't any delayed restart plan action, or
                        // - this host is Ely or above and live patching must have succeeded or there isn't any delayed restart plan action
                        if (restartActions.Count <= 0 ||
                            (Helpers.ElyOrGreater(h) && h.Connection.TryResolveWithTimeout(new XenRef <Host>(h.opaque_ref)).updates_requiring_reboot.Count <= 0))
                        {
                            RunPlanAction(bgw, action);
                        }
                        else
                        {
                            //skip running it, but still need to report progress, mainly for the progress bar

                            action.Visible = false;
                            bgw.ReportProgress(100 / bgw.ActionsCount, action);
                        }
                    }
                }

                //running final actions (eg. revert pre-checks)
                foreach (var a in bgw.FinalActions)
                {
                    action = a;

                    if (bgw.CancellationPending)
                    {
                        doWorkEventArgs.Cancel = true;
                        return;
                    }

                    RunPlanAction(bgw, action);
                }
            }
            catch (Exception e)
            {
                errorActions.Add(action);
                inProgressActions.Remove(action);

                log.Error("Failed to carry out plan.", e);
                log.Debug(action.Title);

                doWorkEventArgs.Result = new Exception(action.Title, e);

                //this pool failed, we will stop here, but try to remove update files at least
                try
                {
                    var positionOfFailedAction = bgw.PlanActions.IndexOf(action);

                    // can try to clean up the host after a failed PlanAction from bgw.PlanActions only
                    if (positionOfFailedAction != -1 && !(action is DownloadPatchPlanAction || action is UploadPatchToMasterPlanAction))
                    {
                        int pos = positionOfFailedAction;

                        if (!(bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction)) //can't do anything if the remove action has failed
                        {
                            while (++pos < bgw.PlanActions.Count)
                            {
                                if (bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction) //find the next remove
                                {
                                    bgw.PlanActions[pos].Run();
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex2)
                {
                    //already in an error case - best effort

                    log.Error("Failed to clean up (this was a best effort attempt)", ex2);
                }

                bgw.ReportProgress(0);
            }
        }
Example #29
0
        private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var        bgw    = sender as UpdateProgressBackgroundWorker;
            PlanAction action = null;

            try
            {
                //running actions (non-delayed)
                foreach (var a in bgw.PlanActions)
                {
                    action = a;

                    if (bgw.CancellationPending)
                    {
                        doWorkEventArgs.Cancel = true;
                        return;
                    }

                    RunPlanAction(bgw, action);
                }

                // running delayed actions, but skipping the ones that should be skipped
                // iterating through hosts
                foreach (var kvp in bgw.DelayedActionsByHost)
                {
                    var h       = kvp.Key;
                    var actions = kvp.Value;

                    //run all restart-alike plan actions
                    foreach (var a in actions.Where(a => a.IsRestartRelatedPlanAction()))
                    {
                        action = a;

                        if (bgw.CancellationPending)
                        {
                            doWorkEventArgs.Cancel = true;
                            return;
                        }

                        RunPlanAction(bgw, action);
                    }

                    //run the rest
                    foreach (var a in actions.Where(a => !a.IsRestartRelatedPlanAction()))
                    {
                        action = a;

                        if (bgw.CancellationPending)
                        {
                            doWorkEventArgs.Cancel = true;
                            return;
                        }

                        // any non-restart-alike delayed action needs to be run if:
                        // - this host is pre-Ely and there isn't any restart plan action among the delayed actions, or
                        // - this host is Ely or above and bgw.AvoidRestartHosts contains the host's uuid (shows that live patching must have succeeded) or there isn't any restart plan action among the delayed actions
                        if (!Helpers.ElyOrGreater(h) && !actions.Any(pa => pa.IsRestartRelatedPlanAction()) ||
                            Helpers.ElyOrGreater(h) && (bgw.AvoidRestartHosts != null && bgw.AvoidRestartHosts.Contains(h.uuid) || !actions.Any(pa => pa.IsRestartRelatedPlanAction())))
                        {
                            RunPlanAction(bgw, action);
                        }
                        else
                        {
                            //skip running it

                            action.Visible = false;
                            bgw.ReportProgress((int)((1.0 / (double)bgw.ActionsCount) * 100), action); //still need to report progress, mainly for the progress bar
                        }
                    }
                }
            }
            catch (Exception e)
            {
                bgw.FailedWithExceptionAction = action;
                errorActions.Add(action);
                inProgressActions.Remove(action);

                log.Error("Failed to carry out plan.", e);
                log.Debug(action.Title);

                doWorkEventArgs.Result = new Exception(action.Title, e);

                //this pool failed, we will stop here, but try to remove update files at least
                try
                {
                    var positionOfFailedAction = bgw.PlanActions.IndexOf(action);

                    // can try to clean up the host after a failed PlanAction from bgw.PlanActions only
                    if (positionOfFailedAction != -1 && !(action is DownloadPatchPlanAction || action is UploadPatchToMasterPlanAction))
                    {
                        int pos = positionOfFailedAction;

                        if (!(bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction)) //can't do anything if the remove action has failed
                        {
                            while (++pos < bgw.PlanActions.Count)
                            {
                                if (bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction) //find the next remove
                                {
                                    bgw.PlanActions[pos].Run();
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex2)
                {
                    //already in an error case - best effort

                    log.Error("Failed to clean up (this was a best effort attempt)", ex2);
                }

                bgw.ReportProgress(0);
            }
        }
    /*
     * Agent main loop
     * BDI Agent
     * The commitment is single-minded
     */
    void Update()
    {
        // Decreases Agent life over time
        // Value can be a public variable
        DecreaseLife(0.5f);
        //single commitment

        foreach (var belief in myBeliefs.Keys) {
            Debug.Log (belief + ":" + myBeliefs [belief]);
        }
        Debug.Log ("---------------");
        if (currentPlan == null) {
            Brf ();
            Options ();
            Filter ();
            Planner planner = CreateNewPlan ();
            currentPlan = planner.Plan ();
        } else {
            ChooseAction ();

            /*Debug.Log (myCurrentIntention.Intention ());
            if (currentAction != null) {
                Debug.Log (currentAction.Action ());
                Debug.Log (myCurrentIntention.Intention ());
            }*/
            bool impossible = Impossible ();
            if(PlanIsEmpty () || Succeeded () || impossible) {
                if(currentAction != null && impossible) {
                    bool removeBelief = (myBeliefs.ContainsKey(myCurrentIntention.Position ()) && myBeliefs [myCurrentIntention.Position ()] != "MyCol");
                    if (removeBelief) {
                        myBeliefs.Remove(myCurrentIntention.Position ());
                    }
                }
                currentPlan = null;
                currentAction = null;
                currentActionHasEnded = false;
                return;
            }
            ExecuteAction ();
            Brf ();
            if (Reconsider ()) {
                Options ();
                Filter ();
            }
        }
    }
Example #31
0
 private void action_OnProgressChange(PlanAction planAction)
 {
     PercentComplete += planAction.IsComplete ? ProgressIncrement * 100 : 0;
     ReportProgress((int)PercentComplete, planAction);
 }
Example #32
0
        private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var bgw = sender as UpdateProgressBackgroundWorker;

            if (bgw == null)
            {
                return;
            }

            PlanAction action = null;

            try
            {
                foreach (var hp in bgw.HostPlans)
                {
                    var host = hp.Host;

                    // Step 1: InitialPlanActions  (e.g. upgrade the host in the RPU case)
                    bgw.ProgressIncrement = bgw.InitialActionsIncrement(hp);
                    if (!SkipInitialPlanActions(host))
                    {
                        var initialActions = hp.InitialPlanActions;

                        foreach (var a in initialActions)
                        {
                            action = a;
                            bgw.RunPlanAction(action, ref doWorkEventArgs);
                        }
                    }

                    DoAfterInitialPlanActions(bgw, host, bgw.HostPlans.Select(h => h.Host).ToList());

                    // Step 2: UpdatesPlanActions  (priority update action)
                    bgw.ProgressIncrement = bgw.UpdatesActionsIncrement(hp);
                    var planActions = hp.UpdatesPlanActions;
                    foreach (var a in planActions)
                    {
                        action = a;
                        bgw.RunPlanAction(action, ref doWorkEventArgs);
                    }

                    // Step 3: Rearrange DelayedActions
                    var suppPackPlanAction = (RpuUploadAndApplySuppPackPlanAction)planActions.FirstOrDefault(pa => pa is RpuUploadAndApplySuppPackPlanAction);

                    if (suppPackPlanAction != null)
                    {
                        foreach (var dpa in suppPackPlanAction.DelayedPlanActions)
                        {
                            if (!hp.DelayedPlanActions.Exists(a => a.GetType() == dpa.GetType()))
                            {
                                hp.DelayedPlanActions.Add(dpa);
                            }
                        }
                    }

                    var restartHostPlanAction = (RestartHostPlanAction)hp.DelayedPlanActions.FirstOrDefault(a => a is RestartHostPlanAction);
                    if (restartHostPlanAction != null)
                    {
                        if (restartHostPlanAction.SkipRestartHost(host))
                        {
                            log.Debug("Did not find patches requiring reboot (live patching succeeded)."
                                      + " Skipping scheduled restart.");
                            hp.DelayedPlanActions.RemoveAll(a => a is RestartHostPlanAction);
                        }
                        else
                        {
                            hp.DelayedPlanActions.RemoveAll(a => a is RestartAgentPlanAction);
                        }
                    }

                    // Step 4: DelayedActions
                    bgw.ProgressIncrement = bgw.DelayedActionsIncrement(hp);
                    // running delayed actions
                    var delayedActions = hp.DelayedPlanActions;
                    var restartActions = delayedActions.Where(a => a is RestartHostPlanAction).ToList();

                    foreach (var a in restartActions)
                    {
                        action = a;
                        bgw.RunPlanAction(action, ref doWorkEventArgs);
                    }

                    var otherActions = delayedActions.Where(a => !(a is RestartHostPlanAction)).ToList();

                    foreach (var a in otherActions)
                    {
                        action = a;
                        bgw.RunPlanAction(action, ref doWorkEventArgs);
                    }
                }

                // Step 5: FinalActions (eg. revert pre-checks)
                bgw.ProgressIncrement = bgw.FinalActionsIncrement;
                foreach (var a in bgw.FinalActions)
                {
                    action = a;
                    bgw.RunPlanAction(action, ref doWorkEventArgs);
                }
            }
            catch (Exception e)
            {
                if (action.Error == null)
                {
                    action.Error = new Exception(Messages.ERROR_UNKNOWN);
                }

                log.ErrorFormat("Failed to carry out plan. {0} {1}", action.CurrentProgressStep, e);
                doWorkEventArgs.Result = new Exception(action.CurrentProgressStep, e);
            }
        }
 void ChooseAction()
 {
     if (currentAction == null && currentPlan.Count > 0) {
         currentAction = currentPlan.Dequeue ();
     } else {
         if (CurrentActionHasEnded () && currentPlan.Count == 0) {
             //currentAction = null;
             return;
         } else if(CurrentActionHasEnded () && currentPlan.Count > 0) {
             currentAction = currentPlan.Dequeue ();
             currentActionHasEnded = false;
         }
     }
 }
        private void BworkerDoWork()
        {
            Host currentHost = null;

            try
            {
                List <Host> hosts = GetAllHosts(_mastersToUpgrade);

                bool   currentMasterFailed      = false;
                string poolHigherProductVersion = string.Empty;
                for (int i = 0; i < hosts.Count; i++)
                {
                    if (_cancel)
                    {
                        return;
                    }
                    //Skip hosts already upgraded
                    var host = currentHost = hosts[i];
                    if (host.IsMaster())
                    {
                        poolHigherProductVersion = host.LongProductVersion();
                        if (CheckMasterIsUpgraded(hosts, i))
                        {
                            log.Debug(string.Format("Skipping master '{0}' because it is upgraded", host.Name()));
                            continue;
                        }
                    }
                    else if (host.LongProductVersion() == poolHigherProductVersion)
                    {
                        log.Debug(string.Format("Skipping host '{0}' because it is upgraded", host.Name()));
                        continue;
                    }
                    log.Debug(string.Format("Starting to upgrade host '{0}'", host.Name()));
                    //Add subtasks for the current host
                    bool allActionsDone = true;
                    foreach (var planAction in _planActions[host])
                    {
                        //if the wizard has been cancelled, skip this action, unless it is a BringBabiesBackAction
                        if (_cancel && !(planAction is BringBabiesBackAction))
                        {
                            continue;
                        }

                        OnReportRunning(planAction, host);

                        try
                        {
                            if (planAction is UpgradeManualHostPlanAction)
                            {
                                var upgradeAction = (UpgradeManualHostPlanAction)planAction;

                                if (ManageSemiAutomaticPlanAction != null)
                                {
                                    ManageSemiAutomaticPlanAction(upgradeAction);
                                }

                                if (host.IsMaster())
                                {
                                    poolHigherProductVersion = upgradeAction.Host.LongProductVersion();
                                }
                            }
                            else
                            {
                                planAction.Run();
                            }
                        }
                        catch (Exception excep)
                        {
                            log.Error(string.Format("Exception in host '{0}' while it was upgraded", host.Name()), excep);
                            PlanAction action1 = planAction;

                            OnReportException(excep, action1, host);

                            if (host.IsMaster())
                            {
                                currentMasterFailed = true;
                            }
                            allActionsDone = false;
                            break;
                        }
                    }

                    if (allActionsDone)
                    {
                        OnReportHostDone(host);
                    }

                    //Skip slaves if master failed
                    if (currentMasterFailed)
                    {
                        i = SkipSlaves(hosts, i);
                    }
                }
            }
            catch (Exception excep)
            {
                log.Error("Upgrade thread error: ", excep);
            }
            finally
            {
                //Revert resolved prechecks
                try
                {
                    log.Debug("Reverting prechecks");
                    OnReportRunning(_revertAction, currentHost);
                    _revertAction.Run();

                    OnReportRevertDone();
                }
                catch (Exception excep)
                {
                    log.Error("Exception reverting prechecks", excep);
                    OnReportException(excep, _revertAction, currentHost);
                }
                OnCompleted();
            }
        }