Пример #1
1
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Transaction example started.");

                var cache = ignite.GetCache<int, Account>("tx");

                // Clean up caches on all nodes before run.
                cache.Clear();

                // Initialize.
                cache.Put(1, new Account(1, 100));
                cache.Put(2, new Account(2, 200));

                Console.WriteLine();
                Console.WriteLine(">>> Accounts before transfer: ");
                Console.WriteLine(">>>     " + cache.Get(1));
                Console.WriteLine(">>>     " + cache.Get(2));
                Console.WriteLine();

                // Transfer money between accounts in a single transaction.
                using (var tx = cache.Ignite.GetTransactions().TxStart(TransactionConcurrency.Pessimistic,
                    TransactionIsolation.RepeatableRead))
                {
                    Account acc1 = cache.Get(1);
                    Account acc2 = cache.Get(2);

                    acc1.Balance += 100;
                    acc2.Balance -= 100;

                    cache.Put(1, acc1);
                    cache.Put(2, acc2);

                    tx.Commit();
                }

                Console.WriteLine(">>> Transfer finished.");

                Console.WriteLine();
                Console.WriteLine(">>> Accounts after transfer: ");
                Console.WriteLine(">>>     " + cache.Get(1));
                Console.WriteLine(">>>     " + cache.Get(2));
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #2
0
        /// <summary>
        /// Install service programmatically.
        /// </summary>
        /// <param name="cfg">Ignite configuration.</param>
        internal static void DoInstall(IgniteConfiguration cfg)
        {
            // 1. Check if already defined.
            if (ServiceController.GetServices().Any(svc => SvcName.Equals(svc.ServiceName)))
            {
                throw new IgniteException("Ignite service is already installed (uninstall it using \"" +
                                          ExeName + " " + IgniteRunner.SvcUninstall + "\" first)");
            }

            // 2. Create startup arguments.
            var args = ArgsConfigurator.ToArgs(cfg);

            if (args.Length > 0)
            {
                Console.WriteLine("Installing \"" + SvcName + "\" service with the following startup " +
                    "arguments:");

                foreach (var arg in args)
                    Console.WriteLine("\t" + arg);
            }
            else
                Console.WriteLine("Installing \"" + SvcName + "\" service ...");

            // 3. Actual installation.
            Install0(args);

            Console.WriteLine("\"" + SvcName + "\" service installed successfully.");
        }
Пример #3
0
        public static void Main()
        {
            Console.WriteLine();
            Console.WriteLine(">>> Lifecycle example started.");

            // Create new configuration.
            var lifecycleExampleBean = new LifecycleExampleBean();

            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\examples-config.xml",
                LifecycleBeans = new List<ILifecycleBean> { lifecycleExampleBean }
            };

            // Provide lifecycle bean to configuration.
            using (Ignition.Start(cfg))
            {
                // Make sure that lifecycle bean was notified about Ignite startup.
                Console.WriteLine();
                Console.WriteLine(">>> Started (should be true): " + lifecycleExampleBean.Started);
            }

            // Make sure that lifecycle bean was notified about Ignite stop.
            Console.WriteLine();
            Console.WriteLine(">>> Started (should be false): " + lifecycleExampleBean.Started);

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #4
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache put-get example started.");

                // Clean up caches on all nodes before run.
                ignite.GetOrCreateCache<object, object>(CacheName).Clear();

                PutGet(ignite);
                PutGetBinary(ignite);
                PutAllGetAll(ignite);
                PutAllGetAllBinary(ignite);

                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #5
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-compute.xml",
                JvmOptions = new List<string> {"-Xms512m", "-Xmx1024m"}
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine(">>> Services example started.");
                Console.WriteLine();

                // Deploy a service
                var svc = new MapService<int, string>();
                Console.WriteLine(">>> Deploying service to all nodes...");
                ignite.GetServices().DeployNodeSingleton("service", svc);

                // Get a sticky service proxy so that we will always be contacting the same remote node.
                var prx = ignite.GetServices().GetServiceProxy<IMapService<int, string>>("service", true);
                
                for (var i = 0; i < 10; i++)
                    prx.Put(i, i.ToString());

                var mapSize = prx.Size;

                Console.WriteLine(">>> Map service size: " + mapSize);

                ignite.GetServices().CancelAll();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #6
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-compute.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Task execution example started.");

                // Generate employees to calculate average salary for.
                ICollection<Employee> employees = Employees();

                Console.WriteLine();
                Console.WriteLine(">>> Calculating average salary for employees:");

                foreach (Employee employee in employees)
                    Console.WriteLine(">>>     " + employee);

                // Execute task and get average salary.
                var avgSalary = ignite.GetCompute().Execute(new AverageSalaryTask(), employees);

                Console.WriteLine();
                Console.WriteLine(">>> Average salary for all employees: " + avgSalary);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #7
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-compute.xml",
                JvmOptions = new List<string> {"-Xms512m", "-Xmx1024m"}
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine(">>> Events example started.");
                Console.WriteLine();

                // Local listen example
                Console.WriteLine(">>> Listening for a local event...");

                var listener = new LocalListener();
                ignite.GetEvents().LocalListen(listener, EventType.TaskExecutionAll);

                ExecuteTask(ignite);

                ignite.GetEvents().StopLocalListen(listener);

                Console.WriteLine(">>> Received events count: " + listener.EventsReceived);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #8
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public IgniteService(IgniteConfiguration cfg)
        {
            AutoLog = true;
            CanStop = true;
            ServiceName = SvcName;

            _cfg = cfg;
        }
