예제 #1
0
        /// <summary>
        /// Checks the string.
        /// </summary>
        /// <param name="ignite">The ignite.</param>
        /// <param name="test">The test string.</param>
        /// <param name="fail">Whether the check should fail.</param>
        private static void CheckString(IIgnite ignite, string test, bool fail = false)
        {
            var res = ignite.GetCompute().ExecuteJavaTask<string>(StringTestTask, test);

            if (fail)
                Assert.AreNotEqual(test, res);
            else
                Assert.AreEqual(test, res);
        }
예제 #2
0
        /** <inheritdoc /> */
        public override void TestSetUp()
        {
            base.TestSetUp();

            // Start another node without spring config
            if (Ignition.TryGetIgnite("grid2") == null)
            {
                var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) {GridName = "grid2"};
                _ignite = Ignition.Start(cfg);
            }
        }
예제 #3
0
        /// <summary>
        /// Executes a task to generate events.
        /// </summary>
        /// <param name="ignite">Ignite instance.</param>
        private static void ExecuteTask(IIgnite ignite)
        {
            var employees = Enumerable.Range(1, 10).SelectMany(x => new[]
            {
                new Employee("Allison Mathis",
                    25300,
                    new Address("2702 Freedom Lane, San Francisco, CA", 94109),
                    new[] {"Development"}),

                new Employee("Breana Robbin",
                    6500,
                    new Address("3960 Sundown Lane, Austin, TX", 78130),
                    new[] {"Sales"})
            }).ToArray();

            ignite.GetCompute().Execute(new AverageSalaryTask(), employees);
        }
예제 #4
0
        public void FixtureSetUp()
        {
            var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                CacheConfiguration = new[]
                {
                    new CacheConfiguration(CacheName)
                    {
                        AffinityFunction = new SimpleAffinityFunction(),
                        Backups = 7
                    }
                }
            };

            _ignite = Ignition.Start(cfg);

            _ignite2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) {GridName = "grid2"});
        }
예제 #5
0
        public void InitClient()
        {
            TestUtils.KillProcesses();

            if (_fork)
            {
                Grid1 = Ignition.Start(Configuration("config\\compute\\compute-standalone.xml"));

                _proc2 = Fork("config\\compute\\compute-standalone.xml");

                while (true)
                {
                    if (!_proc2.Alive)
                        throw new Exception("Process 2 died unexpectedly: " + _proc2.Join());

                    if (Grid1.GetCluster().GetNodes().Count < 2)
                        Thread.Sleep(100);
                    else
                        break;
                }

                _proc3 = Fork("config\\compute\\compute-standalone.xml");

                while (true)
                {
                    if (!_proc3.Alive)
                        throw new Exception("Process 3 died unexpectedly: " + _proc3.Join());

                    if (Grid1.GetCluster().GetNodes().Count < 3)
                        Thread.Sleep(100);
                    else
                        break;
                }
            }
            else
            {
                Grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml"));
                _grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml"));
                _grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml"));
            }
        }
예제 #6
0
        /// <summary>
        /// Execute individual Put and Get.
        /// </summary>
        /// <param name="ignite">Ignite instance.</param>
        private static void PutGet(IIgnite ignite)
        {
            var cache = ignite.GetCache<int, Organization>(CacheName);

            // Create new Organization to store in cache.
            Organization org = new Organization(
                "Microsoft",
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                OrganizationType.Private,
                DateTime.Now
            );

            // Put created data entry to cache.
            cache.Put(1, org);

            // Get recently created employee as a strongly-typed fully de-serialized instance.
            Organization orgFromCache = cache.Get(1);

            Console.WriteLine();
            Console.WriteLine(">>> Retrieved organization instance from cache: " + orgFromCache);
        }
예제 #7
0
파일: DbCache.cs 프로젝트: vladisav/ignite
        public DbCache(IIgnite ignite, CacheConfiguration metaCacheConfiguration, 
            CacheConfiguration dataCacheConfiguration)
        {
            IgniteArgumentCheck.NotNull(ignite, "ignite");
            IgniteArgumentCheck.NotNull(metaCacheConfiguration, "metaCacheConfiguration");
            IgniteArgumentCheck.NotNull(dataCacheConfiguration, "metaCacheConfiguration");

            IgniteArgumentCheck.Ensure(metaCacheConfiguration.Name != dataCacheConfiguration.Name, 
                "dataCacheConfiguration", "Meta and Data cache can't have the same name.");

            _metaCache = ignite.GetOrCreateCache<string, long>(metaCacheConfiguration);
            _cache = ignite.GetOrCreateCache<string, object>(dataCacheConfiguration);

            var metaCfg = _metaCache.GetConfiguration();

            if (metaCfg.AtomicityMode != CacheAtomicityMode.Transactional)
                throw new IgniteException("EntityFramework meta cache should be Transactional.");

            if (metaCfg.CacheMode == CacheMode.Partitioned && metaCfg.Backups < 1)
                ignite.Logger.Warn("EntityFramework meta cache is partitioned and has no backups. " +
                                   "This can lead to data loss and incorrect query results.");
        }
