Пример #1
0
 public string CanApplyHotConfiguration(string cacheId, CacheServerConfig config)
 {
     ManagementCommand command = GetManagementCommand(ManagementUtil.MethodName.CanApplyHotConfig);
     command.Parameters.AddParameter(cacheId);
     command.Parameters.AddParameter(config);
     return ExecuteCommandOnCacehServer(command) as string;
 }
Пример #2
0
        /// <summary>
        /// Get the list of running server caches
        /// </summary>
        /// <returns></returns>
        public virtual Hashtable GetServerCaches()
        {
            try
            {
                Hashtable   cacheList = new Hashtable();
                IDictionary coll      = _server.GetCacheProps();

                IDictionaryEnumerator ie = coll.GetEnumerator();
                while (ie.MoveNext())
                {
                    if (ie.Value is CacheServerConfig)
                    {
                        CacheServerConfig cacheProp = (CacheServerConfig)ie.Value;
                        if (cacheProp.Cluster != null)
                        {
                            if ((cacheProp.Cluster.Topology == "partitioned-server") || (cacheProp.Cluster.Topology == "replicated-server"))
                            {
                                cacheList.Add(ie.Key, cacheProp);
                            }
                        }
                    }
                    else if (ie.Value is Hashtable)
                    {
                        cacheList.Add(ie.Key, ie.Value);
                    }
                }
                return(cacheList);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #3
0
        /// <summary>
        /// Get CacheServerConfig for the specific cache
        /// </summary>
        /// <returns></returns>
        public CacheServerConfig GetConfigDom()
        {
            try
            {
                CacheServerConfig[] configs   = LoadConfig(this._configFileName);
                CacheServerConfig   configDom = null;
                if (configs != null)
                {
                    foreach (CacheServerConfig config in configs)
                    {
                        if (config.Name != null && config.Name.Equals(this._configSection, StringComparison.OrdinalIgnoreCase))
                        {
                            configDom = config;
                            break;
                        }
                    }
                }

                if (configDom != null)
                {
                    return(configDom);
                }
            }
            catch (Exception e)
            {
                throw new ConfigurationException("Error occured while reading configuration", e);
            }
            throw new ConfigurationException(@"Specified config section '" + this._configSection + @"' not found in file '" + this._configFileName + @"'. If it is a cache, it must be registered properly on this machine.");
        }
Пример #4
0
        public CacheServerConfig GetServerConfiguration(string server, int port, string cacheId)
        {
            CacheServerConfig serverConfig = null;

            if (port != -1)
            {
                NCache.Port = port;
            }
            if (port == -1)
            {
                NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort: CacheConfigManager.HttpPort;
            }
            if (server != null && server != string.Empty)
            {
                NCache.ServerName = server;
            }
            cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
            if (cacheServer != null)
            {
                serverConfig = cacheServer.GetCacheConfiguration(cacheId);
                if (serverConfig == null)
                {
                    throw new Exception("Specified cache is not registered on given server.");
                }
            }
            return(serverConfig);
        }
        /// <summary>
        /// Initialize a registered cache given by the ID.
        /// </summary>
        /// <param name="cacheId">A string identifier of configuration.</param>
        static public CacheServerConfig GetConfigDom(string cacheId, string filePath, bool inProc)
        {
            try
            {
                XmlConfigReader   configReader = new XmlConfigReader(filePath, cacheId);
                CacheServerConfig config       = configReader.GetConfigDom();
                CultureInfo       cultureInfo  = Thread.CurrentThread.CurrentCulture;
                if (config == null)
                {
                    return(config);
                }

                if (!inProc)
                {
                    inProc = config.InProc;
                }

                if (inProc)
                {
                    return(config);
                }
                return(null);
            }



            catch (ManagementException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new ManagementException(e.Message, e);
            }
        }
Пример #6
0
        /// <summary>
        /// Populates the object from specified configuration object.
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        internal static CacheConfig FromConfiguration(CacheServerConfig configuration)
        {
            CacheConfig cConfig = null;

            if (configuration != null)
            {
                cConfig = new CacheConfig();

                cConfig._useInProc = configuration.InProc;
                cConfig.CacheId    = configuration.Name;


                if (configuration.Cluster != null)
                {
                    if (configuration.Cluster.Channel != null)
                    {
                        cConfig._clusterPort      = configuration.Cluster.Channel.TcpPort;
                        cConfig._clusterPortRange = configuration.Cluster.Channel.PortRange;
                    }
                    cConfig._useHeartBeat = configuration.Cluster.UseHeartbeat;
                    cConfig._servers      = FromHostListToServers(configuration.Cluster.Channel.InitialHosts);

                    string topology = string.Empty;
                    switch (configuration.Cluster.Topology)
                    {
                    case "partitioned": topology = "partitioned-server"; break;

                    case "replicated": topology = "replicated-server"; break;
                    }
                    cConfig._cacheType = topology;
                }
                else
                {
                    cConfig._cacheType = "local-cache";
                }

                if (configuration.Cleanup != null)
                {
                    cConfig._cleanInterval = configuration.Cleanup.Interval * 1000; ///to millisec
                }

                if (configuration.EvictionPolicy != null)
                {
                    cConfig._evictRatio = (float)Decimal.ToDouble(configuration.EvictionPolicy.EvictionRatio);
                }

                if (configuration.Storage != null)
                {
                    cConfig._cacheMaxSize = configuration.Storage.Size * 1048576; ///from mb to bytes
                }

                if (configuration.Log != null)
                {
                    cConfig._errorLogsEnabled    = configuration.Log.TraceErrors;
                    cConfig._detailedLogsEnabled = configuration.Log.TraceDebug;
                }
            }
            return(cConfig);
        }
Пример #7
0
        public static void StartCache(string cacheId, string serverName, int port, string userId, string password)
        {
            ICacheServer cs = null;

            CacheService      cacheService = new NCacheRPCService(null);
            CacheServerConfig config       = null;

            try
            {
                cacheService.ServerName = serverName;
                cacheService.Port       = port;
                cs = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                if (cs != null)
                {
                    config = cs.GetCacheConfiguration(cacheId);
                    if (config != null)
                    {
                        if (!config.InProc)
                        {
                            cs.StartCache(cacheId);
                        }
                    }
                    else
                    {
                        throw new ManagementException("Unable to Start Cache. Specified cache is not registered.");
                    }
                }
            }

            catch (SecurityException ex)
            {
                if (cs != null)
                {
                    cs.Dispose();
                    cs = null;
                }
                throw ex;
            }

            catch (Exception ex)
            {
                if (cs != null)
                {
                    cs.Dispose();
                    cs = null;
                }
                throw new ManagementException(ex.Message);
            }
            finally
            {
                if (cs != null)
                {
                    cs.Dispose();
                }
                cacheService.Dispose();
            }
        }
Пример #8
0
        void StartCacheOnServer()
        {
            OutputProvider.WriteLine("Licensed to use FREE of cost. Use As-is without support.\n");
            string cacheIp = string.Empty;

            try
            {
                ICacheServer      cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                CacheServerConfig config      = null;
                if (cacheServer != null)
                {
                    cacheIp = cacheServer.GetClusterIP();
                    foreach (string cache in CachesList)
                    {
                        try
                        {
                            config = cacheServer.GetCacheConfiguration(cache);
                            if (config != null && config.InProc)
                            {
                                throw new Exception("InProc caches cannot be started explicitly.");
                            }

                            OutputProvider.WriteLine("Starting cache '{0}' on server {1}:{2}.", cache, cacheIp, NCache.Port);

                            cacheServer.StartCache(cache, _partId);


                            OutputProvider.WriteLine("'{0}' successfully started on server {1}:{2}.\n", cache, cacheIp,
                                                     NCache.Port);
                        }

                        catch (Exception e)
                        {
                            OutputProvider.WriteErrorLine("Failed to start '{0}' on server {1}.", cache,
                                                          cacheIp);
                            OutputProvider.WriteErrorLine(e.ToString() + "\n");
                        }
                    }
                }
            }
            catch (ManagementException ex)
            {
                OutputProvider.WriteErrorLine("Error : {0}", "NCache service could not be contacted on server");

                OutputProvider.WriteErrorLine(ex.ToString());
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error : {0}", e.Message);
                OutputProvider.WriteErrorLine(e.ToString());
            }
            finally
            {
                NCache.Dispose();
            }
        }
Пример #9
0
        public override string CanApplyHotConfiguration(string cacheId, CacheServerConfig config)
        {
            Exception e = CanApplyHotConfig(config);

            if (e != null)
            {
                return(e.Message);
            }
            return(null);
        }
Пример #10
0
        /// <summary>
        /// Get string props representation of config
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private static string GetProps(CacheServerConfig config)
        {
            ///[Ata] This is until we change the use of properties in Cache
            ///from props stirng or hashtable to Dom
            ///
            Hashtable table = ConfigConverter.ToHashtable(config);
            string    props = ConfigReader.ToPropertiesString(table);

            return(props);
        }
Пример #11
0
        /// <summary>
        /// Update TCP cache settings that includes updated list of TCP members
        /// </summary>
        /// <param name="cacheId"></param>
        /// <param name="props"></param>
        /// <exception cref="ArgumentNullException">cacheId is a null reference (Nothing in Visual Basic).</exception>
        public bool ApplyCacheConfiguration(string cacheId, CacheServerConfig props, bool hotApply)

        {
            ManagementCommand command = GetManagementCommand(ManagementUtil.MethodName.ApplyCacheConfiguration);
            command.Parameters.AddParameter(cacheId);
            command.Parameters.AddParameter(props);
            
            command.Parameters.AddParameter(hotApply);

            return (bool)ExecuteCommandOnCacehServer(command);
        }
Пример #12
0
        /// <summary>
        /// Adds Server Node
        /// </summary>
        /// <param name="cacheId"></param>
        /// <param name="config"></param>
        /// <param name="partId"></param>
        /// <param name="overwrite"></param>
        /// <param name="hotApply"></param>
        /// <returns></returns>
        public bool RegisterCache(string cacheId, CacheServerConfig config, string partId, bool overwrite, bool hotApply, bool isLocalNode)
        {
            //overload 1
            ManagementCommand command = GetManagementCommand(ManagementUtil.MethodName.RegisterCache, 1);
            command.Parameters.AddParameter(cacheId);
            command.Parameters.AddParameter(config);
            command.Parameters.AddParameter(partId);
            command.Parameters.AddParameter(overwrite);
            command.Parameters.AddParameter(hotApply);
            command.Parameters.AddParameter(isLocalNode);

            return (bool)ExecuteCommandOnCacehServer(command);
        }
Пример #13
0
 public Exception CanApplyHotConfig(CacheServerConfig config)
 {
     if (cacheInfo != null)
     {
         if (cacheInfo != null)
         {
             InstrumentCache cache = cacheInfo.Cache;
             if (cache != null)
             {
                 return(cacheInfo.Cache.CanApplyHotConfig(config.Storage.Size * 1024 * 1024));
             }
         }
     }
     return(null);
 }
Пример #14
0
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: private static Alachisoft.NCache.Config.Dom.CacheServerConfig[] convertToOldDom(Alachisoft.NCache.Config.NewDom.CacheServerConfig[] newCacheConfigsList) throws Exception
        private static Alachisoft.NCache.Config.Dom.CacheServerConfig[] convertToOldDom(Alachisoft.NCache.Config.NewDom.CacheServerConfig[] newCacheConfigsList)
        {
            Alachisoft.NCache.Config.Dom.CacheServerConfig[] oldCacheConfigsList = new CacheServerConfig[newCacheConfigsList.Length];

            for (int index = 0; index < newCacheConfigsList.Length; index++)
            {
                try
                {
                    oldCacheConfigsList[index] = Alachisoft.NCache.Config.NewDom.DomHelper.convertToOldDom(newCacheConfigsList[index]);
                }
                catch (Exception ex)
                {
                }
            }
            return(oldCacheConfigsList);
        }
Пример #15
0
        /// <summary>
        /// Internal method that actually creates the cache. A HashMap containing the config parameters
        /// is passed to this method.
        /// </summary>
        /// <param name="propertyTable">contains the properties provided by the user in the for of Hashtable</param>
        /// <param name="itemAdded">item added handler</param>
        /// <param name="itemRemoved">item removed handler</param>
        /// <param name="itemUpdated">item updated handler</param>
        /// <param name="cacheMiss">cache miss handler</param>
        /// <param name="cacheCleared">cache cleared handler</param>
        /// <returns>return the Cache object</returns>
        static private Cache CreateFromProperties(IDictionary properties,
                                                  CacheServerConfig config,
                                                  ItemAddedCallback itemAdded,
                                                  ItemRemovedCallback itemRemoved,
                                                  ItemUpdatedCallback itemUpdated,
                                                  CacheClearedCallback cacheCleared,
                                                  CustomRemoveCallback customRemove,
                                                  CustomUpdateCallback customUpdate,
                                                  string userId,
                                                  string password,
                                                  bool isStartingAsMirror,
                                                  bool twoPhaseInitialization)
        {
            Cache cache = new Cache();

            cache.Configuration = config;

            if (itemAdded != null)
            {
                cache.ItemAdded += itemAdded;
            }
            if (itemRemoved != null)
            {
                cache.ItemRemoved += itemRemoved;
            }
            if (itemUpdated != null)
            {
                cache.ItemUpdated += itemUpdated;
            }
            if (cacheCleared != null)
            {
                cache.CacheCleared += cacheCleared;
            }

            if (customRemove != null)
            {
                cache.CustomRemoveCallbackNotif += customRemove;
            }
            if (customUpdate != null)
            {
                cache.CustomUpdateCallbackNotif += customUpdate;
            }

            cache.Initialize(properties, true, isStartingAsMirror, twoPhaseInitialization);
            return(cache);
        }
Пример #16
0
        public static CacheServerConfig GetCacheDom(string cacheId, string userId, string password, bool inproc)
        {
            string            filePath = GetBaseFilePath("config.ncconf");
            CacheServerConfig dom      = null;

            if (filePath != null)
            {
                try
                {
                    dom = ThinClientConfigManager.GetConfigDom(cacheId, filePath, userId, password, inproc);
                }
                catch (ManagementException exception)
                {
                }
            }

            return(dom);
        }
Пример #17
0
        private static Alachisoft.NCache.Config.Dom.CacheServerConfig[] convertToOldDom(Alachisoft.NCache.Config.NewDom.CacheServerConfig[] newCacheConfigsList)
        {
            IList <Alachisoft.NCache.Config.Dom.CacheServerConfig> oldCacheConfigsList = new List <Alachisoft.NCache.Config.Dom.CacheServerConfig>();

            for (int index = 0; index < newCacheConfigsList.Length; index++)
            {
                try
                {
                    oldCacheConfigsList.Add(Alachisoft.NCache.Config.NewDom.DomHelper.convertToOldDom(newCacheConfigsList[index]));
                }
                catch (Exception)
                {
                }
            }
            Alachisoft.NCache.Config.Dom.CacheServerConfig[] oldCacheConfigsArray = new CacheServerConfig[oldCacheConfigsList.Count];
            oldCacheConfigsList.CopyTo(oldCacheConfigsArray, 0);
            return(oldCacheConfigsArray);
        }
Пример #18
0
        /// <summary>
        /// Load all the config sections from the configuration file.
        /// </summary>
        static private void LoadConfiguration(string cacheName)
        {
            try
            {
                CacheServerConfig[] configs = CacheConfigManager.GetConfiguredCaches();
                //Just need to call the static block - stupid logik i know
                Alachisoft.NCache.Util.MiscUtil.RegisterCompactTypes(null);
                if (configs != null)
                {
                    for (int i = 0; i < configs.Length; i++)
                    {
                        CacheServerConfig config = configs[i];
                        if (config != null && !String.IsNullOrEmpty(cacheName) && cacheName.ToLower().Equals(config.Name.ToLower()))
                        {
                            /// Until we completely move to using dom based configuration
                            ///we have to convert it to string props
                            string props = GetProps(config);
                            // all but the listed cache types are loaded in s_caches table.

                            string cacheId = config.Name.ToLower();

                            if (cacheInfo == null)
                            {
                                cacheInfo            = new CacheInfo();
                                cacheInfo.Cache      = new LeasedCache(props);
                                cacheInfo.CacheName  = cacheName;
                                cacheInfo.CacheProps = config;
                            }
                            else
                            {
                                cacheInfo.CacheProps = config;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                string msg = String.Format("CacheServer failed to load configuration information, Error {0}",
                                           e.Message);
                AppUtil.LogEvent(msg, EventLogEntryType.Warning);
            }
        }
Пример #19
0
        /// <summary>
        /// Internal method that actually creates the cache. A HashMap containing the config parameters
        /// is passed to this method.
        /// </summary>
        /// <param name="propertyTable">contains the properties provided by the user in the for of Hashtable</param>
        /// <param name="itemAdded">item added handler</param>
        /// <param name="itemRemoved">item removed handler</param>
        /// <param name="itemUpdated">item updated handler</param>
        /// <param name="cacheMiss">cache miss handler</param>
        /// <param name="cacheCleared">cache cleared handler</param>
        /// <returns>return the Cache object</returns>
        static private Cache CreateFromProperties(IDictionary properties,
                                                  CacheServerConfig config,
                                                  CustomRemoveCallback customRemove,
                                                  CustomUpdateCallback customUpdate,
                                                  bool isStartingAsMirror,
                                                  bool twoPhaseInitialization)
        {
            Cache cache = new Cache();

            cache.Configuration = config;
            if (customRemove != null)
            {
                cache.CustomRemoveCallbackNotif += customRemove;
            }
            if (customUpdate != null)
            {
                cache.CustomUpdateCallbackNotif += customUpdate;
            }

            cache.Initialize(properties, true, isStartingAsMirror, twoPhaseInitialization);
            return(cache);
        }
Пример #20
0
 /// <summary>
 /// Load all the config sections from the configuration file.
 /// </summary>
 static private void LoadConfiguration(string cacheName)
 {
     try
     {
         CacheServerConfig[] configs = CacheConfigManager.GetConfiguredCaches();
         Alachisoft.NCache.Util.MiscUtil.RegisterCompactTypes();
         if (configs != null)
         {
             for (int i = 0; i < configs.Length; i++)
             {
                 CacheServerConfig config = configs[i];
                 if (config != null && !String.IsNullOrEmpty(cacheName) && cacheName.ToLower().Equals(config.Name.ToLower()))
                 {
                     string props   = GetProps(config);
                     string cacheId = config.Name.ToLower();
                     if (cacheInfo == null)
                     {
                         cacheInfo            = new CacheInfo();
                         cacheInfo.Cache      = new LeasedCache(props);
                         cacheInfo.CacheName  = cacheName;
                         cacheInfo.CacheProps = config;
                     }
                     else
                     {
                         cacheInfo.CacheProps = config;
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         string msg = String.Format("CacheServer failed to load configuration information, Error {0}",
                                    e.Message);
         AppUtil.LogEvent(msg, EventLogEntryType.Warning);
     }
 }
Пример #21
0
        public static void AddCache(string cacheId, CacheServerConfig config)
        {
            LoadXml();

            if (_configuration != null)
            {
                if (_configuration.CacheConfigurationsMap == null)
                {
                    _configuration.CacheConfigurationsMap = new Dictionary <string, CacheConfiguration>();
                }

                if (!_configuration.CacheConfigurationsMap.ContainsKey(cacheId.ToLower()))
                {
                    CacheConfiguration cacheConfiguration = new CacheConfiguration();
                    cacheConfiguration.CacheId = cacheId;
                    cacheConfiguration.BindIp  = BindIP; // Internal static property set for local node.
                    if (config.Cluster != null && config.Cluster.Nodes != null)
                    {
                        if (!String.IsNullOrEmpty(config.Cluster.Topology))
                        {
                            cacheConfiguration.LoadBalance = config.Cluster.Topology.Equals("replicated-server");
                        }

                        if (config.Cluster.Nodes.Count > 1)
                        {
                            // Extract server names from config
                            string[] serverList = new string[config.Cluster.NodeIdentities.Count];
                            for (int i = 0; i < serverList.Length; i++)
                            {
                                serverList[i] = config.Cluster.NodeIdentities[i].NodeName;
                            }

                            // Sort priority list i.e. local node at top
                            string[] copyServerList = new string[serverList.Length];
                            int      nodeCount      = 1;
                            int      bindIPPosition = Array.IndexOf(serverList, cacheConfiguration.BindIp);
                            if (bindIPPosition == -1)
                            {
                                for (int serverListCount = 0; serverListCount < serverList.Length; serverListCount++)
                                {
                                    cacheConfiguration.AddServer(serverList[serverListCount], serverListCount);
                                }
                            }
                            else
                            {
                                copyServerList[0] = serverList[bindIPPosition];
                                cacheConfiguration.AddServer(copyServerList[0], 0);
                                for (int serverListCount = 0; serverListCount < serverList.Length; serverListCount++)
                                {
                                    if (serverListCount == bindIPPosition)
                                    {
                                        continue;
                                    }

                                    copyServerList[nodeCount] = serverList[serverListCount];
                                    cacheConfiguration.AddServer(copyServerList[nodeCount], nodeCount);

                                    nodeCount++;
                                }
                            }
                        }
                        else
                        {
                            if (config.Cluster.Nodes.Count > 0)
                            {
                                cacheConfiguration.AddServer(config.Cluster.NodeIdentities[0].NodeName, 0);
                            }
                        }
                    }
                    else
                    {
                        cacheConfiguration.AddLocalServer();
                    }
                    _configuration.CacheConfigurationsMap[cacheId.ToLower()] = cacheConfiguration;
                }
            }

            SaveConfiguration();
        }
Пример #22
0
        private static Cache InitializeCacheInternal(string cacheId, CacheInitParams initParams)
        {
            if (cacheId == null)
            {
                throw new ArgumentNullException("cacheId");
            }
            if (cacheId == string.Empty)
            {
                throw new ArgumentException("cacheId cannot be an empty string");
            }

            CacheMode mode = initParams.Mode;

            int maxTries = 2;

            try
            {
                CacheServerConfig config = null;

                if (mode != CacheMode.OutProc)
                {
                    do
                    {
                        try
                        {
                            config = DirectoryUtil.GetCacheDom(cacheId, mode == CacheMode.InProc);
                        }
                        catch (Exception ex)
                        {
                            if (mode == CacheMode.Default)
                            {
                                mode = CacheMode.OutProc;
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                        if (config != null)
                        {
                            switch (mode)
                            {
                            case CacheMode.InProc: config.InProc = true; break;

                            case CacheMode.OutProc: config.InProc = false; break;
                            }
                        }
                        break;
                    } while (maxTries > 0);
                }

                lock (typeof(NCache))
                {
                    Cache primaryCache = null;

                    lock (s_webCaches)
                    {
                        if (!s_webCaches.Contains(cacheId))
                        {
                            CacheImplBase cacheImpl = null;

                            if (config != null && config.InProc)
                            {
                                Alachisoft.NCache.Caching.Cache ncache = null;
                                Cache cache = null;
                                maxTries = 2;
                                do
                                {
                                    try
                                    {
                                        CacheConfig cacheConfig = CacheConfig.FromDom(config);

                                        if (Web.Caching.APILogging.DebugAPIConfiguraions.LoggingEnabled)
                                        {
                                            cache = new WrapperCache(new Cache(null, cacheConfig));
                                        }
                                        else
                                        {
                                            cache = new Cache(null, cacheConfig);
                                        }

                                        ncache = CacheFactory.CreateFromPropertyString(cacheConfig.PropertyString, config,
                                                                                       false, false);

                                        cacheImpl       = new InprocCache(ncache, cacheConfig, cache);
                                        cache.CacheImpl = cacheImpl;

                                        if (primaryCache == null)
                                        {
                                            primaryCache = cache;
                                        }
                                        break;
                                    }
                                    catch (Exception) { }
                                } while (maxTries > 0);
                            }
                            else
                            {
                                maxTries = 2;
                                do
                                {
                                    try
                                    {
                                        // does an AddRef() internally.

                                        PerfStatsCollector2 perfStatsCollector = new PerfStatsCollector2(cacheId, false);

                                        if (Web.Caching.APILogging.DebugAPIConfiguraions.LoggingEnabled)
                                        {
                                            primaryCache = new WrapperCache(new Cache(null, cacheId, perfStatsCollector));
                                        }
                                        else
                                        {
                                            primaryCache = new Cache(null, cacheId, perfStatsCollector);
                                        }
                                        cacheImpl = new RemoteCache(cacheId, primaryCache, initParams, perfStatsCollector);

                                        perfStatsCollector.InitializePerfCounters(false);
                                        primaryCache.CacheImpl = cacheImpl;

                                        break;
                                    }
                                    catch (OperationNotSupportedException ex)
                                    {
                                        throw ex;
                                    }
                                } while (maxTries > 0);
                            }

                            if (primaryCache != null)
                            {
                                primaryCache.InitializeCompactFramework();
                                s_webCaches.AddCache(cacheId, primaryCache);
                            }
                        }
                        else
                        {
                            lock (s_webCaches.GetCache(cacheId))
                            {
                                primaryCache = s_webCaches.GetCache(cacheId) as Cache;
                                primaryCache.AddRef();
                            }
                        }
                    }

                    lock (s_webCache)
                    {
                        // it is first cache instance.
                        if (s_webCache.CacheImpl == null)
                        {
                            primaryCache.ExceptionsEnabled = ExceptionsEnabled;
                            s_webCache = primaryCache;
                        }
                    }
                    return(primaryCache);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #23
0
        public static Dictionary <string, TopicStats> GetTopicStat(string cacheName, string initialNodeName, Runtime.CacheManagement.CacheContext context, int port)
        {
            CacheService cacheService = GetCacheService(context);

            if (port != 0)
            {
                cacheService.Port = port;
            }
            string            startingNode      = initialNodeName;
            CacheServerConfig cacheServerConfig = null;
            ICacheServer      cacheServer       = null;



            try
            {
                if (initialNodeName.Equals(string.Empty))
                {
                    cacheServerConfig = GetCacheConfigThroughClientConfig(cacheName, port, context);
                    if (cacheServerConfig == null)
                    {
                        throw new ManagementException("cache with name " + cacheName + " not found in " + config);
                    }
                }
                else
                {
                    cacheService.ServerName = initialNodeName;
                    cacheServer             = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                    if (cacheServer == null)
                    {
                        throw new ManagementException("provided initial node not available");
                    }

                    cacheServerConfig = cacheServer.GetCacheConfiguration(cacheName);
                    if (cacheServerConfig == null)
                    {
                        throw new ManagementException("cache with name " + cacheName + " not registered on specified node");
                    }
                }

                //For Local Cache
                if (cacheServerConfig.CacheType.Equals(LOCALCACHE, StringComparison.OrdinalIgnoreCase))
                {
                    if (cacheServerConfig.InProc)
                    {
                        throw new ArgumentException("API is not supported for Local Inproc Cache");
                    }

                    cacheService.ServerName = Environment.MachineName;
                    cacheServer             = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                    if (cacheServer != null && cacheServer.IsRunning(cacheName))
                    {
                        return(cacheServer.GetTopicStats(cacheServerConfig.Name));
                    }
                }
                //For Clustered Cache
                else
                {
                    Dictionary <string, TopicStats> topicWiseStat = new Dictionary <string, TopicStats>();
                    ArrayList initialHost = InitialHostList(cacheServerConfig.Cluster.Channel.InitialHosts);
                    foreach (object host in initialHost)
                    {
                        try
                        {
                            cacheService.ServerName = (string)host;
                            cacheServer             = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                            if (cacheServer.IsRunning(cacheName))
                            {
                                Dictionary <string, TopicStats> NodeWisetopicStat = cacheServer.GetTopicStats(cacheServerConfig.Name);
                                if (NodeWisetopicStat != null)
                                {
                                    foreach (var item in NodeWisetopicStat)
                                    {
                                        if (!topicWiseStat.ContainsKey(item.Key))
                                        {
                                            item.Value.TopicName = item.Key;
                                            topicWiseStat.Add(item.Key, ((TopicStats)item.Value.Clone()));
                                        }
                                        else
                                        {
                                            TopicStats topicStat = topicWiseStat[item.Key];
                                            topicStat.CurrentMessageCount += item.Value.CurrentMessageCount;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    return(topicWiseStat);
                }
            }
            catch (Exception ex)
            {
                throw new ManagementException(ex.Message);
            }
            finally
            {
                if (cacheServer != null)
                {
                    cacheServer.Dispose();
                }
                cacheService.Dispose();
            }
            return(null);
        }
Пример #24
0
 public CacheRegisterationInfo(CacheServerConfig cacheConfig, ArrayList nodesList, ArrayList affectedPartitions)
 {
     _updatedCacheConfig = cacheConfig;
     _affectedNodesList  = nodesList;
     _affectedPartitions = affectedPartitions;
 }
Пример #25
0
 public void Deserialize(Runtime.Serialization.IO.CompactReader reader)
 {
     _updatedCacheConfig = reader.ReadObject() as CacheServerConfig;
     _affectedNodesList  = reader.ReadObject() as ArrayList;
     _affectedPartitions = reader.ReadObject() as ArrayList;
 }
Пример #26
0
        /// <summary>
        /// This overload is used to call the Internal method that actually creates the cache.
        /// </summary>
        /// <param name="propertyString"></param>
        /// <returns></returns>
        static public Cache CreateFromPropertyString(string propertyString, CacheServerConfig config, bool isStartedAsMirror, bool twoPhaseInitialization)
        {
            ConfigReader propReader = new PropsConfigReader(propertyString);

            return(CreateFromProperties(propReader.Properties, config, null, null, isStartedAsMirror, twoPhaseInitialization));
        }
Пример #27
0
        /// <summary>
        /// Populates the object from specified configuration object.
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static CacheConfig FromDom(CacheServerConfig config)
        {
            Hashtable props = ConfigConverter.ToHashtable(config);

            return(FromProperties(props));
        }
Пример #28
0
        private static Cache InitializeCacheInternal(string cacheId, CacheInitParams initParams,
                                                     bool isRemoveCache = true)
        {
            if (cacheId == null)
            {
                throw new ArgumentNullException("cacheId");
            }
            if (cacheId == string.Empty)
            {
                throw new ArgumentException("cacheId cannot be an empty string");
            }

            CacheMode mode = initParams.Mode;


            int maxTries = 2;

            try
            {
                CacheServerConfig config = null;

                if (mode != CacheMode.OutProc)
                {
                    do
                    {
                        try
                        {
                            config = DirectoryUtil.GetCacheDom(cacheId, mode == CacheMode.InProc);
                        }


                        catch (Exception ex)
                        {
                            if (mode == CacheMode.Default)
                            {
                                mode = CacheMode.OutProc;
                            }
                            else
                            {
                                throw ex;
                            }
                        }

                        if (config != null)
                        {
                            if (config.CacheType.ToLower().Equals("clustered-cache"))
                            {
                                throw new Exception("Cluster cache cannot be initialized in In-Proc mode.");
                            }

                            switch (mode)
                            {
                            case CacheMode.InProc:
                                config.InProc = true;
                                break;

                            case CacheMode.OutProc:
                                config.InProc = false;
                                break;
                            }
                        }

                        break;
                    } while (maxTries > 0);
                }

                lock (typeof(NCache))
                {
                    Cache primaryCache = null;

                    lock (s_webCaches)
                    {
                        if (!s_webCaches.Contains(cacheId))
                        {
                            CacheImplBase cacheImpl = null;

                            if (config != null && config.InProc)
                            {
                                Alachisoft.NCache.Caching.Cache ncache = null;
                                Cache cache = null;
                                maxTries = 2;

                                do
                                {
                                    CacheConfig cacheConfig = CacheConfig.FromDom(config);

                                    cache = new Cache(null, cacheConfig);


                                    ncache = CacheFactory.CreateFromPropertyString(cacheConfig.PropertyString, config,
                                                                                   false, false);


                                    cacheImpl       = new InprocCache(ncache, cacheConfig, cache);
                                    cache.CacheImpl = cacheImpl;

                                    if (primaryCache == null)
                                    {
                                        primaryCache = cache;
                                    }

                                    else
                                    {
                                        primaryCache.AddSecondaryInprocInstance(cache);
                                    }

                                    break;
                                } while (maxTries > 0);
                            }
                            else
                            {
                                maxTries = 2;
                                do
                                {
                                    try
                                    {
                                        PerfStatsCollector2 perfStatsCollector =
                                            new PerfStatsCollector2(cacheId, false);

                                        primaryCache = new Cache(null, cacheId, perfStatsCollector);
                                        cacheImpl    = new RemoteCache(cacheId, primaryCache, initParams,
                                                                       perfStatsCollector);

                                        perfStatsCollector.InitializePerfCounters(false);

                                        primaryCache.CacheImpl = cacheImpl;

                                        break;
                                    }


                                    catch (OperationNotSupportedException ex)
                                    {
                                        throw ex;
                                    }
                                } while (maxTries > 0);
                            }

                            if (primaryCache != null)
                            {
                                s_webCaches.AddCache(cacheId, primaryCache);
                            }
                        }
                        else
                        {
                            lock (s_webCaches.GetCache(cacheId))
                            {
                                primaryCache = s_webCaches.GetCache(cacheId) as Cache;

                                primaryCache.AddRef();
                            }
                        }
                    }

                    lock (s_webCache)
                    {
                        if (s_webCache.CacheImpl == null)
                        {
                            primaryCache.ExceptionsEnabled = ExceptionsEnabled;
                            s_webCache = primaryCache;
                        }
                    }

                    return(primaryCache);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #29
0
        public void StopCache()
        {
            try
            {
                if (!ValidateParameters())
                {
                    return;
                }
                ICacheServer m = null;
                try
                {
                    m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                }
                catch (Exception e)
                {
                    OutputProvider.WriteErrorLine("Error: NCache service could not be contacted on server.");
                }

                string            getBindIp = string.Empty;
                CacheServerConfig config    = null;
                if (m != null)
                {
                    foreach (string cache in CachesList)
                    {
                        try
                        {
                            config = m.GetCacheConfiguration(cache);
                            if (config != null && config.InProc)
                            {
                                throw new Exception("InProc caches cannot be stopped explicitly.");
                            }
                            getBindIp = m.GetClusterIP();
                            OutputProvider.WriteLine("Stopping cache '{0}' on server {1}:{2}.", cache, getBindIp, NCache.Port);
                            m.StopCache(cache, _partId);

                            m.StopCache(cache, string.Empty);

                            OutputProvider.WriteLine("'{0}' successfully stopped on server {1}:{2}.\n", cache, getBindIp,
                                                     NCache.Port);
                        }
                        catch (System.Security.SecurityException e)
                        {
                            OutputProvider.WriteErrorLine("Failed to stop '{0}'. Error: {1} ", cache, e.Message);

                            OutputProvider.WriteErrorLine(e.ToString());
                            OutputProvider.WriteLine(Environment.NewLine);
                        }
                        catch (Exception e)
                        {
                            OutputProvider.WriteErrorLine("Failed to stop '{0}'.", cache);

                            OutputProvider.WriteErrorLine("Error: " + e.ToString());
                            OutputProvider.WriteLine(Environment.NewLine);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error : {0}", e.Message);



                OutputProvider.WriteErrorLine(e.ToString());
                OutputProvider.WriteLine(Environment.NewLine);
            }
            finally
            {
                NCache.Dispose();
            }
        }
Пример #30
0
        public static void AddCache(string cacheId, CacheServerConfig config)
        {
            LoadXml();

            if (_configuration != null)
            {
                if (_configuration.CacheConfigurationsMap == null)
                {
                    _configuration.CacheConfigurationsMap = new Dictionary <string, CacheConfiguration>();
                }

                if (!_configuration.CacheConfigurationsMap.ContainsKey(cacheId.ToLower()))
                {
                    CacheConfiguration cacheConfiguration = new CacheConfiguration();
                    cacheConfiguration.CacheId = cacheId;

                    if (config.Cluster != null && config.Cluster.Nodes != null)
                    {
                        if (config.Cluster.Nodes.Count != 1)
                        {
                            // Extract server names from config
                            string[] serverList = new string[config.Cluster.NodeIdentities.Count];
                            for (int i = 0; i < serverList.Length; i++)
                            {
                                serverList[i] = config.Cluster.NodeIdentities[i].NodeName;
                            }

                            // Sort priority list i.e. local node at top
                            string[] copyServerList = new string[serverList.Length];
                            for (int i = 0; i < serverList.Length; i++)
                            {
                                if (serverList[i] == cacheConfiguration.BindIp)
                                {
                                    copyServerList[0] = serverList[i];
                                    cacheConfiguration.AddServer(cacheConfiguration.BindIp, 0);
                                }
                                else if (String.IsNullOrEmpty(copyServerList[0]))
                                {
                                    copyServerList[i + 1] = serverList[i];
                                    cacheConfiguration.AddServer(serverList[i], i + 1);
                                }
                                else
                                {
                                    copyServerList[i] = serverList[i];
                                    cacheConfiguration.AddServer(serverList[i], i);
                                }
                            }
                        }
                        else
                        {
                            cacheConfiguration.AddServer(config.Cluster.NodeIdentities[0].NodeName, 0);
                        }
                    }
                    else
                    {
                        cacheConfiguration.AddLocalServer();
                    }

                    _configuration.CacheConfigurationsMap[cacheId.ToLower()] = cacheConfiguration;
                }
            }

            SaveConfiguration();
        }