public ClusterMetricsCollector(IActorRef publisher)
        {
            _publisher = publisher;
            _cluster = Cluster.Get(Context.System);
            Collector = MetricsCollector.Get(Context.System.AsInstanceOf<ExtendedActorSystem>(), _cluster.Settings);
            LatestGossip = MetricsGossip.Empty;
            Nodes = ImmutableHashSet.Create<Address>();

            _metricsCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(
                _cluster.Settings.PeriodicTasksInitialDelay.Max(_cluster.Settings.MetricsInterval),
                _cluster.Settings.MetricsInterval, Self, InternalClusterAction.MetricsTick.Instance, Self);

            _gossipCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(
                _cluster.Settings.PeriodicTasksInitialDelay.Max(_cluster.Settings.GossipInterval), 
                _cluster.Settings.GossipInterval, Self, InternalClusterAction.GossipTick.Instance, Self);

            Receive<InternalClusterAction.GossipTick>(tick => Gossip());
            Receive<InternalClusterAction.MetricsTick>(tick => Collect());
            Receive<MetricsGossipEnvelope>(envelope => ReceiveGossip(envelope));
            Receive<ClusterEvent.CurrentClusterState>(state => ReceiveState(state));
            Receive<ClusterEvent.MemberUp>(up => AddMember(up.Member));
            Receive<ClusterEvent.MemberRemoved>(removed => RemoveMember(removed.Member));
            Receive<ClusterEvent.MemberExited>(exited => RemoveMember(exited.Member));
            Receive<ClusterEvent.UnreachableMember>(member => RemoveMember(member.Member));
            Receive<ClusterEvent.ReachableMember>(member =>
            {
                if (member.Member.Status == MemberStatus.Up) AddMember(member.Member);
            });
            Receive<ClusterEvent.IMemberEvent>(@event => { }); //not interested in other types of member event
        }
        public void TestFixtureSetUp()
        {
            _cluster = new Cluster("couchbaseClients/couchbase");

            using (var bucket = _cluster.OpenBucket())
            {
                bucket.Upsert(TestKeys.KeyWithInt32Value.Key, TestKeys.KeyWithInt32Value.Value);
                bucket.Upsert(TestKeys.KeyWithStringValue.Key, TestKeys.KeyWithStringValue.Value);

                // ISO-8601 and Microsoft JSON Date format:
                bucket.Upsert(TestKeys.KeyWithIsoDateValue.Key, TestKeys.KeyWithIsoDateValue.Value);
                bucket.Upsert(TestKeys.KeyWithIsoUtcDateValue.Key, TestKeys.KeyWithIsoUtcDateValue.Value);
                bucket.Upsert(TestKeys.KeyWithMsDateValue.Key, TestKeys.KeyWithMsDateValue.Value);

                // De-Serialize const JSON string into a Dictionary<string, dynamic> and write via bucket.Upsert(Couchbase.Document<dynamic>)
                var ADict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(TestKeys.KeyWithJsonDocValueStr);
                var couchDoc = new Couchbase.Document<dynamic>()
                {
                    Id = TestKeys.KeyWithJsonDocKey,
                    Content = ADict
                };
                bucket.Upsert(couchDoc);


            }
        }
        public void Test_Timed_Execution_Parallel_Client()
        {
            var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };
            var n = 1000;//set to a higher # if needed

            using (var cluster = new Cluster("couchbaseClients/couchbase"))
            {
                using (var bucket = cluster.OpenBucket())
                {
                    using (new OperationTimer())
                    {
                        var temp = bucket;
                        Parallel.For(0, n, options, i =>
                        {
                            var key = string.Format("key{0}", i);
                            var value = (int?) i;
                            var result = temp.Upsert(key, value);
                            Assert.IsTrue(result.Success);

                            var result1 = temp.Get<int?>(key);
                            Assert.IsTrue(result1.Success);
                            Assert.AreEqual(i, result1.Value);
                        });
                    }
                }
            }
        }
Esempio n. 4
0
 public ClusterHeartBeat(Cluster cluster, IConnectionProvider provider, TimeSpan pollingInterval)
 {
     Cluster = cluster;
     NodeChecks = new Dictionary<INode, IFixedSizeStack<ConnectivityCheck>>();
     ConnectionProvider = provider;
     PollingInterval = pollingInterval;
 }
 public UserData(string name)
 {
     userName = name;
     likedPages = new List<string>();
     likedWikiPages = new List<WikiPage>();
     likedPagesCluster = new Cluster();
 }
        public IBucket GetBucketForKey(string key)
        {
            var config = new ClientConfiguration();
            var fakeServer = new FakeServer(_connectionPool, null, null, _endPoint,
                new FakeIOStrategy(_endPoint, _connectionPool, false));

            var mappedNode = new Mock<IMappedNode>();
            mappedNode.Setup(x => x.LocatePrimary()).Returns(fakeServer);

            var mockKeyMapper = new Mock<IKeyMapper>();
            mockKeyMapper.Setup(x => x.MapKey(key)).Returns(mappedNode.Object);

            var mockConfigInfo = new Mock<IConfigInfo>();
            mockConfigInfo.Setup(x => x.GetKeyMapper()).Returns(mockKeyMapper.Object);
            mockConfigInfo.Setup(x => x.BucketConfig).Returns(_bucketConfig);
            mockConfigInfo.Setup(x => x.GetServer()).Returns(fakeServer);

            var mockController = new Mock<IClusterController>();
            mockController.Setup(x => x.Configuration).Returns(config);
            mockController.Setup(x => x.CreateBucket("memcached", ""))
                .Returns(new MemcachedBucket(mockController.Object, "memcached", _converter, _transcoder));

            var cluster = new Cluster(config, mockController.Object);
            var bucket = cluster.OpenBucket("memcached", "");

            //simulate a config event
            ((IConfigObserver) bucket).NotifyConfigChanged(mockConfigInfo.Object);

            return bucket;
        }
        public IBucket GetBucketForKey(string key)
        {
            var config = new ClientConfiguration();
            var fakeServer = new FakeServer(_connectionPool, null, null, _endPoint,
                new FakeIOService(_endPoint, _connectionPool, false));

            var mockVBucket = new Mock<IVBucket>();
            mockVBucket.Setup(x => x.LocatePrimary()).Returns(fakeServer);

            var mockKeyMapper = new Mock<IKeyMapper>();
            mockKeyMapper.Setup(x => x.MapKey(key, It.IsAny<uint>())).Returns(mockVBucket.Object);

            var mockConfigInfo = new Mock<IConfigInfo>();
            mockConfigInfo.Setup(x => x.GetKeyMapper()).Returns(mockKeyMapper.Object);
            mockConfigInfo.Setup(x => x.BucketConfig).Returns(_bucketConfig);
            mockConfigInfo.Setup(x => x.GetServer()).Returns(fakeServer);
            mockConfigInfo.Setup(x => x.IsDataCapable).Returns(true);
            mockConfigInfo.Setup(x => x.ClientConfig).Returns(new ClientConfiguration());

            var mockController = new Mock<IClusterController>();
            mockController.Setup(x => x.Configuration).Returns(config);
            mockController.Setup(x => x.CreateBucket("default", "", null))
                .Returns(new CouchbaseBucket(mockController.Object, "default", _converter, _transcoder, null));

            var cluster = new Cluster(config, mockController.Object);
            var bucket = cluster.OpenBucket("default", "");

            //simulate a config event
            ((IConfigObserver)bucket).NotifyConfigChanged(mockConfigInfo.Object);

            return bucket;
        }
 public DeleteCommand(Cluster cluster, WritePolicy policy, Key key)
 {
     this.cluster = cluster;
     this.policy = policy;
     this.key = key;
     this.partition = new Partition(key);
 }
