Sistemas Distribuídos Sincronização de relógios lógicos Prof. Emerson Ribeiro de Mello Instituto Federal de Santa Catarina IFSC campus São José mello@ifsc.edu.br http://docente.ifsc.edu.br/mello 26 de novembro de 2015 1/20
Jogo online com múltiplos jogadores Dois jogadores atiram no mesmo adversário. Quem ganha o ponto? Os relógios físicos dos 3 jogadores precisam estar sincronizados? 2/20
Bolsa de valores 3/20
Bolsa de valores É importante garantir a ordem correta das mensagens Não seria nada desejado vender e depois comprar Como garantir? Sincronizar os relógios físicos? 3/20
Bolsa de valores É importante garantir a ordem correta das mensagens Não seria nada desejado vender e depois comprar Como garantir? Sincronizar os relógios físicos? Não é possível garantir o sincronismo perfeito de dois relógios físicos Mesmo que pequena, sempre haverá uma diferença 3/20
Relógios Lógicos 4/20
Tempo lógico e Relógio lógico Tempo lógico Do ponto de vista de um processo, o tempo lógico indica a ordem de execução dos eventos Por que precisamos de Relógio Lógico em SD? Não é possível sincronizar relógios físicos perfeitamente Processos que interagem entre si devem acordar sobre a ordem de execução dos eventos não requer que estejam com seus relógios físicos sincronizados com a hora exata 4/20
Relógio Lógico de Lamport (1978) Relógio Lógico de Lamport É um contador em software que não possui relação com qualquer relógio físico Premissa Se dois processos não interagem entre si, então não é necessário sincronizar seus relógios lógicos Relação de causalidade (causa e efeito) indica a relação de precedência entre dois eventos Define a ordem causal 5/20
Relógio Lógico de Lamport (1978) Figure Causalidade 14.5 Events e concorrência occurring at three processes SECTION 14.4 LOGICAL TIME AND LOGICAL CLOCKS 607 p 1 a b m 1 p 2 c d m 2 Physical time p 3 e 14.4 Logical time and logical clocks Causalidade Se From athe e bpoint sãoof eventos view of any emsingle umprocess, mesmoevents processo, are ordered e auniquely ocorreby antes times de b, shown on the local clock. However, as Lamport [1978] pointed out, since we cannot então synchronize a clocks b perfectly across a distributed system, we cannot in general use Se physical umtime processo to find out P i the envia order of uma any arbitrary mensagem pair of mevents para occurring um processo within it. P j, o evento send(m) In general, acontece we can use antes a scheme dothat receive(m): is similar to physical b causality c but that applies in distributed systems to order some of the events that occur at different processes. This Se ordering a is bbased e bon two c, simple então and aintuitively c (transitividade) obvious points: Concorrência If two events occurred at the same process p i i = 1 2 N, then they a e eoccurred não possuem in the order relação in which, p i observes são concorrentes them this is the a order e i that we defined above. Whenever a message is sent between processes, the event of sending the message occurred before the event of receiving the message. f 6/20
Relógio Lógico de Lamport (1978) Regras Cada processo P i mantém seu relógio lógico L i próprio e o usa para fazer marcação temporal (timestamp) dos seus eventos 1 L i é incrementado antes de cada evento local gerado pelo processo P i 2 Quando um processo P i envia uma mensagem m, este anexa L i como timestamp de m: t = L i 3 P j ao receber a mensagem (m, t) faz L j = max(l j, t) + 1 antes de entregar a mensagem para a aplicação 7/20
Relógio Lógico de Lamport (1978) 8/20
Relógio Lógico de Lamport (1978) Exemplo 14.6 Lamport timestamps for the events shown in Figure 14.5 SECTION 14.4 LOGICAL TIME AND LOGICAL CLOCKS 609 1 2 p 1 a b m 1 p 2 3 4 c d m 2 Physical time p 3 1 e f 5 L 1, L 2 e L 3 começam com 0 P 1 anexa t = L 1 = 2 a mensagem m 1 antes de enviar para P 2 PTotally ordered logical clocks Some pairs of distinct events, generated by different 2 ao receber (m 1, t) faz L 2 = max(0, 2) + 1, logo L 2 = 3 processes, have numerically identical Lamport timestamps. However, we can create a total order on the set of events that is, one for which all pairs of distinct events are ordered by taking into account the identifiers of the processes at which events occur. If e is an event occurring at p i with local timestamp T i, and e is an event occurring at 9/20 p with local timestamp T, we define the global logical timestamps for these events to
Relógio Lógico de Lamport (1978) Limitação do relógio lógico 14.6 Lamport timestamps for the events shown in Figure 14.5 SECTION 14.4 LOGICAL TIME AND LOGICAL CLOCKS 609 1 2 p 1 a b m 1 p 2 3 4 c d m 2 Physical time p 3 1 e f 5 e e implica em L(e) < L(e ) Ex: a c L(e) Totally< ordered L(e ) logical não necessariamente clocks Some pairs implica of distinct emevents, e generated e by different processes, Ex: L(e) have < numerically L(b), pois identical e b Lamport timestamps. However, we can create a total order on the set of events that is, one for which all pairs of distinct events are ordered by taking into account the identifiers of the processes at which events occur. If e is an event occurring at p i with local timestamp T i, and e is an event occurring at 10/20 p with local timestamp T, we define the global logical timestamps for these events to
Exemplo de uso de relógios lógicos Difusão seletiva com ordem total Garantir que todas as réplicas processem a mesma sequência de operações Banco possui base de dados replicadas e distribuídas Alta disponibilidade, desempenho (réplica mais próxima do cliente) Cliente possui saldo de R$ 1.000,00 e deposita R$ 100,00 e ao mesmo instante Gerente aplica correção de juros de 1% Saldo em réplica 1: R$ 1.111,00 Saldo em réplica 2: R$ 1.110,00 11/20
Difusão seletiva com ordem total Todas as mensagens serão processadas na mesma ordem por todos os processos Premissas Não há perda de mensagens Mensagens enviadas por um mesmo emissor são recebidas na mesma ordem que foram enviadas Mensagens enviadas por um emissor também são recebidas por este 1 Processo P i envia mensagem m i com seu timestamp para todos os demais processos 2 Toda mensagem recebida em P j é armazenada em uma fila ordenada pelo timestamp da mensagem P j envia mensagem de confirmação (ACK) para todos os demais processos 3 P j encaminha uma mensagem m i para sua aplicação se: m i estiver no início da fila m i foi confirmada por todos os demais processos 12/20
Relógios vetoriais 13/20
Relógio de Lamport vs Relógio Vetorial Relógio de Lamport Garante a ordem de eventos que satisfaz a relação causal, porém não completamente a b L(a) < L(b) Se L(a) < L(b), não é possível deduzir a b Relógio vetorial Satisfaz a condição a b L(a) < L(b) 13/20
Relógio vetorial Em um sistema distribuído com N processos, cada processo P i possui seu próprio relógio vetorial de tamanho N: V i [N] Inicialmente V i [j] = 0, i e j Na posição V i [i] tem-se o total de eventos que ocorreram no próprio processo P i Na posição V i [j] tem-se o total de eventos que ocorreram em P j e que puderam ser observados por P i i j 14/20
Relógio vetorial Regras para atualização Evento local em P i V i [i] = V i [i] + 1 Ao enviar mensagem V i é anexado em toda mensagem enviada por P i Ao receber uma mensagem P j ao receber mensagem de P i faz V j [k] = max(v j [k], V i [k]), j k, para k = 1 até n V j [j] = V j [j] + 1 15/20
Relógio vetorial Regras para atualização Evento local em P i V i [i] = V i [i] + 1 Ao enviar mensagem V i é anexado em toda mensagem enviada por P i Ao receber uma mensagem P j ao receber mensagem de P i faz V j [k] = max(v j [k], V i [k]), j k, para k = 1 até n V j [j] = V j [j] + 1 Exemplo V j = {4, 9, 11, 3} e foi recebido {2, 5, 15, 3} resultado: V j = {4, 9, 15, 3} 15/20
Relógio vetorial exemplo igure 14.7 Vector timestamps for the events shown in Figure 14.5 (1,0,0) (2,0,0) p 1 a b m 1 p 2 (2,1,0) (2,2,0) c d m 2 Physical time p 3 (0,0,1) e f (2,2,2) We may compare vector timestamps as follows: V = V iff V j = V j for j = 1 2 N V V iff V j V j for j = 1 2 N V V iff V V V V Let Ve be the vector timestamp applied by the process at which e occurs. It is straightforward to show, by induction on the length of any sequence of events relating two events e and e, that e e Ve Ve. Exercise 10.13 leads the reader to show the converse: if V e Ve, then e e. Figure 14.7 shows the vector timestamps of the events of Figure 14.5. It can be 16/20 seen, for example, that Va Vf, which reflects the fact that a f. Similarly, we
Relógio vetorial exemplo igure 14.7 Vector timestamps for the events shown in Figure 14.5 (1,0,0) (2,0,0) p 1 a b m 1 p 2 (2,1,0) (2,2,0) c d m 2 Physical time p 3 (0,0,1) e f (2,2,2) Precedência: We may bcompare d vector V timestamps (b) < V as (d) follows: {2, 0, 0} {2, 2, 0} = verdade? ( E lógico por posição) = V iff V j = V j for j = 1 2 N {V, V, V } = verdade V V iff V j V j for j = 1 2 N V V iff V V V V Let Ve be the vector timestamp applied by the process at which e occurs. It is straightforward to show, by induction on the length of any sequence of events relating two events e and e, that e e Ve Ve. Exercise 10.13 leads the reader to show the converse: if V e Ve, then e e. Figure 14.7 shows the vector timestamps of the events of Figure 14.5. It can be 16/20 seen, for example, that Va Vf, which reflects the fact that a f. Similarly, we
Relógio vetorial exemplo igure 14.7 Vector timestamps for the events shown in Figure 14.5 (1,0,0) (2,0,0) p 1 a b m 1 p 2 (2,1,0) (2,2,0) c d m 2 Physical time p 3 (0,0,1) e f (2,2,2) Precedência: We may bcompare d vector V timestamps (b) < V as (d) follows: {2, 0, 0} {2, 2, 0} = verdade? ( E lógico por posição) = V iff V j = V j for j = 1 2 N {V, V, V } = verdade Não precedência: V V iff V j f V jc for jv = (f 1 ) 2 < NV (c) {2, 2, 2} {2, 1, 0} = {V, F, F } = falso V V iff V V V V Let Ve be the vector timestamp applied by the process at which e occurs. It is straightforward to show, by induction on the length of any sequence of events relating two events e and e, that e e Ve Ve. Exercise 10.13 leads the reader to show the converse: if V e Ve, then e e. Figure 14.7 shows the vector timestamps of the events of Figure 14.5. It can be 16/20 seen, for example, that Va Vf, which reflects the fact that a f. Similarly, we
Relógio vetorial exemplo igure 14.7 Vector timestamps for the events shown in Figure 14.5 (1,0,0) (2,0,0) p 1 a b m 1 p 2 (2,1,0) (2,2,0) c d m 2 Physical time p 3 (0,0,1) e f (2,2,2) Precedência: We may bcompare d vector V timestamps (b) < V as (d) follows: {2, 0, 0} {2, 2, 0} = verdade? ( E lógico por posição) = V iff V j = V j for j = 1 2 N {V, V, V } = verdade Não precedência: V V iff V j f V jc for jv = (f 1 ) 2 < NV (c) {2, 2, 2} {2, 1, 0} = {V, F, F } = falso V V iff V V V V Concorrência: a e (V (a) < V (e)) (V (e) < V (a)) Let {1, Ve 0, 0} be the {0, vector 0, 1} timestamp = {F, V applied, V } = by falso the process at which e occurs. It is straightforward to show, by induction on the length of any sequence of events relating two {0, events 0, 1} e and {1, e 0,, that 0} = e {V e, V Ve, F } = Ve falso. Exercise 10.13 leads the reader to show the converse: if V e Ve, then e e. Figure 14.7 shows the vector timestamps of the events of Figure 14.5. It can be 16/20 seen, for example, that Va Vf, which reflects the fact that a f. Similarly, we
Exercício 1: Relógio lógico de Lamport 1 Coloque o valor do relógio em cada evento 2 Ciente que o evento i ocorreu antes de n, o que pode-se afirmar sobre seus relógios lógicos? 3 Sabe-se que L(h) < L(c), logo é possível afirmar a relação de precedência entre h e c? 17/20
Exercício 2: Relógio vetorial 1 Coloque o valor do relógio vetorial em cada evento 2 Comprove a relação a j comparando os relógios destes eventos 3 Compare os relógios de d e j e comprove a relação d j 18/20
Exercício 3: Relógio vetorial Em um sistema distribuído o processo P 2 terminou sua execução com o seguinte relógio vetorial: {3, 1, 0, 6, 4} 1 Quantos eventos aconteceram no processo P 2? 2 Quantos eventos de P 3 foram observados por P 2? Este número é igual ao total de eventos que fato ocorreram em P 3? 3 Quantos processos compõem o sistema distribuído? 4 Quantas mensagens P 2 recebeu? 19/20
Exercício 4: Relógio lógico de Lamport 1 Da forma que foi apresentada em sala, é possível que dois eventos em processos distintos tenham timestamp idênticos. Veja em um dos livros da disciplina qual a solução que Lamport criou para garantir timestamps únicos Coloque o valor do relógio em cada evento, considerando a solução de timestamp único 20/20