github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/networkdb/event_delegate.go (about)

     1  package networkdb
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"net"
     7  
     8  	"github.com/containerd/log"
     9  	"github.com/hashicorp/memberlist"
    10  )
    11  
    12  type eventDelegate struct {
    13  	nDB *NetworkDB
    14  }
    15  
    16  func (e *eventDelegate) broadcastNodeEvent(addr net.IP, op opType) {
    17  	value, err := json.Marshal(&NodeAddr{addr})
    18  	if err == nil {
    19  		e.nDB.broadcaster.Write(makeEvent(op, NodeTable, "", "", value))
    20  	} else {
    21  		log.G(context.TODO()).Errorf("Error marshalling node broadcast event %s", addr.String())
    22  	}
    23  }
    24  
    25  func (e *eventDelegate) NotifyJoin(mn *memberlist.Node) {
    26  	log.G(context.TODO()).Infof("Node %s/%s, joined gossip cluster", mn.Name, mn.Addr)
    27  	e.broadcastNodeEvent(mn.Addr, opCreate)
    28  	e.nDB.Lock()
    29  	defer e.nDB.Unlock()
    30  
    31  	// In case the node is rejoining after a failure or leave,
    32  	// just add the node back to active
    33  	if moved, _ := e.nDB.changeNodeState(mn.Name, nodeActiveState); moved {
    34  		return
    35  	}
    36  
    37  	// Every node has a unique ID
    38  	// Check on the base of the IP address if the new node that joined is actually a new incarnation of a previous
    39  	// failed or shutdown one
    40  	e.nDB.purgeReincarnation(mn)
    41  
    42  	e.nDB.nodes[mn.Name] = &node{Node: *mn}
    43  	log.G(context.TODO()).Infof("Node %s/%s, added to nodes list", mn.Name, mn.Addr)
    44  }
    45  
    46  func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) {
    47  	log.G(context.TODO()).Infof("Node %s/%s, left gossip cluster", mn.Name, mn.Addr)
    48  	e.broadcastNodeEvent(mn.Addr, opDelete)
    49  
    50  	e.nDB.Lock()
    51  	defer e.nDB.Unlock()
    52  
    53  	n, currState, _ := e.nDB.findNode(mn.Name)
    54  	if n == nil {
    55  		log.G(context.TODO()).Errorf("Node %s/%s not found in the node lists", mn.Name, mn.Addr)
    56  		return
    57  	}
    58  	// if the node was active means that did not send the leave cluster message, so it's probable that
    59  	// failed. Else would be already in the left list so nothing else has to be done
    60  	if currState == nodeActiveState {
    61  		moved, err := e.nDB.changeNodeState(mn.Name, nodeFailedState)
    62  		if err != nil {
    63  			log.G(context.TODO()).WithError(err).Errorf("impossible condition, node %s/%s not present in the list", mn.Name, mn.Addr)
    64  			return
    65  		}
    66  		if moved {
    67  			log.G(context.TODO()).Infof("Node %s/%s, added to failed nodes list", mn.Name, mn.Addr)
    68  		}
    69  	}
    70  }
    71  
    72  func (e *eventDelegate) NotifyUpdate(n *memberlist.Node) {
    73  }