agency.go 7.53 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
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"

	amsclient "git.rwth-aachen.de/acs/public/cloud/mas/clonemap/pkg/ams/client"
	"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
	logger         *loggerClient
	mqtt           *mqttClient
	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),
		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
	var gracefulStop = make(chan os.Signal)
	signal.Notify(gracefulStop, syscall.SIGTERM)
	signal.Notify(gracefulStop, syscall.SIGINT)
	go agency.terminate(gracefulStop)

	err = agency.listen()
	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()
136
	if len(hostname) < 6 {
Stefan Dähling's avatar
Stefan Dähling committed
137
138
139
		err = errors.New("incorrect hostname")
		return
	}
Stefan Dähling's avatar
Stefan Dähling committed
140
	agency.info.MASID, err = strconv.Atoi(hostname[1])
141
142
	agency.info.ImageGroupID, err = strconv.Atoi(hostname[3])
	agency.info.ID, err = strconv.Atoi(hostname[5])
Stefan Dähling's avatar
Stefan Dähling committed
143
144
145
	agency.info.Name = temp + ".mas" + hostname[1] + "agencies"
	agency.logger = newLoggerClient(agency.info.MASID, agency.logError, agency.logInfo)
	agency.mqtt = newMQTTClient("mqtt", 1883, agency.info.Name, agency.logError, agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
146
147
148
149
150
151
152
153
154
155
	agency.mqtt.init()
	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
	_ = <-gracefulStop
Stefan Dähling's avatar
fix    
Stefan Dähling committed
156
	agency.logInfo.Println("Terminating agency")
Stefan Dähling's avatar
Stefan Dähling committed
157
158
159
160
161
162
163
164
165
166
167
168
169
	agency.mutex.Lock()
	for i := range agency.localAgents {
		agency.localAgents[i].Terminate()
	}
	agency.mutex.Unlock()
	agency.mqtt.close()
	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
170
	var agencyInfoFull schemas.AgencyInfoFull
Stefan Dähling's avatar
Stefan Dähling committed
171
172
	agencyInfoFull, _, err = amsclient.GetAgencyInfo(agency.info.MASID, agency.info.ImageGroupID,
		agency.info.ID)
173
174
	agency.mutex.Lock()
	agency.info.ID = agencyInfoFull.ID
Stefan Dähling's avatar
Stefan Dähling committed
175
	agency.info.Logger = agencyInfoFull.Logger
176
	agency.mutex.Unlock()
Stefan Dähling's avatar
Stefan Dähling committed
177
178
179
180
181
182
183
184
	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
185
186
	for i := 0; i < len(agencyInfoFull.Agents); i++ {
		err = agency.createAgent(agencyInfoFull.Agents[i])
Stefan Dähling's avatar
Stefan Dähling committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
		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
204
	_, agExist := agency.localAgents[agentInfo.ID]
Stefan Dähling's avatar
Stefan Dähling committed
205
206
207
208
209
210
211
212
213
	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()
Stefan Dähling's avatar
Stefan Dähling committed
214
	ag := newAgent(agentInfo, msgIn, agency.aclLookup, agency.logger, agency.info.Logger,
Stefan Dähling's avatar
Stefan Dähling committed
215
		agency.mqtt, agency.logError, agency.logInfo)
Stefan Dähling's avatar
Stefan Dähling committed
216
	agency.localAgents[agentInfo.ID] = ag
Stefan Dähling's avatar
Stefan Dähling committed
217
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
	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) {

	return
}

// getAgencyInfo returns configuration of agency
func (agency *Agency) getAgencyInfo() (agencyInfo schemas.AgencyInfo, err error) {
	// fmt.Println(fmt.Sprintf("Start %v", time.Now()))
	agency.mutex.Lock()
	agencyInfo = agency.info
	agency.mutex.Unlock()
	// fmt.Println(fmt.Sprintf("Stop %v", time.Now()))
	err = nil
	return
}