github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/scripts/juju-inspect/rules/raft.go (about)

     1  // Copyright 2021 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package rules
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  )
    10  
    11  type RaftRule struct {
    12  	found   map[string]bool
    13  	leaders map[string]bool
    14  }
    15  
    16  func NewRaftRule() *RaftRule {
    17  	return &RaftRule{
    18  		found:   make(map[string]bool),
    19  		leaders: make(map[string]bool),
    20  	}
    21  }
    22  
    23  func (r *RaftRule) Run(name string, report Report) error {
    24  	raft, ok := report.Manifolds["raft"]
    25  	if !ok {
    26  		r.found[name] = false
    27  		return nil
    28  	}
    29  
    30  	r.found[name] = true
    31  
    32  	var out RaftReport
    33  	if err := raft.UnmarshalReport(&out); err != nil {
    34  		return err
    35  	}
    36  
    37  	r.leaders[name] = out.State == "Leader"
    38  
    39  	return nil
    40  }
    41  
    42  func (r *RaftRule) Write(w io.Writer) {
    43  	fmt.Fprintln(w, "Raft Leader:")
    44  	fmt.Fprintln(w, "")
    45  
    46  	var leader bool
    47  	var ctrl string
    48  	for name, ldr := range r.leaders {
    49  		if leader && ldr {
    50  			// Two or more leaders
    51  			fmt.Fprintln(w, "\tTwo or more leaders have been found in the files!")
    52  			fmt.Fprintln(w, "")
    53  			return
    54  		}
    55  		if ldr {
    56  			leader = true
    57  			ctrl = name
    58  		}
    59  	}
    60  	if !leader {
    61  		fmt.Fprintln(w, "\tThere are no leaders found.")
    62  		fmt.Fprintln(w, "")
    63  		return
    64  	}
    65  	fmt.Fprintf(w, "\t%s is the leader.\n", ctrl)
    66  	fmt.Fprintln(w, "")
    67  }
    68  
    69  type RaftReport struct {
    70  	State string `yaml:"state"`
    71  }