-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
88 lines (76 loc) · 1.52 KB
/
util.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"net"
"os"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/bakins/onedari/api"
"github.com/spf13/viper"
)
func getName() (string, error) {
name := viper.GetString("name")
if name == "" {
var err error
name, err = os.Hostname()
if err != nil {
return "", fmt.Errorf("failed to get hostname: %s", err)
}
}
name = strings.ToLower(name)
parts := strings.Split(name, ".")
if len(parts) > 1 {
log.Warnf("truncating hostname %s to %s", name, parts[0])
name = parts[0]
}
return name, nil
}
func getIP() (net.IP, error) {
addr := viper.GetString("ip")
if addr == "" {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, fmt.Errorf("failed to get interface addresses: %s", err)
}
for _, a := range addrs {
ip, _, err := net.ParseCIDR(a.String())
if err != nil {
// log error?
continue
}
// XXX: ipv4 only now
if ip.To4() == nil {
continue
}
if ip.IsGlobalUnicast() {
addr = ip.String()
break
}
}
}
if addr == "" {
return nil, fmt.Errorf("failed to get address")
}
ip := net.ParseIP(addr)
if ip == nil {
return nil, fmt.Errorf("failed to parse address: %s", addr)
}
// XXX: ipv4 only now
if ip.To4() == nil {
return nil, fmt.Errorf("not an ipv4 address: %s", ip.String())
}
return ip, nil
}
func createNode() (*api.Node, error) {
n := &api.Node{}
var err error
n.ID, err = getName()
if err != nil {
return nil, err
}
n.Address, err = getIP()
if err != nil {
return nil, err
}
return n, nil
}