예제 #8
0
        public void SetUp()
        {
            const string springConfigUrl = "config\\compute\\compute-grid1.xml";
            
            // ReSharper disable once UnusedVariable
            var proc = new IgniteProcess(
                "-jvmClasspath=" + TestUtils.CreateTestClasspath(),
                "-springConfigUrl=" + Path.GetFullPath(springConfigUrl),
                "-J-ea",
                "-J-Xcheck:jni",
                "-J-Xms512m",
                "-J-Xmx512m",
                "-J-DIGNITE_QUIET=false"
                );

            _grid = Ignition.Start(new IgniteConfiguration
            {
                JvmClasspath = TestUtils.CreateTestClasspath(),
                JvmOptions = TestUtils.TestJavaOptions(),
                SpringConfigUrl = springConfigUrl
            });

            Assert.IsTrue(_grid.WaitTopology(2, 30000));
        }
예제 #9
0
        /** <inheritDoc /> */
        protected override void OnStarted()
        {
            Emps = new Employee[Dataset];

            for (var i = 0; i < Emps.Length; i++)
                Emps[i] = BenchmarkUtils.GetRandomEmployee(Payload);

            var cfg = new IgniteConfiguration
            {
                BinaryConfiguration = GetBinaryConfiguration(),
                JvmOptions = new List<string>
                {
                    "-Xms2g",
                    "-Xmx2g",
                    "-DIGNITE_QUIET=false",
                    "-DIGNITE_NO_SHUTDOWN_HOOK=true"
                },
                JvmClasspath = Classpath ?? Core.Impl.Common.Classpath.CreateClasspath(forceTestClasspath: true),
                JvmDllPath = DllPath,
                SpringConfigUrl = ConfigPath
            };

            Node = Ignition.Start(cfg);
        }
예제 #10
0
        /// <summary>
        /// Execute individual Put and Get, getting value in binary format, without de-serializing it.
        /// </summary>
        /// <param name="ignite">Ignite instance.</param>
        private static void PutGetBinary(IIgnite ignite)
        {
            var cache = ignite.GetCache<int, Organization>(CacheName);

            // Create new Organization to store in cache.
            Organization org = new Organization(
                "Microsoft",
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                OrganizationType.Private,
                DateTime.Now
            );

            // Put created data entry to cache.
            cache.Put(1, org);

            // Create projection that will get values as binary objects.
            var binaryCache = cache.WithKeepBinary<int, IBinaryObject>();

            // Get recently created organization as a binary object.
            var binaryOrg = binaryCache.Get(1);

            // Get organization's name from binary object (note that  object doesn't need to be fully deserialized).
            string name = binaryOrg.GetField<string>("name");

            Console.WriteLine();
            Console.WriteLine(">>> Retrieved organization name from binary object: " + name);
        }
예제 #11
0
        /// <summary>
        /// Execute bulk Put and Get operations getting values in binary format, without de-serializing it.
        /// </summary>
        /// <param name="ignite">Ignite instance.</param>
        private static void PutAllGetAllBinary(IIgnite ignite)
        {
            var cache = ignite.GetCache<int, Organization>(CacheName);

            // Create new Organizations to store in cache.
            Organization org1 = new Organization(
                "Microsoft",
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                OrganizationType.Private,
                DateTime.Now
            );

            Organization org2 = new Organization(
                "Red Cross",
                new Address("184 Fidler Drive, San Antonio, TX", 78205),
                OrganizationType.NonProfit,
                DateTime.Now
            );

            var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } };

            // Put created data entries to cache.
            cache.PutAll(map);

            // Create projection that will get values as binary objects.
            var binaryCache = cache.WithKeepBinary<int, IBinaryObject>();

            // Get recently created organizations as binary objects.
            IDictionary<int, IBinaryObject> binaryMap = binaryCache.GetAll(new List<int> { 1, 2 });

            Console.WriteLine();
            Console.WriteLine(">>> Retrieved organization names from binary objects:");

            foreach (IBinaryObject poratbleOrg in binaryMap.Values)
                Console.WriteLine(">>>     " + poratbleOrg.GetField<string>("name"));
        }
예제 #12
0
 public void TestSetUp()
 {
     // Start fresh cluster for each test
     _grid       = Ignition.Start(Config("config\\compute\\compute-grid1.xml"));
     _clientGrid = Ignition.Start(Config("config\\compute\\compute-grid3.xml"));
 }
예제 #13
0
        public void FixtureSetUp()
        {
            var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                CacheConfiguration = new[]
                {
                    new CacheConfiguration(CacheName)
                    {
                        AffinityFunction = new SimpleAffinityFunction(),
                        Backups = 7
                    },
                    new CacheConfiguration(CacheNameFair)
                    {
                        AffinityFunction = new FairAffinityFunctionEx {Foo = 25}
                    },
                    new CacheConfiguration(CacheNameRendezvous)
                    {
                        AffinityFunction = new RendezvousAffinityFunctionEx {Bar = "test"}
                    }
                }
            };

            _ignite = Ignition.Start(cfg);

            _ignite2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) {GridName = "grid2"});
        }
