Exemple #1
0
 private void add_key(IList <RegistryKey> keys, RegistryHive hive, RegistryView view)
 {
     FaultTolerance.try_catch_with_logging_exception(
         () => keys.Add(RegistryKey.OpenBaseKey(hive, view)),
         "Could not open registry hive '{0}' for view '{1}'".format_with(hive.to_string(), view.to_string()),
         logWarningInsteadOfError: true);
 }
        private void uninstall_cleanup(ChocolateyConfiguration config, PackageResult packageResult)
        {
            _packageInfoService.remove_package_information(packageResult.Package);
            ensure_bad_package_path_is_clean(config, packageResult);
            remove_rollback_if_exists(packageResult);
            handle_extension_packages(config, packageResult);

            if (config.Force)
            {
                var packageDirectory = _fileSystem.combine_paths(packageResult.InstallLocation);

                if (string.IsNullOrWhiteSpace(packageDirectory) || !_fileSystem.directory_exists(packageDirectory))
                {
                    return;
                }

                if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation))
                {
                    packageResult.Messages.Add(
                        new ResultMessage(
                            ResultType.Error,
                            "Install location is not specific enough, cannot force remove directory:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation)
                            )
                        );
                    return;
                }

                FaultTolerance.try_catch_with_logging_exception(
                    () => _fileSystem.delete_directory_if_exists(packageDirectory, recursive: true),
                    "Attempted to remove '{0}' but had an error".format_with(packageDirectory),
                    logWarningInsteadOfError: true);
            }
        }
Exemple #3
0
        private static void set_file_configuration(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem, Action <string> notifyWarnLoggingAction)
        {
            var sources = new StringBuilder();

            var defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled).or_empty_list_if_null().ToList();

            if (configFileSettings.Sources.Any(s => s.Priority > 0))
            {
                defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled && s.Priority != 0).OrderBy(s => s.Priority).or_empty_list_if_null().ToList();
                defaultSourcesInOrder.AddRange(configFileSettings.Sources.Where(s => !s.Disabled && s.Priority == 0).or_empty_list_if_null().ToList());
            }

            foreach (var source in defaultSourcesInOrder)
            {
                sources.AppendFormat("{0};", source.Value);
            }
            if (sources.Length != 0)
            {
                config.Sources = sources.Remove(sources.Length - 1, 1).ToString();
            }

            set_machine_sources(config, configFileSettings);

            set_config_items(config, configFileSettings, fileSystem);

            FaultTolerance.try_catch_with_logging_exception(
                () => fileSystem.create_directory_if_not_exists(config.CacheLocation),
                "Could not create temp directory at '{0}'".format_with(config.CacheLocation),
                logWarningInsteadOfError: true);

            set_feature_flags(config, configFileSettings);
        }
