/// <summary>
        /// Creates a new relay connection from a caller to a callee using a specific application service.
        /// </summary>
        /// <param name="Caller">Network client of the caller.</param>
        /// <param name="Callee">Network client of the callee.</param>
        /// <param name="ServiceName">Name of the application service of the callee that is being used for the call.</param>
        /// <param name="RequestMessage">CallIdentityApplicationServiceRequest message that the caller send in order to initiate the call.</param>
        public RelayConnection(Client Caller, Client Callee, string ServiceName, Message RequestMessage)
        {
            lockObject = new SemaphoreSlim(1);
            id         = Guid.NewGuid();
            string logPrefix = string.Format("[{0}:{1}] ", id, ServiceName);
            string logName   = "HomeNet.Network.ClientList";

            log = new PrefixLogger(logName, logPrefix);

            log.Trace("(Caller.Id:0x{0:X16},Callee.Id:0x{1:X16},ServiceName:'{2}')", Caller.Id, Callee.Id, ServiceName);
            serviceName    = ServiceName;
            caller         = Caller;
            callee         = Callee;
            pendingMessage = RequestMessage;

            callerToken = Guid.NewGuid();
            calleeToken = Guid.NewGuid();
            log.Trace("Caller token is '{0}'.", callerToken);
            log.Trace("Callee token is '{0}'.", calleeToken);

            status = RelayConnectionStatus.WaitingForCalleeResponse;

            // Relay is created by caller's request, it will expire if the callee does not reply within reasonable time.
            timeoutTimer = new Timer(TimeoutCallback, status, CalleeResponseCallNotificationDelayMaxSeconds * 1000, Timeout.Infinite);

            log.Trace("(-)");
        }
Beispiel #2
0
        /// <summary>Initializes the class logger.</summary>
        public ApplicationServices(string LogPrefix)
        {
            string logName = "ProfileServer.Network.ApplicationServices";

            log = new PrefixLogger(logName, LogPrefix);
            log.Trace("()");

            log.Trace("(-)");
        }
        /// <summary>
        /// Creates the instance for a new outgoing TCP client.
        /// </summary>
        /// <param name="RemoteEndPoint">Target IP address and port this client will be connected to.</param>
        /// <param name="UseTls">true if TLS should be used for this TCP client, false otherwise.</param>
        /// <param name="ShutdownCancellationToken">Cancellation token of the parent component.</param>
        public OutgoingClient(IPEndPoint RemoteEndPoint, bool UseTls, CancellationToken ShutdownCancellationToken) :
            base(RemoteEndPoint, UseTls)
        {
            string logPrefix = string.Format("[=>{0}] ", RemoteEndPoint);

            log = new PrefixLogger("ProfileServer.Network.OutgoingClient", logPrefix);

            log.Trace("()");

            shutdownCancellationToken = ShutdownCancellationToken;

            log.Trace("(-)");
        }
Beispiel #4
0
        public SocketConnection(Uri uri, ConnectionSettings connectionSettings, BufferSettings bufferSettings, ILogger logger = null)
        {
            _idPrefix = $"conn-{uri.Host}:{uri.Port}-";
            _id       = $"{_idPrefix}{UniqueIdGenerator.GetId()}";
            _logger   = new PrefixLogger(logger, FormatPrefix(_id));

            _client    = new SocketClient(uri, connectionSettings.SocketSettings, bufferSettings, _logger);
            _authToken = connectionSettings.AuthToken;
            _userAgent = connectionSettings.UserAgent;
            Server     = new ServerInfo(uri);

            _responsePipeline = new ResponsePipeline(_logger);
        }
Beispiel #5
0
        public SocketConnection(Uri uri, ConnectionSettings connectionSettings, BufferSettings bufferSettings,
            IConnectionListener metricsListener = null, IDriverLogger logger = null)
        {
            _id = $"conn-{UniqueIdGenerator.GetId()}";
            _logger = new PrefixLogger(logger, FormatPrefix(_id));

            _client = new SocketClient(uri, connectionSettings.SocketSettings, bufferSettings, metricsListener, _logger);
            _authToken = connectionSettings.AuthToken;
            _userAgent = connectionSettings.UserAgent;
            Server = new ServerInfo(uri);

            _responseHandler = new MessageResponseHandler(_logger);
        }
Beispiel #6
0
        // for test only
        internal SocketConnection(ISocketClient socketClient, IAuthToken authToken,
                                  string userAgent, ILogger logger, IServerInfo server,
                                  IResponsePipeline responsePipeline = null)
        {
            Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient));
            Throw.ArgumentNullException.IfNull(authToken, nameof(authToken));
            Throw.ArgumentNullException.IfNull(userAgent, nameof(userAgent));
            Throw.ArgumentNullException.IfNull(server, nameof(server));

            _client    = socketClient;
            _authToken = authToken;
            _userAgent = userAgent;
            Server     = server;

            _id               = $"{_idPrefix}{UniqueIdGenerator.GetId()}";
            _logger           = new PrefixLogger(logger, FormatPrefix(_id));
            _responsePipeline = responsePipeline ?? new ResponsePipeline(logger);
        }
