public IPEndPoint GetMemcachedEndPoint()
        {
            var hostName = Hostname.Replace(HostToken, LocalHost);

            hostName = hostName.Replace(ViewPort, Ports.Direct.ToString(CultureInfo.InvariantCulture));
            return(IPEndPointExtensions.GetEndPoint(hostName));
        }
Exemple #2
0
        private unsafe IPEndPoint Start(QuicListenerOptions options)
        {
            List <SslApplicationProtocol> applicationProtocols = options.ServerAuthenticationOptions !.ApplicationProtocols !;
            IPEndPoint listenEndPoint = options.ListenEndPoint !;

            Internals.SocketAddress address = IPEndPointExtensions.Serialize(listenEndPoint);

            Debug.Assert(_stateHandle.IsAllocated);
            try
            {
                Debug.Assert(!Monitor.IsEntered(_state), "!Monitor.IsEntered(_state)");
                using var msquicBuffers = new MsQuicBuffers();
                msquicBuffers.Initialize(applicationProtocols, applicationProtocol => applicationProtocol.Protocol);
                // TODO: is the layout same for SocketAddress.Buffer and QuicAddr?
                // TODO: maybe add simple extensions/helpers:
                //       - QuicAddr ToQuicAddr(this IPEndPoint ipEndPoint)
                //       - IPEndPoint ToIPEndPoint(this ref QuicAddr quicAddress)
                fixed(byte *paddress = address.Buffer)
                {
                    ThrowIfFailure(MsQuicApi.Api.ApiTable->ListenerStart(
                                       _state.Handle.QuicHandle,
                                       msquicBuffers.Buffers,
                                       (uint)applicationProtocols.Count,
                                       (QuicAddr *)paddress), "ListenerStart failed");
                }
            }
            catch
            {
                _stateHandle.Free();
                throw;
            }

            Debug.Assert(!Monitor.IsEntered(_state), "!Monitor.IsEntered(_state)");
            return(MsQuicParameterHelpers.GetIPEndPointParam(MsQuicApi.Api, _state.Handle, QUIC_PARAM_LISTENER_LOCAL_ADDRESS));
        }
        public void When_Replica_Index_Postive_LocatePrimary_Returns_It()
        {
            var server = new Server(
                new FakeIOService(IPEndPointExtensions.GetEndPoint("127.0.0.1:8091"),
                                  new FakeConnectionPool(), false),
                new NodeAdapter(new Node {
                Hostname = "127.0.0.1"
            },
                                new NodeExt()),
                new ClientConfiguration(),
                new BucketConfig {
                Name = "default"
            },
                new FakeTranscoder());

            var vbucket =
                new VBucket(new Dictionary <IPAddress, IServer>
            {
                { IPEndPointExtensions.GetEndPoint("127.0.0.1:10210").Address, server },
                { IPEndPointExtensions.GetEndPoint("127.0.0.2:10210").Address, server }
            },
                            100, -1, new[] { 0 }, 0, new VBucketServerMap {
                ServerList = new[] { "127.0.0.1:10210", "127.0.0.2:10210" }
            });
            var found = vbucket.LocatePrimary();

            Assert.IsNotNull(found);
        }
        public override void LoadConfig()
        {
            var servers            = new List <IServer>();
            var clientBucketConfig = ClientConfig.BucketConfigs[BucketConfig.Name];
            var nodes = BucketConfig.GetNodes();

            foreach (var adapter in nodes)
            {
                var endpoint = IPEndPointExtensions.GetEndPoint(adapter, clientBucketConfig, BucketConfig);
                try
                {
                    var connectionPool = ConnectionPoolFactory(clientBucketConfig.PoolConfiguration, endpoint);
                    var ioStrategy     = IOStrategyFactory(connectionPool);
                    var server         = new Core.Server(ioStrategy, adapter, ClientConfig, BucketConfig);
                    var saslMechanism  = SaslFactory(BucketConfig.Name, BucketConfig.Password, ioStrategy, Transcoder);
                    ioStrategy.SaslMechanism = saslMechanism;
                    servers.Add(server);
                }
                catch (Exception e)
                {
                    Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                }
            }
            var old = Interlocked.Exchange(ref Servers, servers);

            if (old != null)
            {
                old.ForEach(x => x.Dispose());
                old.Clear();
            }
            Interlocked.Exchange(ref KeyMapper, new KetamaKeyMapper(Servers));
        }
        public void When_Replica_Index_Postive_LocatePrimary_Returns_It()
        {
            var mockBucketConfig = new Mock <IBucketConfig>();

            var server = new Server(
                new FakeIOService(IPEndPointExtensions.GetEndPoint("127.0.0.1:8091"),
                                  new FakeConnectionPool(), false),
                new NodeAdapter(new Node {
                Hostname = "127.0.0.1"
            }, new NodeExt(), mockBucketConfig.Object),
                new FakeTranscoder(),
                ContextFactory.GetCouchbaseContext());

            var vbucket =
                new VBucket(new Dictionary <IPEndPoint, IServer>
            {
                { IPEndPointExtensions.GetEndPoint("127.0.0.1:10210"), server },
                { IPEndPointExtensions.GetEndPoint("127.0.0.2:10210"), server }
            },
                            100, -1, new[] { 0 }, 0, new VBucketServerMap {
                ServerList = new[] { "127.0.0.1:10210", "127.0.0.2:10210" }
            }, "default");
            var found = vbucket.LocatePrimary();

            Assert.IsNotNull(found);
        }
        public void Test_Authenticate(bool isAuthenticated, bool isEncrypted, bool isSigned)
        {
            var endpoint     = IPEndPointExtensions.GetEndPoint(TestConfiguration.Settings.Hostname, 11207);
            var bootstrapUri = new Uri($@"https://{endpoint.Address}:8091/pools");
            var socket       = new Socket(SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(endpoint);

            var poolConfig = new PoolConfiguration {
                UseSsl = true, Uri = bootstrapUri, ClientConfiguration = new ClientConfiguration()
            };
            var sslStream = new Mock <SslStream>(new MemoryStream(), true, new RemoteCertificateValidationCallback(ServerCertificateValidationCallback));

            sslStream.Setup(x => x.IsAuthenticated).Returns(isAuthenticated);
            sslStream.Setup(x => x.IsEncrypted).Returns(isEncrypted);
            sslStream.Setup(x => x.IsSigned).Returns(isSigned);

            var connPool = new Mock <IConnectionPool <IConnection> >();

            connPool.Setup(x => x.Configuration).Returns(poolConfig);
            var conn = new SslConnection(connPool.Object, socket, sslStream.Object, new DefaultConverter(),
                                         new BufferAllocator(1024, 1024));

            if (isAuthenticated && isEncrypted && isSigned)
            {
                Assert.DoesNotThrow(conn.Authenticate);
            }
            else
            {
                Assert.Throws <AuthenticationException>(conn.Authenticate);
            }
        }
        public void When_Hostname_Is_Provided_IPAdress_Is_Returned()
        {
            var hostname = "127.0.0.1:8091";
            var expected = "127.0.0.1";
            var actual   = IPEndPointExtensions.GetEndPoint(hostname);

            Assert.AreEqual(expected, actual.Address.ToString());
        }
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                if (bucketConfig == null)
                {
                    throw new ArgumentNullException("bucketConfig");
                }
                if (BucketConfig == null || !BucketConfig.Nodes.AreEqual <Node>(bucketConfig.Nodes) || !Servers.Any() ||
                    force)
                {
                    Log.Info(m => m("o1-Creating the Servers {0} list using rev#{1}", Servers.Count(), bucketConfig.Rev));
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new List <IServer>();
                    var nodes = bucketConfig.GetNodes();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = IPEndPointExtensions.GetEndPoint(adapter, clientBucketConfig, BucketConfig);
                        try
                        {
                            var poolConfiguration = ClientConfig.BucketConfigs[bucketConfig.Name].PoolConfiguration;
                            var connectionPool    = ConnectionPoolFactory(poolConfiguration, endpoint);
                            var ioStrategy        = IOStrategyFactory(connectionPool);
                            var saslMechanism     = SaslFactory(bucketConfig.Name, bucketConfig.Password, ioStrategy, Converter);
                            ioStrategy.SaslMechanism = saslMechanism;

                            var server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig);
                            servers.Add(server);
                        }
                        catch (Exception e)
                        {
                            Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                        }
                    }
                    var old = Interlocked.Exchange(ref Servers, servers);
                    if (old != null)
                    {
                        old.ForEach(x => x.Dispose());
                        old.Clear();
                    }
                }
                Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                Interlocked.Exchange(ref KeyMapper, new VBucketKeyMapper(Servers, _bucketConfig.VBucketServerMap)
                {
                    Rev = _bucketConfig.Rev
                });
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
Exemple #9
0
        public static string Connect(IPEndPoint EndPoint, out DateTime LastSeen)
        {
            LastSeen = DateTime.MinValue;
            if (EndPoint == null || EndPoint.Address == null)
            {
                return("");
            }
            MySqlConnection ConX     = null;
            bool            openConX = ConX == null;

            if (openConX)
            {
                ConX = new MySqlConnection(DBOps.ConnectionString);
                ConX.Open();
            }

            uint   ip   = IPEndPointExtensions.ToUint32(EndPoint);
            string hash = IPEndPointExtensions.CalculateHash(EndPoint);
            string sql  = @"INSERT IGNORE INTO geo (ClientHash,IPAddress) VALUES (@ClientHash,@IPAddress);";

            using (var cmd = new MySqlCommand(sql, ConX))
            {
                cmd.Parameters.AddWithValue("ClientHash", hash);
                cmd.Parameters.AddWithValue("IPAddress", ip);
                cmd.ExecuteNonQuery();
                cmd.CommandText = @"UPDATE geo gg
                    JOIN geo g ON gg.ClientHash=g.ClientHash
                    SET gg.IPAddress=@IPAddress
                    WHERE g.IPAddress IS NULL
                    AND g.Geo IS NULL
                    AND g.ClientHash=@ClientHash;";
                cmd.ExecuteNonQuery();
            }

            sql = @"SELECT MAX(`Timestamp`) AS ts
                FROM stats
                WHERE ClientHash=@ClientHash;";
            using (var cmd = new MySqlCommand(sql, ConX))
            {
                cmd.Parameters.AddWithValue("ClientHash", hash);
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        LastSeen = rdr.GetDateTimeSafe("ts");
                        break;
                    }
                }
            }

            if (openConX)
            {
                ConX.Close();
            }

            return(hash);
        }
        public void LoadConfig(IOStrategy ioStrategy)
        {
            try
            {
                Lock.EnterWriteLock();
                Log.Info(m => m("o2-Creating the Servers list using rev#{0}", BucketConfig.Rev));

                var clientBucketConfig = ClientConfig.BucketConfigs[BucketConfig.Name];
                var servers            = new List <IServer>();
                var nodes = BucketConfig.GetNodes();
                foreach (var adapter in nodes)
                {
                    var endpoint = IPEndPointExtensions.GetEndPoint(adapter, clientBucketConfig, BucketConfig);
                    try
                    {
                        IServer server = null;
                        if (Equals(ioStrategy.EndPoint, endpoint) || nodes.Count() == 1)
                        {
                            server = new Core.Server(ioStrategy, adapter, ClientConfig, BucketConfig);
                        }
                        else
                        {
                            var poolConfig     = ClientConfig.BucketConfigs[BucketConfig.Name].PoolConfiguration;
                            var connectionPool = ConnectionPoolFactory(poolConfig, endpoint);
                            var newIoStrategy  = IOStrategyFactory(connectionPool);
                            var saslMechanism  = SaslFactory(BucketConfig.Name, BucketConfig.Password, newIoStrategy, Converter);
                            newIoStrategy.SaslMechanism = saslMechanism;
                            server = new Core.Server(newIoStrategy, adapter, ClientConfig, BucketConfig);
                        }
                        servers.Add(server);
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                    }
                }

                Log.Info(m => m("Creating the KeyMapper list using rev#{0}", BucketConfig.Rev));
                var old = Interlocked.Exchange(ref Servers, servers);
                if (old != null)
                {
                    old.ForEach(x => x.Dispose());
                    old.Clear();
                }
                Interlocked.Exchange(ref KeyMapper, new VBucketKeyMapper(Servers, BucketConfig.VBucketServerMap)
                {
                    Rev = BucketConfig.Rev
                });
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
Exemple #11
0
        internal static unsafe QuicAddr ToQuicAddr(this IPEndPoint iPEndPoint)
        {
            // TODO: is the layout same for SocketAddress.Buffer and QuicAddr on all platforms?
            QuicAddr    result     = default;
            Span <byte> rawAddress = MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref result, 1));

            Internals.SocketAddress address = IPEndPointExtensions.Serialize(iPEndPoint);
            Debug.Assert(address.Size <= rawAddress.Length);

            address.Buffer.AsSpan(0, address.Size).CopyTo(rawAddress);
            return(result);
        }
