private CheckpointFileData ReadCheckpointFile()
        {
            CheckpointFileData checkpointFileData = new CheckpointFileData();
            string             checkpointFilepath = this.GetCheckpointFilePath();

            if (File.Exists(checkpointFilepath))
            {
                string text = File.ReadAllText(checkpointFilepath).Trim();
                try
                {
                    string[] arr = text.Split(' ');
                    checkpointFileData.schedulingDateTime = DateTime.ParseExact(arr[0], "yyyyMMddHHmmss", null);
                    checkpointFileData.rescheduleCount    = (long)Convert.ChangeType(arr[1], typeof(long));
                    checkpointFileData.rescheduleNeeded   = Boolean.Parse(arr[2]);
                    if (arr.Length == 4)
                    {
                        checkpointFileData.lastAttemptedUpdateTime = DateTime.ParseExact(arr[3], "yyyyMMddHHmmss", null);
                    }
                }
                catch (Exception ex)
                {
                    _eventSource.ErrorMessage("TimerCheckPoint.txt is not in correct format. Content of the file : {0}, Exception thrown {1}", text, ex);
                    File.Delete(checkpointFilepath);
                }
            }
            _eventSource.InfoMessage("Checkpoint file read: {0}", checkpointFileData);
            return(checkpointFileData);
        }
        private void WriteCheckpointFile(CheckpointFileData fileData)
        {
            string checkpointFilepath = this.GetCheckpointFilePath();
            string randomFilePath     = this.GetRandomFilePath();

            if (File.Exists(randomFilePath))
            {
                File.Delete(randomFilePath);
            }
            using (FileStream fs = File.Create(randomFilePath))
            {
                string data = fileData.schedulingDateTime.ToString("yyyyMMddHHmmss") + " " + fileData.rescheduleCount + " " + fileData.rescheduleNeeded;
                if (!fileData.lastAttemptedUpdateTime.Equals(_checkpointFileDefaultDateTime))
                {
                    data += " " + fileData.lastAttemptedUpdateTime.ToString("yyyyMMddHHmmss");
                }
                Byte[] info = new System.Text.UTF8Encoding(true).GetBytes(data);
                fs.Write(info, 0, info.Length);
            }

            if (File.Exists(checkpointFilepath))
            {
                File.Delete(checkpointFilepath);
            }
            File.Move(randomFilePath, checkpointFilepath);
            File.Delete(randomFilePath);
            _eventSource.InfoMessage("Checkpoint file written : {0}", fileData);
        }
        private void LoadSettings()
        {
            CheckpointFileData checkpointFileData = ReadCheckpointFile();
            bool scheduleWindowsUpdatesFlag       = this.ScheduleWindowsUpdatesFlag(checkpointFileData);

            if (!File.Exists(this._settingsManager.CopyofSettingsFilePath) || !scheduleWindowsUpdatesFlag)
            {
                this.CreateCopyOfSettingsFile();
            }
            try
            {
                this._settingsManager.UpdateSettings(this._settingsManager.CopyofSettingsFilePath);
            }
            catch
            {
                /**
                 * It could be possible that the setting is corrupt and sheduleWindowsUpdatesFlag is set as
                 * CheckPoint is old. In that case, it will crash here even though we have updated the settings.xml
                 * to remove the invalid values.
                 */
                _eventSource.WarningMessage("UpdateSettings crashed probably because of corrupt settings. So, creating copy of latest settings file.");
                this.CreateCopyOfSettingsFile();
                throw;
            }
            _eventSource.InfoMessage("Loaded settings: {0}", this._settingsManager.GetSettings());

            if (!scheduleWindowsUpdatesFlag)
            {
                // Do not update the last updateAttemptedTime.
                this.CreateNewCheckpointFile(false);
                _eventSource.InfoMessage("Loaded checkpoint file.");
            }
        }
Example #4
0
        private void CreateNewCheckpointFile()
        {
            CheckpointFileData checkpointFileData = new CheckpointFileData();

            checkpointFileData.schedulingDateTime = this.GetNextSchedulingTime();
            checkpointFileData.rescheduleCount    = 0;
            checkpointFileData.rescheduleNeeded   = false;
            this.WriteCheckpointFile(checkpointFileData);
        }