Exemple #4
0
        public void serialize <XmlType>(XmlType xmlType, string xmlFilePath)
        {
            _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(xmlFilePath));

            var xmlUpdateFilePath = xmlFilePath + ".update";

            FaultTolerance.try_catch_with_logging_exception(
                () =>
            {
                var xmlSerializer = new XmlSerializer(typeof(XmlType));
                var textWriter    = new StreamWriter(xmlUpdateFilePath, append: false, encoding: Encoding.UTF8)
                {
                    AutoFlush = true
                };

                xmlSerializer.Serialize(textWriter, xmlType);
                textWriter.Flush();

                textWriter.Close();
                textWriter.Dispose();

                if (!_hashProvider.hash_file(xmlFilePath).is_equal_to(_hashProvider.hash_file(xmlUpdateFilePath)))
                {
                    _fileSystem.copy_file(xmlUpdateFilePath, xmlFilePath, overwriteExisting: true);
                }

                _fileSystem.delete_file(xmlUpdateFilePath);
            },
                "Error serializing type {0}".format_with(typeof(XmlType)),
                throwError: true);
        }
        public void TryFallback_NonPositiveCount_ThrowsArgumentException()
        {
            Action action   = () => { };
            Action fallback = () => { };

            Assert.Throws <ArgumentException>(() => FaultTolerance.TryFallback <Exception>(action, -1, fallback));
        }
        public void TryFallbackMultipleExceptions_Failed_RunRelevantFallback()
        {
            int    count  = 0;
            Action action = () =>
            {
                count++;
                if (count == 1)
                {
                    throw new NotImplementedException();
                }
                else if (count == 2)
                {
                    throw new ArithmeticException();
                }
            };

            bool notImplementedExceptionFallbackHadRun = false;
            bool arithmeticExceptionFallbackHadRun     = false;

            var exceptions = new Dictionary <Type, Action>();

            exceptions.Add(typeof(NotImplementedException), () => notImplementedExceptionFallbackHadRun = true);
            exceptions.Add(typeof(ArithmeticException), () => arithmeticExceptionFallbackHadRun         = true);

            FaultTolerance.TryFallback(exceptions, action, 2);

            Assert.False(notImplementedExceptionFallbackHadRun);
            Assert.True(arithmeticExceptionFallbackHadRun);
        }
        public void TryMultipleExceptions_Failed_ThrowsException()
        {
            int    count  = 0;
            Action action = () =>
            {
                count++;
                if (count == 1)
                {
                    throw new NotImplementedException();
                }
                else if (count == 2)
                {
                    throw new ArithmeticException();
                }
                else
                {
                    throw new ArgumentException();
                }
            };

            var exceptions = new List <Type> {
                typeof(NotImplementedException), typeof(ArithmeticException), typeof(ArgumentException)
            };

            Assert.Throws <ArgumentException>(() => FaultTolerance.Try(exceptions, action, 3));
        }
 private RegistryKey open_key(RegistryHive hive, RegistryView view)
 {
     return(FaultTolerance.try_catch_with_logging_exception(
                () => RegistryKey.OpenBaseKey(hive, view),
                "Could not open registry hive '{0}' for view '{1}'".format_with(hive.to_string(), view.to_string()),
                logWarningInsteadOfError: true));
 }
        private void handle_message(PreRunMessage message)
        {
            this.Log().Debug(ChocolateyLoggers.Verbose, "[Pending] Removing all pending packages that should not be considered installed...");

            var pendingFiles = _fileSystem.get_files(ApplicationParameters.PackagesLocation, ApplicationParameters.PackagePendingFileName, SearchOption.AllDirectories).ToList();

            foreach (var pendingFile in pendingFiles.or_empty_list_if_null())
            {
                var packageFolder     = _fileSystem.get_directory_name(pendingFile);
                var packageFolderName = _fileSystem.get_directory_info_for(packageFolder).Name;

                var pendingSkipFiles = _fileSystem.get_files(packageFolder, PENDING_SKIP_FILE, SearchOption.AllDirectories).ToList();
                if (pendingSkipFiles.Count != 0)
                {
                    this.Log().Warn("Pending file found for {0}, but a {1} file was also found. Skipping removal".format_with(packageFolderName, PENDING_SKIP_FILE));
                    continue;
                }

                // wait for the file to be at least x seconds old
                // this allows commands running from the package for configuring sources, etc
                var fileInfo = _fileSystem.get_file_info_for(pendingFile);
                if (fileInfo.CreationTimeUtc.AddSeconds(PENDING_FILE_AGE_SECONDS) > _dateTimeService.get_current_date_time())
                {
                    this.Log().Debug("Pending file found for {0}, but the file is not {1} seconds old yet.".format_with(packageFolderName, PENDING_FILE_AGE_SECONDS));
                    continue;
                }

                this.Log().Warn("[Pending] Removing incomplete install for '{0}'".format_with(packageFolderName));
                FaultTolerance.retry(2, () => _fileSystem.delete_directory_if_exists(packageFolder, recursive: true, overrideAttributes: true, isSilent: true), 500, isSilent: true);
            }
        }