Exemple #12
0
        /// <summary>
        /// Gets the <see cref="T:System.Net.IPEndPoint" /> for the KV port for this node.
        /// </summary>
        /// <param name="port">The port for the <see cref="T:System.Net.IPEndPoint" /></param>
        /// <returns>
        /// An <see cref="T:System.Net.IPEndPoint" /> with the port passed in.
        /// </returns>
        public IPEndPoint GetIPEndPoint(int port)
        {
            var key = Hostname + ":" + port;

            if (!_cachedEndPoints.TryGetValue(key, out var endPoint))
            {
                endPoint = IPEndPointExtensions.GetEndPoint(Hostname, port);
                IsIPv6   = endPoint.AddressFamily == AddressFamily.InterNetworkV6;
                _cachedEndPoints.TryAdd(key, endPoint);
            }
            return(endPoint);
        }
Exemple #13
0
        /// <summary>
        /// Gets the <see cref="IPEndPoint" /> for the KV port for this node.
        /// </summary>
        /// <param name="port">The port for the <see cref="IPEndPoint" /></param>
        /// <returns>
        /// An <see cref="IPEndPoint" /> with the port passed in.
        /// </returns>
        public IPEndPoint GetIPEndPoint(int port)
        {
            var        key = Hostname + ":" + port;
            IPEndPoint endPoint;

            if (!_cachedEndPoints.TryGetValue(key, out endPoint))
            {
                endPoint = IPEndPointExtensions.GetEndPoint(Hostname + ":" + port);
                _cachedEndPoints.TryAdd(key, endPoint);
            }
            return(endPoint);
        }