예제 #14
0
        /// <summary>
        /// Checks that service has started on specified grid.
        /// </summary>
        private static void CheckServiceStarted(IIgnite grid, int count = 1)
        {
            var services = grid.GetServices().GetServices<TestIgniteServiceSerializable>(SvcName);

            Assert.AreEqual(count, services.Count);

            var svc = services.First();

            Assert.IsNotNull(svc);

            Assert.IsTrue(svc.Initialized);

            Thread.Sleep(100);  // Service runs in a separate thread, wait for it to execute.

            Assert.IsTrue(svc.Executed);
            Assert.IsFalse(svc.Cancelled);

            Assert.AreEqual(grid.GetCluster().GetLocalNode().Id, svc.NodeId);
        }
예제 #15
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="ignite">Grid.</param>
 public IgniteProxy(IIgnite ignite)
 {
     _ignite = ignite;
 }
예제 #16
0
 private void Method2(IIgnite grid)
 {
     _mthdGrid2 = grid;
 }
예제 #17
0
        public static void Main()
        {
            using (IIgnite ignite = Ignition.Start(Utils.GetServerNodeConfiguration()))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache query DDL example started.");

                // Create dummy cache to act as an entry point for SQL queries (new SQL API which do not require this
                // will appear in future versions, JDBC and ODBC drivers do not require it already).
                var cacheCfg = new CacheConfiguration("dummy_cache")
                {
                    SqlSchema = "PUBLIC",
                    CacheMode = CacheMode.Replicated
                };

                ICache <object, object> cache = ignite.GetOrCreateCache <object, object>(cacheCfg);

                // Create reference City table based on REPLICATED template.
                cache.Query(new SqlFieldsQuery(
                                "CREATE TABLE city (id LONG PRIMARY KEY, name VARCHAR) WITH \"template=replicated\"")).GetAll();

                // Create table based on PARTITIONED template with one backup.
                cache.Query(new SqlFieldsQuery(
                                "CREATE TABLE person (id LONG, name VARCHAR, city_id LONG, PRIMARY KEY (id, city_id)) " +
                                "WITH \"backups=1, affinity_key=city_id\"")).GetAll();

                // Create an index.
                cache.Query(new SqlFieldsQuery("CREATE INDEX on Person (city_id)")).GetAll();

                Console.WriteLine("\n>>> Created database objects.");

                const string addCity = "INSERT INTO city (id, name) VALUES (?, ?)";

                cache.Query(new SqlFieldsQuery(addCity, 1L, "Forest Hill"));
                cache.Query(new SqlFieldsQuery(addCity, 2L, "Denver"));
                cache.Query(new SqlFieldsQuery(addCity, 3L, "St. Petersburg"));

                const string addPerson = "INSERT INTO person (id, name, city_id) values (?, ?, ?)";

                cache.Query(new SqlFieldsQuery(addPerson, 1L, "John Doe", 3L));
                cache.Query(new SqlFieldsQuery(addPerson, 2L, "Jane Roe", 2L));
                cache.Query(new SqlFieldsQuery(addPerson, 3L, "Mary Major", 1L));
                cache.Query(new SqlFieldsQuery(addPerson, 4L, "Richard Miles", 2L));

                Console.WriteLine("\n>>> Populated data.");

                IFieldsQueryCursor res = cache.Query(new SqlFieldsQuery(
                                                         "SELECT p.name, c.name FROM Person p INNER JOIN City c on c.id = p.city_id"));

                Console.WriteLine("\n>>> Query results:");

                foreach (var row in res)
                {
                    Console.WriteLine("{0}, {1}", row[0], row[1]);
                }

                cache.Query(new SqlFieldsQuery("drop table Person")).GetAll();
                cache.Query(new SqlFieldsQuery("drop table City")).GetAll();

                Console.WriteLine("\n>>> Dropped database objects.");
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
예제 #18
0
 private static void StaticMethod2(IIgnite grid)
 {
     StaticGrid2 = grid;
 }
예제 #19
0
 public void Method1(IIgnite grid)
 {
     _mthdGrid1 = grid;
 }
예제 #20
0
 public static void StaticMethod1(IIgnite grid)
 {
     _staticGrid1 = grid;
 }
예제 #21
0
        public void TestFixtureSetUp()
        {
            TestUtils.KillProcesses();

            _grid = Ignition.Start(Configuration(SpringCfgPath));
        }
        /// <summary>
        /// Stops the grids.
        /// </summary>
        private void StopGrids()
        {
            _grid1 = null;

            Ignition.StopAll(true);
        }
예제 #23
0
        /// <summary>
        /// Creates exception according to native code class and message.
        /// </summary>
        /// <param name="ignite">The ignite.</param>
        /// <param name="clsName">Exception class name.</param>
        /// <param name="msg">Exception message.</param>
        /// <param name="reader">Error data reader.</param>
        /// <returns>Exception.</returns>
        public static Exception GetException(IIgnite ignite, string clsName, string msg, BinaryReader reader = null)
        {
            ExceptionFactoryDelegate ctor;

            if (Exs.TryGetValue(clsName, out ctor))
            {
                var match = InnerClassRegex.Match(msg ?? string.Empty);

                ExceptionFactoryDelegate innerCtor;

                if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor))
                    return ctor(ignite, msg, innerCtor(ignite, match.Groups[2].Value, null));

                return ctor(ignite, msg, null);
            }

            if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
                    "variable?): " + msg);

            if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
                    "variable?): " + msg);

            if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return ProcessCachePartialUpdateException(ignite, msg, reader);

            return new IgniteException("Java exception occurred [class=" + clsName + ", message=" + msg + ']');
        }
