// Sends a heartbeat to Minecraft.net, and saves response. Runs in its own background thread. static void BeatThreadMinecraftNet() { while (true) { try { HeartbeatData freshData = data; UriBuilder ub = new UriBuilder(data.HeartbeatUri); ub.Query = String.Format("public={0}&max={1}&users={2}&port={3}&version={4}&salt={5}&name={6}", freshData.IsPublic, freshData.MaxPlayers, freshData.PlayerCount, freshData.Port, ProtocolVersion, Uri.EscapeDataString(freshData.Salt), Uri.EscapeDataString(freshData.ServerName)); CreateRequest(ub.Uri); Thread.Sleep(Delay); } catch (Exception ex) { if (ex is WebException) { Console.Error.WriteLine("{0} > Minecraft.net probably down ({1})", Timestamp(), ex.Message); } else { Console.Error.WriteLine("{0} > {1}", Timestamp(), ex); } Thread.Sleep(ErrorDelay); } } }
public Task Heartbeat(byte[] data) { HeartbeatData heartbeatData = HeartbeatDataDotNetSerializer.Deserialize(data); IGameGrain game = GrainFactory.GetGrain <IGameGrain>(heartbeatData.Game); return(game.UpdateGameStatus(heartbeatData.Status)); }
static void RefreshData() { try { string[] rawData = File.ReadAllLines(heartbeatDataFileName, Encoding.ASCII); HeartbeatData newData = new HeartbeatData { Salt = rawData[0], ServerIP = IPAddress.Parse(rawData[1]), Port = Int32.Parse(rawData[2]), PlayerCount = Int32.Parse(rawData[3]), MaxPlayers = Int32.Parse(rawData[4]), ServerName = rawData[5], IsPublic = Boolean.Parse(rawData[6]), WoMDescription = rawData[7], WoMFlags = rawData[8] }; beatToWoM = Boolean.Parse(rawData[9]); data = newData; } catch (Exception ex) { if (ex is UnauthorizedAccessException || ex is IOException) { Console.Error.WriteLine("{0} > Error reading {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } else if (ex is FormatException || ex is ArgumentException) { Console.Error.WriteLine("{0} > Cannot parse one of the data fields of {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } } }
// fetches fresh data from the given file. Should not throw any exceptions. Runs in the main thread. static bool RefreshData() { try { string[] rawData = File.ReadAllLines( heartbeatDataFileName, Encoding.ASCII ); HeartbeatData newData = new HeartbeatData { Salt = rawData[0], ServerIP = IPAddress.Parse( rawData[1] ), Port = Int32.Parse( rawData[2] ), PlayerCount = Int32.Parse( rawData[3] ), MaxPlayers = Int32.Parse( rawData[4] ), ServerName = rawData[5], IsPublic = Boolean.Parse( rawData[6] ) }; data = newData; return true; } catch( Exception ex ) { if( ex is UnauthorizedAccessException || ex is IOException ) { Console.Error.WriteLine( "{0} > Error reading {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message ); } else if( ex is FormatException || ex is ArgumentException ) { Console.Error.WriteLine( "{0} > Cannot parse one of the data fields of {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message ); } else { Console.Error.WriteLine( "{0} > Unexpected error: {1} {2}", Timestamp(), ex.GetType().Name, ex.Message ); } return false; } }
public async Task <bool> ExecuteHeartbeatProtocol(HeartbeatData heartbeat) { var user = await userService.GetUserById(heartbeat.UserId); var history = user.HeartbeatHistory?.ToList() ?? new List <HeartbeatHistory>(); history.Add(new HeartbeatHistory { AverageBpm = heartbeat.AverageBpm, DateTime = DateTime.Now }); user.HeartbeatHistory = history; if (heartbeat.AverageBpm > 100 && heartbeat.IsOutlyingStatus) { var builder = new StringBuilder(); builder.AppendLine("We noticed you are particuarly stressed."); builder.AppendLine("If false alarm reply OK."); builder.AppendLine("If you need a grounding exercise reply HELP."); builder.AppendLine("If you need advice reply ADVICE."); messageBroadcastService.SendMessage(user.Name, user.Number, builder.ToString()); user.AwaitingResponse = true; user.BpmMessageSentTime = DateTime.Now; } await userService.SaveUser(user.Id, user); return(true); }
/// <summary> /// Sends a heart-beat to the server, while also checking for updates /// </summary> public void runHeartBeat() { Boolean hasNewVersion = false; Constants.STATIC_RUN_COUNTER++; Utils util = new Utils(); try { ConfigObj cfg = util.readConfig(); if (cfg != null && cfg.remoteTarget != null && cfg.remoteServer != null && cfg.strId != null) { String data = util.getUrlStatusCode(cfg.remoteTarget); HeartbeatData h = new HeartbeatData(); h.downloadSpeed = WebUtil.DownloadSpeed(false); runUploadTrafficSensor(1024, out h.uploadSpeed); h.assVersion = util.getAssemblyVersion(); h.errorCounter = Constants.STATIC_ERROR_COUNTER; h.runCounter = Constants.STATIC_RUN_COUNTER; h.strId = cfg.strId; h.version = cfg.version; string json = JsonConvert.SerializeObject(h); String link = cfg.remoteServer + "?action=ACK&data=" + data + "&version=" + util.getAssemblyVersion() + "&strId=" + cfg.strId + "&errorcounter=" + Constants.STATIC_ERROR_COUNTER + "&runcounter=" + Constants.STATIC_RUN_COUNTER; link = link.Trim(); String code = util.getUrlStatusCode(link); util.writeToLogFile(link); if (code != null) { if (!code.Equals("OK")) { Constants.STATIC_ERROR_COUNTER++; } else { hasNewVersion = runDownloadTrafficSensor(); runUploadTrafficSensor(); if (hasNewVersion) { updateService(); } } } else { Constants.STATIC_ERROR_COUNTER++; } } } catch (Exception e) { Constants.STATIC_ERROR_COUNTER++; util.writeEventLog(e.Message); util.writeEventLog(e.StackTrace); } }
internal HeartbeatSendingEventArgs([NotNull] HeartbeatData data, [NotNull] Uri url) { if (data == null) { throw new ArgumentNullException("data"); } HeartbeatData = data; Url = url; }
internal HeartbeatSentEventArgs(HeartbeatData heartbeatData, WebHeaderCollection headers, HttpStatusCode status, string text) { HeartbeatData = heartbeatData; ResponseHeaders = headers; ResponseStatusCode = status; ResponseText = text; }
private static IInbound DeserializeHeartbeat(Received received) { HeartbeatData data = JsonConvert.DeserializeObject <HeartbeatData>(received.Data); return(new Inbound.Heartbeat { Sid = received.Sid, Model = received.Model, Token = received.Token }); }
// fetches fresh data from the given file. Should not throw any exceptions. Runs in the main thread. static bool RefreshData() { try { string[] rawData = File.ReadAllLines(heartbeatDataFileName, Encoding.ASCII); HeartbeatData newData = new HeartbeatData { Salt = rawData[0], ServerIP = IPAddress.Parse(rawData[1]), Port = Int32.Parse(rawData[2]), PlayerCount = Int32.Parse(rawData[3]), MaxPlayers = Int32.Parse(rawData[4]), ServerName = rawData[5], IsPublic = Boolean.Parse(rawData[6]), HeartbeatUri = new Uri(rawData[7]) }; data = newData; return(true); } catch (Exception ex) { if (ex is UnauthorizedAccessException || ex is IOException) { Console.Error.WriteLine("{0} > Error reading {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } else if (ex is FormatException || ex is ArgumentException) { Console.Error.WriteLine("{0} > Cannot parse one of the data fields of {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } else { Console.Error.WriteLine("{0} > Unexpected error: {1} {2}", Timestamp(), ex.GetType().Name, ex.Message); } return(false); } }
// Sends a heartbeat to Minecraft.net, and saves response. Runs in its own background thread. static void BeatThreadMinecraftNet() { UriBuilder ub = new UriBuilder(MinecraftNetUri); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" ***Welcome to LegendCraft HeartbeatSaver***\n"); Console.WriteLine(" ...:: The program is designed to send ::...\n .:: a Heartbeat to Minecraft/ClassiCube!::. \n"); Console.WriteLine(" .::.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.::.\n"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.White; while (true) { try { HeartbeatData freshData = data; ub.Query = String.Format("public={0}&max={1}&users={2}&port={3}&version={4}&salt={5}&name={6}", freshData.IsPublic, freshData.MaxPlayers, freshData.PlayerCount, freshData.Port, ProtocolVersion, Uri.EscapeDataString(freshData.Salt), Uri.EscapeDataString(freshData.ServerName)); //start the heartbeat loop here CreateRequest(ub.Uri); } catch (Exception ex) { if (ex is WebException) { Console.Error.WriteLine("{0}: Minecraft.net is probably down :( ({1})", Timestamp(), ex.Message); } else { Console.Error.WriteLine("{0}: {1}", Timestamp(), ex); } Thread.Sleep(ErrorDelay); return; } Console.WriteLine("{0}: Sent!", Timestamp()); Console.WriteLine(""); Thread.Sleep(Delay); } }
public void WriteHeartbeatData(HeartbeatData heartbeat) { if (heartbeat != null) { ProfilerService.DetailWriter?.WriteDetail( new ProfileWriterData("Flow Runs", null, ProfilerType.Usage), new[] { new ProfilerDetail(ProfilerDetailType.Info, "Flow Runs") { Count = heartbeat.NumberOfFlowStarts } }, TimeSpan.Zero); // ProfilerService.DetailWriter?.WriteDetail( new ProfileWriterData("Rule Runs", null, ProfilerType.Usage), new[] { new ProfilerDetail(ProfilerDetailType.Info, "Rule Runs") { Count = heartbeat.NumberOfRuleExecutions } }, TimeSpan.Zero); ProfilerService.DetailWriter?.WriteDetail( new ProfileWriterData("API Calls", null, ProfilerType.Usage), new[] { new ProfilerDetail(ProfilerDetailType.Info, "API Calls") { Count = heartbeat.NumberOfAPICalls } }, TimeSpan.Zero); ProfilerService.DetailWriter?.WriteDetail( new ProfileWriterData("Job Runs", null, ProfilerType.Usage), new[] { new ProfilerDetail(ProfilerDetailType.Info, "Job Runs") { Count = heartbeat.NumberOfJobStarts } }, TimeSpan.Zero); } }
// fetches fresh data from the given file. Should not throw any exceptions. Runs in the main thread. static bool RefreshData() { try { string[] rawData = File.ReadAllLines(heartbeatDataFileName, Encoding.ASCII); //take the data from heartbeatdata.txt that was created from Network/HeartBeat.cs, make sure the orders match up on each :3 HeartbeatData newData = new HeartbeatData { Salt = rawData[0], ServerIP = IPAddress.Parse(rawData[1]), Port = Int32.Parse(rawData[2]), PlayerCount = Int32.Parse(rawData[3]), MaxPlayers = Int32.Parse(rawData[4]), ServerName = rawData[5], IsPublic = Boolean.Parse(rawData[6]) }; data = newData; return(true); } catch (Exception ex) { if (ex is UnauthorizedAccessException || ex is IOException) { Console.Error.WriteLine("{0}: UnauthorizedAccessException - Error reading {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } else if (ex is FormatException || ex is ArgumentException) { Console.Error.WriteLine("{0}: FormatException - Cannot parse one of the data fields of {1}: {2} {3}", Timestamp(), heartbeatDataFileName, ex.GetType().Name, ex.Message); } else { Console.Error.WriteLine("{0}: Unexpected error - {1} {2}", Timestamp(), ex.GetType().Name, ex.Message); } return(false); } }
internal HeartbeatSentEventArgs([NotNull] HeartbeatData heartbeatData, [NotNull] WebHeaderCollection headers, HttpStatusCode status, [NotNull] string text) { if (heartbeatData == null) { throw new ArgumentNullException("heartbeatData"); } if (headers == null) { throw new ArgumentNullException("headers"); } if (text == null) { throw new ArgumentNullException("text"); } HeartbeatData = heartbeatData; ResponseHeaders = headers; ResponseStatusCode = status; ResponseText = text; }
public static byte[] Serialize(HeartbeatData item) { using var stream = new MemoryStream(); Serializer.Pack(stream, item); return(stream.ToArray()); }
public ReplyData domain_heartbeat(IPAddress remoteIP, int remotePort, List <string> arguments, string body, string method, Dictionary <string, string> Headers) { // Check the Authorization header for a valid Access token // If token is valid, begin updating stuff ReplyData rd = new ReplyData(); rd.Status = 200; rd.Body = ""; if (Headers.ContainsKey("Authorization")) { string Token = Headers["Authorization"].Split(new[] { ' ' })[1]; UserAccounts ua = UserAccounts.GetAccounts(); foreach (KeyValuePair <string, UserAccounts.Account> kvp in ua.AllAccounts) { if (kvp.Value.ActiveTokens.ContainsKey(Token)) { // Start updating shit Dictionary <string, HeartbeatPacket> requestData = JsonConvert.DeserializeObject <Dictionary <string, HeartbeatPacket> >(body); DomainMemory mem = Session.Instance.DomainsMem; // Check if this domain is in memory! if (mem.Itms.ContainsKey(arguments[0])) { // start DomainMemory.MemoryItem mi = mem.Itms[arguments[0]]; DomainMemory.DomainObject obj = mi.Obj; // First check that there is a API Key if (obj.API_Key == "" || obj.API_Key == null) { rd.Status = 401; break; } obj.NetworkingMode = requestData["domain"].automatic_networking; HeartbeatData dat = requestData["domain"].heartbeat; obj.Protocol = dat.protocol; obj.Restricted = dat.restricted; obj.Version = dat.version; obj.LoggedIn = dat.num_users; obj.Anon = dat.num_anon_users; obj.TotalUsers = dat.num_anon_users + dat.num_users; mi.Obj = obj; Session.Instance.DomainsMem.Itms[arguments[0]] = mi; rd.Status = 200; rd.Body = ""; } else { rd.Status = 404; // this will trigger a new temporary domain name } } } } // fallback if (Session.Instance.DomainsMem.Itms.ContainsKey(arguments[0]) == false) { rd.Status = 404; } return(rd); }
/// <summary> /// Simulates periodic updates for a bunch of games similar to what game consoles of mobile apps do. /// </summary> static void Main(string[] args) { try { GrainClient.Initialize(); int nGames = 10; // number of games to simulate int nPlayersPerGame = 4; // number of players in each game TimeSpan sendInterval = TimeSpan.FromSeconds(2); // interval for sending updates int nIterations = 100; // Precreate base heartbeat data objects for each of the games. // We'll modify them before every time before sending. HeartbeatData[] heartbeats = new HeartbeatData[nGames]; for (int i = 0; i < nGames; i++) { heartbeats[i] = new HeartbeatData(); heartbeats[i].Game = Guid.NewGuid(); for (int j = 0; j < nPlayersPerGame; j++) { heartbeats[i].Status.Players.Add(GetPlayerId(i * nPlayersPerGame + j)); } } int iteration = 0; IPresenceGrain presence = PresenceGrainFactory.GetGrain(0); // PresenceGrain is a StatelessWorker, so we use a single grain ID for auto-scale List <Task> promises = new List <Task>(); while (iteration++ < nIterations) { Console.WriteLine("Sending heartbeat series #{0}", iteration); promises.Clear(); try { for (int i = 0; i < nGames; i++) { heartbeats[i].Status.Score = String.Format("{0}:{1}", iteration, iteration > 5 ? iteration - 5 : 0); // Simultate a meaningful game score // We serialize the HeartbeatData object to a byte[] only to simulate the real life scenario where data comes in // as a binary blob and requires an initial processing before it can be routed to the proper destination. // We could have sent the HeartbeatData object directly to the game grain because we know the game ID. // For the sake of simulation we just pretend we don't. Task t = presence.Heartbeat(HeartbeatDataDotNetSerializer.Serialize(heartbeats[i])); promises.Add(t); } // Wait for all calls to finish. // It is okay to block the thread here because it's a client program with no parallelism. // One should never block a thread in grain code. Task.WaitAll(promises.ToArray()); } catch (Exception exc) { Console.WriteLine("Exception: {0}", exc.GetBaseException()); } Thread.Sleep(sendInterval); } } catch (Exception exc) { Console.WriteLine("Unexpected Error: {0}", exc.GetBaseException()); } }
private async Task RunAsync() { // number of games to simulate var nGames = 10; // number of players in each game var nPlayersPerGame = 4; // interval for sending updates var sendInterval = TimeSpan.FromSeconds(2); // number of updates to send var nIterations = 100; // Precreate base heartbeat data objects for each of the games. // We'll modify them before every time before sending. var heartbeats = new HeartbeatData[nGames]; for (var i = 0; i < nGames; i++) { heartbeats[i] = new HeartbeatData( Guid.NewGuid(), new GameStatus( Enumerable.Range(0, nPlayersPerGame).Select(j => GetPlayerId(i * nPlayersPerGame + j)).ToImmutableHashSet(), string.Empty)); } var iteration = 0; // PresenceGrain is a StatelessWorker, so we use a single grain ID for auto-scale var presence = _client.GetGrain <IPresenceGrain>(0); var promises = new Task[nGames]; while (++iteration < nIterations) { _logger.LogInformation("Sending heartbeat series #{@Iteration}", iteration); try { for (var i = 0; i < nGames; i++) { // Simultate a meaningful game score heartbeats[i] = heartbeats[i].WithNewScore($"{iteration}:{(iteration > 5 ? iteration - 5 : 0)}"); // We serialize the HeartbeatData object to a byte[] only to simulate the real life scenario where data comes in // as a binary blob and requires an initial processing before it can be routed to the proper destination. // We could have sent the HeartbeatData object directly to the game grain because we know the game ID. // For the sake of simulation we just pretend we don't. promises[i] = presence.HeartbeatAsync(HeartbeatDataDotNetSerializer.Serialize(heartbeats[i])); } // Wait for all calls to finish. await Task.WhenAll(promises); // check for cancellation request if (_executionCancellation.IsCancellationRequested) { return; } } catch (Exception error) { _logger.LogError(error, "Error while sending hearbeats to Orleans cluster"); } try { await Task.Delay(sendInterval, _executionCancellation.Token); } catch (OperationCanceledException) { return; } } }
internal HeartbeatSendingEventArgs(HeartbeatData data, Uri uri, bool getServerUri) { HeartbeatData = data; Uri = uri; GetServerUri = getServerUri; }
internal HeartbeatSendingEventArgs( HeartbeatData data ) { HeartbeatData = data; }
public async Task <IActionResult> Post([FromBody] HeartbeatData heartbeat) { return(Ok(await _helper.ExecuteHeartbeatProtocol(heartbeat))); }
internal HeartbeatSendingEventArgs( HeartbeatData data, Uri uri, bool getServerUri ) { HeartbeatData = data; Uri = uri; GetServerUri = getServerUri; }
internal HeartbeatSendingEventArgs(HeartbeatData data) { HeartbeatData = data; }
internal HeartbeatSentEventArgs( HeartbeatData heartbeatData, WebHeaderCollection headers, HttpStatusCode status, string text ) { HeartbeatData = heartbeatData; ResponseHeaders = headers; ResponseStatusCode = status; ResponseText = text; }
private static async Task RunAsync(string[] args, CancellationToken token) { // build the orleans client var client = new ClientBuilder() .UseLocalhostClustering() .ConfigureLogging(_ => { _.AddConsole(); }) .Build(); // keep a logger for general use var logger = client.ServiceProvider.GetService <ILogger <Program> >(); // connect to the orleans cluster var attempt = 0; var maxAttempts = 100; var delay = TimeSpan.FromSeconds(1); await client.Connect(async error => { if (++attempt < maxAttempts) { logger.LogWarning(error, "Failed to connect to Orleans cluster on attempt {@Attempt} of {@MaxAttempts}.", attempt, maxAttempts); await Task.Delay(delay, token); return(true); } else { logger.LogError(error, "Failed to connect to Orleans cluster on attempt {@Attempt} of {@MaxAttempts}.", attempt, maxAttempts); return(false); } }); // number of games to simulate var nGames = 10; // number of players in each game var nPlayersPerGame = 4; // interval for sending updates var sendInterval = TimeSpan.FromSeconds(2); // number of updates to send var nIterations = 100; // Precreate base heartbeat data objects for each of the games. // We'll modify them before every time before sending. var heartbeats = new HeartbeatData[nGames]; for (var i = 0; i < nGames; i++) { heartbeats[i] = new HeartbeatData( Guid.NewGuid(), new GameStatus( Enumerable.Range(0, nPlayersPerGame).Select(j => GetPlayerId(i * nPlayersPerGame + j)).ToImmutableHashSet(), string.Empty)); } var iteration = 0; // PresenceGrain is a StatelessWorker, so we use a single grain ID for auto-scale var presence = client.GetGrain <IPresenceGrain>(0); var promises = new Task[nGames]; while (++iteration < nIterations) { logger.LogInformation("Sending heartbeat series #{@Iteration}", iteration); try { for (var i = 0; i < nGames; i++) { // Simultate a meaningful game score heartbeats[i] = heartbeats[i].WithNewScore($"{iteration}:{(iteration > 5 ? iteration - 5 : 0)}"); // We serialize the HeartbeatData object to a byte[] only to simulate the real life scenario where data comes in // as a binary blob and requires an initial processing before it can be routed to the proper destination. // We could have sent the HeartbeatData object directly to the game grain because we know the game ID. // For the sake of simulation we just pretend we don't. promises[i] = presence.HeartbeatAsync(HeartbeatDataDotNetSerializer.Serialize(heartbeats[i])); } // Wait for all calls to finish. await Task.WhenAll(promises); } catch (Exception error) { logger.LogError(error, "Error while sending hearbeats to Orleans cluster"); } await Task.Delay(sendInterval, token); } }