Esempio n. 9
0
 void Start()
 {
     cluster = gameObject.GetComponent<Cluster>();
     stageScript = gameObject.GetComponent<Stage> ();
     mouseDragged = Vector3.zero;
     mousePressed = Vector3.zero;
 }
Esempio n. 10
0
    // Update is called once per frame
    void Update()
    {
        if(!HUDDrawer.drawerOut && !SpeechBubble.inFreezeState){
            if(cluster){
                Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                newPosition.z = 1;
                cluster.transform.position = newPosition;
                grid.AlignTransform(cluster.transform);

                if(Input.GetMouseButtonDown(0)){
                    InsertHere();
                }
            }else{
                if(!GameController.Frozen () && !GameController.finished){
                    GameObject nextCluster = GameController.GetNextCluster();
                    if(nextCluster){
                        Cluster returnedCluster = nextCluster.GetComponent<Cluster>();
                        returnedCluster.transform.position = transform.position;
                        if(GameController.remainingEnergy >= 1){
                            Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                            newPosition.z = 1;
                            cluster = returnedCluster;
                            grid.AlignTransform(cluster.transform);
                        }else{
                            Destroy (returnedCluster.gameObject);
                            GameController.LoadLoseScreen();
                        }
                    }
                }
            }
        }
    }
Esempio n. 11
0
        /// <summary>
        /// Need to subscribe to cluster changes
        /// </summary>
        protected override void PreStart()
        {
            this.cluster = Cluster.Get(Context.System);
            this.cluster.Subscribe(
                this.Self,
                ClusterEvent.InitialStateAsEvents,
                new[] { typeof(ClusterEvent.IClusterDomainEvent) });

            Context.GetLogger().Debug(
                "{Type}: Cluster log up",
                this.GetType().Name);

            var seeds = Context.System.Settings.Config.GetStringList("akka.cluster.seed-nodes");
            if (seeds != null && seeds.Count > 0)
            {
                Context.GetLogger().Debug(
                "{Type}: Joining cluster",
                this.GetType().Name);
                this.cluster.JoinSeedNodes(seeds.Select(Address.Parse));
            }

            

            this.cluster.RegisterOnMemberUp(
                () =>
                    {
                        Context.GetLogger().Debug("{Type}: Cluster connection is up", this.GetType().Name);
                    });
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            Logger.ParseArgs(args);

            Console.WriteLine("Init...");
            Prajna.Core.Environment.Init();
            Console.WriteLine("Init done.");

            var cluster = new Cluster("cluster.lst");
            var nodes = cluster.Nodes;
            //var cluster = new Cluster("local[2]");
            Console.WriteLine($"nodes = {cluster.NumNodes}");

            GetProcessInfo(cluster);

            var containers = Prajna.Service.DistributedFunctionBuiltIn.GetConnectedContainers();
            foreach (var container in containers )
            {
                var name = container.Item1;
                var info = container.Item2;
                Console.WriteLine($"The connected containers are = {name}, {info}");
            }
            Console.WriteLine("Cleanup...");
            Prajna.Core.Environment.Cleanup();
            Console.WriteLine("Cleanup done");
        }
 public QueryRecordExecutor(Cluster cluster, QueryPolicy policy, Statement statement)
     : base(cluster, policy, statement)
 {
     this.recordSet = new RecordSet(this, policy.recordQueueSize, cancel.Token);
     statement.Prepare(true);
     InitializeThreads();
 }
        public void Test()
        {
            var keyValues = new Dictionary<string, string>();
            using (var cluster = new Cluster())
            {
                using (var bucket = cluster.OpenBucket())
                {
                    for (int i = 0; i <10; i++)
                    {
                        var key = "MGETKEY" + i;
                        var value = "{\"val:\"MGETVALUE" + i +"\"}";
                        bucket.Upsert(key, value);
                        keyValues.Add(key, value);
                    }

                    foreach (var keyValue in keyValues)
                    {
                        Console.WriteLine(bucket.Get<dynamic>(keyValue.Key).Value);
                    }
                }
            }

            var operations = new ConcurrentDictionary<uint, IOperation>();
            foreach (var keyValue in keyValues)
            {
                var getk = new GetK<dynamic>(keyValue.Key, GetVBucket(), Converter, Transcoder);
                operations.TryAdd(getk.Opaque, getk);
            }
            var noop = new Noop(Converter);
            operations.TryAdd(noop.Opaque, noop);

            var results = IOStrategy.Execute<dynamic>(operations);
        }
        public void Test_CanAuthenticate_Views()
        {
            var credentials = new ClusterCredentials
            {
                ClusterUsername = "******",
                ClusterPassword = "******",
                BucketCredentials = new AttributeDictionary
                {
                    {"authenticated", "secret"}
                }
            };

            var cluster = new Cluster(TestConfiguration.GetCurrentConfiguration());

            cluster.Authenticate(credentials);

            //if authentication failed - an exception would be thrown during bootstrapping
            var bucket = cluster.OpenBucket("authenticated");
            var query = bucket.CreateQuery("somedoc", "someview");
            var result = bucket.Query<dynamic>(query);

            //assert - view does not exist but should still return a response and no auth error
            Assert.IsFalse(result.Success);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
        }
 public void When_Bucket_Is_Not_Open_IsOpen_Returns_False()
 {
     var cluster = new Cluster("couchbaseClients/couchbase");
     var bucket = cluster.OpenBucket("default");
     cluster.CloseBucket(bucket);
     Assert.IsFalse(cluster.IsOpen("default"));
 }
 public void When_Bucket_Is_Closed_By_Dispose_IsOpen_Returns_False()
 {
     var cluster = new Cluster("couchbaseClients/couchbase");
     var bucket = cluster.OpenBucket("default");
     bucket.Dispose();
     Assert.IsFalse(cluster.IsOpen("default"));
 }
        public void When_Configuration_Contains_Bad_Bucket_Password_It_Is_Used_And_Fails()
        {
            var config = new ClientConfiguration((CouchbaseClientSection) ConfigurationManager.GetSection("couchbaseClients/couchbase"));
            config.BucketConfigs = new Dictionary<string, BucketConfiguration>
            {
                {
                    "default",
                    new BucketConfiguration
                    {
                        BucketName = "default",
                        Password = "******"
                    }
                }
            };

            var cluster = new Cluster(config);
            var bucketName = config.BucketConfigs.Single().Value.BucketName;
            try
            {
                var bucket = cluster.OpenBucket(bucketName);
                Assert.Fail("Unexpected GetBucket success");
            }
            catch (AggregateException e)
            {
                e = e.Flatten();
                if (e.InnerExceptions.All(x => x.GetType() != typeof (AuthenticationException)))
                {
                    Assert.Fail("Expected authentication exception, got " + e.InnerException);
                }
                //success
            }
        }