Exemple #14
0
        public void When_NodeExt_And_UseSsl_Is_True_And_IPv6_IPEndpoint_Uses_Port_11207()
        {
            var serverConfigJson = ResourceHelper.ReadResource("Data\\Configuration\\config-with-nodes-ext.json");
            var serverConfig     = JsonConvert.DeserializeObject <BucketConfig>(serverConfigJson);
            var clientConfig     = new BucketConfiguration {
                UseSsl = true
            };

            const string expected = "192.168.56.101:11207";
            var          actual   = IPEndPointExtensions.GetEndPoint(serverConfig.NodesExt[0].Hostname);

            Assert.AreEqual(expected, actual.ToString());
        }
        public void When_NodeAdapter_And_UseSsl_Is_True_IPEndPoint_Uses_Port_11210()
        {
            var serverConfigJson = ResourceHelper.ReadResource("Data\\Configuration\\config-with-nodes-ext.json");
            var serverConfig     = JsonConvert.DeserializeObject <BucketConfig>(serverConfigJson);
            var clientConfig     = new BucketConfiguration {
                UseSsl = false
            };

            const string expected = "192.168.56.102:11210";
            var          actual   = IPEndPointExtensions.GetEndPoint(serverConfig.GetNodes()[0], clientConfig, serverConfig);

            Assert.AreEqual(expected, actual.ToString());
        }
        public void When_Node_And_UseSsl_Is_True_IPEndPoint_Uses_Port_11207()
        {
            var serverConfigJson = File.ReadAllText("Data\\Configuration\\config-with-nodes-ext.json");
            var serverConfig     = JsonConvert.DeserializeObject <BucketConfig>(serverConfigJson);
            var clientConfig     = new BucketConfiguration {
                UseSsl = true
            };

            const string expected = "192.168.56.101:11207";
            var          actual   = IPEndPointExtensions.GetEndPoint(serverConfig.Nodes[0], clientConfig, serverConfig);

            Assert.AreEqual(expected, actual.ToString());
        }
