agency.go 8.93 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
/*
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 is used for running a single agency:
// management of agents located in same container / pod
package agency

import (
	"errors"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

61
	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/client"
Stefan Dähling's avatar
Stefan Dähling committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/schemas"
	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/status"
)

// Agency contains information about agents located in agency
type Agency struct {
	info schemas.AgencyInfo // configuration of agency
	// agents    []schemas.AgentInfo // list of agents in agency
	localAgents    map[int]*Agent
	remoteAgents   map[int]*Agent
	remoteAgencies map[string]*remoteAgency
	mutex          *sync.Mutex // mutex to protect agents from concurrent reads and writes
	agentTask      func(*Agent) error
	msgIn          chan []schemas.ACLMessage
76
	logCollector   *client.LogCollector
Stefan Dähling's avatar
Stefan Dähling committed
77
	mqttCollector  *mqttCollector
Stefan Dähling's avatar
Stefan Dähling committed
78
	dfClient       *client.DFClient
Stefan Dähling's avatar
Stefan Dähling committed
79
	amsClient      *client.AMSClient
80
	agencyClient   *client.AgencyClient
Stefan Dähling's avatar
Stefan Dähling committed
81
82
83
84
85
86
87
88
89
90
91
92
93
	logInfo        *log.Logger // logger for info logging
	logError       *log.Logger // logger for error logging
}

// StartAgency is the entrance function of agency
func StartAgency(task func(*Agent) error) (err error) {
	agency := &Agency{
		mutex:          &sync.Mutex{},
		agentTask:      task,
		localAgents:    make(map[int]*Agent),
		remoteAgents:   make(map[int]*Agent),
		remoteAgencies: make(map[string]*remoteAgency),
		msgIn:          make(chan []schemas.ACLMessage, 1000),
Stefan Dähling's avatar
Stefan Dähling committed
94
		amsClient:      client.NewAMSClient(time.Second*60, time.Second*1, 4),
95
		agencyClient:   client.NewAgencyClient(time.Second*60, time.Second*1, 4),
Stefan Dähling's avatar
Stefan Dähling committed
96
97
98
99
100
101
102
103
104
105
		logError:       log.New(os.Stderr, "[ERROR] ", log.LstdFlags),
	}
	err = agency.init()
	if err != nil {
		agency.logError.Println(err)
		return
	}
	go agency.receiveMsgs()

	// catch kill signal in order to terminate agency and agents before exiting
106
	var gracefulStop = make(chan os.Signal, 10)
Stefan Dähling's avatar
Stefan Dähling committed
107
108
109
110
	signal.Notify(gracefulStop, syscall.SIGTERM)
	signal.Notify(gracefulStop, syscall.SIGINT)
	go agency.terminate(gracefulStop)

Stefan Dähling's avatar
Stefan Dähling committed
111
	serv := agency.server(10000)
Stefan Dähling's avatar
Stefan Dähling committed
112
113
114
115
116
	if err != nil {
		agency.logError.Println(err)
		return
	}
	err = agency.listen(serv)
Stefan Dähling's avatar
Stefan Dähling committed
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
	if err != nil {
		agency.logError.Println(err)
	}
	return
}

// init determines the ID of agency from the container hostname and address suffix from env
func (agency *Agency) init() (err error) {
	logType := os.Getenv("CLONEMAP_LOG_LEVEL")
	switch logType {
	case "info":
		agency.logInfo = log.New(os.Stdout, "[INFO] ", log.LstdFlags)
	case "error":
		agency.logInfo = log.New(ioutil.Discard, "", log.LstdFlags)
	default:
		err = errors.New("Wrong log type: " + logType)
		return
	}
	// agency ID is extracted from hostname mas-{id}-agency-{id}
	//fmt.Println("Getting hostname")
	var temp string
	temp, err = os.Hostname()
	if err != nil {
		return
	}
	agency.logInfo.Println("Starting agency ", temp)
	hostname := strings.Split(temp, "-")
	agency.mutex.Lock()
145
	if len(hostname) < 6 {
Stefan Dähling's avatar
Stefan Dähling committed
146
		err = errors.New("incorrect hostname")
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
147
		agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
148
149
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
150
	agency.info.MASID, err = strconv.Atoi(hostname[1])
151
	if err != nil {
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
152
		agency.mutex.Unlock()
153
154
		return
	}
155
	agency.info.ImageGroupID, err = strconv.Atoi(hostname[3])
156
	if err != nil {
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
157
		agency.mutex.Unlock()
158
159
		return
	}
160
	agency.info.ID, err = strconv.Atoi(hostname[5])
161
	if err != nil {
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
162
		agency.mutex.Unlock()
163
164
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
165
	agency.info.Name = temp + ".mas" + hostname[1] + "agencies"
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
166
167
168
169
170
171
172
173
174
	agency.mutex.Unlock()

	// request configuration
	var agencyInfoFull schemas.AgencyInfoFull
	agencyInfoFull, _, err = agency.amsClient.GetAgencyInfo(agency.info.MASID,
		agency.info.ImageGroupID, agency.info.ID)
	agency.mutex.Lock()
	agency.info.ID = agencyInfoFull.ID
	agency.info.Logger = agencyInfoFull.Logger
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
175
176
	agency.info.DF = agencyInfoFull.DF
	agency.info.MQTT = agencyInfoFull.MQTT
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
177
178
179
180
181
182
183
184
185
186
	agency.mutex.Unlock()
	if err != nil {
		agency.info.Status = schemas.Status{
			Code:       status.Error,
			LastUpdate: time.Now(),
		}
		return
	}

	agency.mutex.Lock()
Stefan Dähling's avatar
Stefan Dähling committed
187
	agency.logCollector = client.NewLogCollector(agency.info.MASID, agency.info.Logger,
188
		agency.logError, agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
189
190
	agency.dfClient = client.NewDFClient(agency.info.DF.Host, agency.info.DF.Port,
		time.Second*60, time.Second*1, 4)
Stefan Dähling's avatar
Stefan Dähling committed
191
	agency.mqttCollector = newMQTTCollector(agency.info.MQTT, agency.info.Name, agency.logError,
192
		agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
193
	agency.mutex.Unlock()
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
194
195

	go agency.startAgents(agencyInfoFull)
Stefan Dähling's avatar
Stefan Dähling committed
196
197
198
199
200
201
202
	return
}

// terminate takes care of terminating all parts of the MAP before exiting. It is to be called as a
// goroutine and waits until an OS signal is inserted into the channel gracefulStop
func (agency *Agency) terminate(gracefulStop chan os.Signal) {
	// var err error
203
	<-gracefulStop
Stefan Dähling's avatar
fix    
Stefan Dähling committed
204
	agency.logInfo.Println("Terminating agency")
Stefan Dähling's avatar
Stefan Dähling committed
205
206
207
208
209
	agency.mutex.Lock()
	for i := range agency.localAgents {
		agency.localAgents[i].Terminate()
	}
	agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
210
	agency.mqttCollector.close()
Stefan Dähling's avatar
Stefan Dähling committed
211
212
213
214
215
	time.Sleep(time.Second * 2)
	os.Exit(0)
}

// startAgents starts all the agents
Stefan Dähling's avatar
fixes    
Stefan Dähling committed
216
func (agency *Agency) startAgents(agencyInfoFull schemas.AgencyInfoFull) (err error) {
Stefan Dähling's avatar
Stefan Dähling committed
217
	agency.logInfo.Println("Starting agents")
Stefan Dähling's avatar
Stefan Dähling committed
218
219
	for i := 0; i < len(agencyInfoFull.Agents); i++ {
		err = agency.createAgent(agencyInfoFull.Agents[i])
Stefan Dähling's avatar
Stefan Dähling committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
		if err != nil {
			agency.mutex.Lock()
			agency.info.Status = schemas.Status{
				Code:       status.Error,
				LastUpdate: time.Now(),
			}
			agency.mutex.Unlock()
			return
		}
	}
	return
}

// createAgent creates a new agent according to agInfo
func (agency *Agency) createAgent(agentInfo schemas.AgentInfo) (err error) {
	// check if agent does not exist
	agency.mutex.Lock()
Stefan Dähling's avatar
Stefan Dähling committed
237
	_, agExist := agency.localAgents[agentInfo.ID]
Stefan Dähling's avatar
Stefan Dähling committed
238
239
240
241
242
243
244
245
246
	agency.mutex.Unlock()
	if agExist {
		err = errors.New("NotAllowedError")
		return
	}
	// allocate port for agent
	agentInfo.Status.Code = status.Starting
	msgIn := make(chan schemas.ACLMessage, 1000)
	agency.mutex.Lock()
247
	ag := newAgent(agentInfo, msgIn, agency.aclLookup, agency.logCollector, agency.info.Logger,
Stefan Dähling's avatar
Stefan Dähling committed
248
249
		agency.mqttCollector, agency.info.DF.Active, agency.dfClient, agency.logError,
		agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
250
	agency.localAgents[agentInfo.ID] = ag
Stefan Dähling's avatar
Stefan Dähling committed
251
252
253
254
255
256
257
258
259
260
261
262
263
	agency.mutex.Unlock()
	ag.startAgent(agency.agentTask)
	return
}

// getAgentStatus returns status of agent
func (agency *Agency) getAgentStatus(agentID int) (ret schemas.Status, err error) {

	return
}

// removeAgent creates a new mas according to masconfig
func (agency *Agency) removeAgent(agentID int) (err error) {
Stefan Dähling's avatar
Stefan Dähling committed
264
265
266
267
268
269
270
271
272
273
	agency.mutex.Lock()
	ag, ok := agency.localAgents[agentID]
	agency.mutex.Unlock()
	if !ok {
		return
	}
	ag.Terminate()
	agency.mutex.Lock()
	delete(agency.localAgents, agentID)
	agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
274
275
276
277
278
279
280
281
282
283
284
	return
}

// getAgencyInfo returns configuration of agency
func (agency *Agency) getAgencyInfo() (agencyInfo schemas.AgencyInfo, err error) {
	agency.mutex.Lock()
	agencyInfo = agency.info
	agency.mutex.Unlock()
	err = nil
	return
}
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302

// updateAgentCustom updates the custom agent config
func (agency *Agency) updateAgentCustom(agentID int, custom string) (err error) {
	agentExist := false
	agency.mutex.Lock()
	for i := range agency.localAgents {
		if i == agentID {
			agentExist = true
			agency.localAgents[i].updateCustomData(custom)
			break
		}
	}
	agency.mutex.Unlock()
	if !agentExist {
		err = errors.New("agent does not exist")
	}
	return
}