Esempio n. 1
0
	IEnumerator EndOfReplica(Replica replica){
		yield return new WaitForSeconds (REPLICA_DURATION);
		Destroy (bulle);
		if (!stop)
			replica.Finished ();
		else
			stop = false;		
	}
 private ReplicationMasterFile(ReplicationMasterStorageImpl storage, IFile file, string localhost, int port, string[] hosts, bool ack, String pageTimestampFilePath) 
 {         
     this.storage = storage;
     this.file = file;
     this.ack = ack;
     this.localhost = localhost;
     this.port = port;
     mutex = new object();
     replicas = new Replica[hosts.Length];
     rcBuf = new byte[1];
     nHosts = 0;
     if (pageTimestampFilePath != null) { 
         FileParameters fileParameters = storage != null ? storage.fileParameters : new FileParameters(false, false, false, 1024*1024);
         pageTimestampFile = new OSFile(pageTimestampFilePath, fileParameters);
         long fileLength = pageTimestampFile.Length;
         if (fileLength == 0) { 
             pageTimestamps = new int[InitPageTimestampsLength];
         } else {
             pageTimestamps = new int[(int)(fileLength/4)];
             byte[] page = new byte[Page.pageSize];
             int i = 0;
             for (long pos = 0; pos < fileLength; pos += Page.pageSize) { 
                 int rc = pageTimestampFile.Read(pos, page);
                 for (int offs = 0; offs < rc; offs += 4, i++) { 
                     pageTimestamps[i] = Bytes.unpack4(page, offs);
                     if (pageTimestamps[i] > timestamp) { 
                         timestamp = pageTimestamps[i];
                     }
                 }
             }
             if (i != pageTimestamps.Length) { 
                 throw new StorageError(StorageError.ErrorCode.FILE_ACCESS_ERROR);
             }
         }
         dirtyPageTimestampMap = new int[(((pageTimestamps.Length*4 + Page.pageSize - 1) >> Page.pageSizeLog) + 31) >> 5];
         txBuf = new byte[12 + Page.pageSize];
     } else { 
         txBuf = new byte[8 + Page.pageSize];
     }
     for (int i = 0; i < hosts.Length; i++) 
     { 
         replicas[i] = new Replica();
         replicas[i].host = hosts[i];
         Connect(i);
     }
     if (port >= 0) 
     {
         storage.SetProperty("perst.alternative.btree", true); // prevent direct modification of pages
         listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         listenSocket.Bind(new IPEndPoint(localhost != null && localhost != "localhost" ? IPAddress.Parse(localhost) : IPAddress.Any, port));          
         listenSocket.Listen(ListenQueueSize);
         listening = true;
         listenThread = new Thread(new ThreadStart(run));
         listenThread.Start();
     }
     watchdogThread = new Thread(new ThreadStart(watchdog));
     watchdogThread.Start();
 }
        public static List <BatchNode> GenerateList
        (
            Cluster cluster,
            BatchPolicy policy,
            List <BatchRead> records,
            uint sequenceAP,
            uint sequenceSC,
            BatchNode batchSeed
        )
        {
            Node[] nodes = cluster.Nodes;

            if (nodes.Length == 0)
            {
                throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Command failed because cluster is empty.");
            }

            // Create initial key capacity for each node as average + 25%.
            int keysPerNode = batchSeed.offsetsSize / nodes.Length;

            keysPerNode += (int)((uint)keysPerNode >> 2);

            // The minimum key capacity is 10.
            if (keysPerNode < 10)
            {
                keysPerNode = 10;
            }

            Replica replica   = policy.replica;
            Replica replicaSC = Partition.GetReplicaSC(policy);

            // Split keys by server node.
            List <BatchNode> batchNodes = new List <BatchNode>(nodes.Length);

            for (int i = 0; i < batchSeed.offsetsSize; i++)
            {
                int offset = batchSeed.offsets[i];

                Node      node      = Partition.GetNodeBatchRead(cluster, records[offset].key, replica, replicaSC, sequenceAP, sequenceSC);
                BatchNode batchNode = FindBatchNode(batchNodes, node);

                if (batchNode == null)
                {
                    batchNodes.Add(new BatchNode(node, keysPerNode, offset));
                }
                else
                {
                    batchNode.AddKey(offset);
                }
            }
            return(batchNodes);
        }
        public void FulfillSyncRequest_ValidRequest_SyncResultBuildCalled()
        {
            var syncResult = Mocking.MockAndBind <ISyncResult <TestItem, Guid> >(_container);

            var replica     = new Replica("test");
            var syncRequest = Mock.Create <ISyncRequest <Guid> >();

            var target = new ReceivingSynchronizer <TestItem, Guid>(_container);

            var result = target.FulfillSyncRequest(syncRequest);

            Mock.Assert(() => syncResult.Build(syncRequest), Occurs.Once());
        }