Exemple #17
0
 // ReSharper disable once InconsistentNaming
 private void EnsureIPEndPointsAreLoaded()
 {
     lock (_syncObj)
     {
         if (_ipEndPoints == null || !_ipEndPoints.Any())
         {
             _ipEndPoints = new List <IPEndPoint>();
             foreach (var server in ServerList)
             {
                 _ipEndPoints.Add(IPEndPointExtensions.GetEndPoint(server));
             }
         }
     }
 }
Exemple #18
0
        public void When_LocalHost_And_CB251_Verify_Ports()
        {
            var bucketConfig =
                JsonConvert.DeserializeObject <BucketConfig>(
                    File.ReadAllText("Data\\Configuration\\carrier-publication-config.json"));

            var nodes = bucketConfig.GetNodes();

            Assert.AreEqual(8091, nodes[0].MgmtApi);
            Assert.AreEqual(8092, nodes[0].Views);
            Assert.AreEqual(18091, nodes[0].MgmtApiSsl);
            Assert.AreEqual(18092, nodes[0].ViewsSsl);
            Assert.AreEqual(11210, nodes[0].KeyValue);
            Assert.AreEqual(11207, nodes[0].KeyValueSsl);
            Assert.AreEqual(IPEndPointExtensions.GetEndPoint(@"127.0.0.1:8092"), nodes[0].GetIPEndPoint(8092));
        }
        public void Test_Authenticate_With_Ssl()
        {
            var endpoint     = IPEndPointExtensions.GetEndPoint(TestConfiguration.Settings.Hostname, 11207);
            var bootstrapUri = new Uri($@"https://{endpoint.Address}:8091/pools");
            var connFactory  = DefaultConnectionFactory.GetGeneric <SslConnection>();
            var poolFactory  = ConnectionPoolFactory.GetFactory();

            ClientConfiguration.IgnoreRemoteCertificateNameMismatch = true;
            var poolConfig = new PoolConfiguration {
                UseSsl = true, Uri = bootstrapUri, ClientConfiguration = new ClientConfiguration()
            };

            var pool = poolFactory(poolConfig, endpoint);
            var conn = connFactory((IConnectionPool <SslConnection>)pool, new DefaultConverter(), new BufferAllocator(1024 * 16, 1024 * 16));

            Assert.IsTrue(conn.IsConnected);
        }
        internal static unsafe void SetIPEndPointParam(MsQuicApi api, SafeHandle nativeObject, uint param, IPEndPoint value)
        {
            Internals.SocketAddress socketAddress = IPEndPointExtensions.Serialize(value);

            // MsQuic always reads same amount of memory as if IPv6 was used, so we can't pass pointer to socketAddress.Buffer directly
            Span <byte> address = stackalloc byte[Internals.SocketAddress.IPv6AddressSize];

            socketAddress.Buffer.AsSpan(0, socketAddress.Size).CopyTo(address);
            address.Slice(socketAddress.Size).Clear();

            fixed(byte *paddress = &MemoryMarshal.GetReference(address))
            {
                QuicExceptionHelpers.ThrowIfFailed(
                    api.SetParamDelegate(nativeObject, param, (uint)address.Length, paddress),
                    "Could not set IPEndPoint");
            }
        }
