amqp.go 4.96 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"
Lukas Burgey's avatar
Lukas Burgey committed
11
	"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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
	"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
		closed     chan *amqp.Error
		connection *amqp.Connection
	}
)

func (src *Source) connect() (deliveries <-chan amqp.Delivery, err error) {
	var (
		channel *amqp.Channel
		queue   amqp.Queue
	)
	// open connection
	src.connection, err = amqp.Dial(src.uri())
	if err != nil {
		return
	}

	// closed signals a closing of the connection
	src.closed = src.connection.NotifyClose(make(chan *amqp.Error))

	channel, err = src.connection.Channel()
	if err != nil {
		return
	}

	// puts this channel into confirm mode
	channel.Confirm(
		false, // noWait
	)

	// 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 {
		return
	}

	// all the bindings from our queue to the topic exchange
	for _, exchange := range src.Exchanges {
		//if *backendDebugging {
		if src.Config.Debug.Backend {
			log.Printf("[AMQP] Binding to '%s' with routing keys %v", exchange.name, exchange.bindingKeys)
		}
		for _, bindingKey := range exchange.bindingKeys {
			if err = channel.QueueBind(
				queue.Name,    // queue name
				bindingKey,    // routing key
				exchange.name, // exchange
				false,         // no-wait
				nil,
			); err != nil {
				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 {
		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
			)
		}
	}
	for d := range deliveries {
		go consumeWrapper(d)
	}
}

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)

	// start consumption / reconnect loop
	go func() {
		var err error
		var deliveries <-chan amqp.Delivery

		for {
			deliveries, err = src.connect()
			if err != nil {
				err = fmt.Errorf("[AMQP] Error connecting: %s", err)
			} else {
				go src.consume(pipe, deliveries)
			}

			// wait for the connection to break
			select {
			case connectionError := <-src.closed:
				if connectionError.Reason != "reconnect failed" {
					log.Printf("[AMQP] Connection closed: %s", connectionError)
				}

				log.Printf("[AMQP] Reconnecting in %s", src.Config.RabbitMQConfig.ReconnectTimeout)
				time.Sleep(src.Config.RabbitMQConfig.ReconnectTimeout)
				log.Printf("[AMQP] Reconnecting")
			}
		}
	}()

	return
}

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