-
Notifications
You must be signed in to change notification settings - Fork 28
/
vegam.go
122 lines (112 loc) · 2.51 KB
/
vegam.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
/*
Copyright 2018 The vegamcache Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vegamcache
import (
"net"
"time"
"github.com/weaveworks/mesh"
)
type Vegam struct {
gossip mesh.Gossip
peer *peer
router *mesh.Router
actions chan<- func()
peers []string
stop chan int
}
func NewVegam(vc *VegamConfig) (*Vegam, error) {
initConfig(vc)
peername, err := mesh.PeerNameFromString(vc.PeerName)
if err != nil {
return nil, err
}
router, err := mesh.NewRouter(
mesh.Config{
Port: vc.Port,
ProtocolMinVersion: mesh.ProtocolMinVersion,
Password: []byte(vc.Password),
Host: vc.Host,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
},
peername,
vc.NickName,
mesh.NullOverlay{},
vc.Logger,
)
if err != nil {
return nil, err
}
peer := &peer{
cache: &cache{
set: make(map[string]Value),
},
}
gossip, err := router.NewGossip(vc.Channel, peer)
if err != nil {
return nil, err
}
return &Vegam{
gossip: gossip,
peer: peer,
router: router,
peers: vc.Peers,
stop: make(chan int),
}, nil
}
func (v *Vegam) Start() {
actions := make(chan func())
v.actions = actions
v.router.Start()
v.router.ConnectionMaker.InitiateConnections(v.peers, true)
go v.loop(actions)
}
func (v *Vegam) loop(actions <-chan func()) {
for {
select {
case f := <-actions:
f()
case <-v.stop:
return
}
}
}
func (v *Vegam) Stop() {
v.stop <- 1
v.router.Stop()
}
func (v *Vegam) Get(key string) (val interface{}, exist bool) {
val, exist = v.peer.cache.get(key)
return
}
func (v *Vegam) Put(key string, val interface{}, expiry time.Duration) {
var expiryTime int64
if expiry == 0 {
expiryTime = 0
} else {
expiryTime = time.Now().Add(expiry).UnixNano()
}
tempVal := Value{
Data: val,
LastWrite: time.Now().UnixNano(),
Expiry: expiryTime,
}
v.peer.cache.put(key, tempVal)
tempCache := &cache{
set: make(map[string]Value),
}
tempCache.set[key] = tempVal
v.actions <- func() {
v.gossip.GossipBroadcast(tempCache)
}
}