Esempio n. 1
0
        /// <summary>
        /// Get an open socket from the connection pool.
        /// </summary>
        /// <returns>Socket returned from the pool or new socket
        /// opened.</returns>
        public SharedCacheTcpClient GetSocket()
        {
            #region Access Log
                        #if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
                        #endif
            #endregion Access Log

            SharedCacheTcpClient socket = null;
            bool stillCheckingSockets   = false;
            lock (bulkObject)
            {
                if (this.availableSockets.Count > 0)
                {
                    socket = this.availableSockets.Dequeue();
                    stillCheckingSockets = true;
                }
            }
            while (stillCheckingSockets)
            {
                if (socket.Connected)
                {
                    TimeSpan sp = DateTime.Now.Subtract(socket.LastUsed);
                    //TODO: read data from config file: SocketPoolTimeout
                    if (sp.Minutes >= 2)
                    {
                        socket.Close();
                        return(this.OpenSocket());
                    }
                    else
                    {
                        return(socket);
                    }
                }
                else
                {
                    if (socket != null)
                    {
                        // MAYBE we should consider to reconnect it instead to close it?
                        socket.Close();
                    }
                }
                stillCheckingSockets = false;
                lock (bulkObject)
                {
                    if (this.availableSockets.Count > 0)
                    {
                        socket = this.availableSockets.Dequeue();
                        stillCheckingSockets = true;
                    }
                }
            }
            return(this.OpenSocket());
        }
        /// <summary>
        /// Puts the server client.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="client">The client.</param>
        public static void PutServerClient(string host, SharedCacheTcpClient client)
        {
            #region Access Log
                        #if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + typeof(ManageServerTcpSocketConnectionPoolFactory).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
                        #endif
            #endregion Access Log

            instanceServer.PutSocketToPool(host, client);
        }
        /// <summary>
        /// Puts the socket to pool.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="socket">The socket.</param>
        public void PutSocketToPool(string host, SharedCacheTcpClient socket)
        {
            #region Access Log
#if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
#endif
#if DEBUG
            Debug.WriteLine(string.Format("put socket to pool: {0}", host));
#endif
            #endregion Access Log

            TcpSocketConnectionPool pool = pools[host];
            pool.PutSocket(socket);
        }
