protected void SetStatus(HostStatus enStatus) { using (RWLockWriteSession lockSession = new RWLockWriteSession(m_hostStatusLocker)) { m_enStatus = enStatus; } }
public async Task <IActionResult> GetHostStatus([FromServices] IScriptHostManager scriptHostManager, [FromServices] IHostIdProvider hostIdProvider) { var status = new HostStatus { State = scriptHostManager.State.ToString(), Version = ScriptHost.Version, VersionDetails = Utility.GetInformationalVersion(typeof(ScriptHost)), Id = await hostIdProvider.GetHostIdAsync(CancellationToken.None), ProcessUptime = (long)(DateTime.UtcNow - Process.GetCurrentProcess().StartTime).TotalMilliseconds }; var lastError = scriptHostManager.LastError; if (lastError != null) { status.Errors = new Collection <string>(); status.Errors.Add(Utility.FlattenException(lastError)); } string message = $"Host Status: {JsonConvert.SerializeObject(status, Formatting.Indented)}"; _logger.LogInformation(message); return(Ok(status)); }
public HostInfo( long id, long ownerId, int locationId, string[] addresses, long environmentId, long clusterId, long imageId, long machineTypeId, ManagedResource resource, HostType type = HostType.Virtual, HostStatus status = HostStatus.Running) { Ensure.IsValidId(id); Ensure.IsValidId(ownerId, nameof(ownerId)); Id = id; OwnerId = ownerId; Type = type; Status = status; Addresses = addresses; ClusterId = clusterId; EnvironmentId = environmentId; LocationId = locationId; ImageId = imageId; MachineTypeId = machineTypeId; ProviderId = resource.ProviderId; ResourceId = resource.ResourceId; }
public async Task TransitionStateAsync(HostInfo host, HostStatus newStatus) { #region Preconditions Validate.NotNull(host, nameof(host)); if (newStatus == default) { throw new ArgumentException("Required", nameof(newStatus)); } #endregion if (host.Status == newStatus) { return; // no change } var cluster = await clusterService.GetAsync(host.ClusterId);; // from pending | suspended if (newStatus == HostStatus.Running) { // register the host with the cluster await clusterManager.RegisterHostAsync(cluster, host); } await db.Hosts.PatchAsync(host.Id, new[] { Change.Replace("status", newStatus) }); }
/// <summary> /// The event that occurs after we received the status of hosting a game. This is a followup of Update_Host(). /// </summary> protected void Host_Post(bool isSuccess, string lobbyCode) { mUpdate_hostStatus = HostStatus.None; if (isSuccess) { UnoccupyLobbySlotAll(); HideLoadingSplash(); mLobbyCode = lobbyCode; if (mMP_Mode == NetworkType.InternetIP) { mLobbyMenu_lobbyCodeWithHeaderText.text = "Lobby IP: " + mLobbyCode; } else { mLobbyMenu_lobbyCodeWithHeaderText.text = "Lobby Room Code: " + mLobbyCode; } SwitchMenu(mLobbyMenu); mLobby.HostLobby_ToggleLobbyHostLogic(true); } else { UpdateLoadingSplashMessage("Failed to create a lobby."); RevealCloseLoadingSplashButton(); } }
public void Fault() { lock (_lock) { _status = HostStatus.Faulted; } }
/// <summary> /// Converts to a Brush /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { HostStatus h = (HostStatus)value; switch (h) { case HostStatus.Online: return(Brushes.LightGreen); case HostStatus.Offline: return(Brushes.LightSalmon); case HostStatus.Disabled: return(Brushes.Transparent); case HostStatus.Pending: return(Brushes.LightBlue); case HostStatus.Checking: return(Brushes.LightYellow); default: return(Brushes.LightGray); } }
public async Task HostStatusReturns_IfHostJsonError() { string hostJsonPath = Path.Combine(_hostPath, ScriptConstants.HostMetadataFileName); // Simulate a non-empty file without a 'version' JObject hostConfig = JObject.FromObject(new { functionTimeout = TimeSpan.FromSeconds(30) }); await File.WriteAllTextAsync(hostJsonPath, hostConfig.ToString()); var host = new TestFunctionHost(_hostPath, _ => { }); // Ping the status endpoint to ensure we see the exception HostStatus status = await host.GetHostStatusAsync(); Assert.Equal("Error", status.State); Assert.Equal("Microsoft.Azure.WebJobs.Script: The host.json file is missing the required 'version' property. See https://aka.ms/functions-hostjson for steps to migrate the configuration file.", status.Errors.Single()); // Now update the file and make sure it auto-restarts. hostConfig["version"] = "2.0"; await File.WriteAllTextAsync(hostJsonPath, hostConfig.ToString()); await TestHelpers.Await(async() => { status = await host.GetHostStatusAsync(); return(status.State == $"{ScriptHostState.Running}"); }); Assert.Null(status.Errors); }
public RegisterHostRequest( long ownerId, string[] addresses, ILocation location, ICluster cluster, IImage image, IProgram program, IMachineType machineType, ManagedResource resource, HostStatus status = HostStatus.Pending, HostType type = HostType.Virtual) { Ensure.IsValidId(ownerId, nameof(ownerId)); Ensure.NotNull(cluster, nameof(cluster)); Ensure.NotNull(location, nameof(location)); Ensure.NotNull(image, nameof(image)); Ensure.NotNull(machineType, nameof(machineType)); OwnerId = ownerId; Addresses = addresses; LocationId = location.Id; EnvironmentId = cluster.EnvironmentId; ClusterId = cluster.Id; ImageId = image.Id; MachineType = new MachineTypeDescriptor { Id = machineType.Id, Name = machineType.Name }; Status = status; Resource = resource; Type = type; }
public async Task Close() { if (CanClose) { await _lock.WaitAsync(); try { if (CanClose) { State = HostStatus.Closing; if (_cancellationSource != null) { _cancellationSource.Cancel(); _cancellationSource = new CancellationTokenSource(); } foreach (var listener in _listeners) { try { listener.Close(); } catch { } } } } finally { this.State = HostStatus.Closed; _lock.Release(); } } }
void Read() { curStatus = HostStatus.AcceptingFile; Buffer = new byte[1024]; server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallBack), server); Debug.Log("read called"); }
public void GetAssemblyFileVersion_Unknown() { var asm = new AssemblyMock(); var version = HostStatus.GetAssemblyFileVersion(asm); Assert.Equal("Unknown", version); }
public void Setup() { master = new HostStatus(new DnsEndPoint("Test", 1000), 2000); slaves = new[] { new HostStatus(new DnsEndPoint("Test", 1000), 1000) }; }
public void OpenServer() { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(new IPEndPoint(IPAddress.Any, 6321)); server.Listen(100); server.BeginAccept(new AsyncCallback(SocketConnectCallback), server); curStatus = HostStatus.AcceptingClient; HostUIManager.ShowStatus("AcceptingClient"); }
public void Stop() { lock (_lock) { if (_status != HostStatus.Faulted) { _status = HostStatus.Stopped; } } }
void SocketConnectCallback(IAsyncResult ar) { Socket iServer = (Socket)ar.AsyncState; curStatus = HostStatus.AcceptingClient; client = iServer.EndAccept(ar); curStatus = HostStatus.Connected; Debug.Log("I'm connected"); HostUIManager.ShowStatus("Client Accepted"); }
/// <summary> /// This is called by Update() to repeatedly inquire status of successful lobby creation). /// /// It is only active if OnClick_Host() is clicked. /// </summary> protected void Update_CreatingLobby() { if (mUpdate_hostStatus == HostStatus.None) { return; // Not invoked yet. } if (Time.time > mUpdate_endTime) { // Timeout. Report Failure. Host_Post(false, null); } else if (Time.time > mUpdate_nextTime) { if (mUpdate_hostStatus == HostStatus.Disconnected) { string result = mLobby.DisconnectResult(); if (result == null) { ; // Try again later. } else if (result == "failure") { Host_Post(false, null); // Report failure. } else { mUpdate_hostStatus = HostStatus.NetworkCreating; // Success. Next phase. } } else if (mUpdate_hostStatus == HostStatus.NetworkCreating) { mLobby.HostLobby_CreateNetwork(mMP_Mode); mUpdate_hostStatus = HostStatus.NetworkCreated; } else if (mUpdate_hostStatus == HostStatus.NetworkCreated) { string lobbyCode = mLobby.HostLobby_CreateNetworkResult(); if (lobbyCode == null) { ; // Try again later. } else if (lobbyCode == "failure") { Host_Post(false, null); // Report failure. } else { Host_Post(true, lobbyCode); // Report success. } } mUpdate_nextTime = Time.time + mUpdate_intervalTime; } }
public void Setup() { master = new HostStatus(new DnsEndPoint("Test", 1000), 2000); slaves = new[] { new HostStatus(new DnsEndPoint("Test", 1000), 1000) }; instance = ReplicationProgress.CreateActive( master, slaves); }
/* 4 - Host or Find Lobby Menu Buttons */ /// <summary> /// Event that occurs when the "Host Game" button is pressed. /// </summary> public void OnClick_Host() { mIsHost = true; ShowLoadingSplash("Creating lobby..."); // Start timer. mUpdate_nextTime = Time.time + mUpdate_intervalTime; mUpdate_endTime = Time.time + mUpdate_maxDuration; mLobby.Disconnect(mIsHost, mMP_Mode); mUpdate_hostStatus = HostStatus.Disconnected; }
public void GetAssemblyFileVersion_ReturnsVersion() { var fileAttr = new AssemblyFileVersionAttribute("1.2.3.4"); var asmMock = new Mock <AssemblyMock>(); asmMock.Setup(a => a.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true)) .Returns(new Attribute[] { fileAttr }) .Verifiable(); var version = HostStatus.GetAssemblyFileVersion(asmMock.Object); Assert.Equal("1.2.3.4", version); asmMock.Verify(); }
public HostStatus GetHostStatus() { HostStatus status = new HostStatus(); var lastError = _scriptHostManager.LastError; if (lastError != null) { status.Errors = new Collection <string>(); status.Errors.Add(Utility.FlattenException(lastError)); } return(status); }
/// <summary> /// Create a new instance of a host with a random ID. /// </summary> public Host() { hostInfo = new HostInfo () { Id = HostCache.RandomId () }; status = HostStatus.NoIdentity; heartbeat.Elapsed += (sender, args) => { log.Info ("Host timed out, terminating"); status = HostStatus.Disconnected; lastInter.DisconnectHost (hostInfo); heartbeat.Stop (); heartbeat.Dispose (); }; NodePool.Instance.Nodes.CollectionChanged += OnGlobalNodesChange; _nodes = new ObservableCollection<NodeInfo> (); _nodes.CollectionChanged += NodesCollectionChanged; }
void Start() { curStatus = HostStatus.Off; string localIP = null; IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } HostUIManager.ShowHostInfo(localIP); }
/// <summary> /// Convert to string /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { HostStatus h = (HostStatus)value; switch (h) { case HostStatus.Online: return("erreichbar"); case HostStatus.Offline: return("nicht erreichbar"); default: return("unbekannt"); } }
public async Task <IActionResult> GetHostStatus([FromServices] IScriptHostManager scriptHostManager, [FromServices] IHostIdProvider hostIdProvider, [FromServices] IServiceProvider serviceProvider = null) { // When making changes to HostStatus, ensure that you update the HostStatus class in AAPT-Antares-Websites repo as well. var status = new HostStatus { State = scriptHostManager.State.ToString(), Version = ScriptHost.Version, VersionDetails = Utility.GetInformationalVersion(typeof(ScriptHost)), PlatformVersion = _environment.GetAntaresVersion(), InstanceId = _environment.GetInstanceId(), ComputerName = _environment.GetAntaresComputerName(), Id = await hostIdProvider.GetHostIdAsync(CancellationToken.None), ProcessUptime = (long)(DateTime.UtcNow - Process.GetCurrentProcess().StartTime).TotalMilliseconds, FunctionAppContentEditingState = Utility.GetFunctionAppContentEditingState(_environment, _applicationHostOptions) }; var bundleManager = serviceProvider.GetService <IExtensionBundleManager>(); if (bundleManager != null) { var bundleInfo = await bundleManager.GetExtensionBundleDetails(); if (bundleInfo != null) { status.ExtensionBundle = new Models.ExtensionBundle() { Id = bundleInfo.Id, Version = bundleInfo.Version }; } } var lastError = scriptHostManager.LastError; if (lastError != null) { status.Errors = new Collection <string>(); status.Errors.Add(Utility.FlattenException(lastError)); } string message = $"Host Status: {JsonConvert.SerializeObject(status, Formatting.Indented)}"; _logger.LogInformation(message); return(Ok(status)); }
public void LogStatusChange(HostPinger host, HostStatus oldStatus, HostStatus newStatus) { switch (newStatus) { case HostStatus.Alive: Log(host, "Host is now alive!"); break; case HostStatus.Dead: Log(host, "Host died!"); break; case HostStatus.DnsError: Log(host, "Host name couldn't be resolved (DNS error)!"); break; } }
public IHttpActionResult GetHostStatus() { var authorizationLevel = Request.GetAuthorizationLevel(); if (Request.IsAuthDisabled() || authorizationLevel == AuthorizationLevel.Admin || Request.IsAntaresInternalRequest()) { var status = new HostStatus { State = _scriptHostManager.State.ToString(), Version = ScriptHost.Version, Id = _scriptHostManager.Instance?.ScriptConfig.HostConfig.HostId }; var lastError = _scriptHostManager.LastError; if (lastError != null) { status.Errors = new Collection <string>(); status.Errors.Add(Utility.FlattenException(lastError)); } var parameters = Request.GetQueryParameterDictionary(); string value = null; if (parameters.TryGetValue(ScriptConstants.CheckLoadQueryParameterName, out value) && value == "1") { status.Load = new LoadStatus { IsHigh = _scriptHostManager.PerformanceManager.IsUnderHighLoad() }; } string message = $"Host Status: {JsonConvert.SerializeObject(status, Formatting.Indented)}"; _traceWriter.Info(message); _logger?.LogInformation(message); return(Ok(status)); } else { return(Unauthorized()); } }
public void Start() { lock (_lock) { if (_status == HostStatus.Executing) { throw new InvalidOperationException(Resources.Host_already_excuting); } if (_status == HostStatus.Faulted) { throw new InvalidOperationException(Resources.Host_is_faulted); } if (_status == HostStatus.Stopped) { throw new InvalidOperationException(Resources.Host_is_stopped); } _status = HostStatus.Executing; } }
void ReadCallBack(IAsyncResult ar) { Socket iServer = (Socket)ar.AsyncState; int bytesRead = iServer.EndReceive(ar); Debug.Log("read complete"); byte[] formatted = new byte[bytesRead]; for (int i = 0; i < bytesRead; ++i) { formatted[i] = Buffer[i]; } string strdata = Encoding.UTF8.GetString(formatted); HostUIManager.ShowClientMessage(strdata); curStatus = HostStatus.Connected; }
private void Connect() { VerifyStatus(HostStatus.WatingToConnect); VerifyHostLibrary(); VerifyJavaRuntime(); _status = HostStatus.WatingToHandshaking; _event.Reset(); try { _handshakeServer = new Server { Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }, Services = { HandshakeService.BindService(new HandshakeRpc(HostProcessOnAck)) } }; _handshakeServer.Start(); _status = HostStatus.Handshaking; _handshakeTimeoutTokenSource = new CancellationTokenSource(); _handshakeTimeoutTokenSource.CancelAfter(TimeSpan.FromSeconds(5)); _handshakeTimeoutTokenRegistration = _handshakeTimeoutTokenSource.Token.Register(HandshakeTimeout); var boundPort = _handshakeServer.Ports.First().BoundPort; SpawnHostProcess(boundPort); } catch (Exception) { _handshakeServer?.KillAsync().Wait(); _handshakeServer = null; throw new PhoenixSqlHostException("Host handshake failed."); } }
private void IncLost() { lock (_syncStatistics) { _sentPackets++; _lostPackets++; lock (_syncOptions) { // enough packets has been lost so we can assume that the host is dead if (++_continousPacketLost > _pingsBeforeDead && _status != HostStatus.Dead) { _statusReachedAt = DateTime.Now; Logger.Instance.Log(this, "Host died!"); _status = HostStatus.Dead; } } } }
public HostStatus GetHostStatus() { HostStatus status = new HostStatus { Id = _scriptHostManager.Instance?.ScriptConfig.HostConfig.HostId }; var lastError = _scriptHostManager.LastError; if (lastError != null) { status.Errors = new Collection<string>(); status.Errors.Add(Utility.FlattenException(lastError)); } return status; }
/// <summary> /// Initialize parameters. /// </summary> /// <param name="oldStatus">previous status of the host.</param> /// <param name="newStatus">new status of the host.</param> public OnHostStatusChangeParams(HostStatus oldStatus, HostStatus newStatus) { _oldState = oldStatus; _newState = newStatus; }
/// <summary> /// Method returns duration of specific status. /// </summary> /// <param name="status">status whose duration is queried.</param> /// <returns>Returns duration of specific status.</returns> public TimeSpan GetStatusDuration(HostStatus status) { lock (_syncObject) { TimeSpan duration = _statusDurations[(int)status]; if (_status == status && _isRunning) duration += DateTime.Now - _statusReachedAt; return duration; } }
/// <summary> /// Process a message for response. /// </summary> /// <param name="inter">Interface.</param> /// <param name="message">Received message.</param> public void ProcessMessage(HostInterface inter, byte[] message) { lastInter = inter; if (status == HostStatus.Disconnected) return; //Reset heartbeat heartbeat.Stop (); heartbeat.Start (); if (status > HostStatus.NoEncryption && message.Length > 1) { //Decrypt message var decrypt = encryption.Decrypt (message.Skip (1).ToArray ()); byte[] finalMessage = new byte[1 + decrypt.Length]; decrypt.CopyTo (finalMessage, 1); finalMessage [0] = message [0]; message = finalMessage; } if (message [0] != (byte)MessageIdentifier.Heartbeat) log.Debug ("Received message: " + Enum.GetName (typeof(MessageIdentifier), message [0])); switch ((MessageIdentifier)message [0]) { case MessageIdentifier.Heartbeat: inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.Heartbeat, null)); break; //Coming from client, this is confirming an identity. case MessageIdentifier.SetIdentity: if (status != HostStatus.NoIdentity) { log.Debug ("Host already has registered."); break; } log.Debug ("Identity confirmed, beginning encryption sequence."); status = HostStatus.NoEncryption; //Begin encryption exchange inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.BeginEncryption, null)); break; //Coming from client, this is the encryption md5. case MessageIdentifier.BeginEncryption: if (status != HostStatus.NoEncryption) { log.Error ("Unexpected BeginEncryption from host."); break; } //Get the encryption key MD5. byte[] keymd5 = message.Skip (1).ToArray (); log.Debug ("Encryption key confirmation request: " + BitConverter.ToString (keymd5).Replace ("-", "").ToLower ()); AES encrypt = EncryptionKeyDB.Instance.ByHash (keymd5); if (encrypt == null) { log.Info ("Key not valid for host, rejecting and disconnecting."); inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.InvalidKey, null)); inter.DisconnectHost (hostInfo); status = HostStatus.Disconnected; } else { log.Debug ("Host accepted, beginning node sync."); status = HostStatus.SyncNodes; inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.ConfirmEncryption, null)); encryption = encrypt; } break; case MessageIdentifier.NodeSync: var inputIndex = Serializer.Deserialize<Dictionary<string, byte[]>> (new MemoryStream (message.Skip (1).ToArray ())); var syncJob = NodeLibraryManager.Instance.CreateSyncJob (inputIndex); if (syncJob == null) { inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.BeginOperation, null)); status = HostStatus.LoadingNodes; } else { byte[] serializedJob; using (var ms = new MemoryStream ()) { Serializer.Serialize (ms, syncJob); serializedJob = ms.ToArray (); status = HostStatus.SyncNodes; } inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.NodeSync, serializedJob)); } break; case MessageIdentifier.GetLibraryURL: //Retreive the library url for the path string dataString = Encoding.Unicode.GetString (message, 1, message.Length - 1); int reqId = int.Parse (dataString.Split (':') [0]); string library = dataString.Split (':') [1]; var libraryUrl = Encoding.UTF8.GetBytes (reqId + ":" + NodeHost.Instance.GetDownloadUrl (library)); inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.GetLibraryURL, libraryUrl)); break; case MessageIdentifier.BeginOperation: if (status == HostStatus.LoadingNodes) { status = HostStatus.Operating; log.Info ("New host ready for operation."); try { Task.Factory.StartNew (() => inter.Controller.OnHostAdded (hostInfo)); } catch (Exception ex) { log.Error ("Error not caught by Controller, " + ex.ToString ()); } } break; case MessageIdentifier.NodeVerify: int verId = BitConverter.ToInt32 (message, 1); NodeInfo info; using (MemoryStream ms = new MemoryStream ()) { var inputBytes = message.Skip (1 + sizeof(int)).ToArray (); ms.Write (inputBytes, 0, inputBytes.Length); ms.Position = 0; info = Serializer.Deserialize<NodeInfo> (ms); } var response = NodePool.Instance.CheckNodeExists (info); var respBytes = new byte[sizeof(int) + sizeof(bool)]; BitConverter.GetBytes (verId).CopyTo (respBytes, 0); BitConverter.GetBytes (response).CopyTo (respBytes, sizeof(int)); inter.SendTo (hostInfo, BuildMessage (MessageIdentifier.NodeVerify, respBytes)); break; case MessageIdentifier.RMIResponse: if (status != HostStatus.Operating) return; var data = message.Skip (1).ToArray (); var rmi = data.Deserialize<NodeRMI> (); var destoNode = NodePool.Instance.NodeForId (rmi.SNodeID); if (destoNode == null) return; if (destoNode.Id == 0) NodePool.Instance.HandleRMIResponse (rmi); else { lastInter.RouteRMIResponse (rmi); } break; case MessageIdentifier.ReqNodeList: if (status != HostStatus.Operating) return; SendEntireNodeList (); break; case MessageIdentifier.RMIInvoke: if (status != HostStatus.Operating) return; NodeRMI trmi = message.Skip (1).ToArray ().Deserialize<NodeRMI> (); var tdestoNode = NodePool.Instance.NodeForId (trmi.NodeID); if (tdestoNode == null) { trmi.SerializeReturnValue (new NodeNotExistException ()); lastInter.SendTo (hostInfo, BuildMessage (MessageIdentifier.RMIResponse, trmi.Serialize ())); break; } lastInter.RouteRMIRequest (trmi, tdestoNode); break; } }
public HostStatusCreateOrUpdateCommand(HostStatus ent) { this.ent = ent; }
public HostStatus[] GetHostList() { _connection.WriteLine("/oper/slb/cur"); var hostList = _connection.ReadUntil(">>"); var match = _hostListPattern.Match(hostList); var result = new List<HostStatus>(); while (match.Success) { var host = new HostStatus { id = Int32.Parse(match.Groups[1].Value), name = match.Groups[2].Value, enabled = match.Groups[3].Value == "enabled" }; result.Add(host); match = match.NextMatch(); } return result.ToArray(); }