Exemple #21
0
        public Stats(DateTime timestamp, string ipAddress, string Page, string Frame)
        {
            Timestamp = timestamp;
            int pageNo;

            int.TryParse(Page, out pageNo);
            if (pageNo < 0)
            {
                throw new InvalidDataException("Invalid page number");
            }
            PageNo = pageNo;
            int frameNo = ((Frame ?? "").Trim() + " ")[0] - 'a';

            if (frameNo < 0 || frameNo > 25)
            {
                throw new InvalidDataException("Invalid frame number");
            }
            FrameNo    = frameNo;
            IPAddress  = IPAddress.Parse(ipAddress);
            ClientHash = IPEndPointExtensions.CalculateHash(ipAddress);
        }
Exemple #22
0
        protected override void OnStart(string[] args)
        {
            Log.DebugFormat("Starting...");

            try
            {
                var configuration = ServerConfiguration.ReadOrCreate(Constants.ApplicationConfigurationFile);

                _repository = PluginRepository.Create();
                var repositoryProxy = new PluginRepositoryProxy(_repository, configuration);
                var ep = IPEndPointExtensions.Parse(configuration.Address);
                _server = new Server(ep, repositoryProxy);

                Log.InfoFormat("Started");
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Caught unexpected exception while trying to start: {0}", e);

                throw;
            }
        }
        internal IVBucket GetVBucket()
        {
            var bucketConfig     = ConfigUtil.ServerConfig.Buckets.First(x => x.Name == "default");
            var vBucketServerMap = bucketConfig.VBucketServerMap;

            var servers = new Dictionary <IPAddress, IServer>();

            foreach (var node in bucketConfig.GetNodes())
            {
                servers.Add(IPEndPointExtensions.GetEndPoint(node.Hostname + ":" + node.KeyValue).Address,
                            new Server(_ioService,
                                       node,
                                       new ClientConfiguration(), bucketConfig,
                                       new FakeTranscoder()));
            }

            var vBucketMap = vBucketServerMap.VBucketMap.First();
            var primary    = vBucketMap[0];
            var replicas   = new int[] { vBucketMap[1] };

            return(new VBucket(servers, 0, primary, replicas, bucketConfig.Rev, vBucketServerMap));
        }