Пример #9
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public IgniteService(IgniteConfiguration cfg)
        {
            AutoLog = true;
            CanStop = true;
            ServiceName = SvcName;

            _cfg = cfg;

            // Subscribe to lifecycle events
            var beans = _cfg.LifecycleBeans ?? new List<ILifecycleBean>();

            beans.Add(this);

            _cfg.LifecycleBeans = beans;
        }
Пример #10
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache.xml",
                JvmOptions = new List<string> {"-Xms512m", "-Xmx1024m"}
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache data streamer example started.");

                // Clean up caches on all nodes before run.
                ignite.GetOrCreateCache<int, Account>(CacheName).Clear();

                Stopwatch timer = new Stopwatch();

                timer.Start();

                using (var ldr = ignite.GetDataStreamer<int, Account>(CacheName))
                {
                    ldr.PerNodeBufferSize = 1024;

                    for (int i = 0; i < EntryCount; i++)
                    {
                        ldr.AddData(i, new Account(i, i));

                        // Print out progress while loading cache.
                        if (i > 0 && i % 10000 == 0)
                            Console.WriteLine("Loaded " + i + " accounts.");
                    }
                }

                timer.Stop();

                long dur = timer.ElapsedMilliseconds;

                Console.WriteLine(">>> Loaded " + EntryCount + " accounts in " + dur + "ms.");
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #11
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache-query.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache query example started.");

                var cache = ignite.GetCache<object, object>(null);

                // Clean up caches on all nodes before run.
                cache.Clear();

                // Populate cache with sample data entries.
                PopulateCache(cache);

                // Create cache that will work with specific types.
                var employeeCache = ignite.GetCache<EmployeeKey, Employee>(null);

                // Run SQL query example.
                SqlQueryExample(employeeCache);

                // Run SQL query with join example.
                SqlJoinQueryExample(employeeCache);

                // Run SQL fields query example.
                SqlFieldsQueryExample(employeeCache);

                // Run full text query example.
                FullTextQueryExample(employeeCache);

                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #12
