-
Notifications
You must be signed in to change notification settings - Fork 2
/
imdgo.go
125 lines (103 loc) · 2.52 KB
/
imdgo.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
120
121
122
123
124
125
package imdgo
import (
"fmt"
"log"
"net"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/go-hclog"
"github.com/inelpandzic/imdgo/store"
)
// Config is imdgo configuration
type Config struct {
Members []string
// LogLevel represents a log level. If the value does not match a known
// logging level or is not set, INFO level is used.
LogLevel string
// Logger is a user-provided logger. If nil, a logger writing to
// os.Stderr with LogLevel INFO is used.
Logger hclog.Logger
}
// Store is a imdgo backing storage
type Store struct {
s *store.S
}
// New creates new imdgo store. Store.Close() must be called in order
// to release all the resources and shut everything down.
func New(conf *Config) (*Store, error) {
err := validateMembers(conf.Members)
if err != nil {
return nil, err
}
ex, err := os.Executable()
if err != nil {
return nil, err
}
addr := getHostAddr(conf.Members)
s := store.New(filepath.Dir(ex), addr, conf.Members, conf.Logger)
err = s.Open()
if err != nil {
return nil, err
}
return &Store{s: s}, nil
}
// Get gets a value for a given key. It will return nil and false
// if the value is not present.
func (s *Store) Get(key string) (interface{}, bool) {
return s.s.Get(key)
}
// Set puts key with associated value into store
func (s *Store) Set(key string, value interface{}) error {
return s.s.Set(key, value)
}
// Delete removes a KV pair for a given key
func (s *Store) Delete(key string) error {
return s.s.Delete(key)
}
// Count return number of items in the store
func (s *Store) Count() int {
return s.s.Count()
}
// Close shuts imdgo down. Must be called in order to release all the resources
func (s *Store) Close() error {
return s.s.Close()
}
// validateMembers checks the validity of members IP addresses
func validateMembers(members []string) error {
for _, m := range members {
if net.ParseIP(m) == nil {
return fmt.Errorf("invalid member address: %s", m)
}
}
return nil
}
// getHostAddr resolves current host IP address
func getHostAddr(members []string) string {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
log.Printf("IMDGO: hostname: %s", hostname)
addresses, err := net.LookupIP(hostname)
if err != nil {
panic(err)
}
log.Printf("IMDGO: host addresses: %v", addresses)
var addr string
for _, v := range addresses {
for _, m := range members {
if v.String() == strings.Split(m, ":")[0] {
addr = m
break
}
}
if addr != "" {
break
}
}
if addr == "" {
panic("can't find host address")
}
return addr
}