Exemple #24
0
        public static bool Update(DateTime Timestamp, string IPAddress, int Page, int Frame)
        {
            if (Timestamp == DateTime.MinValue || string.IsNullOrWhiteSpace(IPAddress) || (Page < 0 && Frame < 0))
            {
                return(false);
            }
            uint ip = IPEndPointExtensions.ToUint32(IPAddress);

            if (ip == 0)
            {
                return(false);
            }
            MySqlConnection ConX     = null;
            bool            openConX = ConX == null;

            if (openConX)
            {
                ConX = new MySqlConnection(DBOps.ConnectionString);
                ConX.Open();
            }

            string hash = IPEndPointExtensions.CalculateHash(IPAddress);
            string sql  = @"INSERT INTO stats (ClientHash,Timestamp,PageNo,FrameNo) 
                VALUES (@ClientHash,@Timestamp,@PageNo,@FrameNo);";
            var    cmd  = new MySqlCommand(sql, ConX);

            cmd.Parameters.AddWithValue("ClientHash", hash);
            cmd.Parameters.AddWithValue("Timestamp", Timestamp);
            cmd.Parameters.AddWithValue("PageNo", Page);
            cmd.Parameters.AddWithValue("FrameNo", Frame);
            cmd.ExecuteNonQuery();

            if (openConX)
            {
                ConX.Close();
            }

            return(true);
        }