0
        public static void Main()
        {
            var atomicCfg = new AtomicConfiguration
            {
                // Each node reserves 10 numbers to itself, so that 10 increments can be done locally, 
                // without communicating to other nodes. After that, another 10 elements are reserved.
                AtomicSequenceReserveSize = 10
            };

            var cfg = new IgniteConfiguration
            {
                DiscoverySpi = new TcpDiscoverySpi
                {
                    IpFinder = new TcpDiscoveryMulticastIpFinder
                    {
                        Endpoints = new[] { "127.0.0.1:47500" }
                    }
                },
                AtomicConfiguration = atomicCfg
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Atomic sequence example started.");

                IAtomicSequence atomicSequence = 
                    ignite.GetAtomicSequence(AtomicSequenceIncrementAction.AtomicSequenceName, 0, true);

                Console.WriteLine(">>> Atomic sequence initial value: " + atomicSequence.Read());

                // Broadcast an action that increments AtomicSequence a number of times.
                ignite.GetCompute().Broadcast(new AtomicSequenceIncrementAction());

                // Actual value will depend on number of participating nodes.
                Console.WriteLine("\n>>> Atomic sequence current value: " + atomicSequence.Read());
            }

            Console.WriteLine("\n>>> Check output on all nodes.");
            Console.WriteLine("\n>>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
        /// <summary>
        /// Copying constructor.
        /// </summary>
        /// <param name="cfg">Configuration.</param>
        internal IgniteConfiguration(IgniteConfiguration cfg)
        {
            SpringConfigUrl = cfg.SpringConfigUrl;
            JvmDllPath = cfg.JvmDllPath;
            IgniteHome = cfg.IgniteHome;
            JvmClasspath = cfg.JvmClasspath;
            SuppressWarnings = cfg.SuppressWarnings;

            JvmOptions = cfg.JvmOptions != null ? new List<string>(cfg.JvmOptions) : null;
            Assemblies = cfg.Assemblies != null ? new List<string>(cfg.Assemblies) : null;

            PortableConfiguration = cfg.PortableConfiguration != null
                ? new PortableConfiguration(cfg.PortableConfiguration)
                : null;

            LifecycleBeans = cfg.LifecycleBeans != null ? new List<ILifecycleBean>(cfg.LifecycleBeans) : null;

            JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
            JvmMaxMemoryMb = cfg.JvmMaxMemoryMb;
        }
Пример #14
0
        /// <summary>
        /// Performs system checks and logs diagnostic messages.
        /// </summary>
        /// <param name="cfg">Configuration.</param>
        /// <param name="log">Log.</param>
        private static void LogDiagnosticMessages(IgniteConfiguration cfg, ILogger log)
        {
            if (!cfg.SuppressWarnings &&
                Interlocked.CompareExchange(ref _diagPrinted, 1, 0) == 0)
            {
                if (!GCSettings.IsServerGC)
                {
                    log.Warn("GC server mode is not enabled, this could lead to less " +
                             "than optimal performance on multi-core machines (to enable see " +
                             "https://docs.microsoft.com/en-us/dotnet/core/run-time-config/garbage-collector).");
                }

                if ((Os.IsLinux || Os.IsMacOs) &&
                    Environment.GetEnvironmentVariable(EnvEnableAlternateStackCheck) != "1")
                {
                    log.Warn("Alternate stack check is not enabled, this will cause 'Stack smashing detected' " +
                             "error when NullReferenceException occurs on .NET Core on Linux and macOS. " +
                             "To enable alternate stack check on .NET Core 3+ and .NET 5+, " +
                             "set {0} environment variable to 1.", EnvEnableAlternateStackCheck);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Preapare configuration.
        /// </summary>
        /// <param name="reader">Reader.</param>
        private static void PrepareConfiguration(BinaryReader reader)
        {
            // 1. Load assemblies.
            IgniteConfiguration cfg = _startup.Configuration;

            LoadAssemblies(cfg.Assemblies);

            ICollection <string> cfgAssembllies;
            BinaryConfiguration  binaryCfg;

            BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg);

            LoadAssemblies(cfgAssembllies);

            // 2. Create marshaller only after assemblies are loaded.
            if (cfg.BinaryConfiguration == null)
            {
                cfg.BinaryConfiguration = binaryCfg;
            }

            _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration);
        }
Пример #16
0
        /// <summary>
        /// Copies the local properties (properties that are not written in Write method).
        /// </summary>
        private void CopyLocalProperties(IgniteConfiguration cfg)
        {
            GridName = cfg.GridName;

            if (BinaryConfiguration != null && cfg.BinaryConfiguration != null)
            {
                BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration);
            }
            else if (cfg.BinaryConfiguration != null)
            {
                BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration);
            }

            JvmClasspath       = cfg.JvmClasspath;
            JvmOptions         = cfg.JvmOptions;
            Assemblies         = cfg.Assemblies;
            SuppressWarnings   = cfg.SuppressWarnings;
            LifecycleBeans     = cfg.LifecycleBeans;
            Logger             = cfg.Logger;
            JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
            JvmMaxMemoryMb     = cfg.JvmMaxMemoryMb;
        }
Пример #17
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-compute.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };
            
            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Closure execution example started.");

                // Split the string by spaces to count letters in each word in parallel.
                ICollection<string> words = "Count characters using closure".Split().ToList();

                Console.WriteLine();
                Console.WriteLine(">>> Calculating character count with manual reducing:");

                var res = ignite.GetCompute().Apply(new CharacterCountClosure(), words);

                int totalLen = res.Sum();

                Console.WriteLine(">>> Total character count: " + totalLen);
                Console.WriteLine();
                Console.WriteLine(">>> Calculating character count with reducer:");

                totalLen = ignite.GetCompute().Apply(new CharacterCountClosure(), words, new CharacterCountReducer());

                Console.WriteLine(">>> Total character count: " + totalLen);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #18
0
        /// <summary>
        /// Copies the local properties (properties that are not written in Write method).
        /// </summary>
        private void CopyLocalProperties(IgniteConfiguration cfg)
        {
            IgniteInstanceName = cfg.IgniteInstanceName;

            if (BinaryConfiguration != null && cfg.BinaryConfiguration != null)
            {
                BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration);
            }
            else if (cfg.BinaryConfiguration != null)
            {
                BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration);
            }

            JvmClasspath                   = cfg.JvmClasspath;
            JvmOptions                     = cfg.JvmOptions;
            Assemblies                     = cfg.Assemblies;
            SuppressWarnings               = cfg.SuppressWarnings;
            LifecycleHandlers              = cfg.LifecycleHandlers;
            Logger                         = cfg.Logger;
            JvmInitialMemoryMb             = cfg.JvmInitialMemoryMb;
            JvmMaxMemoryMb                 = cfg.JvmMaxMemoryMb;
            PluginConfigurations           = cfg.PluginConfigurations;
            AutoGenerateIgniteInstanceName = cfg.AutoGenerateIgniteInstanceName;
        }