예제 #24
0
 public void SetUp()
 {
     _grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml"));
     _grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml"));
     _grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml"));
 }
 public void TestSetUp()
 {
     // Start fresh cluster for each test
     _grid = Ignition.Start(Config("config\\compute\\compute-grid1.xml"));
     _clientGrid = Ignition.Start(Config("config\\compute\\compute-grid3.xml"));
 }
예제 #26
0
 /// <summary>
 /// Gets the primary keys.
 /// </summary>
 public static IEnumerable <int> GetPrimaryKeys(IIgnite ignite, string cacheName,
                                                IClusterNode node = null)
 {
     return(GetKeys(ignite, cacheName, node));
 }
예제 #27
0
        /// <summary>
        /// Starts the grids.
        /// </summary>
        private void StartGrids()
        {
            if (Grid1 != null)
                return;

            Grid1 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid1.xml"));
            Grid2 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid2.xml"));
            Grid3 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid3.xml"));

            Grids = new[] { Grid1, Grid2, Grid3 };
        }
예제 #28
0
 public void FixtureSetUp()
 {
     _ignite = Ignition.Start(TestUtils.GetTestConfiguration());
 }
 protected abstract TBranch CreateInstance(IIgnite ignite, TSchema schema, TBranchNode node);
예제 #30
0
        public static void Start(IgniteConfiguration conf, bool loadCacheFromDatabase = false)
        {
            _ignite = Ignition.Start(conf);

            StartCaches(loadCacheFromDatabase);
        }
        /// <summary>
        /// Stops the grids.
        /// </summary>
        private void StopGrids()
        {
            Grid1 = Grid2 = Grid3 = null;

            Ignition.StopAll(true);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TestIgnitePluginException" /> class.
 /// </summary>
 /// <param name="className">Name of the class.</param>
 /// <param name="message">Message.</param>
 /// <param name="ignite">Ignite.</param>
 /// <param name="cause">Cause.</param>
 public TestIgnitePluginException(string className, string message, IIgnite ignite, Exception cause)
     : base(message, cause)
 {
     _className = className;
     _ignite    = ignite;
 }
예제 #33
0
 /// <summary>
 /// Generates the task event.
 /// </summary>
 private void GenerateTaskEvent(IIgnite grid = null)
 {
     (grid ?? _grid1).GetCompute().Broadcast(new ComputeAction());
 }
예제 #34
0
 public TestTask(IIgnite grid, IPortableObject taskArgField)
 {
     _grid         = grid;
     _taskArgField = taskArgField;
 }
예제 #35
0
 public IgniteProvider(IIgnite store)
 {
     Store = store;
 }
예제 #36
0
        public IgniteDbConfiguration(IIgnite ignite, CacheConfiguration metaCacheConfiguration,
            CacheConfiguration dataCacheConfiguration, IDbCachingPolicy policy)
        {
            IgniteArgumentCheck.NotNull(ignite, "ignite");

            metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration();
            dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration();

            var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration);

            var txHandler = new DbTransactionInterceptor(efCache);

            AddInterceptor(txHandler);

            // SetProviderServices is not suitable. We should replace whatever provider there is with our proxy.
            Loaded += (sender, args) => args.ReplaceService<DbProviderServices>(
                (services, a) => new DbProviderServicesProxy(services, policy, efCache, txHandler));
        }
예제 #37
0
        /// <summary>
        /// Execute bulk Put and Get operations.
        /// </summary>
        /// <param name="ignite">Ignite instance.</param>
        private static void PutAllGetAll(IIgnite ignite)
        {
            var cache = ignite.GetCache<int, Organization>(CacheName);

            // Create new Organizations to store in cache.
            Organization org1 = new Organization(
                "Microsoft",
                new Address("1096 Eddy Street, San Francisco, CA", 94109),
                OrganizationType.Private,
                DateTime.Now
            );

            Organization org2 = new Organization(
                "Red Cross",
                new Address("184 Fidler Drive, San Antonio, TX", 78205),
                OrganizationType.NonProfit,
                DateTime.Now
            );

            var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } };

            // Put created data entries to cache.
            cache.PutAll(map);

            // Get recently created organizations as a strongly-typed fully de-serialized instances.
            IDictionary<int, Organization> mapFromCache = cache.GetAll(new List<int> { 1, 2 });

            Console.WriteLine();
            Console.WriteLine(">>> Retrieved organization instances from cache:");

            foreach (Organization org in mapFromCache.Values)
                Console.WriteLine(">>>     " + org);
        }