Esempio n. 5
0
        public void ReplicarComentario(int id, string replicar)
        {
            Replica replica = new Replica();

            replica.IdCalificacion = Convert.ToInt16(id);
            replica.Comentario     = replicar;
            context.Replica.AddObject(replica);

            Calificacion calificacion = context.Calificacion.Where(e => e.Id == id).FirstOrDefault();

            calificacion.FlagReplicado = 1; //comentario de la calificacion fue replicado
            context.SaveChanges();
        }
Esempio n. 6
0
        protected void PresentaEventoSelezionato(string codice)
        {
            Replica    oReplica    = new Replica();
            ReplicaDAO oReplicaDAO = new ReplicaDAO();

            oReplica = oReplicaDAO.GetReplicaById(codice);


            TableCell tc1 = new TableCell();
            TableCell tc2 = new TableCell();
            TableCell tc3 = new TableCell();
            TableCell tc4 = new TableCell();
            TableCell tc5 = new TableCell();
            TableCell tc6 = new TableCell();
            TableCell tc7 = new TableCell();
            TableCell tc8 = new TableCell();
            TableCell tc9 = new TableCell();


            //Button bt1 = new Button();

            //bt1.Text = "PRENOTA";
            //bt1.CssClass = "btn btn-primary";

            //bt1.ID = oReplica.codReplica;
            //bt1.Click += new EventHandler(prenotaReplica);


            tc1.Text = oReplica.codReplica;
            tc2.Text = oReplica.codEvento;
            tc3.Text = (oReplica.dataEOra).ToString();
            tc4.Text = oReplica.codLocale;
            tc5.Text = oReplica.nomeEvento;
            tc6.Text = oReplica.nomeLocale;
            tc7.Text = oReplica.luogo;
            tc8.Text = (oReplica.posti).ToString();
            //tc9.Controls.Add(bt1);

            TableRow tr = new TableRow();

            tr.Cells.Add(tc1);
            tr.Cells.Add(tc2);
            tr.Cells.Add(tc3);
            tr.Cells.Add(tc4);
            tr.Cells.Add(tc5);
            tr.Cells.Add(tc6);
            tr.Cells.Add(tc7);
            tr.Cells.Add(tc8);
            //tr.Cells.Add(tc9);
            TBLEvento.Rows.Add(tr);
        }
Esempio n. 7
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 public Policy(Policy other)
 {
     this.priority            = other.priority;
     this.readModeAP          = other.readModeAP;
     this.readModeSC          = other.readModeSC;
     this.replica             = other.replica;
     this.predExp             = other.predExp;
     this.socketTimeout       = other.socketTimeout;
     this.totalTimeout        = other.totalTimeout;
     this.maxRetries          = other.maxRetries;
     this.sleepBetweenRetries = other.sleepBetweenRetries;
     this.sendKey             = other.sendKey;
     this.failOnFilteredOut   = other.failOnFilteredOut;
 }