Пример #19
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);
        }
Пример #20
0
        public static void Main()
        {
            Console.WriteLine();
            Console.WriteLine(">>> Lifecycle example started.");

            // Create new configuration.
            var lifecycleExampleBean = new LifecycleExampleBean();

            var cfg = new IgniteConfiguration
            {
                DiscoverySpi = new TcpDiscoverySpi
                {
                    IpFinder = new TcpDiscoveryStaticIpFinder
                    {
                        Endpoints = new[] {"127.0.0.1:47500"}
                    }
                },
                LifecycleBeans = new List<ILifecycleBean> {lifecycleExampleBean}
            };

            // Provide lifecycle bean to configuration.
            using (Ignition.Start(cfg))
            {
                // Make sure that lifecycle bean was notified about Ignite startup.
                Console.WriteLine();
                Console.WriteLine(">>> Started (should be true): " + lifecycleExampleBean.Started);
            }

            // Make sure that lifecycle bean was notified about Ignite stop.
            Console.WriteLine();
            Console.WriteLine(">>> Started (should be false): " + lifecycleExampleBean.Started);

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #21
0
        /// <summary>
        /// Starts Ignite with given configuration.
        /// </summary>
        /// <returns>Started Ignite.</returns>
        public unsafe static IIgnite Start(IgniteConfiguration cfg)
        {
            IgniteArgumentCheck.NotNull(cfg, "cfg");

            // Copy configuration to avoid changes to user-provided instance.
            IgniteConfigurationEx cfgEx = cfg as IgniteConfigurationEx;

            cfg = cfgEx == null ? new IgniteConfiguration(cfg) : new IgniteConfigurationEx(cfgEx);

            // Set default Spring config if needed.
            if (cfg.SpringConfigUrl == null)
            {
                cfg.SpringConfigUrl = DefaultCfg;
            }

            lock (SyncRoot)
            {
                // 1. Check GC settings.
                CheckServerGc(cfg);

                // 2. Create context.
                IgniteUtils.LoadDlls(cfg.JvmDllPath);

                var cbs = new UnmanagedCallbacks();

                IgniteManager.CreateJvmContext(cfg, cbs);

                var gridName = cfgEx != null ? cfgEx.GridName : null;

                var cfgPath = Environment.GetEnvironmentVariable(EnvIgniteSpringConfigUrlPrefix) + cfg.SpringConfigUrl;

                // 3. Create startup object which will guide us through the rest of the process.
                _startup = new Startup(cfg, cbs);

                IUnmanagedTarget interopProc = null;

                try
                {
                    // 4. Initiate Ignite start.
                    UU.IgnitionStart(cbs.Context, cfgPath, gridName, ClientMode);

                    // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
                    var node = _startup.Ignite;
                    interopProc = node.InteropProcessor;

                    // 6. On-start callback (notify lifecycle components).
                    node.OnStart();

                    Nodes[new NodeKey(_startup.Name)] = node;

                    return(node);
                }
                catch (Exception)
                {
                    // 1. Perform keys cleanup.
                    string name = _startup.Name;

                    if (name != null)
                    {
                        NodeKey key = new NodeKey(name);

                        if (Nodes.ContainsKey(key))
                        {
                            Nodes.Remove(key);
                        }
                    }

                    // 2. Stop Ignite node if it was started.
                    if (interopProc != null)
                    {
                        UU.IgnitionStop(interopProc.Context, gridName, true);
                    }

                    // 3. Throw error further (use startup error if exists because it is more precise).
                    if (_startup.Error != null)
                    {
                        throw _startup.Error;
                    }

                    throw;
                }
                finally
                {
                    _startup = null;

                    if (interopProc != null)
                    {
                        UU.ProcessorReleaseStart(interopProc);
                    }
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Gets the Ignite instance.
        /// </summary>
        private static IIgnite GetOrStartIgnite(IgniteConfiguration cfg)
        {
            cfg = cfg ?? new IgniteConfiguration();

            return Ignition.TryGetIgnite(cfg.GridName) ?? Ignition.Start(cfg);
        }
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IgniteDbConfiguration" /> class.
 /// </summary>
 /// <param name="igniteConfiguration">The ignite configuration to use for starting Ignite instance.</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 IgniteDbConfiguration(IgniteConfiguration igniteConfiguration,
     CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration,
     IDbCachingPolicy policy)
     : this(GetOrStartIgnite(igniteConfiguration), metaCacheConfiguration, dataCacheConfiguration, policy)
 {
     // No-op.
 }
Пример #24
0
        /// <summary>
        /// Reads XML from the configuration file.
        /// </summary>
        /// <param name="reader">The reader object, which reads from the configuration file.</param>
        protected override void DeserializeSection(XmlReader reader)
        {
            IgniteArgumentCheck.NotNull(reader, "reader");

            IgniteConfiguration = IgniteConfigurationXmlSerializer.Deserialize <IgniteConfiguration>(reader);
        }
Пример #25
0
 /// <summary>
 /// Copies the local properties (properties that are not written in Write method).
 /// </summary>
 private void CopyLocalProperties(IgniteConfiguration cfg)
 {
     GridName = cfg.GridName;
     BinaryConfiguration = cfg.BinaryConfiguration == null
         ? null
         : new BinaryConfiguration(cfg.BinaryConfiguration);
     JvmClasspath = cfg.JvmClasspath;
     JvmOptions = cfg.JvmOptions;
     Assemblies = cfg.Assemblies;
     SuppressWarnings = cfg.SuppressWarnings;
     LifecycleBeans = cfg.LifecycleBeans;
     Logger = cfg.Logger;
     JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
     JvmMaxMemoryMb = cfg.JvmMaxMemoryMb;
 }
Пример #26
0
        public static void Main()
        {
            Console.WriteLine();
            Console.WriteLine(">>> Multi-tiered cache example started.");

            // Configure swap in the current bin directory (where our assembly is located).
            var binDir = Path.GetDirectoryName(typeof(MultiTieredCacheExample).Assembly.Location);
            var swapDir = Path.Combine(binDir, "ignite-swap");

            Console.WriteLine(">>> Swap space directory: " + swapDir);

            var cfg = new IgniteConfiguration
            {
                DiscoverySpi = new TcpDiscoverySpi
                {
                    IpFinder = new TcpDiscoveryMulticastIpFinder
                    {
                        Endpoints = new[] { "127.0.0.1:47500" }
                    }
                },
                SwapSpaceSpi = new FileSwapSpaceSpi
                {
                    BaseDirectory = swapDir
                }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                var cacheCfg = new CacheConfiguration
                {
                    Name = CacheName,
                    Backups = 1,
                    EvictionPolicy = new LruEvictionPolicy
                    {
                        MaxSize = 10 // Maximum number of entries that will be stored in Java heap. 
                    },
                    // Limit off-heap to roughly 10 entries. Actual entry count will be lower due to metadata overhead.
                    OffHeapMaxMemory = EntrySize * 10,
                    // Data will be swapped to disk if there is no more space in off-heap space.
                    EnableSwap = true 
                };

                ICache<int, byte[]> cache = ignite.GetOrCreateCache<int, byte[]>(cacheCfg);

                // Sample data.
                byte[] dataBytes = new byte[EntrySize];

                // Filling out cache and printing its metrics.
                PrintCacheMetrics(cache);

                for (int i = 0; i < 100; i++)
                {
                    cache.Put(i, dataBytes);

                    if (i%10 == 0)
                    {
                        Console.WriteLine(">>> Cache entries created: {0}", i + 1);

                        PrintCacheMetrics(cache);
                    }
                }

                Console.WriteLine(">>> Waiting for metrics final update...");

                Thread.Sleep(TcpDiscoverySpi.DefaultHeartbeatFrequency);

                PrintCacheMetrics(cache);

                Console.WriteLine();
                Console.WriteLine(">>> Example finished, press any key to exit ...");
                Console.ReadKey();
            }
        }
Пример #27
0
        /// <summary>
        /// Application entry point.
        /// </summary>
        internal static void Main(string[] args)
        {
            IgniteConfiguration cfg;

            bool svc = false;
            bool install = false;

            try
            {
                // Check for special cases.
                if (args.Length > 0)
                {
                    string first = args[0].ToLower();

                    if (Help.Contains(first))
                    {
                        PrintHelp();

                        return;
                    }
                    
                    if (Svc.Equals(first))
                    {
                        args = RemoveFirstArg(args);

                        svc = true;
                    }

                    else if (SvcInstall.Equals(first))
                    {
                        args = RemoveFirstArg(args);

                        install = true;
                    }
                    else if (SvcUninstall.Equals(first))
                    {
                        IgniteService.Uninstall();

                        return;
                    }
                }

                if (!svc)
                {
                    // Pick application configuration.
                    cfg = new IgniteConfiguration();

                    new AppSettingsConfigurator().Configure(cfg, ConfigurationManager.AppSettings);

                    // Pick command line arguments.
                    new ArgsConfigurator().Configure(cfg, args);

                    if (install)
                        IgniteService.DoInstall(cfg);
                    else
                    {
                        Ignition.Start(cfg);

                        IgniteManager.DestroyJvm();
                    }

                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: " + e.Message);

                Environment.Exit(-1);
            }

            // If we are here, then this is a service call.
            cfg = new IgniteConfiguration();

            // Use only arguments, not app.config.
            new ArgsConfigurator().Configure(cfg, args);

            ServiceBase.Run(new IgniteService(cfg));
        }
        /// <summary>
        /// Starts Ignite from application configuration.
        /// </summary>
        private static IIgnite StartFromApplicationConfiguration(string sectionName)
        {
            var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection;

            if (section == null)
                throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, 
                    "Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName));

            var config = section.IgniteConfiguration;

            if (string.IsNullOrWhiteSpace(config.IgniteHome))
            {
                // IgniteHome not set by user: populate from default directory
                config = new IgniteConfiguration(config) {IgniteHome = IgniteWebUtils.GetWebIgniteHome()};
            }

            return Ignition.Start(config);
        }
Пример #29
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache-store.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                Console.WriteLine();
                Console.WriteLine(">>> Cache store example started.");

                var cache = ignite.GetCache<int, Employee>(null);

                // Clean up caches on all nodes before run.
                cache.Clear();

                Console.WriteLine();
                Console.WriteLine(">>> Cleared values from cache.");
                Console.WriteLine(">>> Current cache size: " + cache.GetSize());

                // Load entries from store which pass provided filter.
                cache.LoadCache(new EmployeeStorePredicate());

                Console.WriteLine();
                Console.WriteLine(">>> Loaded entry from store through ICache.LoadCache().");
                Console.WriteLine(">>> Current cache size: " + cache.GetSize());
                
                // Load entry from store calling ICache.Get() method.
                Employee emp = cache.Get(2);

                Console.WriteLine();
                Console.WriteLine(">>> Loaded entry from store through ICache.Get(): " + emp);
                Console.WriteLine(">>> Current cache size: " + cache.GetSize());

                // Put an entry to the cache
                cache.Put(3, new Employee(
                    "James Wilson",
                    12500,
                    new Address("1096 Eddy Street, San Francisco, CA", 94109),
                    new List<string> { "Human Resources", "Customer Service" }
                    ));

                Console.WriteLine();
                Console.WriteLine(">>> Put entry to cache. ");
                Console.WriteLine(">>> Current cache size: " + cache.GetSize());

                // Clear values again.
                cache.Clear();
                
                Console.WriteLine();
                Console.WriteLine(">>> Cleared values from cache again.");
                Console.WriteLine(">>> Current cache size: " + cache.GetSize());

                // Read values from cache after clear.
                Console.WriteLine();
                Console.WriteLine(">>> Read values after clear:");

                for (int i = 1; i <= 3; i++)
                    Console.WriteLine(">>>     Key=" + i + ", value=" + cache.Get(i));
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #30
0
        /// <summary>
        /// Starts Ignite with given configuration.
        /// </summary>
        /// <returns>Started Ignite.</returns>
        public unsafe static IIgnite Start(IgniteConfiguration cfg)
        {
            IgniteArgumentCheck.NotNull(cfg, "cfg");

            // Copy configuration to avoid changes to user-provided instance.
            IgniteConfigurationEx cfgEx = cfg as IgniteConfigurationEx;

            cfg = cfgEx == null ? new IgniteConfiguration(cfg) : new IgniteConfigurationEx(cfgEx);

            // Set default Spring config if needed.
            if (cfg.SpringConfigUrl == null)
                cfg.SpringConfigUrl = DefaultCfg;

            lock (SyncRoot)
            {
                // 1. Check GC settings.
                CheckServerGc(cfg);

                // 2. Create context.
                IgniteUtils.LoadDlls(cfg.JvmDllPath);

                var cbs = new UnmanagedCallbacks();

                void* ctx = IgniteManager.GetContext(cfg, cbs);

                sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfg.SpringConfigUrl ?? DefaultCfg);

                string gridName = cfgEx != null ? cfgEx.GridName : null;
                sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);

                // 3. Create startup object which will guide us through the rest of the process.
                _startup = new Startup(cfg, cbs) { Context = ctx };

                IUnmanagedTarget interopProc = null;

                try
                {
                    // 4. Initiate Ignite start.
                    UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl ?? DefaultCfg,
                        cfgEx != null ? cfgEx.GridName : null, ClientMode);

                    // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
                    var node = _startup.Ignite;
                    interopProc = node.InteropProcessor;

                    // 6. On-start callback (notify lifecycle components).
                    node.OnStart();

                    Nodes[new NodeKey(_startup.Name)] = node;

                    return node;
                }
                catch (Exception)
                {
                    // 1. Perform keys cleanup.
                    string name = _startup.Name;

                    if (name != null)
                    {
                        NodeKey key = new NodeKey(name);

                        if (Nodes.ContainsKey(key))
                            Nodes.Remove(key);
                    }

                    // 2. Stop Ignite node if it was started.
                    if (interopProc != null)
                        UU.IgnitionStop(interopProc.Context, gridName, true);

                    // 3. Throw error further (use startup error if exists because it is more precise).
                    if (_startup.Error != null)
                        throw _startup.Error;

                    throw;
                }
                finally
                {
                    _startup = null;

                    Marshal.FreeHGlobal((IntPtr)cfgPath0);

                    if ((IntPtr)gridName0 != IntPtr.Zero)
                        Marshal.FreeHGlobal((IntPtr)gridName0);

                    if (interopProc != null)
                        UU.ProcessorReleaseStart(interopProc);
                }
            }
        }
Пример #31
0
        public static void Main()
        {
            var cfg = new IgniteConfiguration
            {
                SpringConfigUrl = @"platforms\dotnet\examples\config\example-compute.xml",
                JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                var remotes = ignite.GetCluster().ForRemotes();

                if (remotes.GetNodes().Count == 0)
                {
                    Console.WriteLine(">>> This example requires remote nodes to be started.");
                    Console.WriteLine(">>> Please start at least 1 remote node.");
                    Console.WriteLine(">>> Refer to example's documentation for details on configuration.");
                }
                else
                {
                    Console.WriteLine(">>> Messaging example started.");
                    Console.WriteLine();

                    // Set up local listeners
                    var localMessaging = ignite.GetCluster().ForLocal().GetMessaging();

                    var msgCount = remotes.GetNodes().Count * 10;

                    var orderedCounter = new CountdownEvent(msgCount);
                    var unorderedCounter = new CountdownEvent(msgCount);

                    localMessaging.LocalListen(new LocalListener(unorderedCounter), Topic.Unordered);
                    localMessaging.LocalListen(new LocalListener(orderedCounter), Topic.Ordered);

                    // Set up remote listeners
                    var remoteMessaging = remotes.GetMessaging();

                    remoteMessaging.RemoteListen(new RemoteUnorderedListener(), Topic.Unordered);
                    remoteMessaging.RemoteListen(new RemoteOrderedListener(), Topic.Ordered);

                    // Send unordered
                    Console.WriteLine(">>> Sending unordered messages...");

                    for (var i = 0; i < 10; i++)
                        remoteMessaging.Send(i, Topic.Unordered);

                    Console.WriteLine(">>> Finished sending unordered messages.");

                    // Send ordered
                    Console.WriteLine(">>> Sending ordered messages...");

                    for (var i = 0; i < 10; i++)
                        remoteMessaging.SendOrdered(i, Topic.Ordered);

                    Console.WriteLine(">>> Finished sending ordered messages.");

                    Console.WriteLine(">>> Check output on all nodes for message printouts.");
                    Console.WriteLine(">>> Waiting for messages acknowledgements from all remote nodes...");

                    unorderedCounter.Wait();
                    orderedCounter.Wait();
                }
            }

            Console.WriteLine();
            Console.WriteLine(">>> Example finished, press any key to exit ...");
            Console.ReadKey();
        }
Пример #32
0
        /// <summary>
        /// Starts Ignite with given configuration.
        /// </summary>
        /// <returns>Started Ignite.</returns>
        public static unsafe IIgnite Start(IgniteConfiguration cfg)
        {
            IgniteArgumentCheck.NotNull(cfg, "cfg");

            lock (SyncRoot)
            {
                // 0. Init logger
                var log = cfg.Logger ?? new JavaLogger();

                log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version);

                // 1. Check GC settings.
                CheckServerGc(cfg, log);

                // 2. Create context.
                IgniteUtils.LoadDlls(cfg.JvmDllPath, log);

                var cbs = new UnmanagedCallbacks(log);

                IgniteManager.CreateJvmContext(cfg, cbs, log);
                log.Debug("JVM started.");

                var gridName = cfg.IgniteInstanceName;

                if (cfg.AutoGenerateIgniteInstanceName)
                {
                    gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid();
                }

                // 3. Create startup object which will guide us through the rest of the process.
                _startup = new Startup(cfg, cbs);

                PlatformJniTarget interopProc = null;

                try
                {
                    // 4. Initiate Ignite start.
                    UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null);


                    // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
                    var node = _startup.Ignite;
                    interopProc = (PlatformJniTarget)node.InteropProcessor;

                    var javaLogger = log as JavaLogger;
                    if (javaLogger != null)
                    {
                        javaLogger.SetIgnite(node);
                    }

                    // 6. On-start callback (notify lifecycle components).
                    node.OnStart();

                    Nodes[new NodeKey(_startup.Name)] = node;

                    return(node);
                }
                catch (Exception)
                {
                    // 1. Perform keys cleanup.
                    string name = _startup.Name;

                    if (name != null)
                    {
                        NodeKey key = new NodeKey(name);

                        if (Nodes.ContainsKey(key))
                        {
                            Nodes.Remove(key);
                        }
                    }

                    // 2. Stop Ignite node if it was started.
                    if (interopProc != null)
                    {
                        UU.IgnitionStop(interopProc.Target.Context, gridName, true);
                    }

                    // 3. Throw error further (use startup error if exists because it is more precise).
                    if (_startup.Error != null)
                    {
                        // Wrap in a new exception to preserve original stack trace.
                        throw new IgniteException("Failed to start Ignite.NET, check inner exception for details",
                                                  _startup.Error);
                    }

                    throw;
                }
                finally
                {
                    var ignite = _startup.Ignite;

                    _startup = null;

                    if (ignite != null)
                    {
                        ignite.ProcessorReleaseStart();
                    }
                }
            }
        }
