forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extractor.go
119 lines (97 loc) · 2.04 KB
/
extractor.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package http
import (
"fmt"
"net"
"strconv"
"strings"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/server"
)
var (
privateBlocks []*net.IPNet
)
func init() {
for _, b := range []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"} {
if _, block, err := net.ParseCIDR(b); err == nil {
privateBlocks = append(privateBlocks, block)
}
}
}
func extractAddress(addr string) (string, error) {
if len(addr) > 0 && (addr != "0.0.0.0" && addr != "[::]") {
return addr, nil
}
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", fmt.Errorf("Failed to get interface addresses! Err: %v", err)
}
var ipAddr []byte
for _, rawAddr := range addrs {
var ip net.IP
switch addr := rawAddr.(type) {
case *net.IPAddr:
ip = addr.IP
case *net.IPNet:
ip = addr.IP
default:
continue
}
if ip.To4() == nil {
continue
}
if !isPrivateIP(ip.String()) {
continue
}
ipAddr = ip
break
}
if ipAddr == nil {
return "", fmt.Errorf("No private IP address found, and explicit IP not provided")
}
return net.IP(ipAddr).String(), nil
}
func isPrivateIP(ipAddr string) bool {
ip := net.ParseIP(ipAddr)
for _, priv := range privateBlocks {
if priv.Contains(ip) {
return true
}
}
return false
}
func serviceDef(opts server.Options) *registry.Service {
var advt, host string
var port int
if len(opts.Advertise) > 0 {
advt = opts.Advertise
} else {
advt = opts.Address
}
parts := strings.Split(advt, ":")
if len(parts) > 1 {
host = strings.Join(parts[:len(parts)-1], ":")
port, _ = strconv.Atoi(parts[len(parts)-1])
} else {
host = parts[0]
}
addr, err := extractAddress(host)
if err != nil {
addr = host
}
md := make(map[string]string, len(opts.Metadata))
for k, v := range opts.Metadata {
md[k] = v
}
node := ®istry.Node{
Id: opts.Name + "-" + opts.Id,
Address: addr,
Port: port,
Metadata: md,
}
node.Metadata["server"] = "http"
return ®istry.Service{
Name: opts.Name,
Version: opts.Version,
Nodes: []*registry.Node{node},
}
}