Esempio n. 8
0
        public static void Handle(
            SecretShareMessage message,
            Replica replica,
            string replicaSecretShare,
            Dictionary<int, uint> childSecretHashes,
            Dictionary<int, CancellationTokenSource> secretShareMessageTokenSources,
            ConcurrentDictionary<int, string> verifiedChildrenSecretShares)
        {
            var childReplicaId = message.ReplicaId;
            var childReplicaSecretShare = message.ReplicaSecretShares[message.ReplicaId];

            secretShareMessageTokenSources[childReplicaId].Cancel();
            secretShareMessageTokenSources.Remove(childReplicaId);

            if (Crypto.GetHash(childReplicaSecretShare) != childSecretHashes[childReplicaId])
            {
                replica.ParentReplica.SendMessage(
                    new SuspectMessage
                    {
                        ReplicaId = childReplicaId
                    });
            }

            foreach (var childSecretShare in message.ReplicaSecretShares)
            {
                if (verifiedChildrenSecretShares.TryAdd(childSecretShare.Key, childSecretShare.Value) == false)
                {
                    throw new InvalidOperationException($"The child secret share for replica #{childSecretShare.Key} has already been delivered.");
                }
            }

            if (replica.ChildReplicas.All(chr => verifiedChildrenSecretShares.ContainsKey(chr.Id)) == false)
            {
                return;
            }

            verifiedChildrenSecretShares.TryAdd(replica.Id, replicaSecretShare);

            // we send a message with a secret share to the parent replica
            Network.EmulateLatency();

            replica.ParentReplica.SendMessage(
                new SecretShareMessage
                {
                    ReplicaId = replica.Id,
                    ReplicaSecretShares = verifiedChildrenSecretShares.ToDictionary(kv => kv.Key, kv => kv.Value)
                });

            Log(replica, "Send a secret share to the parent replica (ParentReplicaId: {0})", replica.ParentReplica.Id);
        }
Esempio n. 9
0
        public void Kill(DamageInfo reason)
        {
            if (!isServer)
            {
                return;
            }

            deathReason = reason;
            try {
                OnDeath?.Invoke(reason);
            } finally {
                Replica.Destroy();
            }
        }
Esempio n. 10
0
        void RpcBuild(Replica buildingReplica, BuildingPartType partType, BuildingSlotType buildingSlotType, Vector3 slotPosition)
        {
            var building = buildingReplica.GetComponent <Building>();

            float distance = 0;
            var   slot     = building.GetClosestSlot(slotPosition, buildingSlotType, true, out distance);

            //#TODO check distance

            Assert.IsNotNull(slot);

            building.AddPart(partType, slot);
            building.Rebuild();
        }
Esempio n. 11
0
        public Node GetReadNode(Partition partition, Replica replica)
        {
            switch (replica)
            {
            case Replica.MASTER:
                return(GetMasterNode(partition));

            case Replica.MASTER_PROLES:
                return(GetMasterProlesNode(partition));

            default:
            case Replica.RANDOM:
                return(GetRandomNode());
            }
        }
Esempio n. 12
0
        public static List <BatchNode> GenerateList
        (
            Cluster cluster,
            BatchPolicy policy,
            Key[] keys,
            uint sequenceAP,
            uint sequenceSC,
            BatchNode batchSeed
        )
        {
            Node[] nodes = cluster.ValidateNodes();

            // Create initial key capacity for each node as average + 25%.
            int keysPerNode = batchSeed.offsetsSize / nodes.Length;

            keysPerNode += (int)((uint)keysPerNode >> 2);

            // The minimum key capacity is 10.
            if (keysPerNode < 10)
            {
                keysPerNode = 10;
            }

            Replica replica   = policy.replica;
            Replica replicaSC = Partition.GetReplicaSC(policy);

            // Split keys by server node.
            List <BatchNode> batchNodes = new List <BatchNode>(nodes.Length);

            for (int i = 0; i < batchSeed.offsetsSize; i++)
            {
                int offset = batchSeed.offsets[i];

                Node      node      = Partition.GetNodeBatchRead(cluster, keys[offset], replica, replicaSC, sequenceAP, sequenceSC);
                BatchNode batchNode = FindBatchNode(batchNodes, node);

                if (batchNode == null)
                {
                    batchNodes.Add(new BatchNode(node, keysPerNode, offset));
                }
                else
                {
                    batchNode.AddKey(offset);
                }
            }
            return(batchNodes);
        }
