amqp.go 5.02 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
7
8
9
package amqp

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	"git.scc.kit.edu/feudal/feudalClient/config"
10
	deps "git.scc.kit.edu/feudal/feudalClient/deployments"
lukasburgey's avatar
lukasburgey committed
11
	"git.scc.kit.edu/feudal/feudalClient/indent"
Lukas Burgey's avatar
Lukas Burgey committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
	"github.com/streadway/amqp"
)

type (
	exchange struct {
		name         string
		exchangeType string
		bindingKeys  []string
	}

	// Source implements amqp for the source.Source interface
	Source struct {
		Config     *config.Config
		Exchanges  []exchange
		connection *amqp.Connection
	}
)

Lukas Burgey's avatar
Lukas Burgey committed
30
func (src *Source) connect() (deliveries <-chan amqp.Delivery, closed <-chan *amqp.Error, err error) {
Lukas Burgey's avatar
Lukas Burgey committed
31
32
33
34
	var (
		channel *amqp.Channel
		queue   amqp.Queue
	)
35
36
37
38
39
40
41
42

	closeConn := func() {
		log.Printf("[AMQP] Closing connection after an error (logs will follow)")
		closeErr := src.connection.Close()
		if closeErr != nil {
			log.Printf("[AMQP] Error closing connection: %s", closeErr)
		}
	}
Lukas Burgey's avatar
Lukas Burgey committed
43
44
45
46
47
48
49
50
	// open connection
	src.connection, err = amqp.Dial(src.uri())
	if err != nil {
		return
	}

	channel, err = src.connection.Channel()
	if err != nil {
51
		closeConn()
Lukas Burgey's avatar
Lukas Burgey committed
52
53
		return
	}
54
55
	// closed signals the  closing of the connection / channel
	closed = channel.NotifyClose(make(chan *amqp.Error))
Lukas Burgey's avatar
Lukas Burgey committed
56

57
58
	// put the channel into confirm mode
	err = channel.Confirm(
Lukas Burgey's avatar
Lukas Burgey committed
59
60
		false, // noWait
	)
61
62
63
64
	if err != nil {
		closeConn()
		return
	}
Lukas Burgey's avatar
Lukas Burgey committed
65
66
67
68
69
70
71
72
73
74
75

	// the queue we connect to the topic exchange
	queue, err = channel.QueueDeclare(
		"",    // name
		true,  // durable
		true,  // delete when unused
		true,  // exclusive
		false, // no-wait
		nil,   // arguments
	)
	if err != nil {
76
		closeConn()
Lukas Burgey's avatar
Lukas Burgey committed
77
78
79
80
81
82
83
84
85
		return
	}

	// all the bindings from our queue to the topic exchange
	for _, exchange := range src.Exchanges {
		if src.Config.Debug.Backend {
			log.Printf("[AMQP] Binding to '%s' with routing keys %v", exchange.name, exchange.bindingKeys)
		}
		for _, bindingKey := range exchange.bindingKeys {
86
			err = channel.QueueBind(
Lukas Burgey's avatar
Lukas Burgey committed
87
88
89
90
91
				queue.Name,    // queue name
				bindingKey,    // routing key
				exchange.name, // exchange
				false,         // no-wait
				nil,
92
93
94
			)
			if err != nil {
				closeConn()
Lukas Burgey's avatar
Lukas Burgey committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
				err = fmt.Errorf("Error binding %s:\n\t%s", bindingKey, err)
				return
			}
		}
	}

	deliveries, err = channel.Consume(
		queue.Name, // queue
		"",         // consumer
		false,      // auto-ack
		true,       // exclusive
		false,      // no-local
		false,      // no-wait
		nil,        // args
	)
	if err != nil {
111
		closeConn()
Lukas Burgey's avatar
Lukas Burgey committed
112
113
114
115
116
117
118
119
120
121
		return
	}

	log.Printf("[AMQP] Source connected")
	return
}