Esempio n. 19
0
        private bool Estimate(Cluster cluster)
        {
            var name = Guid.NewGuid().ToString("D");

            var value =
                (new DSet<int> { Name = name, Cluster = cluster })
                .SourceI(NumPartitions, i => Enumerable.Range(1, NumSamplesPerPartition).Select(j => i * NumSamplesPerPartition + j))
                .Select(i =>
                         {
                             var rnd = new Random(i);
                             var x = rnd.NextDouble();
                             var y = rnd.NextDouble();
                             if (x * x + y * y < 1.0)
                                 return 1.0;
                             else
                                 return 0.0;
                         }
                )
                .Aggregate((a, b) => a + b);

            var pi = (value * 4.0) / NumSamples;

            Console.WriteLine("Estimate Pi value: {0}", pi);
            return Math.Abs(pi - Math.PI) < 0.1;
        }
Esempio n. 20
0
        public void SetRenderData(Cluster cluster)
        {
            if (cluster.RenderTag == null)
                cluster.RenderTag = new ClusterRenderer();

            (cluster.RenderTag as ClusterRenderer).Update(cluster);
        }
        public void When_InValid_Credentials_Provided_Bucket_Created_UnSuccesfully()
        {
            try
            {
                var config = ClientConfigUtil.GetConfiguration();
                config.BucketConfigs = new Dictionary<string, BucketConfiguration>
                {
                    {
                        "authenticated",
                        new BucketConfiguration
                        {
                            BucketName = "authenticated"
                        }
                    }
                };

                var cluster = new Cluster(config);
                var bucket = cluster.OpenBucket("authenticated", "secretw");
                cluster.CloseBucket(bucket);
                Assert.IsNotNull(bucket);
            }
            catch (AggregateException e)
            {
                foreach (var exception in e.InnerExceptions)
                {
                    if (exception.GetType() == typeof (AuthenticationException))
                    {
                        throw exception;
                    }
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Creates a missile with homing and target finding capabilities.
        /// </summary>
        public GuidedMissile(IMyEntity missile, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null, bool isSlave = false)
            : base(missile, firedBy)
        {
            myLogger = new Logger("GuidedMissile", () => missile.getBestName(), () => m_stage.ToString());
            myAmmo = ammo;
            myDescr = ammo.Description;
            if (ammo.Description.HasAntenna)
                myAntenna = new MissileAntenna(missile);
            TryHard = true;

            AllGuidedMissiles.Add(this);
            missile.OnClose += missile_OnClose;

            if (myAmmo.IsCluster && !isSlave)
                myCluster = new Cluster(myAmmo.MagazineDefinition.Capacity - 1);
            accelerationPerUpdate = (myDescr.Acceleration + myAmmo.MissileDefinition.MissileAcceleration) / 60f;
            addSpeedPerUpdate = myDescr.Acceleration / 60f;

            Options = opt;
            Options.TargetingRange = ammo.Description.TargetRange;
            myTargetSeen = initialTarget;

            myLogger.debugLog("Options: " + Options, "GuidedMissile()");
            //myLogger.debugLog("AmmoDescription: \n" + MyAPIGateway.Utilities.SerializeToXML<Ammo.AmmoDescription>(myDescr), "GuidedMissile()");
        }
 public CraterInfo(Cluster c)
 {
     this.x1 = c.MinX;
     this.y1 = c.MinY;
     this.x2 = c.MaxX;
     this.y2 = c.MaxY;
 }
 public void Test_GetClusterDisplayLabel() {
     FlagClusteringStrategy strategy = new FlagClusteringStrategy(typeof(TestFlagEnum));
     ICluster cluster = new Cluster(TestFlagEnum.FlagValue2);
     cluster.Count = 2;
     string result = strategy.GetClusterDisplayLabel(cluster);
     Assert.AreEqual("FlagValue2 (2 items)", result);
 }
Esempio n. 25
0
        protected override void PreStart()
        {
            _cluster = Cluster.Get(Context.System);
            _cancelStatusUpdates = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(2), Self, new SendState(), Self);

            base.PreStart();
        }
        public async void Test_Creating_A_Cluster()
        {
            var config = new ClientConfiguration
            {
                Servers = new List<Uri>
                {
                    new Uri("http://192.168.77.101:8091/"),
                    new Uri("http://192.168.77.102:8091/"),
                    new Uri("http://192.168.77.103:8091/"),
                    new Uri("http://192.168.77.104:8091/")
                }
            };

            var cluster = new Cluster(config);
            var provisioner = new ClusterProvisioner(cluster, "Administrator", "password");
           /* var results = await provisioner.ProvisionEntryPointAsync();
            foreach (var res in results.Results)
            {
                Console.WriteLine(res.Message);
            }
            Assert.IsTrue(results.Success);

            var result = await provisioner.ProvisionSampleBucketAsync("beer-sample");
            Assert.IsTrue(result.Success);

            result = await provisioner.ProvisionSampleBucketAsync("travel-sample");
            Assert.IsTrue(result.Success);

            result = await provisioner.ProvisionBucketAsync(new BucketSettings
                {
                    Name = "authenticated",
                    SaslPassword = "******",
                    AuthType = AuthType.Sasl,
                    BucketType = BucketTypeEnum.Couchbase
                });
            Assert.IsTrue(result.Success);

            result = await provisioner.ProvisionBucketAsync(new BucketSettings
                {
                    Name = "memcached",
                    SaslPassword = "",
                    AuthType = AuthType.Sasl,
                    BucketType = BucketTypeEnum.Memcached
                });
            Assert.IsTrue(result.Success);*/

             /*var results = await provisioner.ProvisionNodesAsync(CouchbaseService.Index,
                CouchbaseService.KV,
                CouchbaseService.N1QL);

            foreach (var res in results.Results)
            {
                Console.WriteLine(res.Message);
            }*/

            var result = await provisioner.RebalanceClusterAsync();
            Console.WriteLine(result.Message);

        }
 public ClusterRemoteWatcher(
     IFailureDetectorRegistry<Address> failureDetector,
     TimeSpan heartbeatInterval,
     TimeSpan unreachableReaperInterval,
     TimeSpan heartbeatExpectedResponseAfter) :base(failureDetector, heartbeatInterval, unreachableReaperInterval, heartbeatExpectedResponseAfter)
 {
     _cluster = Cluster.Get(Context.System);
 }
Esempio n. 28
0
 private static Point CalculatePosition(Cluster cluster)
 {
     // Since the box can be rotated, find the minimal Y value of all 4 corners
     var rotatedBox = cluster.Box.Rotate(0); // todo: Add rotation '-viewport.Rotation'
     var minY = rotatedBox.Vertices.Select(v => v.Y).Min();
     var position = new Point(cluster.Box.GetCentroid().X, minY);
     return position;
 }
Esempio n. 29
0
 public BeerSample(Cluster cluster)
     : base(cluster, "beer-sample")
 {
     //Two ways of applying a filter are included in this example.
     //This is by implementing IDocumentFilter and then adding explicitly.
     //adding it to the DocumentFilterManager
     DocumentFilterManager.SetFilter(new BreweryFilter());
 }
 /// <summary>
 /// Construct a cluster from another. 
 /// </summary>
 /// <param name="cluster">The other cluster.</param>
 public BasicCluster(Cluster<BasicMLDataPair> cluster)
 {
     Centroid = (BasicMLDataPairCentroid) cluster.Centroid();
     foreach (IMLDataPair pair in cluster.Contents)
     {
         _data.Add(pair.Input);
     }
 }
Esempio n. 31
0
 public MessageEdited(LastMessageCacheService lastMessageCache, ProxyService proxy, IDatabase db, IMetrics metrics, ModelRepository repo, Cluster client, IDiscordCache cache, Bot bot)
 {
     _lastMessageCache = lastMessageCache;
     _proxy            = proxy;
     _db      = db;
     _metrics = metrics;
     _repo    = repo;
     _client  = client;
     _cache   = cache;
     _bot     = bot;
 }
Esempio n. 32
0
        public void LoggingRetryPolicy_DowngradingConsistency()
        {
            Builder builder = Cluster.Builder().WithRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.Instance));

            DowngradingConsistencyRetryPolicyTest(builder);
        }
