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

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

	"git.scc.kit.edu/feudal/feudalClient/config"
11
	deps "git.scc.kit.edu/feudal/feudalClient/deployments"
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
		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 {
			indented := new(bytes.Buffer)
			if err := json.Indent(indented, del.Body, "  ", "  "); err != nil {
				log.Printf("[AMQP] Received (unable to indent: %v):\n%s", err, del.Body)
			} else {
				log.Printf("[AMQP] Received:\n%s", indented)
			}
		}

		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
151
152

	// log.Printf("[AMQP] Start consuming")
Lukas Burgey's avatar
Lukas Burgey committed
153
154
155
	for d := range deliveries {
		go consumeWrapper(d)
	}
Lukas Burgey's avatar
Lukas Burgey committed
156
	// log.Printf("[AMQP] Done consuming")
Lukas Burgey's avatar
Lukas Burgey committed
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
205
206
207
208
209
}

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
210
	// Reconnect loop
Lukas Burgey's avatar
Lukas Burgey committed
211
212
	go func() {
		for {
Lukas Burgey's avatar
Lukas Burgey committed
213
			deliveries, closed, err := src.connect()
Lukas Burgey's avatar
Lukas Burgey committed
214
			if err != nil {
Lukas Burgey's avatar
Lukas Burgey committed
215
				log.Printf("[AMQP] Error connecting: %s", err)
Lukas Burgey's avatar
Lukas Burgey committed
216
217
218
			} else {
				go src.consume(pipe, deliveries)

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

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

Lukas Burgey's avatar
Lukas Burgey committed
231
	return sink, nil
Lukas Burgey's avatar
Lukas Burgey committed
232
233
234
235
236
237
}

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