Para agentes de IA: um índice de documentação está disponível em https://www.mongodb.com/pt-br/docs/llms.txt — as versões de markdown de todas as páginas estão disponíveis anexando .md a qualquer caminho de URL.

Sincronize novamente um membro de um conjunto de réplicas autogerenciadas

Um membro do conjunto de réplicas torna-se "obsoleto" quando seu processo de replicação fica tão atrasado que o primário substitui as entradas de oplog que o membro ainda não replicou. O membro não consegue se atualizar e torna-se "obsoleto". Quando isso ocorre, você deve ressincronizar completamente o membro removendo seus dados e executando uma initial sync.

Ao sincronizar um membro, escolha um horário em que o sistema tenha a largura de banda para mover uma grande quantidade de dados. Agende a sincronização durante um período de baixo uso ou durante uma janela de manutenção.

Utilize os procedimentos desta página para restaurar um membro de um conjunto de réplicas em um dos seguintes cenários:

  • Use o membro mais atualizado no conjunto de réplicas como fonte de sincronização. Se a fonte de sincronização tiver dados desatualizados, o membro ressincronizado poderá perder as gravações com confirmação majoritária, o que pode resultar em perda de dados.

  • If you resync more than one member, resync the most out-of-date secondary first. In most cases, the data-bearing secondary with the highest replication lag is the most out-of-date. Use rs.printSecondaryReplicationInfo() to check replication lag.

  • Para evitar que o conjunto de réplicas perca a maioria dos votos, nunca resincronize mais de um membro do conjunto de réplicas por vez.

  • If you copy data files, ensure that your copy includes the content of the local database.

Este procedimento exclui os dados existentes do membro. Em seguida, o membro restaura seus dados de outro membro por meio do processo de sincronização inicial regular. Para obter uma visão geral desse processo, consulte Sincronização de Dados do Conjunto de Réplicas.

As operações de sincronização inicial podem afetar os outros membros do conjunto e gerar tráfego adicional para o membro de origem. O membro que está sincronizando precisa de outro membro do conjunto que esteja acessível e atualizado.

Aviso

Durante a sincronização inicial, o mongod remove o conteúdo do diretório dbPath.

1

Connect to the primary with mongosh and run rs.conf(). Note the member's host, priority, votes, and any other settings that you changed from the defaults. You need them to restore the member later.

2

Use rs.remove() to remove the member. Wait for the method to return successfully. If the method times out, do not continue until the new configuration has been installed on a majority of voting members. To learn more, see Reconfiguration Waits Until a Majority of Members Install the Replica Configuration.

3

To ensure a clean shutdown, use the db.shutdownServer() method from mongosh or, on Linux systems, the mongod --shutdown option.

4

Make a backup of all data and sub-directories from the member's dbPath directory. If a full backup is not required, consider backing up just the diagnostic.data directory to preserve potentially-useful troubleshooting data in the event of an issue. See Full Time Diagnostic Data Capture for more information.

5

Exclua todos os dados e subdiretórios do diretório dbPath do membro.

7

Connect to the primary and use rs.add() to add the member with votes: 0 and priority: 0. Non-voting members must have a priority of 0.

rs.add( { host: "<hostname>:<port>", votes: 0, priority: 0 } )

Wait for the method to return successfully. The mongod then performs an initial sync. The length of the initial sync process depends on the size of the database and the network latency between members of the replica set.

Adding the member as a non-voting member prevents the member's initial sync from stalling writes that use the "majority" write concern.

8

Use rs.status() to confirm that the member has returned to the SECONDARY state. Then use rs.printSecondaryReplicationInfo() to confirm that its replication lag is close to 0. The SECONDARY state alone does not guarantee that the member is up to date.

9

Use rs.conf() to retrieve the current configuration. Set the member's votes and priority to the values that you recorded in the first step, and then apply the configuration with rs.reconfig(). Wait for the method to return successfully.

Essa abordagem "inicializa" um membro novo ou obsoleto usando os arquivos de dados de um membro existente do conjunto de réplicas. Os arquivos de dados devem ser suficientemente recentes para permitir que o novo membro se atualize com o oplog. Caso contrário, o membro precisaria realizar uma sincronização inicial.

Se você estiver adicionando um novo membro, ignore as etapas rotuladas como "(Membro existente)".

1

If the member already belongs to the replica set, connect to the primary with mongosh and run rs.conf(). Note the member's host, priority, votes, and any other settings that you changed from the defaults. You need them to restore the member later.

2

Use rs.remove() to remove the member. Wait for the method to return successfully. If the method times out, do not continue until the new configuration has been installed on a majority of voting members. To learn more, see Reconfiguration Waits Until a Majority of Members Install the Replica Configuration.

3

Você pode capturar os arquivos de dados como uma captura instantânea ou uma cópia direta. No entanto, na maioria dos casos, você não pode copiar arquivos de dados de uma instância do mongod em execução para outra, pois os arquivos de dados serão alterados durante a operação de cópia do arquivo.

Importante

Você não pode usar um backup mongodump para os arquivos de dados: apenas um backup de snapshot. Para abordagens para capturar um snapshot consistente de uma instância mongod em execução, consulte a documentação Métodos de backup para uma implantação autogerenciada.

4

Start the mongod instance with a new members[n]._id. Then connect to the primary and use rs.add() to add the member with votes: 0 and priority: 0. Non-voting members must have a priority of 0.

rs.add( { host: "<hostname>:<port>", votes: 0, priority: 0 } )

Aguarde até que o método retorne com sucesso.

5

Allow the member to apply all operations from the oplog until it reflects the current state of the replica set. To see the current status of the replica set, use rs.printSecondaryReplicationInfo() or rs.status(). Wait until the member's replication lag is close to 0.

6

Use rs.conf() to retrieve the current configuration. Set the member's votes and priority to the values that you recorded earlier, or to 1 and 1 for a new member, and then apply the configuration with rs.reconfig(). Wait for the method to return successfully.

Ressincronize um membro portador de dados por vez, começando pelos secundários e terminando pelo primário. Ressincronizar um membro por vez evita que o conjunto de réplicas perca a maioria de votos. Os árbitros não armazenam dados, portanto, ignore-os.

Resyncing the only secondary in a replica set with an arbiter can stall writes that use the "majority" write concern. The automatic sync procedure avoids this stall. It re-adds the member as a non-voting member until the member catches up. To learn more, see Mitigate Performance Issues in Self-Managed PSA Replica Sets.

Antes de começar, confirme se todos os membros estão saudáveis. Confirme também se a janela do oplog é longa o suficiente para cobrir o tempo necessário para a sincronização inicial.

1

Identify the most out-of-date secondary. In most cases, it is the secondary with the highest replication lag, which you can check with rs.printSecondaryReplicationInfo(). Then use the automatically sync a member procedure to resync that secondary.

2

Repeat step 1 for each remaining data-bearing secondary, starting with the most out-of-date.

3

When the secondaries are healthy and caught up, use rs.stepDown() to step down the primary. The method waits for an electable secondary to catch up before it steps down the primary. Confirm that a secondary is elected as the new primary before proceeding.

4

O antigo servidor primário agora é secundário. Use o procedimento de sincronização automática de membros para ressincronizá-lo.

5

Use rs.status() and check replication lag to confirm that all data-bearing members have returned to a healthy state and are sufficiently caught up.

Documentação