Debian Codegraph @

buildkit/examples/kubernetes/consistenthash/main.go

raw symbols SCIP
1 // Package main provides simple consistenthash commandline utility.
2 /*
3 Demo:
4
5 $ seq -f node-%.f 1 100 > /tmp/nodes
6 $ consistenthash < /tmp/nodes apple
7 node-42
8 $ consistenthash < /tmp/nodes banana
9 node-48
10 $ consistenthash < /tmp/nodes chocolate
11 node-2
12
13 Modify /tmp/nodes and confirm that the result rarely changes.
14 */
15 package main
16
17 import (
18 "fmt"
19 "io"
20 "os"
21 "strings"
22
23 "github.com/pkg/errors"
24 "github.com/serialx/hashring"
25 "github.com/sirupsen/logrus"
26 )
27
28 func main() {
29 if err := xmain(); err != nil {
30 logrus.Fatal(err)
31 }
32 }
33
34 func xmain() error {
35 if len(os.Args) != 2 {
36 fmt.Fprintf(os.Stderr, "Usage: %s KEY\nNode list needs to be provided via stdin\n", os.Args[0])
37 os.Exit(1)
38 return errors.New("should not reach here")
39 }
40 key := os.Args[1]
41 stdin, err := io.ReadAll(os.Stdin)
42 if err != nil {
43 return err
44 }
45 var nodes []string
46 for s := range strings.SplitSeq(string(stdin), "\n") {
47 s = strings.TrimSpace(s)
48 if s != "" {
49 nodes = append(nodes, s)
50 }
51 }
52 chosen, err := doConsistentHash(nodes, key)
53 if err != nil {
54 return err
55 }
56 fmt.Println(chosen)
57 return nil
58 }
59
60 func doConsistentHash(nodes []string, key string) (string, error) {
61 ring := hashring.New(nodes)
62 x, ok := ring.GetNode(key)
63 if !ok {
64 return "", errors.Errorf("no node found for key %q", key)
65 }
66 return x, nil
67 }