agency.go 8.8 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"

Stefan Dähling's avatar
Stefan Dähling committed
61
62
	agencyclient "git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/agency/client"
	amsclient "git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/ams/client"
63
	"git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/client"
Stefan Dähling's avatar
Stefan Dähling committed
64
	dfclient "git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/df/client"
Stefan Dähling's avatar
Stefan Dähling committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
	"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
79
	logCollector   *client.LogCollector
Stefan Dähling's avatar
Stefan Dähling committed
80
81
82
83
	mqttClient     *mqttClient
	dfClient       *dfclient.Client
	amsClient      *amsclient.Client
	agencyClient   *agencyclient.Client
Stefan Dähling's avatar
Stefan Dähling committed
84
85
86
87
88
89
90
91
92
93
94
95
96
	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
97
98
99
		dfClient:       dfclient.New(time.Second*60, time.Second*1, 4),
		amsClient:      amsclient.New(time.Second*60, time.Second*1, 4),
		agencyClient:   agencyclient.New(time.Second*60, time.Second*1, 4),
Stefan Dähling's avatar
Stefan Dähling committed
100
101
102
103
104
105
106
107
108
109
110
		logError:       log.New(os.Stderr, "[ERROR] ", log.LstdFlags),
	}
	err = agency.init()
	if err != nil {
		agency.logError.Println(err)
		return
	}
	go agency.receiveMsgs()
	go agency.startAgents()

	// catch kill signal in order to terminate agency and agents before exiting
111
	var gracefulStop = make(chan os.Signal, 10)
Stefan Dähling's avatar
Stefan Dähling committed
112
113
114
115
	signal.Notify(gracefulStop, syscall.SIGTERM)
	signal.Notify(gracefulStop, syscall.SIGINT)
	go agency.terminate(gracefulStop)

Stefan Dähling's avatar
Stefan Dähling committed
116
	serv := agency.server(10000)
Stefan Dähling's avatar
Stefan Dähling committed
117
118
119
120
121
	if err != nil {
		agency.logError.Println(err)
		return
	}
	err = agency.listen(serv)
Stefan Dähling's avatar
Stefan Dähling committed
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
	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()
150
	if len(hostname) < 6 {
Stefan Dähling's avatar
Stefan Dähling committed
151
152
153
		err = errors.New("incorrect hostname")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
154
	agency.info.MASID, err = strconv.Atoi(hostname[1])
155
156
157
	if err != nil {
		return
	}
158
	agency.info.ImageGroupID, err = strconv.Atoi(hostname[3])
159
160
161
	if err != nil {
		return
	}
162
	agency.info.ID, err = strconv.Atoi(hostname[5])
163
164
165
	if err != nil {
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
166
	agency.info.Name = temp + ".mas" + hostname[1] + "agencies"
167
168
169
170
	agency.logCollector, err = client.NewLogCollector(agency.info.MASID, agency.info.Logger,
		agency.logError, agency.logInfo)
	agency.mqttClient = newMQTTClient("mqtt", 1883, agency.info.Name, agency.logError,
		agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
171
172
173
174
175
176
177
178
	agency.mutex.Unlock()
	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
179
	<-gracefulStop
Stefan Dähling's avatar
fix    
Stefan Dähling committed
180
	agency.logInfo.Println("Terminating agency")
Stefan Dähling's avatar
Stefan Dähling committed
181
182
183
184
185
	agency.mutex.Lock()
	for i := range agency.localAgents {
		agency.localAgents[i].Terminate()
	}
	agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
186
	agency.mqttClient.close()
Stefan Dähling's avatar
Stefan Dähling committed
187
188
189
190
191
192
193
	time.Sleep(time.Second * 2)
	os.Exit(0)
}

// startAgents starts all the agents
func (agency *Agency) startAgents() (err error) {
	// request configuration
Stefan Dähling's avatar
Stefan Dähling committed
194
	var agencyInfoFull schemas.AgencyInfoFull
195
196
	agencyInfoFull, _, err = agency.amsClient.GetAgencyInfo(agency.info.MASID,
		agency.info.ImageGroupID, agency.info.ID)
197
198
	agency.mutex.Lock()
	agency.info.ID = agencyInfoFull.ID
Stefan Dähling's avatar
Stefan Dähling committed
199
	agency.info.Logger = agencyInfoFull.Logger
200
	agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
201
202
203
204
205
206
207
208
	if err != nil {
		agency.info.Status = schemas.Status{
			Code:       status.Error,
			LastUpdate: time.Now(),
		}
		return
	}
	agency.logInfo.Println("Starting agents")
Stefan Dähling's avatar
Stefan Dähling committed
209
210
	for i := 0; i < len(agencyInfoFull.Agents); i++ {
		err = agency.createAgent(agencyInfoFull.Agents[i])
Stefan Dähling's avatar
Stefan Dähling committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
		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
228
	_, agExist := agency.localAgents[agentInfo.ID]
Stefan Dähling's avatar
Stefan Dähling committed
229
230
231
232
233
234
235
236
237
	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()
238
	ag := newAgent(agentInfo, msgIn, agency.aclLookup, agency.logCollector, agency.info.Logger,
Stefan Dähling's avatar
Stefan Dähling committed
239
		agency.mqttClient, agency.dfClient, agency.logError, agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
240
	agency.localAgents[agentInfo.ID] = ag
Stefan Dähling's avatar
Stefan Dähling committed
241
242
243
244
245
246
247
248
249
250
251
252
253
	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
254
255
256
257
258
259
260
261
262
263
	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
264
265
266
267
268
269
270
271
272
273
274
	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
}
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

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