Beispiel #7
0
        // for test only
        internal SocketConnection(ISocketClient socketClient, IAuthToken authToken,
            string userAgent, IDriverLogger logger, IServerInfo server,
            IMessageResponseHandler messageResponseHandler = null)
        {
            Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient));
            Throw.ArgumentNullException.IfNull(authToken, nameof(authToken));
            Throw.ArgumentNullException.IfNull(userAgent, nameof(userAgent));
            Throw.ArgumentNullException.IfNull(server, nameof(server));

            _client = socketClient;
            _authToken = authToken;
            _userAgent = userAgent;
            Server = server;

            _id = $"conn-{UniqueIdGenerator.GetId()}";
            _logger = new PrefixLogger(logger, FormatPrefix(_id));
            _responseHandler = messageResponseHandler ?? new MessageResponseHandler(logger);
        }
Beispiel #8
0
        // const int DataSize = 4096;

        static void Main([NotNull][ItemNotNull] string[] args)
        {
            if (args.Length != 2)
            {
                PrintUsage();
                return;
            }

            string source      = args[0];
            string destination = args[1];

            if (!File.Exists(source))
            {
                Console.WriteLine("Source file does not exist");
                return;
            }

            var          initialLogger = new PrefixLogger("[Initial] ");
            var          infoLogger    = new PrefixLogger("[Sorter] ");
            IDataManager manager       = new FileDataManager(source, destination);

            string[] environmentArgs = new string[0];
            using (new Environment(ref environmentArgs))
            {
                var world = Communicator.world;
                initialLogger.Assert(world != null, "Could not retrieve world");
                int processors = world.Size;
                initialLogger.Assert(processors.IsPowerOfTwo(), "Number of processors should be power of two");
                int[] batch         = GetDataBatch(world, initialLogger, manager, processors);
                var   sorter        = new Sorter(batch, world, infoLogger);
                int   numberOfSteps = world.Size.IntegralBinaryLogarithm();

                for (int step = numberOfSteps - 1; step >= 0; step -= 1)
                {
                    sorter.Exchange(step);
                }

                var gathered = world.Gather(sorter.Sort(), 0);
                if (gathered != null)
                {
                    manager.SinkResult(gathered);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Asynchronous read and processing function for each client that connects to the TCP server.
        /// </summary>
        /// <param name="Client">Client that is connected to TCP server.</param>
        /// <remarks>The client is being handled in the processing loop until the connection to it
        /// is terminated by either side. This function implements reading the message from the network stream,
        /// which includes reading the message length prefix followed by the entire message.</remarks>
        private async void ClientHandlerAsync(Client Client)
        {
            this.log.Info("(Client.RemoteEndPoint:{0})", Client.RemoteEndPoint);

            string       prefix = string.Format("{0}[{1}] ", this.logPrefix, Client.RemoteEndPoint);
            PrefixLogger log    = new PrefixLogger(this.logName, prefix);

            clientList.AddNetworkPeer(Client);
            log.Debug("Client ID set to 0x{0:X16}.", Client.Id);

            await Client.ReceiveMessageLoop();

            // Free resources used by the client.
            clientList.RemoveNetworkPeer(Client);
            await Client.HandleDisconnect();

            Client.Dispose();

            log.Info("(-)");
        }
Beispiel #10
0
        /// <summary>
        /// Creates the encapsulation for a new TCP server client.
        /// </summary>
        /// <param name="Server">Role server that the client connected to.</param>
        /// <param name="TcpClient">TCP client class that holds the connection and allows communication with the client.</param>
        /// <param name="Id">Unique identifier of the client's connection.</param>
        /// <param name="UseTls">true if the client is connected to the TLS port, false otherwise.</param>
        /// <param name="KeepAliveIntervalSeconds">Number of seconds for the connection to this client to be without any message until the node can close it for inactivity.</param>
        public Client(TcpRoleServer Server, TcpClient TcpClient, ulong Id, bool UseTls, int KeepAliveIntervalSeconds)
        {
            this.TcpClient = TcpClient;
            this.Id        = Id;
            RemoteEndPoint = this.TcpClient.Client.RemoteEndPoint;

            server = Server;
            string logPrefix = string.Format("[{0}<=>{1}|0x{2:X16}] ", server.EndPoint, RemoteEndPoint, Id);
            string logName   = "HomeNet.Network.Client";

            this.log = new PrefixLogger(logName, logPrefix);

            log.Trace("(UseTls:{0},KeepAliveIntervalSeconds:{1})", UseTls, KeepAliveIntervalSeconds);

            messageProcessor = new MessageProcessor(server, logPrefix);

            this.KeepAliveIntervalSeconds = KeepAliveIntervalSeconds;
            NextKeepAliveTime             = DateTime.UtcNow.AddSeconds(this.KeepAliveIntervalSeconds);

            this.TcpClient.LingerState = new LingerOption(true, 0);
            this.TcpClient.NoDelay     = true;

            this.UseTls = UseTls;
            Stream      = this.TcpClient.GetStream();
            if (this.UseTls)
            {
                Stream = new SslStream(Stream, false, PeerCertificateValidationCallback);
            }

            MessageBuilder = new MessageBuilder(server.IdBase, new List <byte[]>()
            {
                new byte[] { 1, 0, 0 }
            }, Base.Configuration.Keys);
            ConversationStatus   = ClientConversationStatus.NoConversation;
            IsOurCheckedInClient = false;

            ApplicationServices = new ApplicationServices(logPrefix);

            log.Trace("(-)");
        }
Beispiel #11
0
        /// <summary>
        /// Creates a new TCP server to listen on specific IP endpoint.
        /// </summary>
        /// <param name="EndPoint">Specification of the interface and TCP port on which the TCP server should listen. IPAddress.Any is a valid value for the interface.</param>
        /// <param name="UseTls">Indication of whether to use TLS for this TCP server.</param>
        /// <param name="Roles">One or more roles of this server.</param>
        public TcpRoleServer(IPEndPoint EndPoint, bool UseTls, ServerRole Roles)
        {
            logPrefix = string.Format("[{0}/tcp{1}] ", EndPoint.Port, UseTls ? "_tls" : "");
            logName   = "HomeNet.Network.RoleServer";
            log       = new PrefixLogger(logName, logPrefix);

            this.UseTls   = UseTls;
            this.Roles    = Roles;
            this.EndPoint = EndPoint;

            ShutdownSignaling = new ComponentShutdown(Base.Components.GlobalShutdown);

            serverComponent = (Server)Base.ComponentDictionary["Network.Server"];
            clientList      = serverComponent.GetClientList();

            IsRunning = false;
            Listener  = new TcpListener(this.EndPoint);
            Listener.Server.LingerState = new LingerOption(true, 0);
            Listener.Server.NoDelay     = true;

            // We want to determine what types of clients do connect to this server.
            // This information is stored in ServerRoleForNodes dictionary.
            // If ServerRoleForNodes[R] is true for a role R, it means that that role is intended for nodes.
            // Thus if this server roles only consist of roles, for which ServerRoleForNodes[x] is false,
            // it means that the server is intended for clients use.
            IsServingClientsOnly = true;
            foreach (ServerRole role in Enum.GetValues(typeof(ServerRole)))
            {
                if (this.Roles.HasFlag(role) && ServerRoleForNodes[role])
                {
                    this.IsServingClientsOnly = false;
                    break;
                }
            }

            IdBase = ((uint)Roles << 24);
        }
Beispiel #12
0
        /// <summary>
        /// Creates the instance for a new TCP server client.
        /// </summary>
        /// <param name="Server">Role server that the client connected to.</param>
        /// <param name="TcpClient">TCP client class that holds the connection and allows communication with the client.</param>
        /// <param name="Id">Unique identifier of the client's connection.</param>
        /// <param name="UseTls">true if the client is connected to the TLS port, false otherwise.</param>
        /// <param name="KeepAliveIntervalSeconds">Number of seconds for the connection to this client to be without any message until the profile server can close it for inactivity.</param>
        public IncomingClient(TcpRoleServer Server, TcpClient TcpClient, ulong Id, bool UseTls, int KeepAliveIntervalSeconds) :
            base(TcpClient, UseTls, Server.IdBase)
        {
            this.Id = Id;
            server  = Server;
            string logPrefix = string.Format("[{0}<=>{1}|{2}] ", server.EndPoint, RemoteEndPoint, Id.ToHex());
            string logName   = "ProfileServer.Network.IncomingClient";

            log = new PrefixLogger(logName, logPrefix);

            log.Trace("(UseTls:{0},KeepAliveIntervalSeconds:{1})", UseTls, KeepAliveIntervalSeconds);

            messageProcessor = new MessageProcessor(server, logPrefix);

            this.KeepAliveIntervalSeconds = KeepAliveIntervalSeconds;
            NextKeepAliveTime             = DateTime.UtcNow.AddSeconds(this.KeepAliveIntervalSeconds);

            ConversationStatus   = ClientConversationStatus.NoConversation;
            IsOurCheckedInClient = false;

            ApplicationServices = new ApplicationServices(logPrefix);

            log.Trace("(-)");
        }
 public PrefixLoggerTest()
 {
     innerLogger = Substitute.For <IBasicLogger>();
     logger      = new PrefixLogger("MyMod", innerLogger);
 }
 public PrefixLoggerTest()
 {
     logger = new PrefixLogger("MyMod", innerLogger);
 }