amqpclient.go 3.82 KB
Newer Older
1
package amqp
2
3
4
5

import (
	"encoding/json"
	"fmt"
Steffen Vogel's avatar
Steffen Vogel committed
6
	"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
7
8
	"github.com/streadway/amqp"
	"github.com/tidwall/gjson"
9
	"log"
10
11
12
13
14
15
16
17
18
19
20
21
22
	"strings"
	"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
23
24
25
26
27
	Act        string   `json:"action"`
	When       float32  `json:"when"`
	Parameters struct{} `json:"parameters"`
	Model      struct{} `json:"model"`
	Results    struct{} `json:"results"`
28
29
30
31
32
33
34
35
36
37
38
}

var client AMQPclient

func ConnectAMQP(uri string) error {

	var err error

	// connect to broker
	client.connection, err = amqp.Dial(uri)
	if err != nil {
39
		return fmt.Errorf("AMQP: failed to connect to RabbitMQ broker %v", uri)
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
	}

	// 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")
	}

	// add a queue for the simulators
	simulatorQueue, err := client.channel.QueueDeclare("simulators",
		true,
		false,
		false,
		false,
		nil)
	if err != nil {
		return fmt.Errorf("AMQP: failed to declare the queue")
	}

	err = client.channel.QueueBind(simulatorQueue.Name, "", VILLAS_EXCHANGE, false, nil)
	if err != nil {
		return fmt.Errorf("AMQP: failed to bind the queue")
	}

	// consume deliveries
	client.replies, err = client.channel.Consume(simulatorQueue.Name,
		"",
		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 {
90
91
92
93
			//err = message.Ack(false)
			//if err != nil {
			//	fmt.Println("AMQP: Unable to ack message:", err)
			//}
94
95
96

			content := string(message.Body)

97
			// any action message sent by the VILLAScontroller should be ignored by the web backend
98
99
100
101
			if strings.Contains(content, "action") {
				continue
			}

102
103
			var sToBeUpdated database.Simulator
			db := database.GetDB()
104
105
			err = db.Where("UUID = ?", gjson.Get(content, "properties.uuid")).Find(sToBeUpdated).Error
			if err != nil {
106
				log.Println("AMQP: Unable to find simulator with UUID: ", gjson.Get(content, "properties.uuid"), " DB error message: ", err)
107
108
109
110
111
112
113
114
115
116
117
			}

			err = db.Model(&sToBeUpdated).Updates(map[string]interface{}{
				"Host":          gjson.Get(content, "host"),
				"Modeltype":     gjson.Get(content, "model"),
				"Uptime":        gjson.Get(content, "uptime"),
				"State":         gjson.Get(content, "state"),
				"StateUpdateAt": time.Now().String(),
				"RawProperties": gjson.Get(content, "properties"),
			}).Error
			if err != nil {
118
				log.Println("AMQP: Unable to update simulator in DB: ", err)
119
120
			}

121
			log.Println("AMQP: Updated simulator with UUID ", gjson.Get(content, "properties.uuid"))
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
		}
	}()

	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 {
159
	log.Println("AMQP: sending ping command to all simulators")
160
161
162
163
164
165
166

	var a Action
	a.Act = "ping"

	err := SendActionAMQP(a, "")
	return err
}
167
168
169

func CheckConnection() error {

170
171
172
173
174
175
	if client.connection != nil {
		if client.connection.IsClosed() {
			return fmt.Errorf("connection to broker is closed")
		}
	} else {
		return fmt.Errorf("connection is nil")
176
177
178
179
	}

	return nil
}