示例#1
0
        private void SendAlertSignalEmail(InternalSignal signal, NamedValueSet props)
        {
            try
            {
                var smtpHost = props.GetValue <string>(AlertRule.MailHost);
                IEnumerable <string> recipients = ResolveMultipleEmailAddresses(props.GetArray <string>(AlertRule.MailTo));
                string sender      = ResolveSingleEmailAddress(props.GetValue <string>(AlertRule.MailFrom));
                var    email       = new MailMessage();
                string instanceMsg = GetInstanceMsg(signal.ReminderCount);
                signal.ReminderCount += 1;
                email.Subject         =
                    $"QDS Alert {EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv)}. {signal.RuleName}: {signal.Status}";

                if (signal.Status == AlertStatus.Alerted)
                {
                    email.Subject += $"({instanceMsg})";
                }
                var body = new StringBuilder(signal.SignalMessage);
                if (props.GetValue <bool>("rule.DebugEnabled", false))
                {
                    body.AppendLine();
                    body.AppendLine();
                    body.AppendLine("[debug-begin]");
                    props.LogValues(text => body.AppendLine("  " + text));
                    body.AppendLine("[debug-end]");
                }
                email.Body = body.ToString();
                SendEmail(smtpHost, email, sender, recipients);
            }
            catch (Exception excp)
            {
                ReportUncaughtError("EmailAlertSignal", signal.RuleName, excp, props);
            }
        }