Esempio n. 13
0
        static void RunAfterMakeLabel(
            List <string> filteredRepos,
            List <string> dstServers,
            List <RepoMapping> mappings,
            string labelName,
            string repoName,
            string serverName,
            ErrorEmailSender emailSender)
        {
            Logger.LogInfo("Running as after-makelabel trigger...");

            Branch branchToReplicate = null;

            if (!FindBranchForLabel(
                    labelName, repoName, serverName, out branchToReplicate))
            {
                return;
            }

            List <Replica> pendingReplicas =
                Replica.BuildPendingReplicas(
                    branchToReplicate.BranchName,
                    branchToReplicate.RepositoryName,
                    branchToReplicate.ServerName,
                    filteredRepos,
                    dstServers,
                    mappings);

            Logger.LogInfo(
                $"Found {pendingReplicas.Count} destinations to replicate to.");

            List <Replica> failedReplicas = new List <Replica>();

            foreach (Replica pendingReplica in pendingReplicas)
            {
                if (!Replicate(pendingReplica))
                {
                    failedReplicas.Add(pendingReplica);
                }
            }

            NotifyFailedReplicas(
                "after-makelabel",
                failedReplicas,
                emailSender);
        }
        public Node GetReadNode(Partition partition, Replica replica)
        {
            // This method should only be called by batch.
            switch (replica)
            {
            default:
            case Replica.SEQUENCE:                      // Use Command.GetReadNode() to really use sequence mode.
            case Replica.MASTER:
                return(GetMasterNode(partition));

            case Replica.MASTER_PROLES:
                return(GetMasterProlesNode(partition));

            case Replica.RANDOM:
                return(GetRandomNode());
            }
        }
