amqpclient.go 5.89 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/** AMQP package, client.
*
* @author Sonja Happ <sonja.happ@eonerc.rwth-aachen.de>
* @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
* @license GNU General Public License (version 3)
*
* VILLASweb-backend-go
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************************/
22
package amqp
23
24
25
26

import (
	"encoding/json"
	"fmt"
Steffen Vogel's avatar
Steffen Vogel committed
27
	"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
28
	"github.com/gin-gonic/gin"
29
	"github.com/streadway/amqp"
30
	"log"
Sonja Happ's avatar
Sonja Happ committed
31
	"math"
32
	"strconv"
33
34
35
36
37
38
39
40
41
42
43
44
	"time"
)

const VILLAS_EXCHANGE = "villas"

type AMQPclient struct {
	connection *amqp.Connection
	channel    *amqp.Channel
	replies    <-chan amqp.Delivery
}

type Action struct {
Sonja Happ's avatar
Sonja Happ committed
45
46
47
48
49
	Act        string   `json:"action"`
	When       float32  `json:"when"`
	Parameters struct{} `json:"parameters"`
	Model      struct{} `json:"model"`
	Results    struct{} `json:"results"`
50
51
52
53
54
55
56
57
58
59
60
}

var client AMQPclient

func ConnectAMQP(uri string) error {

	var err error

	// connect to broker
	client.connection, err = amqp.Dial(uri)
	if err != nil {
61
		return fmt.Errorf("AMQP: failed to connect to RabbitMQ broker %v", uri)
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
	}

	// create channel
	client.channel, err = client.connection.Channel()
	if err != nil {
		return fmt.Errorf("AMQP: failed to open a channel")
	}
	// declare exchange
	err = client.channel.ExchangeDeclare(VILLAS_EXCHANGE,
		"headers",
		true,
		false,
		false,
		false,
		nil)
	if err != nil {
		return fmt.Errorf("AMQP: failed to declare the exchange")
	}

81
82
	// add a queue for the ICs
	ICQueue, err := client.channel.QueueDeclare("infrastructure_components",
83
84
85
86
87
88
89
90
91
		true,
		false,
		false,
		false,
		nil)
	if err != nil {
		return fmt.Errorf("AMQP: failed to declare the queue")
	}

92
	err = client.channel.QueueBind(ICQueue.Name, "", VILLAS_EXCHANGE, false, nil)
93
94
95
96
97
	if err != nil {
		return fmt.Errorf("AMQP: failed to bind the queue")
	}

	// consume deliveries
98
	client.replies, err = client.channel.Consume(ICQueue.Name,
99
100
101
102
103
104
105
106
107
108
109
110
111
		"",
		false,
		false,
		false,
		false,
		nil)
	if err != nil {
		return fmt.Errorf("AMQP: failed to consume deliveries")
	}

	// consuming queue
	go func() {
		for message := range client.replies {
112
113
114
115
			//err = message.Ack(false)
			//if err != nil {
			//	fmt.Println("AMQP: Unable to ack message:", err)
			//}
116

117
118
119
120
121
122
			var payload map[string]interface{}
			if err := json.Unmarshal(message.Body, &payload); err != nil {
				panic(err)
			}
			//content := string(message.Body)
			fmt.Println("APQM: message payload", message.Body)
123
			// any action message sent by the VILLAScontroller should be ignored by the web backend
Sonja Happ's avatar
Sonja Happ committed
124
			/*if strings.Contains(content, "action") {
125
				continue
Sonja Happ's avatar
Sonja Happ committed
126
			}*/
127

128
			var sToBeUpdated database.InfrastructureComponent
129
			db := database.GetDB()
130
			ICUUID := fmt.Sprintf("%v", payload["properties.uuid"])
Sonja Happ's avatar
Sonja Happ committed
131
132
133
			uptime_s := fmt.Sprintf("%v", payload["uptime"])
			uptime, _ := strconv.ParseFloat(uptime_s, 64)
			uptime = math.Round(uptime)
134
135
136
			state := fmt.Sprintf("%v", payload["state"])
			var stateUpdateAt = message.Timestamp.UTC()

137
138
			if ICUUID == "" {
				log.Println("AMQP: Could not extract UUID of IC from content of received message, COMPONENT NOT UPDATED")
139
			} else {
140
				err = db.Where("UUID = ?", ICUUID).Find(sToBeUpdated).Error
141
				if err != nil {
142
					log.Println("AMQP: Unable to find IC with UUID: ", ICUUID, " DB error message: ", err)
143
					continue
144
145
146
				}

				err = db.Model(&sToBeUpdated).Updates(map[string]interface{}{
147
148
					//"Host":          gjson.Get(content, "host"),
					//"Type":          gjson.Get(content, "model"),
Sonja Happ's avatar
Sonja Happ committed
149
					"Uptime":        uptime,
150
					"State":         state,
151
					"StateUpdateAt": stateUpdateAt.Format(time.RFC1123),
152
					//"RawProperties": gjson.Get(content, "properties"),
153
154
				}).Error
				if err != nil {
155
					log.Println("AMQP: Unable to update IC in DB: ", err)
156
157
				}

158
				log.Println("AMQP: Updated IC with UUID ", ICUUID)
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
			}
		}
	}()

	return nil
}

func SendActionAMQP(action Action, uuid string) error {

	payload, err := json.Marshal(action)
	if err != nil {
		return err
	}

	msg := amqp.Publishing{
		DeliveryMode:    2,
		Timestamp:       time.Now(),
		ContentType:     "application/json",
		ContentEncoding: "utf-8",
		Priority:        0,
		Body:            payload,
	}

	if uuid != "" {
		msg.Headers["uuid"] = uuid
		msg.Headers["action"] = "ping"
	}

	err = client.channel.Publish(VILLAS_EXCHANGE,
		"",
		false,
		false,
		msg)
	return err

}

func PingAMQP() error {
197
	log.Println("AMQP: sending ping command to all ICs")
198
199
200
201
202
203
204

	var a Action
	a.Act = "ping"

	err := SendActionAMQP(a, "")
	return err
}
205
206
207

func CheckConnection() error {

208
209
210
211
212
213
	if client.connection != nil {
		if client.connection.IsClosed() {
			return fmt.Errorf("connection to broker is closed")
		}
	} else {
		return fmt.Errorf("connection is nil")
214
215
216
217
	}

	return nil
}
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

func StartAMQP(AMQPurl string, api *gin.RouterGroup) error {
	if AMQPurl != "" {
		log.Println("Starting AMQP client")

		err := ConnectAMQP(AMQPurl)
		if err != nil {
			return err
		}

		// register IC action endpoint only if AMQP client is used
		RegisterAMQPEndpoint(api.Group("/ic"))

		// Periodically call the Ping function to check which ICs are still there
		ticker := time.NewTicker(10 * time.Second)
		go func() {

			for {
				select {
				case <-ticker.C:
					err = PingAMQP()
					if err != nil {
						log.Println("AMQP Error: ", err.Error())
					}
				}
			}

		}()

		log.Printf("Connected AMQP client to %s", AMQPurl)
	}

	return nil
}