예제 #38
0
        public IgniteDbConfiguration(IIgnite ignite, CacheConfiguration metaCacheConfiguration,
            CacheConfiguration dataCacheConfiguration, IDbCachingPolicy policy)
        {
            IgniteArgumentCheck.NotNull(ignite, "ignite");

            InitializeIgniteCachingInternal(this, ignite, metaCacheConfiguration, dataCacheConfiguration, policy);
        }
예제 #39
0
        /// <summary>
        /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>.
        /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>.
        /// </summary>
        /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized
        /// for Ignite caching.</param>
        /// <param name="ignite">The ignite instance to use.</param>
        /// <param name="metaCacheConfiguration">
        /// Configuration of the metadata cache which holds entity set information. Null for default configuration.
        /// <para />
        /// This cache holds small amount of data, but should not lose entries. At least one backup recommended.
        /// </param>
        /// <param name="dataCacheConfiguration">
        /// Configuration of the data cache which holds query results. Null for default configuration.
        /// <para />
        /// This cache tolerates lost data and can have no backups.
        /// </param>
        /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param>
        private static void InitializeIgniteCachingInternal(DbConfiguration dbConfiguration, IIgnite ignite,
                                                            CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration,
                                                            IDbCachingPolicy policy)
        {
            Debug.Assert(ignite != null);
            Debug.Assert(dbConfiguration != null);

            metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration();
            dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration();

            var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration);

            var txHandler = new DbTransactionInterceptor(efCache);

            AddInterceptorDelegate(dbConfiguration, txHandler);

            RegisterProviderServicesReplacer(dbConfiguration, policy, efCache, txHandler);
        }
예제 #40
0
        /// <summary>
        /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>.
        /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>.
        /// </summary>
        /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized
        /// for Ignite caching.</param>
        /// <param name="ignite">The ignite instance to use.</param>
        /// <param name="metaCacheConfiguration">
        /// Configuration of the metadata cache which holds entity set information. Null for default configuration. 
        /// <para />
        /// This cache holds small amount of data, but should not lose entries. At least one backup recommended.
        /// </param>
        /// <param name="dataCacheConfiguration">
        /// Configuration of the data cache which holds query results. Null for default configuration.
        /// <para />
        /// This cache tolerates lost data and can have no backups.
        /// </param>
        /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param>
        private static void InitializeIgniteCachingInternal(DbConfiguration dbConfiguration, IIgnite ignite, 
            CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration, 
            IDbCachingPolicy policy)
        {
            Debug.Assert(ignite != null);
            Debug.Assert(dbConfiguration != null);

            metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration();
            dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration();

            var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration);

            var txHandler = new DbTransactionInterceptor(efCache);

            AddInterceptorDelegate(dbConfiguration, txHandler);

            RegisterProviderServicesReplacer(dbConfiguration, policy, efCache, txHandler);
        }
예제 #41
0
        /// <summary>
        /// Asserts that specified field is serialized as Timestamp.
        /// </summary>
        private static void AssertTimestampField <T>(Action <T, DateTime> setValue,
                                                     Func <T, DateTime> getValue, string fieldName, IIgnite ignite = null) where T : new()
        {
            // Non-UTC DateTime throws.
            var binary = ignite != null?ignite.GetBinary() : Ignition.GetIgnite().GetBinary();

            var obj = new T();

            setValue(obj, DateTime.Now);

            var ex = Assert.Throws <BinaryObjectException>(() => binary.ToBinary <IBinaryObject>(obj),
                                                           "Timestamp fields should throw an error on non-UTC values");

            Assert.AreEqual(NotUtcDate, ex.Message);

            // UTC DateTime works.
            setValue(obj, DateTime.UtcNow);
            var bin = binary.ToBinary <IBinaryObject>(obj);
            var res = bin.Deserialize <T>();

            Assert.AreEqual(getValue(obj), getValue(res));
            Assert.AreEqual(getValue(obj), bin.GetField <DateTime>(fieldName));
            Assert.AreEqual("Timestamp", bin.GetBinaryType().GetFieldTypeName(fieldName));
        }
예제 #42
0
        private static Exception ProcessCachePartialUpdateException(IIgnite ignite, string msg, string stackTrace,
            BinaryReader reader)
        {
            if (reader == null)
                return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available."));

            bool dataExists = reader.ReadBoolean();

            Debug.Assert(dataExists);

            if (reader.ReadBoolean())
            {
                bool keepBinary = reader.ReadBoolean();

                BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary);

                try
                {
                    return new CachePartialUpdateException(msg, ReadNullableList(keysReader));
                }
                catch (Exception e)
                {
                    // Failed to deserialize data.
                    return new CachePartialUpdateException(msg, e);
                }
            }

            // Was not able to write keys.
            string innerErrCls = reader.ReadString();
            string innerErrMsg = reader.ReadString();

            Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace);

            return new CachePartialUpdateException(msg, innerErr);
        }
예제 #43
0
 public ModelBranchProvider(IIgnite ignite, ITimeProvider timeProvider)
     : base(new ModelBranchSchema(), ignite, timeProvider)
 {
 }
예제 #44
0
 /// <summary>
 /// Gets the primary key.
 /// </summary>
 public static int GetKey(IIgnite ignite, string cacheName, IClusterNode node = null, bool primaryKey = false)
 {
     return(GetKeys(ignite, cacheName, node, primaryKey).First());
 }