Esempio n. 15
0
	public void StartReplica(Replica replica){
		GameObject o = new GameObject ("bulle") as GameObject;
		o.transform.SetParent (transform);
		o.transform.position = transform.position + Vector3.up * 50;
		SpriteRenderer sr = o.AddComponent<SpriteRenderer> ();
		sr.sprite = PreparationManager.Instance.bulleSprite;
		sr.color = new Color (1, 1, 1, 0.9f);
		bulle = o;
		GameObject phrase = GameObject.Instantiate (PreparationManager.Instance.PhrasePrefab) as GameObject;
		phrase.transform.SetParent (o.transform);
		phrase.transform.localPosition = PreparationManager.Instance.PhrasePrefab.transform.localPosition;
		phrase.transform.localScale = Vector3.one;
		phrase.GetComponentInChildren<Text> ().text = replica.text;

		//Debug.Log (name + " is saying : " + replica.text);
		StartCoroutine (EndOfReplica (replica));
	}
        private static void Server()
        {
            var    port   = 55001;
            Server server = new Server
            {
                Services = { Replica.BindService(new KafkaSyncImpl()) },
                Ports    = { new ServerPort("0.0.0.0", port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Greeter server listening on port " + port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
Esempio n. 17
0
    public void PlayReplica(CharacterType character, string key)
    {
        portraitUncleVo.SetActive(false);
        portraitVita.SetActive(false);
        portraitDitto.SetActive(false);

        MonologData data = null;

        switch (character)
        {
        case CharacterType.Ditto:
            data = dittoData;
            portraitDitto.SetActive(true);
            break;

        case CharacterType.Vita:
            data = vitaData;
            portraitVita.SetActive(true);
            break;

        case CharacterType.UncleVo:
            data = uncleVoData;
            portraitUncleVo.SetActive(true);
            break;
        }

        Replica replica = null;

        foreach (var r in data.replics)
        {
            if (r.key == key)
            {
                replica = r;
            }
        }

        if (replica == null)
        {
            Debug.LogError("Invalid key!");
            return;
        }

        replicaCharachter = character;
        SetText(replica.text, character.ToString() + replica.key);
    }
Esempio n. 18
0
        public async Task <IActionResult> Post([FromBody] ReplicaCadastroViewModel model)
        {
            Usuario user = db.Usuarios.SingleOrDefault(u => u.Id == model.AprendizId);

            Replica replica = new Replica();

            replica.Texto       = model.Texto;
            replica.TopicoId    = model.TopicoId;
            replica.DataCriacao = DateTime.Now;
            replica.Usuario     = user; // await userManager.GetUserAsync(this.User);

            System.Console.WriteLine("[" + user.Nome + "]");

            db.Replicas.Add(replica);
            await db.SaveChangesAsync();

            return(Ok());
        }
Esempio n. 19
0
        public Node GetReadNode(Cluster cluster, Partition partition, Replica replica)
        {
            switch (replica)
            {
            case Replica.MASTER:
                return(cluster.GetMasterNode(partition));

            case Replica.MASTER_PROLES:
                return(cluster.GetMasterProlesNode(partition));

            case Replica.SEQUENCE:
                return(GetSequenceNode(cluster, partition));

            default:
            case Replica.RANDOM:
                return(cluster.GetRandomNode());
            }
        }
Esempio n. 20
0
        static void RunAfterCheckin(
            List <string> filteredRepos,
            List <string> dstServers,
            List <RepoMapping> mappings,
            string csetSpecs,
            ErrorEmailSender emailSender)
        {
            Logger.LogInfo("Running as after-checkin trigger...");

            List <Changeset> csets =
                Changeset.ParsePlasticChangesetEnvironVar(csetSpecs);

            List <Replica> pendingReplicas = new List <Replica>();

            foreach (Changeset cset in csets)
            {
                pendingReplicas.AddRange(
                    Replica.BuildPendingReplicas(
                        cset.BranchName,
                        cset.RepositoryName,
                        cset.ServerName,
                        filteredRepos,
                        dstServers,
                        mappings));
            }

            Logger.LogInfo(
                $"Found {pendingReplicas.Count} destinations to replicate to.");

            List <Replica> failedReplicas = new List <Replica>();

            foreach (Replica pendingReplica in pendingReplicas)
            {
                if (!Replicate(pendingReplica))
                {
                    failedReplicas.Add(pendingReplica);
                }
            }

            NotifyFailedReplicas(
                "after-checkin",
                failedReplicas,
                emailSender);
        }
Esempio n. 21
0
        public static void Handle(
            ViewChangeMessage message,
            Replica replica,
            Replica[] activeReplicas,
            ConcurrentDictionary <int, int> viewChangesCount,
            byte[] signedByPrimaryReplicaAheadBlocksOrTreeHashAndCounterViewNumber,
            string encryptedViewKey
            )
        {
            // execute the requests in O that have not been executed
            // extract and store information from T

            var activeReplica = activeReplicas.SingleOrDefault(r => r.Id == message.ReplicaId);

            if (activeReplica == null)
            {
                return;
            }

            byte[] buffer;

            if (Crypto.Verify(replica.PublicKey, message.SignedAheadBlocksOrTreeHashAndCounterViewNumber, out buffer) ==
                false)
            {
                return;
            }

            viewChangesCount.AddOrUpdate(buffer.Sum(v => v), 1, (_, count) => count + 1);

            var maxViewChangeCount = viewChangesCount
                                     .OrderByDescending(vchc => vchc.Value)
                                     .FirstOrDefault();

            if (maxViewChangeCount.Key == 0 || maxViewChangeCount.Value < activeReplicas.Length - 1)
            {
                return;
            }

            replica.Tee.UpdateView(
                replica.PrimaryReplica.PublicKey,
                signedByPrimaryReplicaAheadBlocksOrTreeHashAndCounterViewNumber,
                encryptedViewKey);
        }
Esempio n. 22
0
        static bool Replicate(Replica replica)
        {
            int    result;
            string stdOut, stdErr;

            Logger.LogInfo($"Replicating {replica}");

            string cmdLine = string.Format(
                "cm replicate --push \"br:{0}@{1}@{2}\" {3}@{4}",
                replica.SrcBranch,
                replica.SrcRepo,
                replica.SrcServer,
                replica.DstRepo,
                replica.DstServer);

            Logger.LogInfo($"Executing: '{cmdLine}'");

            result = CmdRunner.CmdRunner.ExecuteCommandWithResult(
                cmdLine,
                Environment.CurrentDirectory,
                out stdOut,
                out stdErr,
                false);

            if (result == 0)
            {
                Logger.LogInfo("The replication process succeeded.");
                return(true);
            }

            Logger.LogError(
                string.Format(
                    "Replicating a branch failed.{0}" +
                    "Command line: '{1}'{0}" +
                    "cm stdout: {2}{0}" +
                    "cm stderr: {3}{0}",
                    Environment.NewLine,
                    cmdLine,
                    stdOut,
                    stdErr));

            return(false);
        }
Esempio n. 23
0
        public Node GetNode(Cluster cluster, Partition partition, Replica replica, bool isRead)
        {
            // Handle default case first.
            if (replica == Replica.SEQUENCE)
            {
                return(GetSequenceNode(cluster, partition));
            }

            if (replica == Replica.MASTER || !isRead)
            {
                return(cluster.GetMasterNode(partition));
            }

            if (replica == Replica.MASTER_PROLES)
            {
                return(cluster.GetMasterProlesNode(partition));
            }
            return(cluster.GetRandomNode());
        }
Esempio n. 24
0
        private async Task DistributeToEndpoint(Service service, Replica replica, string endpoint, InflightMessage message, CancellationToken cancelToken)
        {
            //TODO: security

            var failureDetected = false;
            var failureReason   = Empty;

            try
            {
                var uriBuilder = new UriBuilder(new Uri(endpoint))
                {
                    Path = Format(CultureInfo.InvariantCulture, MessageIngestUrlFormat,
                                  HttpUtility.UrlEncode(message.Type))
                };

                var resp = await HttpClient.PostAsync(uriBuilder.Uri,
                                                      new StringContent(message.Payload, Encoding.UTF8, "application/json"),
                                                      cancelToken);

                if (!resp.IsSuccessStatusCode && resp.StatusCode != HttpStatusCode.NotFound)
                {
                    failureDetected = true;
                    failureReason   = $"Status Code returned - {resp.StatusCode}";
                }
            }
            catch (Exception e)
            {
                failureDetected = true;
                failureReason   = e.Message;
            }
            finally
            {
                if (failureDetected)
                {
                    _bb?.Publish(GetEndpointFailureMessage(service, replica, endpoint, failureReason));
                }
                else
                {
                    _bb?.Publish(GetEndpointSuccessMessage(service, replica, endpoint));
                }
            }
        }
        public static List <BatchNode> GenerateList(Cluster cluster, BatchPolicy policy, Key[] keys)
        {
            Node[] nodes = cluster.Nodes;

            if (nodes.Length == 0)
            {
                throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Command failed because cluster is empty.");
            }

            // Create initial key capacity for each node as average + 25%.
            int keysPerNode = keys.Length / nodes.Length;

            keysPerNode += (int)((uint)keysPerNode >> 2);

            // The minimum key capacity is 10.
            if (keysPerNode < 10)
            {
                keysPerNode = 10;
            }

            Replica replica   = policy.replica;
            Replica replicaSC = Partition.GetReplicaSC(policy);

            // Split keys by server node.
            List <BatchNode> batchNodes = new List <BatchNode>(nodes.Length);

            for (int i = 0; i < keys.Length; i++)
            {
                Node      node      = Partition.GetNodeBatchRead(cluster, keys[i], replica, replicaSC, 0, 0);
                BatchNode batchNode = FindBatchNode(batchNodes, node);

                if (batchNode == null)
                {
                    batchNodes.Add(new BatchNode(node, keysPerNode, i));
                }
                else
                {
                    batchNode.AddKey(i);
                }
            }
            return(batchNodes);
        }
Esempio n. 26
0
        /// <summary>
        /// </summary>
        /// <param name="replicaObj"></param>
        /// <param name="partitionGuid"></param>
        public ReplicaEntity(Replica replicaObj, Guid partitionGuid)
        {
            Assert.IsNotNull(replicaObj, "Replica object can't be null");
            this.Id                  = replicaObj.Id;
            this.HealthState         = replicaObj.HealthState;
            this.ReplicaStatus       = replicaObj.ReplicaStatus;
            this.LastInBuildDuration = replicaObj.LastInBuildDuration;
            this.NodeName            = replicaObj.NodeName;
            this.ServiceKind         = replicaObj.ServiceKind;
            this.ReplicaRole         = ReplicaRole.Unknown;
            this.PartitionId         = partitionGuid;

            // Check if stateful service and if yes, assign appropriate replica role.
            var statefulReplica = replicaObj as StatefulServiceReplica;

            if (statefulReplica != null)
            {
                this.ReplicaRole = statefulReplica.ReplicaRole;
            }
        }
Esempio n. 27
0
        public void BuildPendingReplicasForMappedRepoTest()
        {
            string srcBranch = "br:/main/task-001";
            string srcRepo   = "default";
            string srcServer = "JAIR:8087";

            List <string> filteredRepos = new List <string>();
            List <string> dstServers    = new List <string>()
            {
                "ssl://myserver.mydomain.com:9095",
                "calavera.home:7074"
            };
            List <RepoMapping> repoMappings = new List <RepoMapping>();

            repoMappings.Add(new RepoMapping(
                                 srcRepo, "default_myserver", dstServers[0]));
            repoMappings.Add(new RepoMapping(
                                 srcRepo, "default_calavera", dstServers[1]));

            List <Replica> pendingReplicas =
                Replica.BuildPendingReplicas(
                    srcBranch,
                    srcRepo,
                    srcServer,
                    filteredRepos,
                    dstServers,
                    repoMappings);

            Assert.AreEqual(2, pendingReplicas.Count);

            Replica firstExpectedReplica = new Replica(
                srcBranch, srcRepo, srcServer, "default_myserver", dstServers[0]);

            Replica secondExpectedReplica = new Replica(
                srcBranch, srcRepo, srcServer, "default_calavera", dstServers[1]);

            AssertReplicasEqual(firstExpectedReplica, pendingReplicas[0]);
            AssertReplicasEqual(secondExpectedReplica, pendingReplicas[1]);
        }
Esempio n. 28
0
        void AssertReplicasEqual(Replica left, Replica right)
        {
            Assert.AreEqual(
                left.SrcBranch, right.SrcBranch,
                "The SrcBranch property does not match.");

            Assert.AreEqual(
                left.SrcRepo, right.SrcRepo,
                "The SrcRepo property does not match.");

            Assert.AreEqual(
                left.SrcServer, right.SrcServer,
                "The SrcServer property does not match.");

            Assert.AreEqual(
                left.DstRepo, right.DstRepo,
                "The DstRepo property does not match.");

            Assert.AreEqual(
                left.DstServer, right.DstServer,
                "The DstServer property does not match.");
        }
        public static Node GetNodeBatchRead(Cluster cluster, Key key, Replica replica, Replica replicaSC, uint sequence, uint sequenceSC)
        {
            // Must copy hashmap reference for copy on write semantics to work.
            Dictionary <string, Partitions> map = cluster.partitionMap;
            Partitions partitions;

            if (!map.TryGetValue(key.ns, out partitions))
            {
                throw new AerospikeException.InvalidNamespace(key.ns, map.Count);
            }

            if (partitions.scMode)
            {
                replica  = replicaSC;
                sequence = sequenceSC;
            }

            Partition p = new Partition(partitions, key, replica, false);

            p.sequence = sequence;
            return(p.GetNodeRead(cluster));
        }
Esempio n. 30
0
        static void RunAfterReplicationWrite(
            List <string> filteredRepos,
            List <string> dstServers,
            List <RepoMapping> mappings,
            string branchSpec,
            ErrorEmailSender emailSender)
        {
            Logger.LogInfo("Running as after-replicationwrite trigger...");

            Branch branchToReplicate =
                Branch.ParsePlasticBranchEnvironVar(branchSpec);

            List <Replica> pendingReplicas =
                Replica.BuildPendingReplicas(
                    branchToReplicate.BranchName,
                    branchToReplicate.RepositoryName,
                    branchToReplicate.ServerName,
                    filteredRepos,
                    dstServers,
                    mappings);

            Logger.LogInfo(
                $"Found {pendingReplicas.Count} destinations to replicate to.");

            List <Replica> failedReplicas = new List <Replica>();

            foreach (Replica pendingReplica in pendingReplicas)
            {
                if (!Replicate(pendingReplica))
                {
                    failedReplicas.Add(pendingReplica);
                }
            }

            NotifyFailedReplicas(
                "after-replicationwrite",
                failedReplicas,
                emailSender);
        }
Esempio n. 31
0
        void ApplyToCorrespondingReplica(Replica replica, Action <Replica> func)
        {
            Action <GameObject> impl = (go) => {
                var correspondingReplicas = go.GetComponentsInChildren <Replica>();
                foreach (var correspondingReplica in correspondingReplicas)
                {
                    if (correspondingReplica.Id == replica.Id)
                    {
                        func(correspondingReplica);
                        break;
                    }
                }
            };

            if (replica.isClient)
            {
                var otherReplica = ServerReplicaManager.Main.GetReplica(replica.Id);
                if (otherReplica != null)
                {
                    impl(otherReplica.gameObject);
                }
            }

            if (replica.isServer)
            {
                foreach (var replicaManager in ClientReplicaManager.All)
                {
                    var otherReplica = replicaManager.GetReplica(replica.Id);
                    if (otherReplica == null)
                    {
                        continue;
                    }

                    impl(otherReplica.gameObject);
                    break;
                }
            }
        }
Esempio n. 32
0
        public static List <BatchNode> GenerateList(Cluster cluster, BatchPolicy policy, List <BatchRead> records)
        {
            Node[] nodes = cluster.ValidateNodes();

            // Create initial key capacity for each node as average + 25%.
            int max         = records.Count;
            int keysPerNode = max / nodes.Length;

            keysPerNode += (int)((uint)keysPerNode >> 2);

            // The minimum key capacity is 10.
            if (keysPerNode < 10)
            {
                keysPerNode = 10;
            }

            Replica replica   = policy.replica;
            Replica replicaSC = Partition.GetReplicaSC(policy);

            // Split keys by server node.
            List <BatchNode> batchNodes = new List <BatchNode>(nodes.Length);

            for (int i = 0; i < max; i++)
            {
                Node      node      = Partition.GetNodeBatchRead(cluster, records[i].key, replica, replicaSC, 0, 0);
                BatchNode batchNode = FindBatchNode(batchNodes, node);

                if (batchNode == null)
                {
                    batchNodes.Add(new BatchNode(node, keysPerNode, i));
                }
                else
                {
                    batchNode.AddKey(i);
                }
            }
            return(batchNodes);
        }
Esempio n. 33
0
        private void CheckReplicas(IDictionary <long, Replica> expectedReplicas, BlockListAsLongs
                                   decodedBlocks)
        {
            NUnit.Framework.Assert.AreEqual(expectedReplicas.Count, decodedBlocks.GetNumberOfBlocks
                                                ());
            IDictionary <long, Replica> reportReplicas = new Dictionary <long, Replica>(expectedReplicas
                                                                                        );

            foreach (BlockListAsLongs.BlockReportReplica replica in decodedBlocks)
            {
                NUnit.Framework.Assert.IsNotNull(replica);
                Replica expected = Sharpen.Collections.Remove(reportReplicas, replica.GetBlockId(
                                                                  ));
                NUnit.Framework.Assert.IsNotNull(expected);
                NUnit.Framework.Assert.AreEqual("wrong bytes", expected.GetNumBytes(), replica.GetNumBytes
                                                    ());
                NUnit.Framework.Assert.AreEqual("wrong genstamp", expected.GetGenerationStamp(),
                                                replica.GetGenerationStamp());
                NUnit.Framework.Assert.AreEqual("wrong replica state", expected.GetState(), replica
                                                .GetState());
            }
            NUnit.Framework.Assert.IsTrue(reportReplicas.IsEmpty());
        }
        private void addConnection(Socket s) 
        {
            lock (mutex) 
            { 
                int n = replicas.Length;

                Replica[] newReplicas = new Replica[n+1];
                Array.Copy(replicas, 0, newReplicas, 0, n);
                Replica replica = new Replica();
                newReplicas[n] = replica;
                replica.host = s.RemoteEndPoint.ToString();
                replica.socket = s;
                replica.isDynamic = true;
                replicas = newReplicas;

                nHosts += 1;
    
                SynchronizeThread syncThread = new SynchronizeThread(this, n);
                Thread t = new Thread(new ThreadStart(syncThread.run));           
                replica.syncThread = t;
                t.Start();
            }
        }
Esempio n. 35
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 public Policy(Policy other)
 {
     this.priority = other.priority;
     this.consistencyLevel = other.consistencyLevel;
     this.replica = other.replica;
     this.timeout = other.timeout;
     this.maxRetries = other.maxRetries;
     this.sleepBetweenRetries = other.sleepBetweenRetries;
     this.sendKey = other.sendKey;
 }
Esempio n. 36
0
        public Node GetReadNode(Partition partition, Replica replica)
        {
            switch (replica)
            {
                case Replica.MASTER:
                    return GetMasterNode(partition);

                case Replica.MASTER_PROLES:
                    return GetMasterProlesNode(partition);

                default:
                case Replica.RANDOM:
                    return GetRandomNode();
            }
        }