File: main.go

package info (click to toggle)
docker.io 27.5.1%2Bdfsg4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 67,384 kB
  • sloc: sh: 5,847; makefile: 1,146; ansic: 664; python: 162; asm: 133
file content (67 lines) | stat: -rw-r--r-- 1,321 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Package main provides simple consistenthash commandline utility.
/*
Demo:

  $ seq -f node-%.f 1 100 > /tmp/nodes
  $ consistenthash < /tmp/nodes apple
  node-42
  $ consistenthash < /tmp/nodes banana
  node-48
  $ consistenthash < /tmp/nodes chocolate
  node-2

Modify /tmp/nodes and confirm that the result rarely changes.
*/
package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/pkg/errors"
	"github.com/serialx/hashring"
	"github.com/sirupsen/logrus"
)

func main() {
	if err := xmain(); err != nil {
		logrus.Fatal(err)
	}
}

func xmain() error {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s KEY\nNode list needs to be provided via stdin\n", os.Args[0])
		os.Exit(1)
		return errors.New("should not reach here")
	}
	key := os.Args[1]
	stdin, err := io.ReadAll(os.Stdin)
	if err != nil {
		return err
	}
	var nodes []string
	for _, s := range strings.Split(string(stdin), "\n") {
		s = strings.TrimSpace(s)
		if s != "" {
			nodes = append(nodes, s)
		}
	}
	chosen, err := doConsistentHash(nodes, key)
	if err != nil {
		return err
	}
	fmt.Println(chosen)
	return nil
}

func doConsistentHash(nodes []string, key string) (string, error) {
	ring := hashring.New(nodes)
	x, ok := ring.GetNode(key)
	if !ok {
		return "", errors.Errorf("no node found for key %q", key)
	}
	return x, nil
}