-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (104 loc) · 2.39 KB
/
main.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
package main
import (
"errors"
"flag"
"fmt"
"os"
"time"
log "github.com/sirupsen/logrus"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Leader struct {
Name string `json:"name"`
Updated time.Time `json:"updated"`
}
var session *mgo.Session
var name string
var database string
var hostname string
func main() {
if err := parseArguments(); err != nil {
fmt.Println(err)
os.Exit(1)
}
info := &mgo.DialInfo{
Addrs: []string{hostname},
Database: database,
Username: "",
Password: "",
Timeout: 30 * time.Second,
}
sess, err := mgo.DialWithInfo(info)
if err != nil {
log.Errorf("Error in getting mongo connection: %s", err)
}
session = sess
for {
leader, err := getLeader()
if err != nil {
log.Errorf("Error in fetching current leader: %s", err)
log.Info("No leader found")
}
if leader.Name == "" || leader.Updated.Before(time.Now().Add(-2*time.Minute)) {
leaderName, err := acquireLeader(name)
if err != nil {
log.Errorf("Error while acquiring leader: %s", err)
}
log.Infof("New Leader is: %s", leaderName)
} else if leader.Name == name {
err = updateLeader(leader.Name)
if err != nil {
log.Errorf("Updating leader failed: %s", err)
}
log.Infof("Leader updated: %s", leader.Name)
} else {
log.Infof("Current leader is: %s", leader.Name)
}
time.Sleep(1 * time.Minute)
}
}
func parseArguments() error {
flag.StringVar(&name, "name", "", "name for this node")
flag.StringVar(&database, "database", "", "Database name to connect")
flag.StringVar(&hostname, "hostname", "", "MongoDB Hostname")
flag.Parse()
if name == "" {
return errors.New("required argument name not provided")
}
return nil
}
func acquireLeader(name string) (string, error) {
s := session.Copy()
defer s.Close()
l := Leader{
Name: name,
Updated: time.Now(),
}
if err := s.DB("leader").C("lock").Insert(l); err != nil {
return "", err
}
return l.Name, nil
}
func getLeader() (Leader, error) {
s := session.Copy()
defer s.Close()
var leader Leader
err := s.DB("leader").C("lock").Find(bson.M{}).Sort("-updated").One(&leader)
if err != nil {
return leader, err
}
return leader, nil
}
func updateLeader(name string) error {
s := session.Copy()
defer s.Close()
l := Leader{
Name: name,
Updated: time.Now(),
}
if err := s.DB("leader").C("lock").Update(bson.M{"name": name}, l); err != nil {
return err
}
return nil
}