Exemple #25
0
        internal IVBucket GetVBucket()
        {
            var bucketConfig     = ConfigUtil.ServerConfig.Buckets.First(x => x.Name == "default");
            var vBucketServerMap = bucketConfig.VBucketServerMap;

            var servers = new Dictionary <IPEndPoint, IServer>();

            foreach (var node in bucketConfig.GetNodes())
            {
                servers.Add(IPEndPointExtensions.GetEndPoint(node.Hostname + ":" + node.KeyValue),
                            new Server(IOService,
                                       node,
                                       new FakeTranscoder(),
                                       ContextFactory.GetCouchbaseContext(bucketConfig)));
            }

            var vBucketMap = vBucketServerMap.VBucketMap.First();
            var primary    = vBucketMap[0];
            var replicas   = new [] { vBucketMap[1] };

            return(new VBucket(servers, 0, primary, replicas, bucketConfig.Rev, vBucketServerMap, "default"));
        }
Exemple #26
0
        private int SendEcho(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool isAsync)
        {
            Interop.IpHlpApi.IPOptions ipOptions = new Interop.IpHlpApi.IPOptions(options);
            if (!_ipv6)
            {
                return((int)Interop.IpHlpApi.IcmpSendEcho2(
                           _handlePingV4,
                           GetWaitHandle(isAsync),
                           IntPtr.Zero,
                           IntPtr.Zero,
#pragma warning disable CS0618 // Address is marked obsolete
                           (uint)address.Address,
#pragma warning restore CS0618
                           _requestBuffer,
                           (ushort)buffer.Length,
                           ref ipOptions,
                           _replyBuffer,
                           MaxUdpPacket,
                           (uint)timeout));
            }

            IPEndPoint ep = new IPEndPoint(address, 0);
            Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
            byte[] sourceAddr = new byte[28];

            return((int)Interop.IpHlpApi.Icmp6SendEcho2(
                       _handlePingV6,
                       GetWaitHandle(isAsync),
                       IntPtr.Zero,
                       IntPtr.Zero,
                       sourceAddr,
                       remoteAddr.Buffer,
                       _requestBuffer,
                       (ushort)buffer.Length,
                       ref ipOptions,
                       _replyBuffer,
                       MaxUdpPacket,
                       (uint)timeout));
        }
Exemple #27
0
        private unsafe IPEndPoint Start(QuicListenerOptions options)
        {
            List <SslApplicationProtocol> applicationProtocols = options.ServerAuthenticationOptions !.ApplicationProtocols !;
            IPEndPoint listenEndPoint = options.ListenEndPoint !;

            Internals.SocketAddress address = IPEndPointExtensions.Serialize(listenEndPoint);

            uint status;

            Debug.Assert(_stateHandle.IsAllocated);

            MemoryHandle[]? handles = null;
            QuicBuffer[]? buffers   = null;
            try
            {
                Debug.Assert(!Monitor.IsEntered(_state), "!Monitor.IsEntered(_state)");
                MsQuicAlpnHelper.Prepare(applicationProtocols, out handles, out buffers);
                fixed(byte *paddress = address.Buffer)
                {
                    status = MsQuicApi.Api.ListenerStartDelegate(_state.Handle, (QuicBuffer *)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)applicationProtocols.Count, paddress);
                }
            }
            catch
            {
                _stateHandle.Free();
                throw;
            }
            finally
            {
                MsQuicAlpnHelper.Return(ref handles, ref buffers);
            }

            QuicExceptionHelpers.ThrowIfFailed(status, "ListenerStart failed.");

            Debug.Assert(!Monitor.IsEntered(_state), "!Monitor.IsEntered(_state)");
            return(MsQuicParameterHelpers.GetIPEndPointParam(MsQuicApi.Api, _state.Handle, (uint)QUIC_PARAM_LISTENER.LOCAL_ADDRESS));
        }