Esempio n. 33
0
        static async Task Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args).WithParsed(RunOptions);

            var config = TransactionConfigBuilder.Create();

            config.DurabilityLevel(ParseDurability(_options.Durability));

            // Initialize the Couchbase cluster
            var cluster = await Cluster.ConnectAsync(_options.Cluster, _options.UserName, _options.Password).ConfigureAwait(false);

            var bucket = await cluster.BucketAsync(_options.Bucket).ConfigureAwait(false);

            var collection = bucket.DefaultCollection();

            // Initialize transactions.  Must only be one Transactions object per app as it creates background resources.
            var transactions = Transactions.Create(cluster, config);

            //Logging dependencies
            var services = new ServiceCollection();

            services.AddLogging(builder =>
            {
                builder.AddFile(AppContext.BaseDirectory);
                builder.AddConsole();
            });
            await using var provider = services.BuildServiceProvider();
            var loggerFactory = provider.GetService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <Program>();

            var gameServer = new GameServer(transactions, collection, logger);

            // Initialise some sample data - a player and a monster.  This is based on the Game Simulation sample bucket
            // provided with Couchbase, though that does not have to be installed.
            var playerId = "player_jane";
            var player   = new
            {
                experiance = 14248,
                hitpoints  = 23832,
                jsonType   = "player",
                level      = 141,
                loggedIn   = true,
                name       = "Jane",
                uuid       = Guid.NewGuid()
            };

            var monsterId = "a_grue";
            var monster   = new
            {
                experienceWhenKilled = 91,
                hitpoints            = 4000,
                itemProbability      = 0.19239324085462631,
                name = "grue",
                uuid = Guid.NewGuid()
            };

            await collection.UpsertAsync(playerId, player).ConfigureAwait(false);

            logger.LogInformation($"Upserted sample player document {playerId}");

            await collection.UpsertAsync(monsterId, monster).ConfigureAwait(false);

            logger.LogInformation($"Upserted sample monster document {monsterId}");

            // Now perform the transaction
            // The player is hitting the monster for a certain amount of damage
            await gameServer.PlayerHitsMonster(

                // This UUID identifies this action from the player's client
                Guid.NewGuid().ToString(),

                // This has a 50% chance of killing the monster, which has 4000 hitpoints
                new Random().Next(0, 8000),

                playerId,
                monsterId).ConfigureAwait(false);

            // Shutdown resources cleanly
            transactions.Dispose();
            await cluster.DisposeAsync().ConfigureAwait(false);

            Console.Read();
        }
Esempio n. 34
0
        public void RoutingWithThreeGroups()
        {
            var graph = LoadGraph("abstract.msagl.geom");
            var root  = graph.RootCluster;
            var a     = new Cluster {
                UserData = "a"
            };

            foreach (string id in new[] { "17", "39", "13", "19", "28", "12" })
            {
                a.AddChild(graph.FindNodeByUserData(id));
            }

            var b = new Cluster {
                UserData = "b"
            };

            b.AddChild(a);
            b.AddChild(graph.FindNodeByUserData("18"));
            root.AddChild(b);

            var c = new Cluster {
                UserData = "c"
            };

            foreach (string id in new[] { "30", "5", "6", "7", "8" })
            {
                c.AddChild(graph.FindNodeByUserData(id));
            }
            root.AddChild(c);

            var clusterNodes = new Set <Node>(root.AllClustersDepthFirst().SelectMany(cl => cl.Nodes));

            foreach (var node in graph.Nodes.Where(n => clusterNodes.Contains(n) == false))
            {
                root.AddChild(node);
            }

            FixClusterBoundariesWithNoRectBoundaries(root, 5);
            var defaultSettings = new FastIncrementalLayoutSettings();
            var rootSettings    = new FastIncrementalLayoutSettings()
            {
                AvoidOverlaps = true
            };

            var initialLayout = new InitialLayoutByCluster(graph, new[] { graph.RootCluster }, cl => cl == root ? rootSettings : defaultSettings);

            initialLayout.Run();

            const double Padding = 5;

            SplineRouter splineRouter = new SplineRouter(graph, Padding / 3, Padding, Math.PI / 6);

            splineRouter.Run();
#if TEST_MSAGL
            if (!DontShowTheDebugViewer())
            {
                graph.UpdateBoundingBox();
                DisplayGeometryGraph.ShowGraph(graph);
            }
#endif
        }
