acc.go 7.5 KB
Newer Older
Stefan Dähling's avatar
Stefan Dähling committed
1
2
3
4
5
6
7
8
9
10
11
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
/*
Copyright 2020 Institute for Automation of Complex Power Systems,
E.ON Energy Research Center, RWTH Aachen University

This project is licensed under either of
- Apache License, Version 2.0
- MIT License
at your option.

Apache License, Version 2.0:

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package agency

import (
	"errors"
	"log"
	"net"
	"net/http"
	"strconv"

	agencyclient "git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/agency/client"
	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/schemas"
)

// remoteAgency holds the channel used for sending messages to remot agency
type remoteAgency struct {
	msgIn chan schemas.ACLMessage // ACL message inbox
	// agents map[int]*agent.Agent
}

// aclLookup provides the correct acl object for an agent
func (agency *Agency) aclLookup(agentID int) (acl *ACL, err error) {
	var ag *Agent
	var ok bool
	agency.mutex.Lock()
	ag, ok = agency.localAgents[agentID]
	agency.mutex.Unlock()
	// check if agent is local agent
	if ok {
		acl = ag.ACL
		return
	}
	agency.mutex.Lock()
	ag, ok = agency.remoteAgents[agentID]
	agency.mutex.Unlock()
	// check if remote agent is already known
	if ok {
		acl = ag.ACL
		return
	}

	// request address of unknown agent
	var address schemas.Address
	address, err = agency.requestAgentAddress(agentID)
	if err != nil {
		return
	}
	agency.logInfo.Println("Request address of unknown agent")
	agentInfo := schemas.AgentInfo{}
	agency.mutex.Lock()
Stefan Dähling's avatar
Stefan Dähling committed
94
	agencyName := agency.info.Name
Stefan Dähling's avatar
Stefan Dähling committed
95
96
97
98
99
	agency.mutex.Unlock()
	if address.Agency == agencyName {
		err = errors.New("MassiveError")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
100
101
102
103
	if address.Agency == "" {
		err = errors.New("Receiver is not active")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
104
105
106
107
108
109
	var remAgency *remoteAgency
	agency.mutex.Lock()
	remAgency, ok = agency.remoteAgencies[address.Agency]
	agency.mutex.Unlock()
	// check if remote agency is already known
	if ok {
Stefan Dähling's avatar
Stefan Dähling committed
110
		agency.logInfo.Println("New remote agent ", agentID, " in known agency ", address.Agency)
Stefan Dähling's avatar
Stefan Dähling committed
111
112
		ag = newAgent(agentInfo, remAgency.msgIn, nil, nil, schemas.LogConfig{}, nil, agency.logError, agency.logInfo)
	} else {
Stefan Dähling's avatar
Stefan Dähling committed
113
		agency.logInfo.Println("New remote agent ", agentID, " in unknown agency ", address.Agency)
Stefan Dähling's avatar
Stefan Dähling committed
114
115
116
117
118
119
120
121
122
123
124
		// create new remote agency
		remAgency = &remoteAgency{
			msgIn: make(chan schemas.ACLMessage, 1000),
		}
		agency.mutex.Lock()
		agency.remoteAgencies[address.Agency] = remAgency
		numRemAgencies := len(agency.remoteAgencies)
		numLocalAgs := len(agency.localAgents)
		agency.mutex.Unlock()
		// start go routine for sending to new remote agency
		go remAgency.sendMsgs(address.Agency, agencyName, agency.logError)
Stefan Dähling's avatar
Stefan Dähling committed
125
		agency.logInfo.Println("Started go routine for sending to agency ", address.Agency)
Stefan Dähling's avatar
Stefan Dähling committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
		// start additional go routine for incoming messages
		if numRemAgencies > 1 &&
			numRemAgencies < numLocalAgs {
			go agency.receiveMsgs()
		}
		ag = newAgent(agentInfo, remAgency.msgIn, nil, nil, schemas.LogConfig{}, nil, agency.logError, agency.logInfo)
	}
	agency.mutex.Lock()
	agency.remoteAgents[agentID] = ag
	agency.mutex.Unlock()

	acl = ag.ACL
	return
}

// requestAgentAddress requests the address of an agent from ams
func (agency *Agency) requestAgentAddress(agentID int) (address schemas.Address, err error) {
	agency.mutex.Lock()
Stefan Dähling's avatar
Stefan Dähling committed
144
	masID := agency.info.MASID
Stefan Dähling's avatar
Stefan Dähling committed
145
	agency.mutex.Unlock()
146
	address, _, err = agency.amsClient.GetAgentAddress(masID, agentID)
Stefan Dähling's avatar
Stefan Dähling committed
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
227
	return
}

// sendMsgs is to be executed as go routine. It sends msgs to remote agency
func (remAgency *remoteAgency) sendMsgs(remName string, localName string, logErr *log.Logger) {
	var err error
	var ip string
	var stat int
	ip, err = getIP(remName)
	if err != nil {
		logErr.Println(err)
		return
	}
	for {
		msg := <-remAgency.msgIn
		num := len(remAgency.msgIn)
		if num > 99 {
			num = 99
		}
		msgs := make([]schemas.ACLMessage, num+1, num+1)
		msgs[0] = msg
		msgs[0].AgencySender = localName
		msgs[0].AgencyReceiver = remName
		for i := 0; i < num; i++ {
			msgs[i+1] = <-remAgency.msgIn
			msgs[i+1].AgencySender = localName
			msgs[i+1].AgencyReceiver = remName
		}
		stat, err = agencyclient.PostMsgs(ip, msgs)
		if err != nil || stat != http.StatusCreated {
			ip, err = getIP(remName)
			if err != nil {
				logErr.Println(err)
				return
			}
			stat, err = agencyclient.PostMsgs(ip, msgs)
			if err != nil {
				logErr.Println(err)
			}
			if stat != http.StatusCreated {
				logErr.Println("Wrong http code: " + strconv.Itoa(stat))
			}
		}
		// fmt.Println(time.Now().String() + " sent " + strconv.Itoa(len(msgs)) + " messages to agency " + msgs[0].AgencyReceiver)
	}
}

// getIP requests IT from DNS
func getIP(dnsName string) (ip string, err error) {
	for i := 0; i < 5; i++ {
		var ips []string
		ips, err = net.LookupHost(dnsName)
		if len(ips) > 0 && err == nil {
			ip = ips[0]
			break
		}
	}
	return
}

// receiveMsgs is to be executed as go routine. It delivers incoming messages to local agents
func (agency *Agency) receiveMsgs() {
	agency.logInfo.Println("Started go routine for message receiving")
	var msgs []schemas.ACLMessage
	for {
		msgs = <-agency.msgIn
		for i := range msgs {
			var ok bool
			var ag *Agent
			agency.mutex.Lock()
			ag, ok = agency.localAgents[msgs[i].Receiver]
			agency.mutex.Unlock()
			if ok {
				err := ag.ACL.newIncomingMessage(msgs[i])
				if err != nil {
					_, err = agencyclient.ReturnMsg(msgs[i].AgencySender, msgs[i])
					if err != nil {
						agency.logError.Println(err)
						return
					}
				}
Stefan Dähling's avatar
Stefan Dähling committed
228
229
230
231
232
233
			} else {
				_, err := agencyclient.ReturnMsg(msgs[i].AgencySender, msgs[i])
				if err != nil {
					agency.logError.Println(err)
					return
				}
Stefan Dähling's avatar
Stefan Dähling committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
			}
		}
	}
}

// resendUndeliverableMsg resends a messages that has been returned as undeliverable by a
// remote agency
func (agency *Agency) resendUndeliverableMsg(msg schemas.ACLMessage) (err error) {
	var remAg, locAg *Agent
	var ok bool
	agency.mutex.Lock()
	remAg, ok = agency.remoteAgents[msg.Receiver]
	agency.mutex.Unlock()
	if ok {
		agency.mutex.Lock()
		locAg, ok = agency.localAgents[msg.Sender]
		agency.mutex.Unlock()
		if ok {
			remAg.ACL.close()
			agency.mutex.Lock()
			delete(agency.remoteAgents, msg.Receiver)
			agency.mutex.Unlock()
			locAg.ACL.SendMessage(msg)
		}
	}
	return
}