public void TestProtocolMismatch() { using (Ignition.Start(TestUtils.GetTestConfiguration())) { // Connect to Ignite REST endpoint. var cfg = new IgniteClientConfiguration("127.0.0.1:11211"); var ex = GetSocketException(Assert.Catch(() => Ignition.StartClient(cfg))); Assert.AreEqual(SocketError.ConnectionAborted, ex.SocketErrorCode); } }
public void TestDefaults() { var cfg = new IgniteClientConfiguration(); Assert.AreEqual(IgniteClientConfiguration.DefaultPort, cfg.Port); Assert.AreEqual(IgniteClientConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize); Assert.AreEqual(IgniteClientConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize); Assert.AreEqual(IgniteClientConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay); Assert.AreEqual(IgniteClientConfiguration.DefaultSocketTimeout, cfg.SocketTimeout); }
/// <summary> /// Starts the client. /// </summary> /// <param name="configuration">Configuration.</param> /// <returns>Started client.</returns> public static async Task <IIgniteClient> StartAsync(IgniteClientConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, nameof(configuration)); var socket = new ClientFailoverSocket(configuration); await socket.ConnectAsync().ConfigureAwait(false); return(new IgniteClientInternal(socket)); }
public void TestDefaultLoggerWritesToConsole() { IgniteClientConfiguration cfg = null; TestConsoleLogging(c => { cfg = c; }, (client, log) => { Assert.AreSame(cfg.Logger, client.GetConfiguration().Logger); StringAssert.Contains("Partition awareness has been disabled", log); }); }
public void TestEmptyPortRangeThrows() { var cfg = new IgniteClientConfiguration("127.0.0.1:10800..10700"); var ex = Assert.Throws <IgniteClientException>(() => Ignition.StartClient(cfg)); Assert.AreEqual( "Invalid format of IgniteClientConfiguration.Endpoint, port range is empty: 127.0.0.1:10800..10700", ex.Message); }
public static void Services() { var cfg = new IgniteClientConfiguration(); //tag::client-services[] IIgniteClient client = Ignition.StartClient(cfg); IServicesClient services = client.GetServices(); IMyService serviceProxy = services.GetServiceProxy <IMyService>("MyService"); serviceProxy.MyServiceMethod("hello"); //end::client-services[] }
/// <summary> /// Initializes a new instance of <see cref="ClientRetryPolicyContext"/> class. /// </summary> /// <param name="configuration">Configuration.</param> /// <param name="operation">Operation.</param> /// <param name="iteration">Iteration.</param> /// <param name="exception">Exception.</param> public ClientRetryPolicyContext( IgniteClientConfiguration configuration, ClientOperationType operation, int iteration, Exception exception) { Configuration = configuration; Operation = operation; Iteration = iteration; Exception = exception; }
public static void ClientCluster() { var cfg = new IgniteClientConfiguration(); //tag::client-cluster[] IIgniteClient client = Ignition.StartClient(cfg); IClientCluster cluster = client.GetCluster(); cluster.SetActive(true); cluster.EnableWal("my-cache"); //end::client-cluster[] }
public void TestPutGetUserObjects() { var cfg = new IgniteClientConfiguration { BinaryProcessor = new NoopBinaryProcessor(), BinaryConfiguration = new BinaryConfiguration { CompactFooter = false }, Host = IPAddress.Loopback.ToString() }; using (var client = Ignition.StartClient(cfg)) { var serverCache = Ignition.GetIgnite().GetOrCreateCache <int?, Person>( new CacheConfiguration(CacheName, new QueryEntity { KeyType = typeof(int), ValueType = typeof(Person), Fields = new[] { new QueryField("id", typeof(int)), new QueryField("name", typeof(string)) } })); var clientCache = client.GetCache <int?, Person>(CacheName); // Put through client cache. clientCache.Put(1, new Person { Id = 100, Name = "foo" }); clientCache[2] = new Person { Id = 200, Name = "bar" }; // Read from client cache. Assert.AreEqual("foo", clientCache.Get(1).Name); Assert.AreEqual(100, clientCache[1].Id); Assert.AreEqual(200, clientCache[2].Id); // Read from server cache. Assert.AreEqual("foo", serverCache.Get(1).Name); Assert.AreEqual(100, serverCache[1].Id); Assert.AreEqual(200, serverCache[2].Id); // SQL from server cache. var sqlRes = serverCache.Query(new SqlQuery(typeof(Person), "where id = 100")).GetAll().Single(); Assert.AreEqual(1, sqlRes.Key); Assert.AreEqual(100, sqlRes.Value.Id); Assert.AreEqual("foo", sqlRes.Value.Name); } }
public IgniteBookCache(ILogger logger, IIgniteClient igniteClient, IgniteClientConfiguration configuration) { this.logger = logger; this.igniteClient = igniteClient; bookCache = this.igniteClient.GetOrCreateCache <BookKey, Book>(new CacheClientConfiguration { Name = "Books", AtomicityMode = CacheAtomicityMode.Transactional, DataRegionName = configuration.DataRegion }); }
public void TestFromXml() { // Empty (root element name does not matter). var cfg = IgniteClientConfiguration.FromXml("<foo />"); Assert.AreEqual(new IgniteClientConfiguration().ToXml(), cfg.ToXml()); // Properties. cfg = IgniteClientConfiguration.FromXml("<a host='h' port='123' />"); Assert.AreEqual("h", cfg.Host); Assert.AreEqual(123, cfg.Port); // Full config. var fullCfg = new IgniteClientConfiguration { Host = "test1", Port = 345, SocketReceiveBufferSize = 222, SocketSendBufferSize = 333, TcpNoDelay = false, SocketTimeout = TimeSpan.FromSeconds(15), BinaryConfiguration = new BinaryConfiguration { CompactFooter = false, KeepDeserialized = false, Types = new[] { "foo", "bar" } }, SslStreamFactory = new SslStreamFactory { CertificatePath = "abc.pfx", CertificatePassword = "******", CheckCertificateRevocation = true, SkipServerCertificateValidation = true, SslProtocols = SslProtocols.None }, Endpoints = new [] { "foo", "bar:123", "baz:100..103" }, EnableAffinityAwareness = true }; using (var xmlReader = XmlReader.Create(Path.Combine("Config", "Client", "IgniteClientConfiguration.xml"))) { xmlReader.MoveToContent(); cfg = IgniteClientConfiguration.FromXml(xmlReader); Assert.AreEqual(cfg.ToXml(), fullCfg.ToXml()); } }
/// <summary> /// Starts the client. /// </summary> private static IIgniteClient StartClient() { var cfg = new IgniteClientConfiguration(JavaServer.GetClientConfiguration()) { Logger = new ListLogger(new ConsoleLogger { MinLevel = LogLevel.Trace }), EnablePartitionAwareness = true }; return(Ignition.StartClient(cfg)); }
private static async Task MainAsync() { var cfg = new IgniteConfiguration { DiscoverySpi = new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }, ClientConnectorConfiguration = new ClientConnectorConfiguration { Port = 10842 }, Localhost = "127.0.0.1" }; using (var ignite = Ignition.Start(cfg)) { var cacheCfg = new CacheConfiguration( "cache1", new QueryEntity(typeof(int), typeof(Person))); var cache = ignite.CreateCache <int, Person>(cacheCfg); cache.Put(1, new Person(1)); Debug.Assert(1 == cache[1].Age); var resPerson = cache.AsCacheQueryable() .Where(e => e.Key > 0 && e.Value.Name.StartsWith("Person")) .Select(e => e.Value) .Single(); Debug.Assert(1 == resPerson.Age); var clientCfg = new IgniteClientConfiguration("127.0.0.1:10842"); using (var igniteThin = Ignition.StartClient(clientCfg)) { var cacheThin = igniteThin.GetCache <int, Person>(cacheCfg.Name); var personThin = await cacheThin.GetAsync(1); Debug.Assert("Person-1" == personThin.Name); var personNames = cacheThin.AsCacheQueryable() .Where(e => e.Key != 2 && e.Value.Age < 10) .Select(e => e.Value.Name) .ToArray(); Debug.Assert(personNames.SequenceEqual(new[] { "Person-1" })); } } }
public static void ClientClusterGroups() { var cfg = new IgniteClientConfiguration(); //tag::client-cluster-groups[] IIgniteClient client = Ignition.StartClient(cfg); IClientClusterGroup serversInDc1 = client.GetCluster().ForServers().ForAttribute("dc", "dc1"); foreach (IClientClusterNode node in serversInDc1.GetNodes()) { Console.WriteLine($"Node ID: {node.Id}"); } //end::client-cluster-groups[] }
public async Task TestFailoverWithRetryPolicyDoesNotRetryUnrelatedErrors() { var cfg = new IgniteClientConfiguration { RetryPolicy = RetryAllPolicy.Instance }; using var server = new FakeServer(reqId => reqId % 2 == 0); using var client = await server.ConnectClientAsync(cfg); var ex = Assert.ThrowsAsync <IgniteClientException>(async() => await client.Tables.GetTableAsync("bad-table")); Assert.AreEqual(FakeServer.Err, ex !.Message); }
/// <summary> /// Initializes a new instance of the <see cref="IgniteClient"/> class. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> public IgniteClient(IgniteClientConfiguration clientConfiguration) { Debug.Assert(clientConfiguration != null); _socket = new ClientSocket(clientConfiguration); _marsh = new Marshaller(clientConfiguration.BinaryConfiguration) { Ignite = this }; _binProc = clientConfiguration.BinaryProcessor ?? new BinaryProcessorClient(_socket); }
public static void ExecutingSql() { using (var ignite = Ignition.Start()) { var cfg = new IgniteClientConfiguration { Endpoints = new[] { "127.0.0.1:10800" } }; using (var client = Ignition.StartClient(cfg)) { //tag::executingSql[] var cache = client.GetOrCreateCache <int, Person>("Person"); cache.Query(new SqlFieldsQuery( $"CREATE TABLE IF NOT EXISTS Person (id INT PRIMARY KEY, name VARCHAR) WITH \"VALUE_TYPE={typeof(Person)}\"") { Schema = "PUBLIC" }).GetAll(); var key = 1; var val = new Person { Id = key, Name = "Person 1" }; cache.Query( new SqlFieldsQuery("INSERT INTO Person(id, name) VALUES(?, ?)") { Arguments = new object[] { val.Id, val.Name }, Schema = "PUBLIC" } ).GetAll(); var cursor = cache.Query( new SqlFieldsQuery("SELECT name FROM Person WHERE id = ?") { Arguments = new object[] { key }, Schema = "PUBLIC" } ); var results = cursor.GetAll(); var first = results.FirstOrDefault(); if (first != null) { Console.WriteLine("name = " + first[0]); } //end::executingSql[] } } }
public static void ThinClientCacheOperations() { var cfg = new IgniteClientConfiguration { Endpoints = new[] { "127.0.0.1:10800" } }; using (var client = Ignition.StartClient(cfg)) { //tag::createCache[] var cacheCfg = new CacheClientConfiguration { Name = "References", CacheMode = CacheMode.Replicated, WriteSynchronizationMode = CacheWriteSynchronizationMode.FullSync }; var cache = client.GetOrCreateCache <int, string>(cacheCfg); //end::createCache[] //tag::basicOperations[] var data = Enumerable.Range(1, 100).ToDictionary(e => e, e => e.ToString()); cache.PutAll(data); var replace = cache.Replace(1, "2", "3"); Console.WriteLine(replace); //false var value = cache.Get(1); Console.WriteLine(value); //1 replace = cache.Replace(1, "1", "3"); Console.WriteLine(replace); //true value = cache.Get(1); Console.WriteLine(value); //3 cache.Put(101, "101"); cache.RemoveAll(data.Keys); var sizeIsOne = cache.GetSize() == 1; Console.WriteLine(sizeIsOne); //true value = cache.Get(101); Console.WriteLine(value); //101 cache.RemoveAll(); var sizeIsZero = cache.GetSize() == 0; Console.WriteLine(sizeIsZero); //true //end::basicOperations[] } }
private static async Task <string> ConnectAndGetLog(TimeSpan heartbeatInterval) { var logger = new ListLogger(); var cfg = new IgniteClientConfiguration(GetConfig()) { Logger = logger, HeartbeatInterval = heartbeatInterval }; using var client = await IgniteClient.StartAsync(cfg); return(logger.GetLogString()); }
/// <summary> /// Gets the socket stream. /// </summary> private static Stream GetSocketStream(Socket socket, IgniteClientConfiguration cfg, string host) { var stream = new NetworkStream(socket) { WriteTimeout = (int)cfg.SocketTimeout.TotalMilliseconds }; if (cfg.SslStreamFactory == null) { return(stream); } return(cfg.SslStreamFactory.Create(stream, host)); }
public async Task TestRetryReadPolicyDoesNotRetryWriteOperations() { var cfg = new IgniteClientConfiguration { RetryPolicy = new RetryReadPolicy() }; using var server = new FakeServer(reqId => reqId % 2 == 0); using var client = await server.ConnectClientAsync(cfg); var table = await client.Tables.GetTableAsync(FakeServer.ExistingTableName); Assert.ThrowsAsync <IgniteClientException>(async() => await table !.RecordBinaryView.UpsertAsync(null, new IgniteTuple())); }
/// <summary> /// Initializes a new instance of the <see cref="ClientSocket" /> class. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> /// <param name="endPoint">The end point to connect to.</param> /// <param name="host">The host name (required for SSL).</param> /// <param name="version">Protocol version.</param> /// <param name="topVerCallback">Topology version update callback.</param> /// <param name="marshaller">Marshaller.</param> public ClientSocket(IgniteClientConfiguration clientConfiguration, EndPoint endPoint, string host, ClientProtocolVersion?version, Action <AffinityTopologyVersion> topVerCallback, Marshaller marshaller) { Debug.Assert(clientConfiguration != null); Debug.Assert(endPoint != null); Debug.Assert(!string.IsNullOrWhiteSpace(host)); Debug.Assert(topVerCallback != null); Debug.Assert(marshaller != null); _topVerCallback = topVerCallback; _marsh = marshaller; _timeout = clientConfiguration.SocketTimeout; _logger = (clientConfiguration.Logger ?? NoopLogger.Instance).GetLogger(GetType()); _socket = Connect(clientConfiguration, endPoint, _logger); _stream = GetSocketStream(_socket, clientConfiguration, host); ServerVersion = version ?? CurrentProtocolVersion; Validate(clientConfiguration); _features = Handshake(clientConfiguration, ServerVersion); if (clientConfiguration.EnableHeartbeats) { if (_features.HasFeature(ClientBitmaskFeature.Heartbeat)) { _heartbeatInterval = GetHeartbeatInterval(clientConfiguration); _heartbeatTimer = new Timer(SendHeartbeat, null, dueTime: _heartbeatInterval, period: TimeSpan.FromMilliseconds(-1)); } else { _logger.Warn("Heartbeats are enabled, but server does not support heartbeat feature."); } } // Check periodically if any request has timed out. if (_timeout > TimeSpan.Zero) { // Minimum Socket timeout is 500ms. _timeoutCheckTimer = new Timer(CheckTimeouts, null, _timeout, TimeSpan.FromMilliseconds(500)); } // Continuously and asynchronously wait for data from server. // TaskCreationOptions.LongRunning actually means a new thread. TaskRunner.Run(WaitForMessages, TaskCreationOptions.LongRunning); }
private static Socket Connect(IgniteClientConfiguration cfg) { List <Exception> errors = null; foreach (var ipEndPoint in GetEndPoints(cfg)) { try { var socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = cfg.TcpNoDelay, Blocking = true, SendTimeout = (int)cfg.SocketTimeout.TotalMilliseconds, ReceiveTimeout = (int)cfg.SocketTimeout.TotalMilliseconds }; if (cfg.SocketSendBufferSize != IgniteClientConfiguration.DefaultSocketBufferSize) { socket.SendBufferSize = cfg.SocketSendBufferSize; } if (cfg.SocketReceiveBufferSize != IgniteClientConfiguration.DefaultSocketBufferSize) { socket.ReceiveBufferSize = cfg.SocketReceiveBufferSize; } socket.Connect(ipEndPoint); return(socket); } catch (SocketException e) { if (errors == null) { errors = new List <Exception>(); } errors.Add(e); } } if (errors == null) { throw new IgniteException("Failed to resolve client host: " + cfg.Host); } throw new AggregateException("Failed to establish Ignite thin client connection, " + "examine inner exceptions for details.", errors); }
public async Task TestFailoverWithRetryPolicyDoesNotRetryTxCommit() { var testRetryPolicy = new TestRetryPolicy(); var cfg = new IgniteClientConfiguration { RetryPolicy = testRetryPolicy }; using var server = new FakeServer(reqId => reqId % 2 == 0); using var client = await server.ConnectClientAsync(cfg); var tx = await client.Transactions.BeginAsync(); Assert.ThrowsAsync <IgniteClientException>(async() => await tx.CommitAsync()); Assert.IsEmpty(testRetryPolicy.Invocations); }
public void TestFailover() { // Start 3 nodes. Ignition.Start(TestUtils.GetTestConfiguration(name: "0")); Ignition.Start(TestUtils.GetTestConfiguration(name: "1")); Ignition.Start(TestUtils.GetTestConfiguration(name: "2")); // Connect client. var port = IgniteClientConfiguration.DefaultPort; var cfg = new IgniteClientConfiguration { Endpoints = new[] { "localhost", string.Format("127.0.0.1:{0}..{1}", port + 1, port + 2) } }; using (var client = Ignition.StartClient(cfg)) { Assert.AreEqual(0, client.GetCacheNames().Count); // Stop target node. var nodeId = ((IPEndPoint)client.RemoteEndPoint).Port - port; Ignition.Stop(nodeId.ToString(), true); // Check failure. Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); // Check reconnect. Assert.AreEqual(0, client.GetCacheNames().Count); // Stop target node. nodeId = ((IPEndPoint)client.RemoteEndPoint).Port - port; Ignition.Stop(nodeId.ToString(), true); // Check failure. Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); // Check reconnect. Assert.AreEqual(0, client.GetCacheNames().Count); // Stop all nodes. Ignition.StopAll(true); Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames()))); } }
/// <summary> /// Gets the endpoints: all combinations of IP addresses and ports according to configuration. /// </summary> private IEnumerable <SocketEndpoint> GetIpEndPoints(IgniteClientConfiguration cfg) { foreach (var e in Endpoint.GetEndpoints(cfg)) { var host = e.Host; Debug.Assert(host != null); // Checked by GetEndpoints. for (var port = e.Port; port <= e.PortRange + e.Port; port++) { foreach (var ip in GetIps(e.Host)) { yield return(new SocketEndpoint(new IPEndPoint(ip, port), e.Host)); } } } }
public static void Main() { Ignition.Start(); var cfg = new IgniteClientConfiguration { Host = "192.168.1.35" }; using (IIgniteClient client = Ignition.StartClient(cfg)) { ICacheClient <int, string> cache = client.GetCache <int, string>("cache"); cache.Put(1, "Hello, World!"); } Console.ReadKey(); }
public static void ThinClientConnecting() { //tag::connecting[] var cfg = new IgniteClientConfiguration { Endpoints = new[] { "127.0.0.1:10800" } }; using (var client = Ignition.StartClient(cfg)) { var cache = client.GetOrCreateCache <int, string>("cache"); cache.Put(1, "Hello, World!"); } //end::connecting[] }
public void TestReconnectToOldNodeDisablesPartitionAwareness() { IIgniteClient client = null; var clientConfiguration = new IgniteClientConfiguration(JavaServer.GetClientConfiguration()) { EnablePartitionAwareness = true, Logger = new ListLogger(new ConsoleLogger { MinLevel = LogLevel.Trace }) }; try { using (StartNewServer()) { client = Ignition.StartClient(clientConfiguration); var cache = client.GetOrCreateCache <int, int>(TestContext.CurrentContext.Test.Name); cache.Put(1, 42); Assert.AreEqual(42, cache.Get(1)); Assert.IsTrue(client.GetConfiguration().EnablePartitionAwareness); } Assert.Catch(() => client.GetCacheNames()); using (StartOldServer()) { var cache = client.GetOrCreateCache <int, int>(TestContext.CurrentContext.Test.Name); cache.Put(1, 42); Assert.AreEqual(42, cache.Get(1)); Assert.IsFalse(client.GetConfiguration().EnablePartitionAwareness); var log = ((ListLogger)client.GetConfiguration().Logger).Entries .FirstOrDefault(e => e.Message.StartsWith("Partition")); Assert.IsNotNull(log); Assert.AreEqual("Partition awareness has been disabled: " + "server protocol version 1.0.0 is lower than required 1.4.0", log.Message); } } finally { if (client != null) { client.Dispose(); } } }
public void TestPutGetUserObjects() { var cfg = new IgniteClientConfiguration { BinaryProcessor = new NoopBinaryProcessor(), BinaryConfiguration = new BinaryConfiguration { CompactFooter = false }, Endpoints = new[] { IPAddress.Loopback.ToString() } }; using (var client = Ignition.StartClient(cfg)) { var serverCache = Ignition.GetIgnite().GetOrCreateCache <int?, Person>( new CacheConfiguration("person", new QueryEntity(typeof(int?), typeof(Person)))); var clientCache = client.GetCache <int?, Person>(serverCache.Name); // Put through client cache. clientCache.Put(1, new Person { Id = 100, Name = "foo" }); clientCache[2] = new Person { Id = 200, Name = "bar" }; // Read from client cache. Assert.AreEqual("foo", clientCache.Get(1).Name); Assert.AreEqual(100, clientCache[1].Id); Assert.AreEqual(200, clientCache[2].Id); // Read from server cache. Assert.AreEqual("foo", serverCache.Get(1).Name); Assert.AreEqual(100, serverCache[1].Id); Assert.AreEqual(200, serverCache[2].Id); // SQL from server cache. #pragma warning disable 618 var sqlRes = serverCache.Query(new SqlQuery(typeof(Person), "where id = 100")).GetAll().Single(); Assert.AreEqual(1, sqlRes.Key); Assert.AreEqual(100, sqlRes.Value.Id); Assert.AreEqual("foo", sqlRes.Value.Name); #pragma warning restore 618 } }