Esempio n. 35
0
        public void Cluster_seed_nodes__must_be_able_to_restart_first_seed_node_and_join_other_seed_nodes()
        {
            Within(TimeSpan.FromSeconds(40), () =>
            {
                RunOn(() =>
                {
                    Sys.ActorOf(Props.Create(() => new Listener())
                                .WithDeploy(Deploy.Local), "address-receiver");

                    EnterBarrier("seed1-address-receiver-ready");
                }, _config.Seed2, _config.Seed3);

                RunOn(() =>
                {
                    EnterBarrier("seed1-address-receiver-ready");
                    _seedNode1Address = Cluster.Get(seed1System.Value).SelfAddress;
                    foreach (var r in new List <RoleName> {
                        _config.Seed2, _config.Seed3
                    })
                    {
                        Sys.ActorSelection(new RootActorPath(GetAddress(r)) / "user" / "address-receiver").Tell(_seedNode1Address);
                        ExpectMsg("ok", TimeSpan.FromSeconds(5));
                    }
                }, _config.Seed1);
                EnterBarrier("seed1-address-transfered");

                // now we can join seed1System, seed2, seed3 together
                RunOn(() =>
                {
                    var seeds = GetSeedNodes();
                    seeds.Count.Should().Be(4); // validate that we have complete seed node list
                    var cluster = Cluster.Get(seed1System.Value);
                    cluster.JoinSeedNodes(seeds);
                    AwaitAssert(() =>
                    {
                        cluster.State.Members.Count.Should().Be(3);
                    }, TimeSpan.FromSeconds(20));
                    AwaitAssert(() =>
                    {
                        cluster
                        .State.Members.All(c => c.Status == MemberStatus.Up)
                        .Should().BeTrue();
                    });
                }, _config.Seed1);
                RunOn(() =>
                {
                    var seeds = GetSeedNodes();
                    seeds.Count.Should().Be(4); // validate that we have complete seed node list
                    Cluster.JoinSeedNodes(seeds);
                    AwaitMembersUp(3);
                }, _config.Seed2, _config.Seed3);
                EnterBarrier("started");

                // shutdown seed1System
                RunOn(() =>
                {
                    Shutdown(seed1System.Value, RemainingOrDefault);
                }, _config.Seed1);
                EnterBarrier("seed1-shutdown");

                RunOn(() =>
                {
                    Cluster.Get(restartedSeed1System.Value).JoinSeedNodes(GetSeedNodes());
                    Within(TimeSpan.FromSeconds(20), () =>
                    {
                        AwaitAssert(() =>
                        {
                            Cluster.Get(restartedSeed1System.Value)
                            .State.Members.Count
                            .Should()
                            .Be(3);
                        });
                        AwaitAssert(() =>
                        {
                            Cluster.Get(restartedSeed1System.Value)
                            .State.Members.All(c => c.Status == MemberStatus.Up)
                            .Should()
                            .BeTrue();
                        });
                    });
                }, _config.Seed1);

                RunOn(() =>
                {
                    AwaitMembersUp(3);
                }, _config.Seed2, _config.Seed3);
                EnterBarrier("seed1-restarted");
            });
        }
Esempio n. 36
0
 private static void GenerateHierarchicalVertices(BidirectionalGraph <HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex,
                                                  IBidirectionalGraph <Cluster <Variety>, ClusterEdge <Variety> > tree, Cluster <Variety> cluster)
 {
     foreach (ClusterEdge <Variety> edge in tree.OutEdges(cluster))
     {
         double depth     = vertex.Depth + edge.Length;
         var    newVertex = edge.Target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(edge.Target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth);
         graph.AddVertex(newVertex);
         graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length));
         GenerateHierarchicalVertices(graph, newVertex, tree, edge.Target);
     }
 }
 public Grains(Cluster cluster) => Cluster = cluster;
Esempio n. 38
0
        private static PredictionOutput GetPrediction(PredictionInput input, bool ft, bool checkCollision)
        {
            PredictionOutput result = null;

            if (!input.Unit.IsValidTarget(float.MaxValue, false))
            {
                return(new PredictionOutput());
            }
            if (ft)
            {
                input.Delay += Game.Ping / 2000f + 0.06f;
                if (input.AoE)
                {
                    return(Cluster.GetAoEPrediction(input));
                }
            }
            if (Math.Abs(input.Range - float.MaxValue) > float.Epsilon &&
                input.Unit.DistanceSquared(input.RangeCheckFrom) > Math.Pow(input.Range * 1.5, 2))
            {
                return(new PredictionOutput {
                    Input = input
                });
            }
            if (input.Unit.IsDashing())
            {
                result = GetDashingPrediction(input);
            }
            else
            {
                var remainingImmobileT = UnitIsImmobileUntil(input.Unit);
                if (remainingImmobileT >= 0d)
                {
                    result = GetImmobilePrediction(input, remainingImmobileT);
                }
            }
            if (result == null)
            {
                result = GetStandardPrediction(input);
            }
            if (Math.Abs(input.Range - float.MaxValue) > float.Epsilon)
            {
                if (result.Hitchance >= HitChance.High &&
                    input.RangeCheckFrom.DistanceSquared(input.Unit.Position)
                    > Math.Pow(input.Range + input.RealRadius * 3 / 4, 2))
                {
                    result.Hitchance = HitChance.Medium;
                }
                if (input.RangeCheckFrom.DistanceSquared(result.UnitPosition)
                    > Math.Pow(input.Range + (input.Type == SkillshotType.SkillshotCircle ? input.RealRadius : 0), 2))
                {
                    result.Hitchance = HitChance.OutOfRange;
                }
                if (input.RangeCheckFrom.DistanceSquared(result.CastPosition) > Math.Pow(input.Range, 2))
                {
                    if (result.Hitchance != HitChance.OutOfRange)
                    {
                        result.CastPosition = input.RangeCheckFrom
                                              + input.Range
                                              * (result.UnitPosition - input.RangeCheckFrom).Normalized().SetZ();
                    }
                    else
                    {
                        result.Hitchance = HitChance.OutOfRange;
                    }
                }
            }
            if (result.Hitchance > HitChance.Medium)
            {
                WayPointAnalysis(result, input);
            }
            if (checkCollision && input.Collision)
            {
                var positions = new List <Vector3> {
                    result.UnitPosition, result.CastPosition, input.Unit.Position
                };
                var originalUnit = input.Unit;
                result.CollisionObjects = Collisions.GetCollision(positions, input);
                result.CollisionObjects.RemoveAll(i => i.NetworkId == originalUnit.NetworkId);
                result.Hitchance = result.CollisionObjects.Count > 0 ? HitChance.Collision : result.Hitchance;
            }
            return(result);
        }
 /// <inheritdoc/>
 public HttpTransformer Build(ProxyRoute route, Cluster cluster)
 {
     return(BuildInternal(route, cluster));
 }
