| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/gomodule/redigo/redis" |
| 8 | log "github.com/sirupsen/logrus" |
| 9 | ) |
| 10 | |
| 11 | var reNodeAddress = regexp.MustCompile(`^(?P<ip>.+):(?P<port>\d+)@(?P<cport>\d+)(?:,(?P<hostname>.+))?`) |
| 12 | |
| 13 | func (e *Exporter) getClusterNodes(c redis.Conn) ([]string, error) { |
| 14 | output, err := redis.String(doRedisCmd(c, "CLUSTER", "NODES")) |
| 15 | if err != nil { |
| 16 | log.Errorf("Error getting cluster nodes: %s", err) |
| 17 | return nil, err |
| 18 | } |
| 19 | |
| 20 | lines := strings.Split(output, "\n") |
| 21 | nodes := []string{} |
| 22 | |
| 23 | for _, line := range lines { |
| 24 | if node, ok := parseClusterNodeString(line, e.options.ClusterDiscoverHostnames); ok { |
| 25 | nodes = append(nodes, node) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | return nodes, nil |
| 30 | } |
| 31 | |
| 32 | /* |
| 33 | <id> <ip:port@cport[,hostname]> <flags> <master> <ping-sent> <pong-recv> <config-epoch> <link-state> <slot> <slot> ... <slot> |
| 34 | eaf69c70d876558a948ba62af0884a37d42c9627 127.0.0.1:7002@17002 master - 0 1742836359057 3 connected 10923-16383 |
| 35 | */ |
| 36 | func parseClusterNodeString(node string, resolveHostname bool) (string, bool) { |
| 37 | log.Debugf("parseClusterNodeString node: [%s]", node) |
| 38 | |
| 39 | fields := strings.Fields(node) |
| 40 | if len(fields) < 2 { |
| 41 | log.Debugf("Invalid field count for node: %s", node) |
| 42 | return "", false |
| 43 | } |
| 44 | |
| 45 | address := reNodeAddress.FindStringSubmatch(fields[1]) |
| 46 | if len(address) < 3 { |
| 47 | log.Debugf("Invalid format for node address, got: %s", fields[1]) |
| 48 | return "", false |
| 49 | } |
| 50 | |
| 51 | // address[1] = ip, address[2] = port, address[4] = hostname (may be empty) |
| 52 | if resolveHostname && len(address) >= 5 && address[4] != "" { |
| 53 | return address[4] + ":" + address[2], true |
| 54 | } |
| 55 | return address[1] + ":" + address[2], true |
| 56 | } |