Пример #33
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="cfg">Configuration.</param>
 /// <param name="cbs"></param>
 internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs)
 {
     Configuration = cfg;
     Callbacks     = cbs;
 }
Пример #34
0
        /// <summary>
        /// Starts Ignite with given configuration.
        /// </summary>
        /// <returns>Started Ignite.</returns>
        public static unsafe IIgnite Start(IgniteConfiguration cfg)
        {
            IgniteArgumentCheck.NotNull(cfg, "cfg");

            lock (SyncRoot)
            {
                // 1. Check GC settings.
                CheckServerGc(cfg);

                // 2. Create context.
                IgniteUtils.LoadDlls(cfg.JvmDllPath);

                var cbs = new UnmanagedCallbacks();

                IgniteManager.CreateJvmContext(cfg, cbs);

                var gridName = cfg.GridName;

                var cfgPath = cfg.SpringConfigUrl == null
                    ? null
                    : Environment.GetEnvironmentVariable(EnvIgniteSpringConfigUrlPrefix) + cfg.SpringConfigUrl;

                // 3. Create startup object which will guide us through the rest of the process.
                _startup = new Startup(cfg, cbs);

                IUnmanagedTarget interopProc = null;

                try
                {
                    // 4. Initiate Ignite start.
                    UU.IgnitionStart(cbs.Context, cfgPath, gridName, ClientMode);

                    // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
                    var node = _startup.Ignite;
                    interopProc = node.InteropProcessor;

                    // 6. On-start callback (notify lifecycle components).
                    node.OnStart();

                    Nodes[new NodeKey(_startup.Name)] = node;

                    return node;
                }
                catch (Exception)
                {
                    // 1. Perform keys cleanup.
                    string name = _startup.Name;

                    if (name != null)
                    {
                        NodeKey key = new NodeKey(name);

                        if (Nodes.ContainsKey(key))
                            Nodes.Remove(key);
                    }

                    // 2. Stop Ignite node if it was started.
                    if (interopProc != null)
                        UU.IgnitionStop(interopProc.Context, gridName, true);

                    // 3. Throw error further (use startup error if exists because it is more precise).
                    if (_startup.Error != null)
                        throw _startup.Error;

                    throw;
                }
                finally
                {
                    _startup = null;

                    if (interopProc != null)
                        UU.ProcessorReleaseStart(interopProc);
                }
            }
        }