Exemple #10
0
 private void allow_retries(Action action)
 {
     FaultTolerance.retry(
         TIMES_TO_TRY_OPERATION,
         action,
         waitDurationMilliseconds: 200,
         increaseRetryByMilliseconds: 100);
 }
Exemple #11
0
        public void Try_indexOutOfRangeEx_true()
        {
            Action action = () => throw new IndexOutOfRangeException();

            FaultTolerance faultTolerance = new FaultTolerance();

            Assert.ThrowsException <IndexOutOfRangeException>(() => faultTolerance.Try(action, 2));
        }
Exemple #12
0
        private static void set_file_configuration(ChocolateyConfiguration config, IFileSystem fileSystem, IXmlService xmlService, Action <string> notifyWarnLoggingAction)
        {
            var globalConfigPath = ApplicationParameters.GlobalConfigFileLocation;

            AssemblyFileExtractor.extract_text_file_from_assembly(fileSystem, Assembly.GetExecutingAssembly(), ApplicationParameters.ChocolateyConfigFileResource, globalConfigPath);

            var configFileSettings = xmlService.deserialize <ConfigFileSettings>(globalConfigPath);
            var sources            = new StringBuilder();

            foreach (var source in configFileSettings.Sources.or_empty_list_if_null())
            {
                sources.AppendFormat("{0};", source.Value);
            }
            if (sources.Length != 0)
            {
                config.Sources = sources.Remove(sources.Length - 1, 1).ToString();
            }

            config.CacheLocation = !string.IsNullOrWhiteSpace(configFileSettings.CacheLocation) ? configFileSettings.CacheLocation : System.Environment.GetEnvironmentVariable("TEMP");
            if (string.IsNullOrWhiteSpace(config.CacheLocation))
            {
                config.CacheLocation = fileSystem.combine_paths(ApplicationParameters.InstallLocation, "temp");
            }

            FaultTolerance.try_catch_with_logging_exception(
                () => fileSystem.create_directory_if_not_exists(config.CacheLocation),
                "Could not create temp directory at '{0}'".format_with(config.CacheLocation),
                logWarningInsteadOfError: true);

            config.ContainsLegacyPackageInstalls = configFileSettings.ContainsLegacyPackageInstalls;
            if (configFileSettings.CommandExecutionTimeoutSeconds <= 0)
            {
                configFileSettings.CommandExecutionTimeoutSeconds = ApplicationParameters.DefaultWaitForExitInSeconds;
            }
            config.CommandExecutionTimeoutSeconds = configFileSettings.CommandExecutionTimeoutSeconds;

            set_feature_flags(config, configFileSettings);
            if (!config.PromptForConfirmation)
            {
                if (notifyWarnLoggingAction != null)
                {
                    const string logMessage = @"
Config has insecure allowGlobalConfirmation set to true.
 This setting lowers the integrity of the security of your system. If
 this is not intended, please change the setting using the feature
 command.
";
                    notifyWarnLoggingAction.Invoke(logMessage);
                }
            }


            // save so all updated configuration items get set to existing config
            FaultTolerance.try_catch_with_logging_exception(
                () => xmlService.serialize(configFileSettings, globalConfigPath),
                "Error updating '{0}'. Please ensure you have permissions to do so".format_with(globalConfigPath),
                logWarningInsteadOfError: true);
        }
