github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/gnmi/arbitration.go (about)

     1  // Copyright (c) 2019 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package gnmi
     6  
     7  import (
     8  	"fmt"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/openconfig/gnmi/proto/gnmi_ext"
    13  )
    14  
    15  // ArbitrationExt takes a string representation of a master arbitration value
    16  // (e.g. "23", "role:42") and return a *gnmi_ext.Extension.
    17  func ArbitrationExt(s string) (*gnmi_ext.Extension, error) {
    18  	if s == "" {
    19  		return nil, nil
    20  	}
    21  	roleID, electionID, err := parseArbitrationString(s)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	arb := &gnmi_ext.MasterArbitration{
    26  		Role:       &gnmi_ext.Role{Id: roleID},
    27  		ElectionId: &gnmi_ext.Uint128{High: 0, Low: electionID},
    28  	}
    29  	ext := gnmi_ext.Extension_MasterArbitration{MasterArbitration: arb}
    30  	return &gnmi_ext.Extension{Ext: &ext}, nil
    31  }
    32  
    33  // parseArbitrationString parses the supplied string and returns the role and election id
    34  // values. Input is of the form [<role>:]<election_id>, where election_id is a uint64.
    35  //
    36  // Examples:
    37  //
    38  //	"1"
    39  //	"admin:42"
    40  func parseArbitrationString(s string) (string, uint64, error) {
    41  	tokens := strings.Split(s, ":")
    42  	switch len(tokens) {
    43  	case 1: // just election id
    44  		id, err := parseElectionID(tokens[0])
    45  		return "", id, err
    46  	case 2: // role and election id
    47  		id, err := parseElectionID(tokens[1])
    48  		return tokens[0], id, err
    49  	}
    50  	return "", 0, fmt.Errorf("badly formed arbitration id (%s)", s)
    51  }
    52  
    53  func parseElectionID(s string) (uint64, error) {
    54  	id, err := strconv.ParseUint(s, 0, 64)
    55  	if err != nil {
    56  		return 0, fmt.Errorf("badly formed arbitration id (%s)", s)
    57  	}
    58  	return id, nil
    59  }