예제 #45
0
        /// <summary>
        /// Check event.
        /// </summary>
        /// <param name="evt">Event.</param>
        /// <param name="expGrid1">Expected grid 1.</param>
        /// <param name="expGrid2">Expected grid 2.</param>
        /// <param name="expProp1">Expected property 1.</param>
        /// <param name="expProp2">Expected property 2.</param>
        private static void CheckEvent(Event evt, IIgnite expGrid1, IIgnite expGrid2, int expProp1, string expProp2)
        {
            if (evt.Grid1 != null && evt.Grid1 is IgniteProxy)
                evt.Grid1 = (evt.Grid1 as IgniteProxy).Target;

            if (evt.Grid2 != null && evt.Grid2 is IgniteProxy)
                evt.Grid2 = (evt.Grid2 as IgniteProxy).Target;

            Assert.AreEqual(expGrid1, evt.Grid1);
            Assert.AreEqual(expGrid2, evt.Grid2);
            Assert.AreEqual(expProp1, evt.Prop1);
            Assert.AreEqual(expProp2, evt.Prop2);
        }
예제 #46
0
 protected override ModelBranch CreateInstance(IIgnite ignite, ModelBranchSchema schema, ModelBranchNode node)
 {
     return(new ModelBranch(ignite, schema, node));
 }
예제 #47
0
        /// <summary>
        /// Asserts that the handle registry has specified number of entries.
        /// </summary>
        /// <param name="grid">The grid to check.</param>
        /// <param name="expectedCount">Expected item count.</param>
        /// <param name="timeout">Timeout, in milliseconds.</param>
        public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
        {
            var handleRegistry = ((Ignite)grid).HandleRegistry;

            if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
                return;

            var items = handleRegistry.GetItems();

            if (items.Any())
                Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name,
                    items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
        }
예제 #48
0
 // ReSharper disable once UnusedMember.Global (used by injector)
 public void InjectIgnite(IIgnite ignite)
 {
     // Propagate injection
     ResourceProcessor.Inject(_func, (IgniteProxy)ignite);
 }
예제 #49
0
        /// <summary>
        /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>.
        /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>.
        /// </summary>
        /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized
        /// for Ignite caching.</param>
        /// <param name="ignite">The ignite instance to use.</param>
        /// <param name="metaCacheConfiguration">
        /// Configuration of the metadata cache which holds entity set information. Null for default configuration. 
        /// <para />
        /// This cache holds small amount of data, but should not lose entries. At least one backup recommended.
        /// </param>
        /// <param name="dataCacheConfiguration">
        /// Configuration of the data cache which holds query results. Null for default configuration.
        /// <para />
        /// This cache tolerates lost data and can have no backups.
        /// </param>
        /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param>
        public static void InitializeIgniteCaching(DbConfiguration dbConfiguration, IIgnite ignite,
            CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration,
            IDbCachingPolicy policy)
        {
            IgniteArgumentCheck.NotNull(ignite, "ignite");
            IgniteArgumentCheck.NotNull(dbConfiguration, "configuration");

            IgniteArgumentCheck.Ensure(!(dbConfiguration is IgniteDbConfiguration), "dbConfiguration",
                "IgniteDbConfiguration.InitializeIgniteCaching should not be called for IgniteDbConfiguration " +
                "instance. This method should be used only when IgniteDbConfiguration can't be inherited.");

            InitializeIgniteCachingInternal(dbConfiguration, ignite, metaCacheConfiguration, dataCacheConfiguration, 
                policy);
        }
예제 #50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheFieldsQueryProvider"/> class.
        /// </summary>
        public CacheFieldsQueryProvider(IQueryParser queryParser, CacheFieldsQueryExecutor executor, IIgnite ignite,
                                        CacheConfiguration cacheConfiguration, string tableName, Type cacheValueType)
        {
            Debug.Assert(queryParser != null);
            Debug.Assert(executor != null);
            Debug.Assert(ignite != null);
            Debug.Assert(cacheConfiguration != null);
            Debug.Assert(cacheValueType != null);

            _parser             = queryParser;
            _executor           = executor;
            _ignite             = ignite;
            _cacheConfiguration = cacheConfiguration;

            if (tableName != null)
            {
                _tableName = tableName;

                ValidateTableName();
            }
            else
            {
                _tableName = InferTableName(cacheValueType);
            }
        }