Exemple #13
0
        public void set_key_values(RegistryApplicationKey appKey, params string[] properties)
        {
            // Hive is in double with appKey.KeyPath.Split('\\')[0]
            // https://stackoverflow.com/questions/58510869/c-sharp-get-basekey-from-registrykey
            // maybe makes sense to centralize later on.

            var    key     = open_key(appKey.Hive, appKey.RegistryView);
            string subPath = String.Join("\\", appKey.KeyPath.Split('\\').Skip(1));
            var    subKey  = FaultTolerance.try_catch_with_logging_exception(
                () => key.OpenSubKey(subPath, true),
                $"Could not open subkey {appKey.KeyPath}",
                logWarningInsteadOfError: true);

            if (subKey == null)
            {
                subKey = FaultTolerance.try_catch_with_logging_exception(
                    () => key.CreateSubKey(subPath, true),
                    $"Could not open subkey {appKey.KeyPath}",
                    logWarningInsteadOfError: true);
            }

            if (subKey != null)
            {
                foreach (string prop in properties)
                {
                    var               propInfo = appKey.GetType().GetProperty(prop);
                    object            value;
                    RegistryValueKind type = RegistryValueKind.DWord;

                    if (propInfo.PropertyType == typeof(long))
                    {
                        value = (long)propInfo.GetValue(appKey);
                        type  = RegistryValueKind.DWord;
                    }
                    else if (propInfo.PropertyType == typeof(bool))
                    {
                        bool bvalue = (bool)propInfo.GetValue(appKey);

                        if (!bvalue && propInfo.Name == nameof(RegistryApplicationKey.IsPinned))
                        {
                            subKey.DeleteValue(propInfo.Name, false);
                            continue;
                        }

                        value = (bvalue) ? 1: 0;
                        type  = RegistryValueKind.DWord;
                    }
                    else
                    {
                        value = propInfo.GetValue(appKey).ToString();
                        type  = RegistryValueKind.String;
                    }

                    subKey.SetValue(propInfo.Name, value, type);
                }
            }
        }
Exemple #14
0
            public void should_throw_an_error_if_retries_are_reached()
            {
                reset();

                Assert.Throws <Exception>(
                    () => FaultTolerance.retry(2, () => { throw new Exception("YIKES"); }, waitDurationMilliseconds: 0),
                    "YIKES"
                    );
            }
Exemple #15
0
 private void allow_retries(Action action, bool isSilent = false)
 {
     FaultTolerance.retry(
         TimesToRetryOperation,
         action,
         waitDurationMilliseconds: OperationRetryTimeMilliseconds,
         increaseRetryByMilliseconds: IncreaseRetryMilliseconds,
         isSilent: isSilent);
 }
            public void should_throw_an_error_if_throwError_set_to_true()
            {
                reset();

                FaultTolerance.try_catch_with_logging_exception(
                    () => { throw new Exception("This is the message"); },
                    "You have an error",
                    throwError: true
                    );
            }
        public void Try_NotAllTypesDerivedFromException_ThrowsArgumentException()
        {
            Action action = () => { };

            var exceptions = new List <Type> {
                typeof(int), typeof(Exception)
            };

            Assert.Throws <ArgumentException>(() => FaultTolerance.Try(exceptions, action, -1));
        }
Exemple #18
0
        private static void set_config_file_settings(ConfigFileSettings configFileSettings, IXmlService xmlService)
        {
            var globalConfigPath = ApplicationParameters.GlobalConfigFileLocation;

            // save so all updated configuration items get set to existing config
            FaultTolerance.try_catch_with_logging_exception(
                () => xmlService.serialize(configFileSettings, globalConfigPath),
                "Error updating '{0}'. Please ensure you have permissions to do so".format_with(globalConfigPath),
                logWarningInsteadOfError: true);
        }
            public void should_not_allow_the_number_of_retries_to_be_zero()
            {
                reset();

                FaultTolerance.retry(
                    0,
                    () =>
                {
                });
            }
            public void should_still_throw_an_error_when_warn_is_set_if_throwError_set_to_true()
            {
                reset();

                FaultTolerance.try_catch_with_logging_exception(
                    () => { throw new Exception("This is the message"); },
                    "You have an error",
                    logWarningInsteadOfError: true,
                    throwError: true
                    );
            }
            public void should_log_the_expected_error_message()
            {
                reset();

                FaultTolerance.try_catch_with_logging_exception(
                    () => { throw new Exception("This is the message"); },
                    "You have an error"
                    );

                MockLogger.MessagesFor(LogLevel.Error)[0].ShouldEqual("You have an error:{0} This is the message".format_with(Environment.NewLine));
            }
            public void should_log_an_error_message()
            {
                reset();

                FaultTolerance.try_catch_with_logging_exception(
                    () => { throw new Exception("This is the message"); },
                    "You have an error"
                    );

                MockLogger.MessagesFor(LogLevel.Error).Count.ShouldEqual(1);
            }
        public void TryFallback_Failed_RunFallback()
        {
            bool fallbackHadRun = false;

            Action action   = () => throw new NotImplementedException();
            Action fallback = () => fallbackHadRun = true;

            FaultTolerance.TryFallback <NotImplementedException>(action, 2, fallback);

            Assert.True(fallbackHadRun);
        }