Example #5
0
        /// <summary>
        /// This will disable the windows update on system.
        /// </summary>
        private void DisableWindowsUpdate()
        {
            CheckpointFileData fileData = this.ReadCheckpointFile();

            DateTime initialTime = DateTime.Now;

            if (!fileData.lastAttemptedUpdateTime.Equals(_checkpointFileDefaultDateTime))
            {
                initialTime = fileData.lastAttemptedUpdateTime;
            }

            long timeToLive = (long)((fileData.schedulingDateTime - initialTime) + TimeSpan.FromDays(1)).TotalMinutes;

            if (!this._serviceSettings.DisableWindowsUpdates)
            {
                _eventSource.InfoMessage("Not disabling automatic windows updates.");
                return;
            }

            _eventSource.InfoMessage("Disabling automatic windows updates.");
            do
            {
                string msg = "Not able to disable the 'Windows Updates'. ";
                try
                {
                    WindowsAutoUpdateUtility auUtility = new WindowsAutoUpdateUtility();
                    if (auUtility.IsWindowsServer2012R2OrLower())
                    {
                        _eventSource.InfoMessage("Detected OS version is Windows Server 2012R2 or lower");
                        AutomaticUpdatesClass updates = new AutomaticUpdatesClass();

                        _eventSource.InfoMessage("Current automatic windows updates notification level {0}.", updates.Settings.NotificationLevel);
                        auUtility.DisableAUThroughWUApi(updates);
                    }
                    else
                    {
                        _eventSource.InfoMessage("Detected OS version is higher than Windows Server 2012R2");
                        _eventSource.InfoMessage("Current AU registry values are {0}", auUtility.LogCurrentAUValues());
                        auUtility.SetAUOptions();
                        _eventSource.InfoMessage("New AU registry values are {0}", auUtility.LogCurrentAUValues());
                    }
                    string updateMsg = "Windows Update policy has been configured to Notify before Download";
                    this._nodeAgentSfUtility.ReportHealth(WUOperationSetting, updateMsg, HealthState.Ok, timeToLive, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes));
                    return;
                }
                catch (Exception e)
                {
                    msg = string.Format(msg + "Failing with exception : {0}", e);
                }

                _eventSource.WarningMessage(msg);
                this._nodeAgentSfUtility.ReportHealth(WUOperationSetting, msg, HealthState.Warning, -1, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes));
                this._helper.WaitOnTask(Task.Delay(TimeSpan.FromMinutes(WaitTimeInMinutes)), this._cancellationToken);
            } while (true);
        }
        private void CreateNewCheckpointFile(bool updateAttempted = true)
        {
            CheckpointFileData checkpointFileData = this.ReadCheckpointFile();

            checkpointFileData.schedulingDateTime = this.GetNextSchedulingTime();
            if (updateAttempted)
            {
                checkpointFileData.lastAttemptedUpdateTime = DateTime.UtcNow;
            }
            checkpointFileData.rescheduleCount  = 0;
            checkpointFileData.rescheduleNeeded = false;
            this.WriteCheckpointFile(checkpointFileData);
            this.PostWUUpdateEventOnService();
        }
