private IUpdateClient getUpdateClientWithUpdatesToInstall(IEnumerable <string> kbIds)
        {
            var updateCollection = new UpdateCollectionClass();

            foreach (var kbId in kbIds)
            {
                IUpdate update          = Mock.Of <IUpdate>();
                var     kbIdsCollection = new StringCollectionClass();
                kbIdsCollection.Add(kbId);
                Mock.Get(update).Setup(u => u.KBArticleIDs).Returns(kbIdsCollection);
                updateCollection.Add(update);
            }

            var updateClient = Mock.Of <IUpdateClient>();

            Mock.Get(updateClient).Setup(uc => uc.GetAvailableUpdates()).Returns(updateCollection);

            var updateInstallationLogEntries = new UpdateInstallationLog();

            kbIds.ToList().ForEach(kbid => updateInstallationLogEntries.Add(new UpdateInstallationLogEntry(kbid, InstallationStatus.Success, "", DateTime.UtcNow)));

            var result = new Result
            {
                InstallationResult    = Mock.Of <IInstallationResult>(),
                UpdateInstallationLog = updateInstallationLogEntries
            };

            Mock.Get(updateClient).Setup(uc => uc.InstallUpdates(It.IsAny <UpdateCollection>())).Returns(result);

            return(updateClient);
        }
        public void Given_SavedReportsSuccessfullySaved_Then_DeleteReportsIsCalled()
        {
            var reportStorage = Mock.Of <IReportStorage>();
            var savedReports  = new UpdateInstallationLog
            {
                new UpdateInstallationLogEntry("999", InstallationStatus.Failure, "Some message", DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0)))
            };

            Mock.Get(reportStorage).Setup(rs => rs.LoadReportLog()).Returns(savedReports);

            var reporter = Mock.Of <IStatusReporter>();

            Mock.Get(reporter).Setup(r => r.CommitWithRetry(It.IsAny <IScheduler>())).Returns(true);
            mController = createController(null, null, getUpdateClientWithUpdatesToInstall(new[] { "4269002", "2267602" }), null, null, reporter, reportStorage);

            bool inactivate = false;

            mController.Inactivated += (s, e) => { inactivate = true; };
            mController.BeginUpdate();

            while (!inactivate)
            {
                Thread.Sleep(0);
            }

            Mock.Get(reportStorage).Verify(s => s.DeleteReports(), Times.Once);
        }
示例#3
0
        public void SaveReportTest()
        {
            var log = new UpdateInstallationLog();

            log.Add(new UpdateInstallationLogEntry("123", InstallationStatus.Success, "", DateTime.UtcNow));
            log.Add(new UpdateInstallationLogEntry("321", InstallationStatus.Failure, "it failed.", DateTime.UtcNow));

            var    rs       = new ReportStorage();
            string filePath = rs.SaveReportLog(log);

            Assert.IsTrue(File.Exists(filePath));
        }
示例#4
0
 private void saveReport(UpdateInstallationLog log)
 {
     try
     {
         Logger.Debug("Saving report to disk...");
         string path = ReportStorage.SaveReportLog(log);
         Logger.Debug("Report log was saved to disk: " + path);
     }
     catch (Exception ex)
     {
         Logger.Error("Failed to write report to disk: ", ex);
     }
 }
示例#5
0
        private void reportStatus(Result result)
        {
            Logger.Debug("START Installation report");
            Logger.Debug("Result code: " + result.InstallationResult.ResultCode);
            Logger.Debug("Reboot required: " + result.InstallationResult.RebootRequired);

            Logger.Debug("Update log:");

            var sortedUpdateLog = result.UpdateInstallationLog.OrderBy(log => log.UpdateInstallationStatus);

            reportUpdateInstallationStatus(UpdateInstallationLog.Create(sortedUpdateLog), true);

            Logger.Debug("END Installation report");
        }
