public static void Main(string[] args) { var helpText = @" Usage: Notifier --ravendbUrl=<url> --orchestratorUrl=<url> [--forceUpdate=force] "; var defaults = new NotifierArgs(); var rcArgs = new HandleArgs <NotifierArgs>().ProcessArgs(args, helpText, defaults); bool forceUpdate = rcArgs.ForceUpdate != null && rcArgs.ForceUpdate.ToLower().Equals("force"); if (rcArgs.RavendbUrl == null) { Console.WriteLine("Must specify --ravendbUrl"); Console.WriteLine(helpText); Environment.Exit(1); } if (rcArgs.OrchestratorUrl == null) { Console.WriteLine("Must specify --orchestratorUrl"); Console.WriteLine(helpText); Environment.Exit(1); } int lastDaySent = DateTime.Now.Day; Console.WriteLine($"Notifier of Embedded Server : {rcArgs.RavendbUrl}"); var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .SetBasePath(Environment.CurrentDirectory); var config = builder.Build(); var appConfig = new NotifierConfig(); ConfigurationBinder.Bind(config, appConfig); while (true) { try { ReadAndNotify(rcArgs, forceUpdate, ref lastDaySent, Console.Out, appConfig); } catch (Exception e) { Console.WriteLine("ERROR:"); Console.WriteLine(e); } Thread.Sleep(TimeSpan.FromHours(1)); } // ReSharper disable once FunctionNeverReturns }
public static void ReadAndNotify(NotifierArgs rcArgs, bool forceUpdate, ref int lastDaySent, TextWriter stdOut, NotifierConfig appConfig) { stdOut.WriteLine(); using (var store = new DocumentStore { Urls = new[] { rcArgs.RavendbUrl }, Database = "Orchestrator" }.Initialize()) { stdOut.WriteLine($"{DateTime.Now} Read index results..."); using (var session = store.OpenAsyncSession()) { var roundResult = session.LoadAsync <StaticInfo>("staticInfo/1").Result; var round = roundResult.Round; var copyRound = round; var results = session.Query <TestInfo, FailTests>().Where(x => x.Round == copyRound, true).ToListAsync().Result; stdOut.WriteLine("Total=" + results.Count); stdOut.WriteLine("Round=" + round); var fails = new Dictionary <string, int>(); var notFinished = new Dictionary <string, int>(); var totalFailuresCount = 0; var totalNotCompletedCount = 0; foreach (var item in results) { if (item.Finished) { if (fails.ContainsKey(item.Name)) { fails[item.Name] = fails[item.Name] + 1; } else { fails[item.Name] = 1; } ++totalFailuresCount; } else { if (notFinished.ContainsKey(item.Name)) { notFinished[item.Name] = notFinished[item.Name] + 1; } else { notFinished[item.Name] = 1; } ++totalNotCompletedCount; } } var failureText = new StringBuilder(); bool first = true; stdOut.WriteLine(); stdOut.WriteLine("Failed:"); stdOut.WriteLine("======"); if (fails.Count > 0) { failureText.Append(@" { ""title"": ""*_Failures_*"", ""value"": ""Unique Tests Count: " + fails.Count + @""", ""short"": false }, "); failureText.Append(@" { ""title"": ""Test Names (FailCount):"", ""value"": """); foreach (var kv in fails) { if (first) { first = false; } else { failureText.Append(", "); } stdOut.WriteLine($"{ kv.Key} = {kv.Value}"); failureText.Append($"{kv.Key}({kv.Value})"); } failureText.Append(@""", ""short"": true }, "); } var notFinishedText = new StringBuilder(); stdOut.WriteLine(); stdOut.WriteLine("Not Finished:"); stdOut.WriteLine("============ "); first = true; foreach (var kv in notFinished) { if (first) { notFinishedText.Append(@" { ""title"": ""*_Not Completed_*"", ""value"": ""Unique Tests Count: " + notFinished.Count + @""", ""short"": false }, "); first = false; } stdOut.WriteLine($"{kv.Key} = {kv.Value}"); notFinishedText.Append(@" { ""title"": """ + kv.Key + @""", ""value"": ""Count: " + kv.Value + @""", ""short"": true }, "); } var copyRound2 = round; var total = session.Query <TestInfo>().Where(x => x.Author != "TestRunner" && x.Round == copyRound2, true).CountAsync().Result; stdOut.WriteLine($"Out of total={total}"); var color = "good"; // green if (fails.Count > 0) { color = "danger"; // red } else if (total == 0 || notFinished.Count > 1) { color = "warning"; // yellow } string msgstring = @" { ""Username"": """ + appConfig.UserEmail + @""", ""Channel"": """ + appConfig.UserName + @""", ""attachments"": [ { ""mrkdwn_in"": [""text""], ""color"": """ + color + @""", ""pretext"": ""Testing Environment Results"", ""author_name"": ""Round " + round + @" (Click to view)"", ""author_link"": """ + rcArgs.OrchestratorUrl + @"/round-results?round=" + round + @""", ""author_icon"": ""https://ravendb.net/img/team/adi_avivi.jpg"", ""title"": ""Total Tests: " + total + @" | Total Failures: " + totalFailuresCount + @" | Still Running: " + totalNotCompletedCount + @""", ""text"": ""<" + rcArgs.RavendbUrl + @"/studio/index.html#databases/query/index/FailTests?&database=Orchestrator|RavenDB Studio> - See all rounds errors\n"", ""fields"": [ " + /*notFinishedText.ToString()*/ "" + @" " + failureText + @" ], ""thumb_url"": ""https://ravendb.net/img/home/raven.png"", ""footer"": ""The results were generated at " + DateTime.Now + @""", ""footer_icon"": ""https://platform.slack-edge.com/img/default_application_icon.png"" } ] } "; var now = DateTime.Now; stdOut.WriteLine($"now={now}, now.Hour={now.Hour}, now.Day={now.Day}, lastDaySent={lastDaySent}"); if (forceUpdate || (now.Hour >= 9 && now.Day != lastDaySent)) { stdOut.WriteLine(); stdOut.WriteLine("Sending:"); stdOut.WriteLine(msgstring); lastDaySent = now.Day; using (WebClient client = new WebClient()) { NameValueCollection data = new NameValueCollection { ["payload"] = msgstring }; var response = client.UploadValues(appConfig.Uri, "POST", data); //The response text is usually "ok" string responseText = Encoding.UTF8.GetString(response); stdOut.WriteLine(); stdOut.WriteLine(responseText); stdOut.WriteLine("Done"); } } } } }
public ActionResult Configuration([FromBody] NotifierConfig notifierConfig) { this.heaterRepository.SetMailNotifierConfig(notifierConfig); return(base.NoContent()); }
/// <summary> /// Ermittelt die NotifierConfig aus der Datenbank /// </summary> /// <param name="notifierConfig">Die Konfiguration, welche gespeichert werden soll</param> /// <exception type="Exception">Wird geworfen, wenn ein Datenbankfehler auftritt</exception> public void SetMailNotifierConfig(NotifierConfig notifierConfig) { List <string> valuesList = new List <string>(); for (var i = 0; i < notifierConfig.MailConfigs.Count; i++) { valuesList.Add($"({i}, '{notifierConfig.MailConfigs[i].Mail}')"); } using (MySqlConnection connectionA = new MySqlConnection(this.connectionString)) { using (MySqlConnection connectionB = new MySqlConnection(this.connectionString)) { try { connectionA.Open(); connectionB.Open(); var updateNotifierConfigQueryTask = connectionA.ExecuteAsync($"UPDATE NotifierConfig SET LowerThreshold = @lowerThreshhold", new { lowerThreshhold = notifierConfig.LowerThreshold }); connectionB.Execute("TRUNCATE TABLE NotifierMails"); using (var insertCommand = connectionB.CreateCommand()) { var stringBuilder = new StringBuilder(60); stringBuilder.Append("INSERT INTO NotifierMails (Id, Mail) VALUES "); var isFirst = true; for (var i = 0; i < notifierConfig.MailConfigs.Count; i++) { var mailConfig = notifierConfig.MailConfigs[i]; if (isFirst == true) { isFirst = false; } else { stringBuilder.Append(", "); } stringBuilder.AppendFormat("(@id{0}, @mail{0})", i); insertCommand.Parameters.AddWithValue("@id" + i, i); insertCommand.Parameters.AddWithValue("@mail" + i, mailConfig.Mail); } insertCommand.CommandText = stringBuilder.ToString(); insertCommand.ExecuteNonQuery(); } updateNotifierConfigQueryTask.Wait(); if (updateNotifierConfigQueryTask.IsFaulted) { throw updateNotifierConfigQueryTask.Exception ?? new Exception(); } } finally { connectionA.Close(); connectionB.Close(); } } } }
/// <summary> /// Ermittelt die NotifierConfig aus der Datenbank /// </summary> /// <returns>Git die NotifierConfig zurück</returns> public NotifierConfig GetMailNotifierConfig() { var result = new NotifierConfig() { MailConfigs = new List <MailConfig>() }; var from = DateTime.Now.AddHours(-2); IList <string> valuesStrings = new List <string>(); using (var connectionA = new MySqlConnection(this.connectionString)) { using (var connectionB = new MySqlConnection(this.connectionString)) { try { connectionA.Open(); connectionB.Open(); var lowerThresholdQueryTask = connectionA.QueryAsync("SELECT LowerThreshold FROM NotifierConfig;"); var notifierMailsQueryTask = connectionB.QueryAsync("SELECT Mail FROM NotifierMails;"); Task.WaitAll(lowerThresholdQueryTask, notifierMailsQueryTask); IList <Exception> exceptions = new List <Exception>(); if (lowerThresholdQueryTask.IsFaulted) { exceptions.Add(lowerThresholdQueryTask.Exception ?? new Exception()); } if (notifierMailsQueryTask.IsFaulted) { exceptions.Add(notifierMailsQueryTask.Exception ?? new Exception()); } if (exceptions.Count > 0) { throw new AggregateException("Beim ermitteln von der MailConfig ist mindestens ein Fehler aufgetreten", exceptions); } if (lowerThresholdQueryTask.Result.Count() > 0) { result.LowerThreshold = lowerThresholdQueryTask.Result.ElementAt(0).LowerThreshold; foreach (var row in notifierMailsQueryTask.Result) { result.MailConfigs.Add(new MailConfig(row.Mail)); } } } finally { connectionA.Close(); connectionB.Close(); } } } return(result); }