-
Notifications
You must be signed in to change notification settings - Fork 3
/
rabbitmq.go
136 lines (118 loc) · 2.55 KB
/
rabbitmq.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
126
127
128
129
130
131
132
133
134
135
136
package rabbitmq
import (
"encoding/json"
"net"
"os"
"time"
"github.com/streadway/amqp"
"k8s.io/klog/v2"
)
const queueSize = 200
type VerbType string
const (
VerbCreate VerbType = "create"
VerbConfigure VerbType = "configure"
VerbDelete VerbType = "delete"
)
type Msg struct {
Verb VerbType `bson:"verb" json:"verb"`
JobName string `bson:"job_name" json:"job_name"`
}
func ConnectRabbitMQ() *amqp.Connection {
// Find service IP and port from kube-dns (CoreDNS)
// my-svc.my-namespace.svc.cluster-domain.example
host := "rabbitmq.voda-scheduler.svc.cluster.local"
iprecords, err := net.LookupIP(host)
if err != nil {
klog.ErrorS(err, "Failed to look up rabbit-mq service host IP", "host", host)
klog.Flush()
os.Exit(1)
}
ip := iprecords[0]
// TODO(heyfey): replace temporary url
url := "amqp://guest:guest@" + ip.String() + ":5672/"
conn, err := amqp.Dial(url)
if err != nil {
klog.ErrorS(err, "Failed to connect to rabbit-mq", "url", url)
klog.Flush()
os.Exit(1)
} else {
klog.InfoS("Connected to rabbit-mq", "url", url)
}
return conn
}
func PublishToQueue(conn *amqp.Connection, queueName string, msg Msg) error {
ch, err := conn.Channel()
if err != nil {
return err
}
defer ch.Close()
// TODO(heyfey)
q, err := ch.QueueDeclare(
queueName, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
body, _ := json.Marshal(msg)
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
Timestamp: time.Now(),
})
if err != nil {
return err
}
return nil
}
func ReceiveFromQueue(conn *amqp.Connection, queueName string) (<-chan Msg, error) {
ch, err := conn.Channel()
if err != nil {
return nil, err
}
// defer ch.Close()
// TODO(heyfey)
q, err := ch.QueueDeclare(
queueName, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return nil, err
}
// TODO(heyfey)
msgsRaw, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return nil, err
}
msgs := make(chan Msg, queueSize)
go func() {
for d := range msgsRaw {
var msg Msg
json.Unmarshal(d.Body, &msg)
msgs <- msg
}
}()
return msgs, nil
}