-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
109 lines (87 loc) · 2.54 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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
"brokerha/internal/api"
"brokerha/internal/broker"
"brokerha/internal/bus"
"brokerha/internal/discovery"
"brokerha/internal/metric"
"github.com/mochi-mqtt/server/v2/hooks/auth"
)
var (
// Minimal sleep time after start.
// This is used to introduce some random delay, in case all PODs are restarted
// and trying to form cluster in exact same moment.
minInitSleep = 5
// Maximal sleep time after start.
maxInitSleep = 60
)
// main will start discovery instance and mqtt broker instance.
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Llongfile)
// This sleep is needed in case container is killed by k8s.
// Without it, there is possibility that POD will be restarted faster than memberlist will
// be able to detect member down.
log.Printf("sleeping for %ds before starting broker", minInitSleep)
time.Sleep(time.Duration(minInitSleep) * time.Second)
config, err := getConfig()
if err != nil {
log.Fatal(err)
}
subMLConfig := config.Sub("cluster.config")
if subMLConfig == nil {
log.Fatal("cluster.config is nil")
}
evBus := bus.New()
subscriptionSize := make(map[string]int)
config.UnmarshalKey("discovery.subscription_size", &subscriptionSize)
d, _, err := discovery.New(&discovery.Options{
Domain: config.GetString("discovery.domain"),
MemberListConfig: createMemberlistConfig(subMLConfig),
Bus: evBus,
SubscriptionSize: subscriptionSize,
})
if err != nil {
log.Fatal(err)
}
mqttAuth := auth.AuthRules{}
config.UnmarshalKey("mqtt.auth", &mqttAuth)
mqttACL := auth.ACLRules{}
config.UnmarshalKey("mqtt.acl", &mqttACL)
config.UnmarshalKey("mqtt.subscription_size", &subscriptionSize)
b, _, err := broker.New(&broker.Options{
MQTTPort: config.GetInt("mqtt.port"),
Auth: mqttAuth,
ACL: mqttACL,
Bus: evBus,
SubscriptionSize: subscriptionSize,
})
if err != nil {
log.Fatal(err)
}
metric.Initialize(&metric.Options{
Discovery: d,
Broker: b,
})
httpRouter := api.NewRouter(&api.Options{
Discovery: d,
Broker: b,
Bus: evBus,
ClusterExpectedMembers: config.GetInt("cluster.expected_members"),
AuthUsers: config.GetStringMapString("api.user"),
})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", api.HTTPPort), httpRouter))
}()
if err := d.FormCluster(minInitSleep, maxInitSleep); err != nil {
log.Fatal(err)
}
wg.Wait()
}