Пример #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
        /// </summary>
        /// <param name="configuration">The configuration to copy.</param>
        public IgniteConfiguration(IgniteConfiguration configuration)
        {
            IgniteArgumentCheck.NotNull(configuration, "configuration");

            CopyLocalProperties(configuration);

            using (var stream = IgniteManager.Memory.Allocate().GetStream())
            {
                var marsh = new Marshaller(configuration.BinaryConfiguration);

                configuration.Write(marsh.StartMarshal(stream));

                stream.SynchronizeOutput();

                stream.Seek(0, SeekOrigin.Begin);

                ReadCore(marsh.StartUnmarshal(stream));
            }
        }
Пример #36
0
 /// <summary>
 /// Check whether GC is set to server mode.
 /// </summary>
 /// <param name="cfg">Configuration.</param>
 private static void CheckServerGc(IgniteConfiguration cfg)
 {
     if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0)
         Logger.LogWarning("GC server mode is not enabled, this could lead to less " +
             "than optimal performance on multi-core machines (to enable see " +
             "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx).");
 }
Пример #37
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="cfg">Configuration.</param>
 /// <param name="cbs"></param>
 internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs)
 {
     Configuration = cfg;
     Callbacks = cbs;
 }
        /// <summary>
        /// Reads XML from the configuration file.
        /// </summary>
        /// <param name="reader">The reader object, which reads from the configuration file.</param>
        protected override void DeserializeSection(XmlReader reader)
        {
            IgniteArgumentCheck.NotNull(reader, "reader");

            IgniteConfiguration = IgniteConfigurationXmlSerializer.Deserialize(reader);
        }