Esempio n. 40
0
 public bool Equals(SQLNode other)
 {
     return(other != null && Cluster.Equals(other.Cluster) && string.Equals(Name, other.Name));
 }
        public async Task Test_BootStrap_Error_Propagates_To_Collection_Operations()
        {
            const string id    = "key;";
            var          value = new { x = "y" };

            var settings = ClusterFixture.GetSettings();
            var cluster  = await Cluster.ConnectAsync(settings.ConnectionString, "Administrator", "password");

            var bucket = await cluster.BucketAsync("doesnotexist");

            var defaultCollection = bucket.DefaultCollection();

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.GetAsync(id));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.ExistsAsync(id));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.GetAndLockAsync(id, TimeSpan.MaxValue));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.GetAndTouchAsync(id, TimeSpan.MaxValue));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.GetAnyReplicaAsync(id));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.LookupInAsync(id, null));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.MutateInAsync(id, null));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.RemoveAsync(id));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.TouchAsync(id, TimeSpan.Zero));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.InsertAsync(id, value));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.ReplaceAsync(id, value));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.UnlockAsync <dynamic>(id, 0));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.UpsertAsync(id, value));
            });

            await Assert.ThrowsAsync <AuthenticationFailureException>(async() =>
            {
                await ThrowAuthenticationException(() => defaultCollection.GetAllReplicasAsync(id).First());
            });
        }
 public HTxQueue(string name, DistributedObjectFactory factory, Cluster cluster, MemberConnection transactionClientConnection, Guid transactionId, ISerializationService serializationService, ILoggerFactory loggerFactory)
     : base(HQueue.ServiceName, name, factory, cluster, transactionClientConnection, transactionId, serializationService, loggerFactory)
 {
 }
Esempio n. 43
0
 private static void GenerateHierarchicalVertices(BidirectionalGraph <HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex,
                                                  IUndirectedGraph <Cluster <Variety>, ClusterEdge <Variety> > tree, Cluster <Variety> parent, Cluster <Variety> cluster)
 {
     foreach (ClusterEdge <Variety> edge in tree.AdjacentEdges(cluster).Where(e => e.GetOtherVertex(cluster) != parent))
     {
         Cluster <Variety> target = edge.GetOtherVertex(cluster);
         double            depth  = vertex.Depth + edge.Length;
         var newVertex            = target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth);
         graph.AddVertex(newVertex);
         graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length));
         GenerateHierarchicalVertices(graph, newVertex, tree, cluster, target);
     }
 }