Esempio n. 4
0
 /// <summary>
 /// Return the given socket back to the socket pool.
 /// </summary>
 /// <param name="socket">Socket connection to return.</param>
 public void PutSocket(SharedCacheTcpClient socket)
 {
     #region Access Log
                 #if TRACE
     {
         Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
     }
                 #endif
     #endregion Access Log
     //TODO: Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolMinAvailableSize
     // if (this.availableSockets.Count < Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolMinAvailableSize)
     if (this.availableSockets.Count <= this.PoolSize)
     // if (this.availableSockets.Count < TcpSocketConnectionPool.POOL_SIZE)
     {
         if (socket != null)
         {
             if (socket.Connected)
             {
                 // Set the socket back to blocking and enqueue
                 socket.SetBlockingMode(true);
                 socket.LastUsed = DateTime.Now;
                 lock (bulkObject)
                 {
                     this.availableSockets.Enqueue(socket);
                 }
             }
             else
             {
                 socket.Close();
             }
         }
     }
     else
     {
         // Number of sockets is above the pool size, so just close it.
         socket.Close();
     }
 }
		/// <summary>
		/// Puts the socket to pool.
		/// </summary>
		/// <param name="host">The host.</param>
		/// <param name="socket">The socket.</param>
		public void PutSocketToPool(string host, SharedCacheTcpClient socket)
		{
			#region Access Log
#if TRACE
			
			{
				Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
#if DEBUG
			Debug.WriteLine(string.Format("put socket to pool: {0}", host));
#endif
			#endregion Access Log

			TcpSocketConnectionPool pool = pools[host];
			pool.PutSocket(socket);
		}
Esempio n. 6
0
        /// <summary>
        /// Validates this instance.
        /// </summary>
        internal void Validate()
        {
            #region Access Log
                        #if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
                        #endif
            #endregion Access Log

            if (this.PoolAvailable)
            {
                #region validate all open connections when they used last time
                for (int i = 0; i < this.availableSockets.Count; i++)
                {
                    SharedCacheTcpClient client = null;
                    lock (bulkObject)
                    {
                        client = this.availableSockets.Dequeue();
                    }
                    TimeSpan sp = DateTime.Now.Subtract(client.LastUsed);
                    // Console.WriteLine(@"last used: {0}m {1}s {2}ms", sp.Minutes, sp.Seconds, sp.Milliseconds);
                    if (sp.Minutes >= 2)
                    {
                        client.Dispose();
                    }
                    else if (client != null && !client.Connected)
                    {
                        // this will close the socket in case we have to much open sockets.
                        this.PutSocket(client);
                    }
                    else if (client != null)
                    {
                        lock (bulkObject)
                        {
                            this.availableSockets.Enqueue(client);
                        }
                    }
                }
                #endregion
            }
            else
            {
                #region try to enable pool in case its disabled
                if (CacheUtil.Ping(this.Host))
                {
                    this.Enable();
                    #region Logging
                    string msg = "Client could reconnect to host {0} and it enables this node.";
                                        #if TRACE
                    Console.WriteLine(msg, this.Host);
                                        #endif
                                        #if DEBUG
                    Console.WriteLine(msg, this.Host);
                                        #endif
                    Handler.LogHandler.Fatal(string.Format(msg, this.Host));
                    #endregion
                }
                else
                {
                    #region Logging
                    string msg = "Client could NOT reconnect to host {0} and keeps this node disabled";
                                        #if TRACE
                    Console.WriteLine(msg, this.Host);
                                        #endif
                                        #if DEBUG
                    Console.WriteLine(msg, this.Host);
                                        #endif
                    Handler.LogHandler.Fatal(string.Format(msg, this.Host));
                    #endregion
                }
                #endregion
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Sends this instance.
        /// </summary>
        /// <returns></returns>
        public bool Send()
        {
            #region Access Log
#if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
#endif
            #endregion Access Log

            Sockets.SharedCacheTcpClient client = null;
            StatusValue statusBeforeSending     = this.Status;
            try
            {
                if (statusBeforeSending != StatusValue.ReplicationRequest)
                {
                    client = Sockets.ManageClientTcpSocketConnectionPoolFactory.GetClient(this.hostname);
                    //try
                    //{
                    //
                    //}
                    //catch (Exception ex)
                    //{
                    //  Console.WriteLine(ex.ToString());
                    //}

                    // case for replication mode, choose another server node.
                    if (client == null && Provider.Cache.IndexusDistributionCache.SharedCache.ReplicatedServersList.Count > 0)
                    {
                        client = Sockets.ManageClientTcpSocketConnectionPoolFactory.GetClient(
                            Provider.Cache.IndexusDistributionCache.SharedCache.ReplicatedServersList[0].IpAddress
                            );
                    }
                }
                else
                {
                    // server to server node communication
                    client = Sockets.ManageServerTcpSocketConnectionPoolFactory.GetServerClient(this.hostname);
                }

                if (client != null)
                {
                    byte[] dataToSend = this.GetBytes();

                    #region Pre Logging
#if DEBUG
                    System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();
                    sp.Start();
                    if (this.ClientContext)
                    {
                        if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
                        {
                            #region Client
                            // Add request to log
                            Handler.LogHandler.Traffic(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
                    else
                    {
                        if (1 == Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
                        {
                            #region Server
                            // Add request to log
                            Handler.LogHandler.SyncInfo(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
#else
                    if (this.ClientContext)
                    {
                        if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
                        {
                            #region Client
                            // Add request to log
                            Handler.LogHandler.Traffic(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
                    else
                    {
                        if (1 == Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
                        {
                            #region Client
                            // Add request to log
                            Handler.LogHandler.SyncInfo(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
#endif
                    #endregion Pre Logging

                    // potential botleneck!!!
                    this.Copy(client.Send(dataToSend));

                    #region Post Logging
#if DEBUG
                    if (this.ClientContext)
                    {
                        if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
                        {
                            sp.Stop();
                            #region Client
                            // Add request to log
                            Handler.LogHandler.Traffic(
                                string.Format(Constants.POSTTRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              this.GetBytes().LongLength,
                                              sp.ElapsedMilliseconds
                                              )
                                );
                            #endregion
                        }
                    }
                    else
                    {
                        if (1 == Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
                        {
                            sp.Stop();
                            #region Server
                            // Add request to log
                            Handler.LogHandler.SyncInfo(
                                string.Format(Constants.POSTTRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              this.GetBytes().LongLength,
                                              sp.ElapsedMilliseconds
                                              )
                                );
                            #endregion
                        }
                    }
#else
                    if (this.ClientContext)
                    {
                        if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
                        {
                            #region Client
                            // Add request to log
                            Handler.LogHandler.Traffic(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
                    else
                    {
                        if (1 == Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
                        {
                            #region Server
                            // Add request to log
                            Handler.LogHandler.SyncInfo(
                                string.Format(Constants.TRAFFICLOG,
                                              client.ServerConnection.LocalEndPoint,
                                              System.Threading.Thread.CurrentThread.ManagedThreadId,
                                              this.Id,
                                              this.Action.ToString(),
                                              this.Status.ToString(),
                                              dataToSend.LongLength
                                              )
                                );
                            #endregion
                        }
                    }
#endif
                    #endregion Postlogging
                    switch (this.action)
                    {
                    case ActionValue.Successful:
                    {
                        // Action done successfully;
                        return(true);
                    }

                    case ActionValue.Error:
                    {
                        // TODO: Error handling somehow, maybe we need to extend
                        // to return an error code or something similar.
                        //try
                        //{
                        //  //
                        //  //CacheException ex = Formatters.Serialization.BinaryDeSerialize<CacheException>(this.Payload);
                        //  //Console.WriteLine(ex.Title);
                        //}
                        //catch (Exception ex)
                        //{}
                        Handler.LogHandler.Error("Error, check log files!");
                        return(false);
                    }
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("Could not receive Socket Client from pool {0}", this.hostname));
                    Handler.LogHandler.Force(string.Format("Could not receive Socket Client from pool {0}", this.hostname));
                    Handler.LogHandler.Fatal(string.Format("Could not receive Socket Client from pool {0}", this.hostname));
                    return(false);
                }
            }
            finally
            {
                if (client != null)
                {
                    if (statusBeforeSending != StatusValue.ReplicationRequest)
                    {
                        Sockets.ManageClientTcpSocketConnectionPoolFactory.PutClient(this.hostname, client);
                    }
                    else
                    {
                        Sockets.ManageServerTcpSocketConnectionPoolFactory.PutServerClient(this.hostname, client);
                    }
                }
            }

            return(false);
        }
		/// <summary>
		/// Puts the client back to the pool
		/// </summary>
		/// <param name="host">The host.</param>
		/// <param name="client">The client.</param>
		public static void PutClient(string host, SharedCacheTcpClient client)
		{
			#region Access Log
#if TRACE
			
			{
				Handler.LogHandler.Tracking("Access Method: " + typeof(ManageClientTcpSocketConnectionPoolFactory).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			instance.PutSocketToPool(host, client);
		}