Exemple #28
0
        public void LoadConfig_When_Reused_Server_Use_Latest_NodeAdapter_Settings()
        {
            var initialConfig = JsonConvert.DeserializeObject <BucketConfig>(
                ResourceHelper.ReadResource(@"Data\config-rev-46.json"));

            var mockConnectionPool = new Mock <IConnectionPool>();
            var mockIoService      = new Mock <IIOService>();

            mockIoService.Setup(x => x.ConnectionPool).Returns(mockConnectionPool.Object);
            mockIoService.Setup(x => x.SupportsEnhancedDurability).Returns(true);
            var mockSasl = new Mock <ISaslMechanism>();

            var clientConfig = new ClientConfiguration();
            var context      = new CouchbaseConfigContext(
                initialConfig,
                clientConfig,
                p => mockIoService.Object,
                (a, b) => mockConnectionPool.Object,
                (a, b, c, d) => mockSasl.Object,
                new DefaultTranscoder(),
                null, null);

            context.LoadConfig();
            var server = context.GetServers().First(x => Equals(x.EndPoint, IPEndPointExtensions.GetEndPoint("172.23.120.212", 0)));

            Assert.IsFalse(server.IsQueryNode);

            var newConfig = JsonConvert.DeserializeObject <BucketConfig>(
                ResourceHelper.ReadResource(@"Data\config-rev-60.json"));

            // load first config with single node
            context.LoadConfig(newConfig);

            server = context.GetServers().First(x => Equals(x.EndPoint, IPEndPointExtensions.GetEndPoint("172.23.120.212", 0)));
            Assert.IsTrue(server.IsQueryNode);
        }
Exemple #29
0
 public CachedSerializedEndPoint(IPAddress address)
 {
     IPEndPoint    = new IPEndPoint(address, 0);
     SocketAddress = IPEndPointExtensions.Serialize(IPEndPoint);
 }
Exemple #30
0
        // Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException.
        // We do not need to or want to capture such exceptions into the returned task.
        private Task <PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            var tcs = new TaskCompletionSource <PingReply>();

            _taskCompletionSource = tcs;

            _ipv6     = (address.AddressFamily == AddressFamily.InterNetworkV6);
            _sendSize = buffer.Length;

            // Get and cache correct handle.
            if (!_ipv6 && _handlePingV4 == null)
            {
                _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile();
                if (_handlePingV4.IsInvalid)
                {
                    _handlePingV4 = null;
                    throw new Win32Exception();                     // Gets last error.
                }
            }
            else if (_ipv6 && _handlePingV6 == null)
            {
                _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile();
                if (_handlePingV6.IsInvalid)
                {
                    _handlePingV6 = null;
                    throw new Win32Exception();                     // Gets last error.
                }
            }

            var ipOptions = new Interop.IpHlpApi.IPOptions(options);

            if (_replyBuffer == null)
            {
                _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
            }

            // Queue the event.
            int error;

            try
            {
                if (_pingEvent == null)
                {
                    _pingEvent = new ManualResetEvent(false);
                }
                else
                {
                    _pingEvent.Reset();
                }

                _registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true);

                SetUnmanagedStructures(buffer);

                if (!_ipv6)
                {
                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.IcmpSendEcho2(
                        _handlePingV4,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        (uint)address.GetAddress(),
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
                else
                {
                    IPEndPoint ep = new IPEndPoint(address, 0);
                    SystemNet.Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
                    byte[] sourceAddr = new byte[28];

                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.Icmp6SendEcho2(
                        _handlePingV6,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        sourceAddr,
                        remoteAddr.Buffer,
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
            }
            catch
            {
                UnregisterWaitHandle();
                throw;
            }

            if (error == 0)
            {
                error = Marshal.GetLastWin32Error();

                // Only skip Async IO Pending error value.
                if (error != Interop.IpHlpApi.ERROR_IO_PENDING)
                {
                    // Cleanup.
                    FreeUnmanagedStructures();
                    UnregisterWaitHandle();

                    throw new Win32Exception(error);
                }
            }

            return(tcs.Task);
        }