Esempio n. 44
0
        public FooActor()
        {
            Cluster cluster = Cluster.Get(Context.System);

            _log.Info($">>> Foo Address : {cluster.SelfAddress}, {Self.Path.ToStringWithAddress()}");
        }
        // This is separate from Build for testing purposes.
        internal StructuredTransformer BuildInternal(ProxyRoute route, Cluster cluster)
        {
            var rawTransforms = route.Transforms;

            var context = new TransformBuilderContext
            {
                Services = _services,
                Route    = route,
                Cluster  = cluster,
            };

            if (rawTransforms?.Count > 0)
            {
                foreach (var rawTransform in rawTransforms)
                {
                    var handled = false;
                    foreach (var factory in _factories)
                    {
                        if (factory.Build(context, rawTransform))
                        {
                            handled = true;
                            break;
                        }
                    }

                    if (!handled)
                    {
                        throw new ArgumentException($"Unknown transform: {string.Join(';', rawTransform.Keys)}");
                    }
                }
            }

            // Let the app add any more transforms it wants.
            foreach (var transformProvider in _providers)
            {
                transformProvider.Apply(context);
            }

            // RequestHeaderOriginalHostKey defaults to false, and CopyRequestHeaders defaults to true.
            // If RequestHeaderOriginalHostKey was not specified then we need to make sure the transform gets
            // added anyways to remove the original host. If CopyRequestHeaders is false then we can omit the
            // transform.
            if (context.CopyRequestHeaders.GetValueOrDefault(true) &&
                !context.RequestTransforms.Any(item => item is RequestHeaderOriginalHostTransform))
            {
                context.AddOriginalHost(false);
            }

            // Add default forwarders only if they haven't already been added or disabled.
            if (context.UseDefaultForwarders.GetValueOrDefault(true))
            {
                context.AddXForwarded();
            }

            return(new StructuredTransformer(
                       context.CopyRequestHeaders,
                       context.CopyResponseHeaders,
                       context.CopyResponseTrailers,
                       context.RequestTransforms,
                       context.ResponseTransforms,
                       context.ResponseTrailersTransforms));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="NearCache"/> class.
 /// </summary>
 /// <param name="name">The name of the cache.</param>
 /// <param name="cluster">The cluster.</param>
 /// <param name="serializationService">The localization service.</param>
 /// <param name="loggerFactory">A logger factory.</param>
 /// <param name="nearCacheNamedOptions">NearCache options.</param>
 /// <param name="maxToleratedMissCount"></param>
 public NearCache(string name, Cluster cluster, ISerializationService serializationService, ILoggerFactory loggerFactory, NearCacheNamedOptions nearCacheNamedOptions, int maxToleratedMissCount)
     : base(name, cluster, serializationService, loggerFactory, nearCacheNamedOptions)
 {
     _maxToleratedMissCount = maxToleratedMissCount;
 }
        public void A_3_node_cluster_should_avoid_a_split_brain_when_two_unreachable_but_can_talk_via_third()
        {
            var cluster = Cluster.Get(Sys);

            RunOn(() =>
            {
                cluster.Join(cluster.SelfAddress);
            }, _config.Node1);
            EnterBarrier("node1 joined");
            RunOn(() =>
            {
                cluster.Join(Node(_config.Node1).Address);
            }, _config.Node2, _config.Node3);
            Within(TimeSpan.FromSeconds(10), () =>
            {
                AwaitAssert(() =>
                {
                    cluster.State.Members.Count.Should().Be(3);
                    foreach (var m in cluster.State.Members)
                    {
                        m.Status.Should().Be(MemberStatus.Up);
                    }
                });
            });
            EnterBarrier("Cluster formed");

            RunOn(() =>
            {
                TestConductor.Blackhole(_config.Node2, _config.Node3, ThrottleTransportAdapter.Direction.Both).Wait();
            }, _config.Node1);
            EnterBarrier("Blackholed");

            Within(TimeSpan.FromSeconds(10), () =>
            {
                AwaitAssert(() =>
                {
                    RunOn(() =>
                    {
                        cluster.State.Unreachable.Select(i => i.Address).Should().BeEquivalentTo(Node(_config.Node2).Address);
                    }, _config.Node3);
                    RunOn(() =>
                    {
                        cluster.State.Unreachable.Select(i => i.Address).Should().BeEquivalentTo(Node(_config.Node3).Address);
                    }, _config.Node2);
                    RunOn(() =>
                    {
                        cluster.State.Unreachable.Select(i => i.Address).Should().BeEquivalentTo(new[] { _config.Node3, _config.Node2 }.Select(i => Node(i).Address));
                    }, _config.Node1);
                });
            });
            EnterBarrier("unreachable");

            RunOn(() =>
            {
                Within(TimeSpan.FromSeconds(15), () =>
                {
                    AwaitAssert(() =>
                    {
                        cluster.State.Members.Select(i => i.Address).Should().BeEquivalentTo(Node(_config.Node1).Address);
                        foreach (var m in cluster.State.Members)
                        {
                            m.Status.Should().Be(MemberStatus.Up);
                        }
                    });
                });
            }, _config.Node1);

            RunOn(() =>
            {
                // downed
                AwaitCondition(() => cluster.IsTerminated, max: TimeSpan.FromSeconds(15));
            }, _config.Node2, _config.Node3);

            EnterBarrier("done");
        }
 protected internal override Node GetNode(Cluster cluster)
 {
     return(partition.GetNodeWrite(cluster));
 }
Esempio n. 49
0
 static IEnumerable <Point> ClusterPoints(Cluster cluster)
 {
     return(cluster.BoundaryCurve as Polyline);
 }
 public DeleteCommand(Cluster cluster, WritePolicy policy, Key key)
 {
     this.policy    = policy;
     this.key       = key;
     this.partition = Partition.Write(cluster, policy, key);
 }
Esempio n. 51
0
        public static Algorithm ParseJson(String jsonString, List <MinMaxValue> minMaxValues)
        {
            dynamic   jsonModel = JsonConvert.DeserializeObject(jsonString);
            Algorithm algorithm = new Algorithm()
            {
                AlgorithmName = jsonModel.algorithm,
                Models        = new List <Model>()
            };
            Model model = new Model()
            {
                Clusters         = new List <Cluster>(),
                DataSet          = jsonModel.dataSet,
                Date             = DateTime.Now,
                NumberOfSolvents = 0,
                NumberOfFeatures = 0,
                ModelPath        = jsonModel.modelPath,
                AlgorithmName    = jsonModel.algorithm
            };

            foreach (var cluster in jsonModel.clusters)
            {
                Cluster clusterTemp = new Cluster()
                {
                    DistanceToClusters = new List <ClusterDistanceCenter>(),
                    Number             = cluster.clusterNumber,
                    Solvents           = new List <Solvent>(),
                    VectorData         = new List <VectorData>(),
                };
                foreach (var vector in cluster.vectorData)
                {
                    VectorData vectorData = new VectorData()
                    {
                        Value       = vector.value,
                        FeatureName = vector.name
                    };

                    clusterTemp.VectorData.Add(vectorData);
                }

                foreach (var distance in cluster.distanceToCluster)
                {
                    ClusterDistanceCenter clusterDistanceCenter = new ClusterDistanceCenter()
                    {
                        ToClusterId = distance.clusterId,
                        Distance    = distance.distance
                    };
                    clusterTemp.DistanceToClusters.Add(clusterDistanceCenter);
                }

                foreach (var solvent in cluster.solvents)
                {
                    Solvent solventTemp = new Solvent()
                    {
                        CasNumber = solvent.casNumber,
                        Name      = solvent.name,
                        DistanceToClusterCenter = solvent.distanceToCluster,
                        Features = new List <Feature>(),
                        MetaData = new SolventMetaData()
                        {
                            Label       = solvent.predictLabel,
                            IdCasNr     = solvent.iD_CAS_Nr_1,
                            IdEgNr      = solvent.iD_EG_Nr,
                            IdEgAnnexNr = solvent.iD_EG_Annex_Nr,
                            Input       = solvent.input,
                            IdName1     = solvent.iD_Name_1
                        }
                    };
                    solventTemp.CasNumber = solventTemp.CasNumber.Replace("\"", "");
                    solventTemp.Name      = solventTemp.Name.Replace("\"", "");
                    foreach (var feature in solvent.features)
                    {
                        FeatureName featureName;
                        Enum.TryParse <FeatureName>(feature.name.ToString(), out featureName);
                        var     value       = minMaxValues.FirstOrDefault(a => a.FeatureName == featureName);
                        Feature featureTemp = new Feature()
                        {
                            FeatureName = feature.name,
                            Value       = feature.value
                        };
                        featureTemp.MinMaxValue = value;
                        solventTemp.Features.Add(featureTemp);
                    }
                    clusterTemp.Solvents.Add(solventTemp);
                    model.NumberOfFeatures = solventTemp.Features.Count;
                }
                model.NumberOfSolvents += clusterTemp.Solvents.Count;
                model.Clusters.Add(clusterTemp);
            }
            algorithm.Models.Add(model);
            return(algorithm);
        }
 public HelloGrainClient(Cluster cluster, string id)
 {
     _id      = id;
     _cluster = cluster;
 }
Esempio n. 53
0
 public static void waitForDecommission(string node, Cluster cluster, int maxTry)
 {
     WaitFor(node, cluster, maxTry, true, true);
 }
Esempio n. 54
0
 /// <summary>
 /// 构造函数
 /// </summary>
 public ManagerPlay(Member member)
 {
     _member             = member;
     _cluster            = _member.Cluster;
     _executeAmountLimit = Environment.ProcessorCount;
 }
Esempio n. 55
0
        private static void WaitForMeta(string nodeHost, Cluster cluster, int maxTry, bool waitForUp)
        {
            string expectedFinalNodeState = "UP";

            if (!waitForUp)
            {
                expectedFinalNodeState = "DOWN";
            }
            for (int i = 0; i < maxTry; ++i)
            {
                try
                {
                    // Are all nodes in the cluster accounted for?
                    bool disconnected = !cluster.RefreshSchema();
                    if (disconnected)
                    {
                        string warnStr = "While waiting for host " + nodeHost + " to be " + expectedFinalNodeState + ", the cluster is now totally down, returning now ... ";
                        Trace.TraceWarning(warnStr);
                        return;
                    }

                    Metadata metadata = cluster.Metadata;
                    foreach (Host host in metadata.AllHosts())
                    {
                        bool hostFound = false;
                        if (host.Address.ToString() == nodeHost)
                        {
                            hostFound = true;
                            if (host.IsUp && waitForUp)
                            {
                                Trace.TraceInformation("Verified according to cluster meta that host " + nodeHost + " is " + expectedFinalNodeState + ", returning now ... ");
                                return;
                            }
                            Trace.TraceWarning("We're waiting for host " + nodeHost + " to be " + expectedFinalNodeState);
                        }
                        // Is the host even in the meta list?
                        if (!hostFound)
                        {
                            if (!waitForUp)
                            {
                                Trace.TraceInformation("Verified according to cluster meta that host " + host.Address + " is not available in the MetaData hosts list, returning now ... ");
                                return;
                            }
                            else
                            {
                                Trace.TraceWarning("We're waiting for host " + nodeHost + " to be " + expectedFinalNodeState + ", but this host was not found in the MetaData hosts list!");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("None of the hosts tried for query are available") && !waitForUp)
                    {
                        Trace.TraceInformation("Verified according to cluster meta that host " + nodeHost + " is not available in the MetaData hosts list, returning now ... ");
                        return;
                    }
                    Trace.TraceInformation("Exception caught while waiting for meta data: " + e.Message);
                }
                Trace.TraceWarning("Waiting for node host: " + nodeHost + " to be " + expectedFinalNodeState);
                Thread.Sleep(DefaultSleepIterationMs);
            }
            string errStr = "Node host should have been " + expectedFinalNodeState + " but was not after " + maxTry + " tries!";

            Trace.TraceError(errStr);
        }
Esempio n. 56
0
 private static void WaitFor(string node, Cluster cluster, int maxTry, bool waitForDead, bool waitForOut)
 {
     WaitForMeta(node, cluster, maxTry, !waitForDead);
 }
Esempio n. 57
0
 public BoltV4IT(ITestOutputHelper output, CausalClusterIntegrationTestFixture fixture)
     : base(output, fixture)
 {
     _driver = GraphDatabase.Driver(Cluster.AnyCore().BoltRoutingUri, Cluster.AuthToken,
                                    o => o.WithLogger(TestLogger.Create(output)));
 }
Esempio n. 58
0
 public static void WaitForDown(string node, Cluster cluster, int maxTry)
 {
     WaitFor(node, cluster, maxTry, true, false);
 }
Esempio n. 59
0
        public void ReplicationFactorOne_DowngradingConsistencyRetryPolicy()
        {
            ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3);

            testCluster.Builder = Cluster.Builder()
                                  .WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
                                  .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance);
            testCluster.InitClient();
            _policyTestTools.CreateSchema(testCluster.Session, 1);
            _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.One);
            _policyTestTools.Query(testCluster, 12, ConsistencyLevel.One);

            string coordinatorHostQueried = _policyTestTools.Coordinators.First().Key.Split(':').First();
            int    awareCoord             = int.Parse(coordinatorHostQueried.Split('.').Last());

            _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + awareCoord + ":" + DefaultCassandraPort, 12);

            _policyTestTools.ResetCoordinators();
            testCluster.StopForce(awareCoord);
            TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30);

            var acceptedList = new List <ConsistencyLevel> {
                ConsistencyLevel.Any
            };

            var failList = new List <ConsistencyLevel>
            {
                ConsistencyLevel.One,
                ConsistencyLevel.Two,
                ConsistencyLevel.Three,
                ConsistencyLevel.Quorum,
                ConsistencyLevel.All
            };

            // Test successful writes
            foreach (ConsistencyLevel consistencyLevel in acceptedList)
            {
                try
                {
                    _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel);
                }
                catch (Exception e)
                {
                    Assert.Fail(String.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message));
                }
            }

            // Test successful reads
            foreach (ConsistencyLevel consistencyLevel in acceptedList)
            {
                try
                {
                    _policyTestTools.Query(testCluster, 12, consistencyLevel);
                }
                catch (InvalidQueryException e)
                {
                    var acceptableErrorMessages = new List <string>
                    {
                        "ANY ConsistencyLevel is only supported for writes"
                    };
                    Assert.True(acceptableErrorMessages.Contains(e.Message));
                }
            }

            // Test writes which should fail
            foreach (ConsistencyLevel consistencyLevel in failList)
            {
                try
                {
                    _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel);
                    Assert.Fail(String.Format("Test passed at CL.{0}.", consistencyLevel));
                }
                catch (InvalidQueryException e)
                {
                    var acceptableErrorMessages = new List <string>
                    {
                        "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
                        "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)"
                    };
                    Assert.True(acceptableErrorMessages.Contains(e.Message), String.Format("Received: {0}", e.Message));
                }
                catch (UnavailableException)
                {
                    // expected to fail when the client has already marked the
                    // node as DOWN
                }
                catch (WriteTimeoutException)
                {
                    // expected to fail when the client hasn't marked the'
                    // node as DOWN yet
                }
            }

            // Test reads which should fail
            foreach (ConsistencyLevel consistencyLevel in failList)
            {
                try
                {
                    _policyTestTools.Query(testCluster, 12, consistencyLevel);
                    Assert.Fail(String.Format("Test passed at CL.{0}.", consistencyLevel));
                }
                catch (InvalidQueryException e)
                {
                    var acceptableErrorMessages = new List <string>
                    {
                        "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)",
                        "EACH_QUORUM ConsistencyLevel is only supported for writes"
                    };
                    Assert.True(acceptableErrorMessages.Contains(e.Message), String.Format("Received: {0}", e.Message));
                }
                catch (ReadTimeoutException)
                {
                    // expected to fail when the client hasn't marked the'
                    // node as DOWN yet
                }
                catch (UnavailableException)
                {
                    // expected to fail when the client has already marked the
                    // node as DOWN
                }
            }
        }