예제 #51
0
        /// <summary>
        /// Creates exception according to native code class and message.
        /// </summary>
        /// <param name="ignite">The ignite.</param>
        /// <param name="clsName">Exception class name.</param>
        /// <param name="msg">Exception message.</param>
        /// <param name="stackTrace">Native stack trace.</param>
        /// <param name="reader">Error data reader.</param>
        /// <param name="innerException">Inner exception.</param>
        /// <returns>Exception.</returns>
        public static Exception GetException(IIgnite ignite, string clsName, string msg, string stackTrace,
            BinaryReader reader = null, Exception innerException = null)
        {
            // Set JavaException as inner only if there is no InnerException.
            if (innerException == null && !string.IsNullOrEmpty(stackTrace))
                innerException = new JavaException(stackTrace);

            ExceptionFactoryDelegate ctor;

            if (Exs.TryGetValue(clsName, out ctor))
            {
                var match = InnerClassRegex.Match(msg ?? string.Empty);

                ExceptionFactoryDelegate innerCtor;

                if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor))
                    return ctor(ignite, msg, innerCtor(ignite, match.Groups[2].Value, innerException));

                return ctor(ignite, msg, innerException);
            }

            if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
                    "variable?): " + msg, innerException);

            if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
                    "variable?): " + msg, innerException);

            if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
                return ProcessCachePartialUpdateException(ignite, msg, stackTrace, reader);

            return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg),
                innerException);
        }
예제 #52
0
 /// <summary>
 /// Gets the primary key.
 /// </summary>
 public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
 {
     return(GetPrimaryKeys(ignite, cacheName, node).First());
 }
예제 #53
0
        /// <summary>
        /// Uses the ignite.
        /// </summary>
        /// <param name="ignite">The ignite.</param>
        private static void UseIgnite(IIgnite ignite)
        {
            // Create objects holding references to java objects.
            var comp = ignite.Compute();

            // ReSharper disable once RedundantAssignment
            comp = comp.WithKeepPortable();

            var prj = ignite.Cluster.ForOldest();

            Assert.IsTrue(prj.Nodes().Count > 0);

            Assert.IsNotNull(prj.Compute());

            var cache = ignite.Cache<int, int>("cache1");

            Assert.IsNotNull(cache);

            cache.GetAndPut(1, 1);

            Assert.AreEqual(1, cache.Get(1));
        }
예제 #54
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="ignite">Grid.</param>
 /// <param name="entry">Entry.</param>
 public FilterEvent(IIgnite ignite, ICacheEntryEvent <object, object> entry)
 {
     this.ignite = ignite;
     this.entry  = entry;
 }
예제 #55
0
        /// <summary>
        /// Stops the grids.
        /// </summary>
        private void StopGrids()
        {
            Grid1 = Grid2 = Grid3 = null;
            Grids = null;

            Ignition.StopAll(true);
        }
예제 #56
0
        /// <summary>
        /// Checks that data storage metrics reflect some write operations.
        /// </summary>
        private static void CheckDataStorageMetrics(IIgnite ignite)
        {
            var metrics = ignite.GetDataStorageMetrics();

            Assert.Greater(metrics.WalLoggingRate, 0);
        }