Example #7
0
        private CheckpointFileData ReadCheckpointFile()
        {
            CheckpointFileData checkpointFileData = new CheckpointFileData();
            string             checkpointFilepath = this.GetCheckpointFilePath();

            if (File.Exists(checkpointFilepath))
            {
                string   text = File.ReadAllText(checkpointFilepath).Trim();
                string[] arr  = text.Split(' ');
                checkpointFileData.schedulingDateTime = DateTime.ParseExact(arr[0], "yyyyMMddHHmmss", null);
                checkpointFileData.rescheduleCount    = (long)Convert.ChangeType(arr[1], typeof(long));
                checkpointFileData.rescheduleNeeded   = Boolean.Parse(arr[2]);
            }
            _eventSource.InfoMessage("Checkpoint file read: {0}", checkpointFileData);
            return(checkpointFileData);
        }
        /// <summary>
        /// This will post an event containing the information about patching on CoordinatorService.
        /// </summary>
        private void PostWUUpdateEventOnService()
        {
            CheckpointFileData fileData          = this.ReadCheckpointFile();
            string             formatString      = "Last patching attempt happened at : {0}, Next patching cycle is scheduled at : {1}";
            string             healthDescription = "";

            if (fileData.lastAttemptedUpdateTime.Equals(_checkpointFileDefaultDateTime))
            {
                healthDescription = string.Format(formatString, "N/A", fileData.schedulingDateTime.ToString());
            }
            else
            {
                healthDescription = string.Format(formatString, fileData.lastAttemptedUpdateTime.ToString(), fileData.schedulingDateTime.ToString());
            }
            healthDescription += "\nFor detailed installation results, refer to https://docs.microsoft.com/azure/service-fabric/service-fabric-patch-orchestration-application#view-the-windows-update-results";
            this._nodeAgentSfUtility.ReportHealth(WUOperationStatus, healthDescription, HealthState.Ok, -1, TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes));
        }
        private bool IncrementRetryCount()
        {
            _eventSource.InfoMessage("Incrementing reschedule Count.");
            CheckpointFileData checkpointFileData = this.ReadCheckpointFile();

            if (checkpointFileData.rescheduleCount >= this._serviceSettings.WURescheduleCount)
            {
                _eventSource.InfoMessage("Exceeded reschedule count. WU retry count : {0} , Current NT Service retry count : {1}", this._serviceSettings.WURescheduleCount, (checkpointFileData.rescheduleCount + 1));
                return(false);
            }
            checkpointFileData.rescheduleCount++;
            checkpointFileData.schedulingDateTime.AddMinutes(this._serviceSettings.WURescheduleTimeInMinutes);
            checkpointFileData.rescheduleNeeded = false;
            _eventSource.InfoMessage("Incremented reschedule count. Service reschedule Count is :{0}",
                                     (checkpointFileData.rescheduleCount + 1));
            this.WriteCheckpointFile(checkpointFileData);
            return(true);
        }
        private bool ScheduleWindowsUpdates()
        {
            _eventSource.InfoMessage("Timer Callback started.");
            this._windowsUpdateManager.ResetManager();
            bool rescheduleNeeded = this._windowsUpdateManager.StartUpdate();

            // before reboot writing in checkpoint file.
            if (this._windowsUpdateManager.RebootRequired())
            {
                if (rescheduleNeeded)
                {
                    CheckpointFileData fileData = this.ReadCheckpointFile();
                    fileData.rescheduleNeeded = true;
                    this.WriteCheckpointFile(fileData);
                }

                this._windowsUpdateManager.HandleRestart();
            }

            this._windowsUpdateManager.CompleteWUOperations();
            return(rescheduleNeeded);
        }
 private bool ScheduleWindowsUpdatesFlag(CheckpointFileData fileData)
 {
     return(!fileData.schedulingDateTime.Equals(_checkpointFileDefaultDateTime) &&
            DateTime.Compare(fileData.schedulingDateTime, DateTime.UtcNow) <= 0);
 }
        // polls every 5 minutes, execute the callback if the date-time is according to frequency mentioned in Settings.xml.
        private void ScheduleTimer()
        {
            try
            {
                if (!this.CheckApplicationExists())
                {
                    _eventSource.InfoMessage("Application deleted. Removing NT service...");
                    this._windowsUpdateManager.ResetStateMachine();
                    this.RemoveSelf();
                    return;
                }

                // If cancellation token is canceled or application is not found
                if (this._cancellationToken.IsCancellationRequested)
                {
                    _eventSource.InfoMessage("Canceled timer.");
                    return;
                }

                NodeAgentSfUtilityExitCodes exitCode = this._nodeAgentSfUtility.GetWuOperationState(
                    TimeSpan.FromMinutes(this._serviceSettings.OperationTimeOutInMinutes));
                _eventSource.InfoMessage("Current Wu state: {0}", exitCode);
                if (exitCode == NodeAgentSfUtilityExitCodes.RestartRequested)
                {
                    _eventSource.ErrorMessage("Not able to restart system.");

                    //wait for sometime before retrying. This delay is recommended if posting health reports.
                    if (this._helper.WaitOnTask(Task.Delay(TimeSpan.FromMinutes(WaitTimeInMinutes)),
                                                this._cancellationToken))
                    {
                        this.ScheduleWindowsUpdates();
                        this.ScheduleTimer();
                    }
                    return;
                }
                else if (exitCode == NodeAgentSfUtilityExitCodes.RestartCompleted)
                {
                    this.ScheduleWindowsUpdates();

                    this.CreateNewCheckpointFile();

                    this.ScheduleTimer();
                    return;
                }

                CheckpointFileData fileData = this.ReadCheckpointFile();

                if (fileData.rescheduleNeeded)
                {
                    // If total retries are exhausted, schedule the call back for next interval mentioned in Settings.xml.
                    if (this.IncrementRetryCount() == false)
                    {
                        if (this._windowsUpdateManager.ResetStateMachine())
                        {
                            this.UpdateSettingsAndCreateCheckpoint();
                            this.CreateNewCheckpointFile();
                        }
                        else
                        {
                            if (this._helper.WaitOnTask(Task.Delay(TimeSpan.FromMinutes(WaitTimeInMinutes)),
                                                        this._cancellationToken))
                            {
                                this.ScheduleTimer();
                            }
                            return;
                        }
                    }
                }
                else
                {
                    // Do not update the lastAttemptedTime.
                    this.UpdateSettingsAndCreateCheckpoint(false);
                }

                // read checkpoint file after modifications.
                fileData = this.ReadCheckpointFile();

                // Execute call back
                if (this.ScheduleWindowsUpdatesFlag(fileData))
                {
                    bool retryNeeded = this.ScheduleWindowsUpdates();

                    if (retryNeeded)
                    {
                        fileData.rescheduleNeeded = true;
                        this.WriteCheckpointFile(fileData);
                    }
                    else
                    {
                        this.CreateNewCheckpointFile();
                    }

                    this.ScheduleTimer();
                    return;
                }
            }
            catch (Exception e)
            {
                _eventSource.ErrorMessage("ScheduleTimer ended with exception : {0}", e);
            }
            TimeSpan operationTimeSpan = TimeSpan.FromMinutes(WaitTimeInMinutes);

            if (this._helper.WaitOnTask(Task.Delay(operationTimeSpan), this._cancellationToken))
            {
                this.ScheduleTimer();
            }
        }