Exemple #24
0
        public void delete_key(RegistryApplicationKey appKey)
        {
            var    key     = open_key(appKey.Hive, appKey.RegistryView);
            string subPath = String.Join("\\", appKey.KeyPath.Split('\\').Skip(1));

            FaultTolerance.try_catch_with_logging_exception(
                () => key.DeleteSubKey(subPath, false),
                $"Could not delete subkey {appKey.KeyPath}",
                logWarningInsteadOfError: true
                );
        }
        private void move_bad_package_to_failure_location(PackageResult packageResult)
        {
            _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackageFailuresLocation);

            if (packageResult.InstallLocation != null && _fileSystem.directory_exists(packageResult.InstallLocation))
            {
                FaultTolerance.try_catch_with_logging_exception(
                    () => _fileSystem.move_directory(packageResult.InstallLocation, packageResult.InstallLocation.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageFailuresLocation)),
                    "Could not move bad package to failure directory It will show as installed.{0} {1}{0} The error".format_with(Environment.NewLine, packageResult.InstallLocation));
            }
        }
        private static void set_config_file_settings(ConfigFileSettings configFileSettings, IXmlService xmlService, ChocolateyConfiguration config)
        {
            var shouldLogSilently = (!config.Information.IsProcessElevated || !config.Information.IsUserAdministrator);

            var globalConfigPath = ApplicationParameters.GlobalConfigFileLocation;

            // save so all updated configuration items get set to existing config
            FaultTolerance.try_catch_with_logging_exception(
                () => xmlService.serialize(configFileSettings, globalConfigPath, isSilent: shouldLogSilently),
                "Error updating '{0}'. Please ensure you have permissions to do so".format_with(globalConfigPath),
                logDebugInsteadOfError: true);
        }
        public void TryFallback_NotAllTypesDerivedFromException_ThrowsArgumentException()
        {
            Action action   = () => { };
            Action fallback = () => { };

            var exceptionFallbacks = new Dictionary <Type, Action>();

            exceptionFallbacks.Add(typeof(int), fallback);
            exceptionFallbacks.Add(typeof(string), fallback);

            Assert.Throws <ArgumentException>(() => FaultTolerance.TryFallback(exceptionFallbacks, action, -1));
        }
            public void should_return_immediately_when_successful()
            {
                reset();

                var i = 0;

                FaultTolerance.retry(3, () => { i += 1; }, waitDurationMilliseconds: 0);

                i.ShouldEqual(1);

                MockLogger.MessagesFor(LogLevel.Warn).Count.ShouldEqual(0);
            }
Exemple #29
0
        public void Try_Fallback_true()
        {
            int IsFallback = 0;

            Action         action         = () => throw new ContextMarshalException();
            Action         fallback       = () => IsFallback = 1;
            FaultTolerance faultTolerance = new FaultTolerance();

            faultTolerance.Fallback(action, fallback);

            Assert.AreEqual(1, IsFallback);
        }
            public void should_log_a_warning_message_when_set_to_warn()
            {
                reset();

                FaultTolerance.try_catch_with_logging_exception(
                    () => { throw new Exception("This is the message"); },
                    "You have an error",
                    logWarningInsteadOfError: true
                    );

                MockLogger.MessagesFor(LogLevel.Warn).Count.ShouldEqual(1);
            }