func (src *Source) consume(sink chan<- deps.Dep, deliveries <-chan amqp.Delivery) {
	consumeWrapper := func(del amqp.Delivery) {
		if src.Config.Debug.Backend {
lukasburgey's avatar
lukasburgey committed
122
			log.Printf("[AMQP] Received: %s", indent.Indent(del.Body))
Lukas Burgey's avatar
Lukas Burgey committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
		}

		var newDep deps.Dep
		err := json.Unmarshal(del.Body, &newDep)

		if err != nil {
			msg := "Failed to read deployment task"

			log.Printf("[E] %s: %s", msg, err)
			del.Nack(
				false, // multiple
				false, // signal the server to requeue the message
			)
		} else {
			log.Printf("[AMQP] Received via %v-%v: %s", del.Exchange, del.RoutingKey, newDep)

			// enqueue the task
			sink <- newDep
			del.Ack(
				false, // multiple
			)
		}
	}
Lukas Burgey's avatar
Lukas Burgey committed
146
147

	// log.Printf("[AMQP] Start consuming")
Lukas Burgey's avatar
Lukas Burgey committed
148
149
150
	for d := range deliveries {
		go consumeWrapper(d)
	}
Lukas Burgey's avatar
Lukas Burgey committed
151
	// log.Printf("[AMQP] Done consuming")
Lukas Burgey's avatar
Lukas Burgey committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
}

func (src *Source) uri() string {
	return fmt.Sprintf("amqps://%s:%s@%s", src.Config.Username, src.Config.Password, src.Config.Hostname)
}

// Init initializes the source
func (src *Source) Init(conf *config.Config) {
	src.Config = conf

	// calculate all the routing keys for the exchanges
	var (
		groupRoutingKeys       = make([]string, len(conf.GroupToServiceIDs))
		entitlementRoutingKeys = make([]string, len(conf.EntitlementToServiceIDs))
		serviceRoutingKeys     = make([]string, len(conf.Services))
	)

	i := 0
	for groupName := range conf.GroupToServiceIDs {
		groupRoutingKeys[i] = groupName
		i++
	}

	i = 0
	for entitlementName := range conf.EntitlementToServiceIDs {
		entitlementRoutingKeys[i] = entitlementName
		i++
	}

	i = 0
	for _, service := range conf.Services {
		serviceRoutingKeys[i] = service.Name
		i++
	}
	src.Exchanges = []exchange{
		exchange{
			"groups", "topic", groupRoutingKeys,
		},
		exchange{
			"entitlements", "topic", entitlementRoutingKeys,
		},
		exchange{
			"services", "topic", serviceRoutingKeys,
		},
	}
	return
}

// Connect connects the source and writes new tasks to the sink
func (src *Source) Connect() (sink <-chan deps.Dep, err error) {
	pipe := make(chan deps.Dep)
	sink = (<-chan deps.Dep)(pipe)

Lukas Burgey's avatar
Lukas Burgey committed
205
	// Reconnect loop
Lukas Burgey's avatar
Lukas Burgey committed
206
207
	go func() {
		for {
Lukas Burgey's avatar
Lukas Burgey committed
208
			deliveries, closed, err := src.connect()
Lukas Burgey's avatar
Lukas Burgey committed
209
			if err != nil {
Lukas Burgey's avatar
Lukas Burgey committed
210
				log.Printf("[AMQP] Error connecting: %s", err)
Lukas Burgey's avatar
Lukas Burgey committed
211
212
213
			} else {
				go src.consume(pipe, deliveries)

Lukas Burgey's avatar
Lukas Burgey committed
214
215
216
				// Wait for the connection to close
				select {
				case connectionError := <-closed:
217
					log.Printf("[AMQP] Connection/Channel closed: %s", connectionError)
Lukas Burgey's avatar
Lukas Burgey committed
218
219
				}
			}
Lukas Burgey's avatar
Lukas Burgey committed
220
221
222

			log.Printf("[AMQP] Reconnecting in %s", src.Config.ReconnectTimeout)
			time.Sleep(src.Config.ReconnectTimeout)
Lukas Burgey's avatar
Lukas Burgey committed
223
224
225
		}
	}()

Lukas Burgey's avatar
Lukas Burgey committed
226
	return sink, nil
Lukas Burgey's avatar
Lukas Burgey committed
227
228
229
230
231
232
}

// Close stops the source
func (src *Source) Close() {
	src.connection.Close()
}