示例#2
0
        private void ReportUncaughtError(string method, string ruleName, Exception ex, NamedValueSet debugProps)
        {
            // first log to EventLog
            string message = string.IsNullOrEmpty(ruleName)
                ? $"Exception in '{method}': \n\n{ex}"
                : $"Exception in '{method}', Rule '{ruleName}': \n\n{ex}'";

            Logger.LogError(message);
            // then email
            try
            {
                string smtpHost = _defaultSmtpServer;
                IEnumerable <string> recipients = ResolveMultipleEmailAddresses(_defaultMailTo);
                string sender = ResolveSingleEmailAddress(_defaultMailFrom);
                var    email  = new MailMessage
                {
                    Subject =
                        $"QDS Alert {EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv)}. UNHANDLED ERROR"
                };
                //new
                var body = new StringBuilder(message);
                if (debugProps != null)
                {
                    body.AppendLine();
                    body.AppendLine();
                    body.AppendLine("[debug-begin]");
                    debugProps.LogValues(text => body.AppendLine("  " + text));
                    body.AppendLine("[debug-end]");
                }
                email.Body = body.ToString();
                //end new
                SendEmail(smtpHost, email, sender, recipients);
            }
            catch (Exception excp)
            {
                Logger.LogError(excp);
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            using (ConsoleLogger logger = new ConsoleLogger("SetAppCfg: "))
            {
                logger.LogInfo("Running...");
                int exitCode = 0;
                try
                {
                    // set defaults
                    string coreAddr = null;
                    string applName = null;
                    string userName = null;
                    string hostName = null;
                    bool   replace  = false;
                    //bool debugOn = false;
                    // process arguments
                    NamedValueSet appCfg = new NamedValueSet();
                    foreach (var arg in args)
                    {
                        bool argProcessed = true;
                        // switches - begin with /
                        if (arg.StartsWith("/"))
                        {
                            // arg is a switch
                            string[] argParts = arg.Split(':');
                            string   argName  = argParts[0].Substring(1);
                            string   argValue = "";
                            for (int j = 1; j < argParts.Length; j++)
                            {
                                if (j > 1)
                                {
                                    argValue += ':';
                                }
                                argValue += argParts[j];
                            }
                            switch (argName.ToLower())
                            {
                            case "a":
                                applName = argValue;
                                logger.LogInfo("  ApplName: {0}", applName);
                                break;

                            case "u":
                                userName = argValue;
                                logger.LogInfo("  UserName: {0}", userName);
                                break;

                            case "h":
                                hostName = argValue;
                                logger.LogInfo("  HostName: {0}", hostName);
                                break;

                            case "p":     // simple string property
                                string[] propParts = argValue.Split('=');
                                appCfg.Set(new NamedValue(propParts[0], propParts[1]));
                                logger.LogInfo("  Property: {0}={1}", propParts[0], propParts[1]);
                                break;

                            case "nv":     // typed serialised named value
                                appCfg.Set(new NamedValue(argValue));
                                logger.LogInfo("  Property: {0}", argValue);
                                break;

                            case "replace":
                                replace = true;
                                logger.LogInfo("  Replace Old");
                                break;

                            case "debug":
                                //debugOn = true;
                                logger.LogInfo("  Debug On");
                                break;

                            case "s":
                                coreAddr = argValue;
                                logger.LogInfo("  Server  : {0}", coreAddr);
                                break;

                            default:
                                argProcessed = false;
                                break;
                            }
                        }
                        if (!argProcessed)
                        {
                            logger.LogInfo(" Sets configuration values for applications, users and machines");
                            logger.LogInfo(" usage:");
                            logger.LogInfo("   SetAppCfg [options]");
                            logger.LogInfo("      /a:applname           the application name (default: all applications)");
                            logger.LogInfo("      /u:username           the user name (default: all users)");
                            logger.LogInfo("      /h:hostname           the host (machine) name (default: all machines)");
                            logger.LogInfo("      /p:name=value         sets a string property value");
                            logger.LogInfo("      /nv:name/type=value   sets a typed property value with a serialised named value");
                            logger.LogInfo("      /s:address            the address of the core server to connect to eg. localhost:8114");
                            logger.LogInfo("      /replace              old values for the same application/user/host are deleted");
                            logger.LogInfo("      /debug                logs the internal query and results to the debug port");
                            logger.LogInfo(" returns:");
                            logger.LogInfo("  0: success - settings updated");
                            logger.LogInfo("  2: error - see error output for details");
                            throw new ArgumentException("Unknown argument '" + arg + "'");
                        }
                    }
                    // save the app config
                    var refLogger = Reference <ILogger> .Create(logger);

                    using (ICoreClient client = new CoreClientFactory(refLogger).SetServers(coreAddr).Create())
                    {
                        logger.LogInfo("Old/new settings comparison for:");
                        logger.LogInfo("  Application: {0}", applName ?? "(all)");
                        logger.LogInfo("  User name  : {0}", userName ?? "(all)");
                        logger.LogInfo("  Host name  : {0}", hostName ?? "(all)");
                        // get old settings
                        NamedValueSet oldAppCfg = client.LoadAppSettings(applName, userName, hostName);
                        logger.LogInfo("Old settings:");
                        oldAppCfg.LogValues(delegate(string text) { logger.LogInfo("  " + text); });
                        // set new settings
                        client.SaveAppSettings(appCfg, applName, userName, hostName, replace);
                        // get new settings
                        NamedValueSet newAppCfg = client.LoadAppSettings(applName, userName, hostName);
                        logger.LogInfo("New settings:");
                        newAppCfg.LogValues(delegate(string text) { logger.LogInfo("  " + text); });
                    }
                    logger.LogInfo("Success");
                    Environment.ExitCode = exitCode;
                }
                catch (Exception e)
                {
                    logger.Log(e);
                    for (int i = 0; i < args.Length; i++)
                    {
                        logger.LogDebug("  args[{0}]='{1}'", i, args[i]);
                    }
                    logger.LogInfo("FAILED");
                    Environment.ExitCode = 2;
                }
            }
        }
示例#4
0
        private void ProcessRule(ICoreClient client, InternalRule rule, DateTimeOffset currentTime)
        {
            RuleStatusEnum ruleStatus;
            ILogger        logger = new FilterLogger(
                Logger, $"Rule {rule.RuleName}: ",
                rule.DebugEnabled ? LogSeverity.Debug : LogSeverity.Info);

            using (var settings = new SettingsTracker(client, "FileImporter." + rule.RuleName))
            {
                bool           lastCheckFailed    = false;
                string         lastCheckException = "(null)";
                DateTimeOffset lastCheckDateTime  = currentTime;
                //logger.LogDebug("Processing...");
                try
                {
                    ruleStatus = RuleStatusEnum.Disabled;
                    if (!rule.Disabled)
                    {
                        // evaluate rule constraint and condition
                        var properties = new NamedValueSet(settings.GetAllValues(true));
                        properties.Add(rule.Properties);
                        // last import date/time (default to 4 days ago)
                        var lastImportDateTime = settings.GetSetValue(RuleConst.LastImportDateTime, DateTimeOffset.Now.AddDays(-4));
                        properties.Set(RuleConst.LastImportDateTime, lastImportDateTime);
                        // calculate effective "as at" date
                        var thisImportDateTime = Expr.CastTo(rule.EffectiveDateExpr.Evaluate(properties, currentTime), currentTime);
                        properties.Set(RuleConst.EffectiveDateTime, thisImportDateTime);
                        // add useful date/time tokens
                        //foreach (string token in new string[] { "dd", "ddd", "MM", "MMM", "yyyy" })
                        //{
                        //    properties.Set(token, thisImportDateTime.ToString(token));
                        //}
                        // calculate import delay
                        var thisImportDelay = Expr.CastTo(rule.ImportDelayExpr.Evaluate(properties, currentTime), TimeSpan.Zero);
                        properties.Set(RuleConst.ImportDelay, thisImportDelay);
                        // evaluate rule check constraint and import condition
                        logger.LogDebug("Evaluation Params :");
                        properties.LogValues(text => logger.LogDebug("    " + text));
                        logger.LogDebug("Check Constraint  : {0}", rule.CheckConstraint);
                        ruleStatus = RuleStatusEnum.Inactive;
                        if (Expr.CastTo(rule.CheckConstraint.Evaluate(properties, currentTime), false))
                        {
                            logger.LogDebug("Import Condition  : {0}", rule.ImportCondition);
                            ruleStatus = RuleStatusEnum.NotReady;
                            if (Expr.CastTo(rule.ImportCondition.Evaluate(properties, currentTime), false))
                            {
                                ruleStatus = RuleStatusEnum.Failed;
                                // import condition is true
                                // process date/time tokens
                                string targetLocation = StringHelper.ReplaceDateTimeTokens(rule.TargetLocation, thisImportDateTime);
                                string sourceLocation = StringHelper.ReplaceDateTimeTokens(rule.SourceLocation, thisImportDateTime);
                                var    importedFiles  = new List <string>();
                                logger.LogInfo("Source Location  : {0}", sourceLocation);
                                logger.LogInfo("Target Location  : {0}", targetLocation);
                                logger.LogInfo("Filenames to copy: {0}", rule.CopyFilePatterns);
                                string thisImportException = "(null)";
                                try
                                {
                                    // import the file
                                    // - optionally clean up old files aged more than 7 days
                                    if (rule.RemoveOldTargetFiles)
                                    {
                                        try
                                        {
                                            string[] oldTargetFiles = Directory.GetFiles(targetLocation, "*.*", SearchOption.TopDirectoryOnly);
                                            foreach (string oldTargetFile in oldTargetFiles)
                                            {
                                                var targetFileInfo = new FileInfo(oldTargetFile);
                                                if ((currentTime - targetFileInfo.LastWriteTime) > TimeSpan.FromDays(2))
                                                {
                                                    File.Delete(oldTargetFile);
                                                }
                                            }
                                        }
                                        catch (IOException removeExcp)
                                        {
                                            logger.LogWarning("Error removing old files: {0}", removeExcp.GetType().Name);
                                            // ignored
                                        }
                                    }
                                    // - create target directory if required
                                    if (!Directory.Exists(targetLocation))
                                    {
                                        Directory.CreateDirectory(targetLocation);
                                    }
                                    // - copy file(s) from source to target
                                    foreach (string ruleFilePattern in rule.CopyFilePatterns.Split(';'))
                                    {
                                        string   filePattern = StringHelper.ReplaceDateTimeTokens(ruleFilePattern, thisImportDateTime);
                                        string[] sourceFiles = Directory.GetFiles(sourceLocation, filePattern, SearchOption.TopDirectoryOnly);
                                        logger.LogInfo("Copying file(s): {0} ({1} found)", filePattern, sourceFiles.Length);
                                        int copiedCount  = 0;
                                        int skippedCount = 0;
                                        foreach (string sourceFileFullname in sourceFiles)
                                        {
                                            string sourceFileBaseName = Path.GetFileName(sourceFileFullname);
                                            string targetFileFullname = $@"{targetLocation}\{sourceFileBaseName}";
                                            bool   copyRequired       = true;
                                            if (File.Exists(targetFileFullname) && rule.OnlyCopyUpdatedFiles)
                                            {
                                                var sourceFileInfo = new FileInfo(sourceFileFullname);
                                                var targetFileInfo = new FileInfo(targetFileFullname);
                                                copyRequired = (sourceFileInfo.LastWriteTime > targetFileInfo.LastWriteTime);
                                            }
                                            if (copyRequired)
                                            {
                                                logger.LogInfo("Copying file : {0}", sourceFileBaseName);
                                                logger.LogInfo("  From source: {0}", sourceLocation);
                                                logger.LogInfo("    To target: {0}", targetLocation);
                                                DateTime copyCommenced = DateTime.Now;
                                                File.Copy(sourceFileFullname, targetFileFullname, true);
                                                TimeSpan copyDuration = DateTime.Now - copyCommenced;
                                                importedFiles.Add(sourceFileBaseName);
                                                var targetFileInfo = new FileInfo(targetFileFullname);
                                                copiedCount++;
                                                logger.LogInfo("  Copied {0}MB in {1}s ({2}KB/sec)",
                                                               (targetFileInfo.Length / 1000000.0).ToString("N"),
                                                               copyDuration.TotalSeconds.ToString("N"),
                                                               (targetFileInfo.Length / (1000.0 * copyDuration.TotalSeconds)).ToString("N"));
                                                // publish rule import status
                                                var importFileResult = new ImportFileResult
                                                {
                                                    hostEnvName     = EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
                                                    hostComputer    = IntClient.Target.ClientInfo.HostName,
                                                    hostInstance    = null,
                                                    hostUserName    = client.ClientInfo.UserName,
                                                    RuleName        = rule.RuleName,
                                                    FileName        = sourceFileBaseName,
                                                    DebugEnabled    = rule.DebugEnabled,
                                                    DebugProperties = rule.DebugProperties.Serialise(),
                                                    FileContentType = rule.FileContentType,
                                                    ImportResult    = RuleStatusEnum.Completed.ToString(),
                                                    ImportException = null,
                                                    ImportDateTime  = currentTime.ToString("o"),
                                                    SourceSystem    = rule.SourceSystem,
                                                    SourceLocation  = sourceLocation,
                                                    TargetLocation  = targetLocation
                                                };
                                                IntClient.Target.SaveObject(importFileResult, true, TimeSpan.FromDays(30));
                                            }
                                            else
                                            {
                                                skippedCount++;
                                                logger.LogDebug("Skipping file : {0}", sourceFileBaseName);
                                            }
                                        } // foreach file
                                        logger.LogInfo("Copied {0} file(s), skipped {1} file(s).", copiedCount, skippedCount);
                                    }
                                    // - optionally decompress target
                                    // todo
                                    // done
                                    ruleStatus         = RuleStatusEnum.Completed;
                                    lastImportDateTime = Expr.CastTo(rule.DateUpdateExpr.Evaluate(properties, currentTime), currentTime);
                                }
                                catch (Exception e2)
                                {
                                    logger.Log(e2);
                                    thisImportException = e2.ToString();
                                    ruleStatus          = RuleStatusEnum.Failed;
                                }
                                finally
                                {
                                    settings.SetNewValue(RuleConst.LastImportResult, ruleStatus.ToString());
                                    settings.SetNewValue(RuleConst.LastImportException, thisImportException);
                                    settings.SetNewValue(RuleConst.LastImportDateTime, lastImportDateTime);
                                }
                                // publish rule import status
                                var importRuleResult = new ImportRuleResult
                                {
                                    hostEnvName     = EnvHelper.EnvName(IntClient.Target.ClientInfo.ConfigEnv),
                                    hostComputer    = IntClient.Target.ClientInfo.HostName,
                                    hostInstance    = null,
                                    hostUserName    = client.ClientInfo.UserName,
                                    RuleName        = rule.RuleName,
                                    ImportResult    = ruleStatus.ToString(),
                                    ImportException = thisImportException,
                                    ImportDateTime  = currentTime.ToString("o"),
                                    SourceSystem    = rule.SourceSystem,
                                    SourceLocation  = sourceLocation,
                                    TargetLocation  = targetLocation,
                                    FileNames       = importedFiles.ToArray()
                                };
                                IntClient.Target.SaveObject(importRuleResult, true, TimeSpan.FromDays(30));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Log(e);
                    lastCheckFailed    = true;
                    lastCheckException = e.ToString();
                    ruleStatus         = RuleStatusEnum.Failed;
                }
                settings.SetNewValue(RuleConst.LastCheckFailed, lastCheckFailed);
                settings.SetNewValue(RuleConst.LastCheckException, lastCheckException);
                settings.SetNewValue(RuleConst.LastCheckDateTime, lastCheckDateTime);
            } // commit unsaved settings
            logger.LogDebug("Status={0}", ruleStatus);
        }