Esempio n. 60
0
        public void FailoverThenReconnect()
        {
            var parallelOptions = new ParallelOptions
            {
                TaskScheduler          = new ThreadPerTaskScheduler(),
                MaxDegreeOfParallelism = 100
            };

            var policy = new ConstantReconnectionPolicy(500);
            var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false);

            using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build())
            {
                var session = cluster.Connect();
                // Check query to host distribution before killing nodes
                var      queriedHosts   = new List <string>();
                DateTime futureDateTime = DateTime.Now.AddSeconds(120);
                while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime)
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    queriedHosts.Add(rs.Info.QueriedHost.ToString());
                    Thread.Sleep(50);
                }
                Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!");

                // Create list of actions
                Action selectAction = () =>
                {
                    var rs = session.Execute("SELECT * FROM system.local");
                    Assert.Greater(rs.Count(), 0);
                };
                var actions = new List <Action>();
                for (var i = 0; i < 100; i++)
                {
                    actions.Add(selectAction);
                    //Check that the control connection is using first host
                    StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString());

                    //Kill some nodes
                    //Including the one used by the control connection
                    actions.Insert(20, () => nonShareableTestCluster.Stop(1));
                    actions.Insert(20, () => nonShareableTestCluster.Stop(2));
                    actions.Insert(80, () => nonShareableTestCluster.Stop(3));

                    //Execute in parallel more than 100 actions
                    Parallel.Invoke(parallelOptions, actions.ToArray());

                    //Wait for the nodes to be killed
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20);
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20);
                    TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20);

                    actions = new List <Action>();
                    for (var j = 0; j < 100; j++)
                    {
                        actions.Add(selectAction);
                    }

                    //Check that the control connection is using first host
                    //bring back some nodes
                    actions.Insert(3, () => nonShareableTestCluster.Start(3));
                    actions.Insert(50, () => nonShareableTestCluster.Start(2));
                    actions.Insert(50, () => nonShareableTestCluster.Start(1));

                    //Execute in parallel more than 100 actions
                    Trace.TraceInformation("Start invoking with restart nodes");
                    Parallel.Invoke(parallelOptions, actions.ToArray());

                    //Wait for the nodes to be restarted
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
                    TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30);

                    queriedHosts.Clear();
                    // keep querying hosts until they are all queried, or time runs out
                    futureDateTime = DateTime.Now.AddSeconds(120);
                    while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime)
                    {
                        var rs = session.Execute("SELECT * FROM system.local");
                        queriedHosts.Add(rs.Info.QueriedHost.ToString());
                        Thread.Sleep(50);
                    }
                    //Check that one of the restarted nodes were queried
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, queriedHosts);
                    Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, queriedHosts);
                    //Check that the control connection is still using last host
                    StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString());
                }
            }
        }