示例#6
0
        private void reportUpdateInstallationStatus(UpdateInstallationLog updateLog, bool isCurrent)
        {
            Logger.Debug("Update log:");

            var sortedUpdateLog = UpdateInstallationLog.Create(updateLog.OrderBy(log => log.UpdateInstallationStatus));

            foreach (var updateInstallationLogEntry in sortedUpdateLog)
            {
                log(updateInstallationLogEntry);
                Reporter.ReportStatus(updateInstallationLogEntry);
            }

            bool success = commitWithRetry();

            if (!success)
            {
                Logger.Debug("Writing event log: " + Constants.CEventLogFailedToWriteToDatabase);
                WindowsTaskHandler.WriteEventLog(Constants.CEventLogId, EventLogEntryType.Warning, Constants.CEventLogFailedToWriteToDatabase);
            }

            if (isCurrent)
            {
                if (!success)
                {
                    saveReport(sortedUpdateLog);
                }
            }
            else
            {
                if (success)
                {
                    deleteReport();
                }
            }

            Logger.Debug("Finished reporting installation status.");
        }
示例#7
0
        private void runUpdateProcedure()
        {
            lock (mSyncObject)
            {
                try
                {
                    Logger.Debug("START runUpdateProcedure");

                    mInactivated = false;

                    mStopServiceEvent.Reset();

                    logSystemInfo();

                    readLocalConfiguration();
                    readCentralConfiguration();
                    getExcludedUpdates();

                    if (mCentralConfiguration == null)
                    {
                        Logger.DebugFormat("Going idle - Customer name '{0}' was not found in the CustomerConfigurations section.", LocalConfig.CustomerName);
                        inactivate();
                        return;
                    }

                    if (isServerInExclusionList())
                    {
                        Logger.Debug("Going idle - Server is present in exclusion list.");
                        inactivate();
                        return;
                    }

                    if (!isWithinMaintenanceTimeFrame())
                    {
                        Logger.Debug("Going idle - Not within maintenance timeframe.");
                        inactivate();
                        return;
                    }

                    trySendSavedReports();

                    Logger.Debug("Fetching available updates.");
                    IUpdateCollection updates = WindowsUpdateClient.GetAvailableUpdates();

                    if (updates == null || updates.Count == 0)
                    {
                        Logger.Debug("Going idle - No updates retrieved from WUA.");
                        inactivate();
                        return;
                    }

                    var updatesToInstall = new UpdateCollectionClass();
                    var excludedUpdates  = new UpdateCollectionClass();

                    for (int i = 0; i < updates.Count; i++)
                    {
                        IUpdate update = updates[i];
                        if (!isUpdateExcluded(update))
                        {
                            updatesToInstall.Add(update);
                        }
                        else
                        {
                            excludedUpdates.Add(update);
                        }
                    }

                    if (updatesToInstall.Count == 0)
                    {
                        if (excludedUpdates.Count > 0)
                        {
                            var entries = UpdateInstallationLog.CreateExcludedLogEntries(excludedUpdates);
                            var log     = UpdateInstallationLog.Create(entries);
                            reportUpdateInstallationStatus(log, true);
                        }
                        Logger.Debug("Going idle - No new updates found.");
                        inactivate();
                        return;
                    }

                    Logger.Debug("Writing event log and monitoring API call.");
                    WindowsTaskHandler.WriteEventLog(Constants.CEventLogId, Constants.CEventLogDescription);
                    WindowsTaskHandler.CallMonitoringApi();

                    Logger.Debug("Installing updates.");
                    Result result = WindowsUpdateClient.InstallUpdates(updatesToInstall);

                    // add excluded updates to result
                    var excludedEntries = UpdateInstallationLog.CreateExcludedLogEntries(excludedUpdates);
                    result.UpdateInstallationLog.AddRange(excludedEntries);

                    reportStatus(result);

                    if (result.InstallationResult.RebootRequired)
                    {
                        Logger.Debug("Rebooting system.");
                        WindowsTaskHandler.RebootSystem();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
                finally
                {
                    if (!mInactivated)
                    {
                        inactivate();
                    }

                    Logger.Debug("FINISH runUpdateProcedure");
                    mStopServiceEvent.Set();
                }
            }
        }
示例#8
0
        public Result InstallUpdates(IUpdateCollection updates)
        {
            //TODO: use NetBIOS name (until first .)

            Logger.Debug("START InstallUpdates");

            var updateLog = new UpdateInstallationLog();

            var uSession   = new UpdateSessionClass();
            var downloader = uSession.CreateUpdateDownloader();

            downloader.Updates = (UpdateCollection)updates;

            Logger.Debug("Downloading the following updates:");
            foreach (IUpdate update in updates)
            {
                Logger.DebugFormat("  KB = '{0}', Title = '{1}'", update.KBArticleIDs[0], update.Title);
            }

            downloader.Download();

            var updatesToInstall = new UpdateCollectionClass();

            foreach (IUpdate update in updates)
            {
                if (update.IsDownloaded)
                {
                    bool addUpdate = true;

                    if (!update.EulaAccepted)
                    {
                        update.AcceptEula();
                    }

                    string message = string.Empty;

                    if (update.InstallationBehavior.CanRequestUserInput)
                    {
                        addUpdate = false;
                        message   = Constants.CMessageUpdateCanRequestUserInput;
                        Logger.DebugFormat("KB='{0}', Title='{1}' can request user input and it will not be installed.", update.KBArticleIDs[0], update.Title);
                    }

                    if (addUpdate)
                    {
                        updatesToInstall.Add(update);
                    }
                    else
                    {
                        Logger.DebugFormat("KB='{0}', Title='{1}' was not installed because: {2}", update.KBArticleIDs[0], update.Title, message);
                        updateLog.Add(new UpdateInstallationLogEntry(update.KBArticleIDs[0], InstallationStatus.NotAttempted, message, DateTime.UtcNow));
                    }
                }
                else
                {
                    Logger.DebugFormat("KB='{0}', Title='{1}' was in the list of available updates but it was not downloaded.", update.KBArticleIDs[0], update.Title);
                    updateLog.Add(new UpdateInstallationLogEntry(update.KBArticleIDs[0], InstallationStatus.NotAttempted, Constants.CMessageUpdateNotDownloaded, DateTime.UtcNow));
                }
            }

            Logger.Debug("Installing the following updates:");
            foreach (IUpdate update in updatesToInstall)
            {
                var sb = new StringBuilder();
                foreach (var id in update.KBArticleIDs)
                {
                    sb.Append(id + ", ");
                }
                string kbArticleIds = sb.ToString();
                kbArticleIds = kbArticleIds.Remove(kbArticleIds.Length - 2);

                Logger.DebugFormat("  KB = '{0}', Title = '{1}', KB_Articles = '{2}'", update.KBArticleIDs[0], update.Title, kbArticleIds);
            }

            IInstallationResult installationResult;

            if (updatesToInstall.Count == 0)
            {
                Logger.Debug("No updates to install.");
                installationResult = new EmptyInstallationResult();
            }
            else
            {
                IUpdateInstaller installer = uSession.CreateUpdateInstaller();
                installer.Updates = updatesToInstall;

                installationResult = installer.Install();

                for (int i = 0; i < updatesToInstall.Count; i++)
                {
                    var result = installationResult.GetUpdateResult(i);
                    if (result.ResultCode == OperationResultCode.orcSucceeded)
                    {
                        updateLog.Add(new UpdateInstallationLogEntry(updatesToInstall[i].KBArticleIDs[0], InstallationStatus.Success, "", DateTime.UtcNow));
                    }
                    else
                    {
                        updateLog.Add(new UpdateInstallationLogEntry(updatesToInstall[i].KBArticleIDs[0], InstallationStatus.Failure
                                                                     , "Operation result: " + result.ResultCode
                                                                     , DateTime.UtcNow));
                    }
                }
            }

            Logger.Debug("END InstallUpdates");

            var processResult = new Result
            {
                InstallationResult    = installationResult,
                UpdateInstallationLog = updateLog
            };

            return(processResult);
        }