amqp.go 4.82 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
	"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
35
36
37
38
39
40
41
	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
Lukas Burgey's avatar
Lukas Burgey committed
42
	closed = src.connection.NotifyClose(make(chan *amqp.Error))
Lukas Burgey's avatar
Lukas Burgey committed
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

	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 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
			)
		}
	}
Lukas Burgey's avatar
Lukas Burgey committed
135
136

	// log.Printf("[AMQP] Start consuming")
Lukas Burgey's avatar
Lukas Burgey committed
137
138
139
	for d := range deliveries {
		go consumeWrapper(d)
	}
Lukas Burgey's avatar
Lukas Burgey committed
140
	// log.Printf("[AMQP] Done consuming")
Lukas Burgey's avatar
Lukas Burgey committed
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
}

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
194
	// Reconnect loop
Lukas Burgey's avatar
Lukas Burgey committed
195
196
	go func() {
		for {
Lukas Burgey's avatar
Lukas Burgey committed
197
			deliveries, closed, err := src.connect()
Lukas Burgey's avatar
Lukas Burgey committed
198
			if err != nil {
Lukas Burgey's avatar
Lukas Burgey committed
199
				log.Printf("[AMQP] Error connecting: %s", err)
Lukas Burgey's avatar
Lukas Burgey committed
200
201
202
			} else {
				go src.consume(pipe, deliveries)

Lukas Burgey's avatar
Lukas Burgey committed
203
204
205
				// Wait for the connection to close
				select {
				case connectionError := <-closed:
Lukas Burgey's avatar
Lukas Burgey committed
206
207
208
					log.Printf("[AMQP] Connection closed: %s", connectionError)
				}
			}
Lukas Burgey's avatar
Lukas Burgey committed
209
210
211

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

Lukas Burgey's avatar
Lukas Burgey committed
215
	return sink, nil
Lukas Burgey's avatar
Lukas Burgey committed
216
217
218
219
220
221
}

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