예제 #57
0
        /// <summary>
        /// Asserts that the handle registry has specified number of entries.
        /// </summary>
        /// <param name="grid">The grid to check.</param>
        /// <param name="expectedCount">Expected item count.</param>
        /// <param name="timeout">Timeout, in milliseconds.</param>
        public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
        {
            var handleRegistry = ((Ignite)grid).HandleRegistry;

            expectedCount++;  // Skip default lifecycle bean

            if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
                return;

            var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleBeanHolder)).ToList();

            if (items.Any())
                Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name,
                    items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
        }
        static void Main(string[] args)
        {
            //string conn_string = ConfigurationManager.ConnectionStrings["CacheService.Properties.Settings.testConnectionString"].Name;
            Ignition.ClientMode = true;
            using (ignite = Ignition.StartFromApplicationConfiguration())
            {
                ICluster cluster              = ignite.GetCluster();
                ICollection <IClusterNode> t  = cluster.ForRemotes().GetNodes();
                List <IClusterNode>        t1 = t.ToList <IClusterNode>();
                Console.WriteLine("{0}", t1.ToString());
                PreLoad preload   = new PreLoad();
                String  CacheName = "Cache";
                var     caches    = ignite.GetCacheNames();
                cache = ignite.GetOrCreateCache <long, CustomerAccount_ignite>(
                    new CacheConfiguration(CacheName, typeof(CustomerAccount_ignite))
                {
                    CacheMode = CacheMode.Partitioned
                }
                    );//"Cache"
                IDataStreamer <long, CustomerAccount_ignite> streamer = ignite.GetDataStreamer <long, CustomerAccount_ignite>("Cache");
                streamer.AllowOverwrite = true;
                IQueryable <ICacheEntry <long, CustomerAccount_ignite> > queryable = cache.AsCacheQueryable();

                if (!caches.Contains(CacheName))
                {
                    preload.Process(streamer);
                }


                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Populating Account IDs");
                PopulateAccountIDs();
                Console.WriteLine(accountIDs.Count);
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Start writing tasks");

                CancellationTokenSource writeTokenSource = new CancellationTokenSource();
                CancellationToken       writeToken       = writeTokenSource.Token;
                List <Task>             writeTasks       = new List <Task>();

                for (int i = 0; i < numWriteThread; i++)
                {
                    writeTasks.Add(new Task(() =>
                    {
                        Thread.Sleep(2000);
                        ///Console.Write("tasks1 start ", i);
                        while (!writeToken.IsCancellationRequested)
                        {
                            Stopwatch sw = Stopwatch.StartNew();
                            try
                            {
                                long p       = Helper.GetRandomAccountID(accountIDs);
                                var accounts = queryable.Where(customer => customer.Value._AccountId == p).ToArray();
                                foreach (var account in accounts)
                                {
                                    account.Value._AgencyName = Helper.GetRandomString(20);
                                    streamer.AddData(account.Key, account.Value);
                                }
                                Interlocked.Increment(ref writeSucceeded);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                                Interlocked.Increment(ref writeFailed);
                            }
                            sw.Stop();
                            Interlocked.Add(ref writeTotalLatency, sw.ElapsedMilliseconds);
                            Interlocked.Increment(ref writeCalls);
                        }
                    }, writeToken));
                }

                Parallel.ForEach(writeTasks, task => task.Start());

                {
                    CancellationTokenSource tokenSource = new CancellationTokenSource();
                    CancellationToken       token       = tokenSource.Token;
                    List <Task>             tasks       = new List <Task>();

                    for (int i = 0; i < numReadThread; i++)
                    {
                        tasks.Add(new Task(() =>
                        {
                            Thread.Sleep(2000);
                            //Console.Write("{0} tasks start" ,i);
                            while (!token.IsCancellationRequested)
                            {
                                Stopwatch sw = Stopwatch.StartNew();
                                try
                                {
                                    long p       = Helper.GetRandomAccountID(accountIDs);
                                    var accounts = queryable.Where(customer => customer.Value._AccountId == p).ToArray();
                                    foreach (var account in accounts)
                                    {
                                        //
                                    }
                                    Interlocked.Increment(ref succeeded);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex);
                                    Interlocked.Increment(ref failed);
                                }

                                sw.Stop();
                                Interlocked.Add(ref totalLatency, sw.ElapsedMilliseconds);
                                Interlocked.Increment(ref calls);
                            }
                        }, token));
                    }

                    Parallel.ForEach(tasks, task => task.Start());

                    Thread.Sleep(numDuration * 1000 * 60);
                    tokenSource.Cancel();

                    Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    Console.WriteLine(" Reads:");
                    Console.WriteLine("averge latency: " + 1.0 * totalLatency / calls + " ms");
                    Console.WriteLine("throughput: {0} calls/sec", 1.0 * calls / (numDuration * 60));
                    Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * succeeded / calls, succeeded, failed, calls);
                }

                Reset();

                {
                    CancellationTokenSource tokenSource = new CancellationTokenSource();
                    CancellationToken       token       = tokenSource.Token;
                    List <Task>             tasks       = new List <Task>();

                    for (int i = 0; i < numReadThread; i++)
                    {
                        tasks.Add(new Task(() =>
                        {
                            Thread.Sleep(2000);
                            while (!token.IsCancellationRequested)
                            {
                                Stopwatch sw = Stopwatch.StartNew();
                                try
                                {
                                    long p       = Helper.GetRandomAccountID(accountIDs);
                                    var accounts = queryable.Where(customer => customer.Value._AccountId == p).ToArray();
                                    foreach (var account in accounts)
                                    {
                                        //
                                    }
                                    Interlocked.Increment(ref succeeded);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex);
                                    Interlocked.Increment(ref failed);
                                }

                                sw.Stop();
                                Interlocked.Add(ref totalLatency, sw.ElapsedMilliseconds);
                                Interlocked.Increment(ref calls);
                            }
                        }, token));
                    }

                    Parallel.ForEach(tasks, task => task.Start());

                    Thread.Sleep(numDuration * 1000 * 60);
                    tokenSource.Cancel();

                    Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    Console.WriteLine(" Reads:");
                    Console.WriteLine("averge latency: " + 1.0 * totalLatency / calls + " ms");
                    Console.WriteLine("throughput: {0} calls/sec", 1.0 * calls / (numDuration * 60));
                    Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * succeeded / calls, succeeded, failed, calls);
                }
                writeTokenSource.Cancel();

                Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                Console.WriteLine(" Writes:");
                Console.WriteLine("averge latency: " + 1.0 * writeTotalLatency / writeCalls + " ms");
                Console.WriteLine("throughput: {0} calls/sec", 1.0 * writeCalls / (numDuration * 60));
                Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * writeSucceeded / writeCalls, writeSucceeded, writeFailed, writeCalls);

                /*long id = 1;
                 * int times = 10000;
                 * var stopwatch = new Stopwatch();
                 * stopwatch.Start();
                 * for (int i=0;i<times;i++)
                 * {
                 * query.Process(cache,id);
                 * id = (id + 3) % 100000;
                 * }
                 * stopwatch.Stop();
                 * long elapsed_time = stopwatch.ElapsedMilliseconds;
                 * Console.WriteLine("Finish SQL querying\n");
                 * Console.WriteLine("Preload Time on {0} times using {1} ms", times, elapsed_time);
                 * var cache = ignite.GetOrCreateCache<int, string>("myCache");*/
                // Store keys in cache (values will end up on different cache nodes).

                /*for (int i = 0; i < 10; i++)
                 *  cache.Put(i, i.ToString());
                 *
                 * for (int i = 0; i < 10; i++)
                 *  Console.WriteLine("Got [key={0}, val={1}]", i, cache.Get(i));*/
            }
        }