forked from open-horizon/edge-sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
404 lines (338 loc) · 10 KB
/
base.go
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
136
137
138
139
140
141
142
143
144
145
146
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
228
229
230
231
232
233
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package base
import (
"fmt"
"net"
"os"
"sync"
"time"
"github.com/open-horizon/edge-sync-service/common"
"github.com/open-horizon/edge-sync-service/core/communications"
"github.com/open-horizon/edge-sync-service/core/leader"
"github.com/open-horizon/edge-sync-service/core/security"
"github.com/open-horizon/edge-sync-service/core/storage"
"github.com/open-horizon/edge-utilities/logger"
"github.com/open-horizon/edge-utilities/logger/trace"
)
var store storage.Storage
var communication communications.Communicator
var resendTimer *time.Timer
var resendStopChannel chan int
var activateTimer *time.Timer
var activateStopChannel chan int
var maintenanceTimer *time.Timer
var maintenanceStopChannel chan int
var pingTicker *time.Ticker
var pingStopChannel chan int
var removeESSTicker *time.Ticker
var removeESSStopChannel chan int
var waitingOnBlockChannel bool
var blockChannel chan int
var startStopLock sync.Mutex
var started bool
var waitersForStartChannel chan chan int
func init() {
blockChannel = make(chan int, 1)
waitersForStartChannel = make(chan chan int, 40)
}
// Start starts up the sync service
func Start(swaggerFile string, registerHandlers bool) common.SyncServiceError {
startStopLock.Lock()
defer startStopLock.Unlock()
resendStopChannel = make(chan int, 1)
activateStopChannel = make(chan int, 1)
maintenanceStopChannel = make(chan int, 1)
pingStopChannel = make(chan int, 1)
removeESSStopChannel = make(chan int, 1)
common.ResetGoRoutineCounter()
if started {
return &common.SetupError{Message: "An attempt was made to start the Sync Service after it was already started"}
}
var ipAddress string
var err error
if common.Configuration.ListeningType != common.ListeningUnix &&
common.Configuration.ListeningType != common.ListeningSecureUnix &&
(common.ServingAPIs ||
(common.Configuration.NodeType == common.CSS &&
common.Configuration.CommunicationProtocol != common.MQTTProtocol &&
common.Configuration.CommunicationProtocol != common.WIoTP)) {
ipAddress, err = checkIPAddress(common.Configuration.ListeningAddress)
if err != nil {
return err
}
} else {
ipAddress = ""
}
if err = setupCertificates(); err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to create TLS certificate. Error: %s\n", err.Error())}
}
security.Start()
if common.Configuration.NodeType == common.CSS {
var cssStore storage.Storage
if common.Configuration.StorageProvider == common.Mongo {
cssStore = &storage.MongoStorage{}
} else {
cssStore = &storage.BoltStorage{}
}
if common.Configuration.CommunicationProtocol == common.HybridMQTT ||
common.Configuration.CommunicationProtocol == common.HybridWIoTP {
store = &storage.Cache{Store: cssStore}
} else {
store = cssStore
}
} else {
if common.Configuration.StorageProvider == common.Bolt {
store = &storage.BoltStorage{}
} else {
store = &storage.InMemoryStorage{}
}
}
if err := store.Init(); err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to initialize storage driver. Error: %s\n", err.Error())}
}
communications.Store = store
security.Store = store
leader.StartLeaderDetermination(store)
var mqttComm *communications.MQTT
if common.Configuration.CommunicationProtocol != common.HTTPProtocol {
mqttComm = &communications.MQTT{}
if err := mqttComm.StartCommunication(); err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to initialize MQTT communication driver. Error: %s\n", err.Error())}
}
}
var httpComm *communications.HTTP
if (common.Configuration.NodeType == common.ESS && common.Configuration.CommunicationProtocol == common.HTTPProtocol) ||
(common.Configuration.NodeType == common.CSS &&
(common.Configuration.CommunicationProtocol == common.HTTPProtocol ||
common.Configuration.CommunicationProtocol == common.HybridMQTT ||
common.Configuration.CommunicationProtocol == common.HybridWIoTP)) {
httpComm = &communications.HTTP{}
if err := httpComm.StartCommunication(); err != nil {
return &common.SetupError{Message: fmt.Sprintf("Failed to initialize HTTP communication driver. Error: %s\n", err.Error())}
}
}
communication = communications.NewWrapper(httpComm, mqttComm)
communications.Comm = communication
if common.Configuration.NodeType == common.ESS {
common.Registered = false
if common.Configuration.CommunicationProtocol == common.HTTPProtocol {
go communication.Register()
}
}
common.ResendAcked = true
common.InitObjectLocks()
go func() {
common.GoRoutineStarted()
keepRunning := true
for keepRunning {
resendTimer = time.NewTimer(time.Second * time.Duration(common.Configuration.ResendInterval))
select {
case <-resendTimer.C:
communications.ResendNotifications()
case <-resendStopChannel:
keepRunning = false
}
}
resendTimer = nil
common.GoRoutineEnded()
}()
go func() {
common.GoRoutineStarted()
keepRunning := true
for keepRunning {
activateTimer = time.NewTimer(time.Second * time.Duration(common.Configuration.ObjectActivationInterval))
select {
case <-activateTimer.C:
if leader.CheckIfLeader() {
communications.ActivateObjects()
}
case <-activateStopChannel:
keepRunning = false
}
}
activateTimer = nil
common.GoRoutineEnded()
}()
if common.Configuration.NodeType == common.CSS {
go func() {
common.GoRoutineStarted()
keepRunning := true
for keepRunning {
maintenanceTimer = time.NewTimer(time.Second * time.Duration(common.Configuration.StorageMaintenanceInterval))
select {
case <-maintenanceTimer.C:
if leader.CheckIfLeader() {
store.PerformMaintenance()
}
case <-maintenanceStopChannel:
keepRunning = false
}
}
maintenanceTimer = nil
common.GoRoutineEnded()
}()
}
if common.Configuration.NodeType == common.ESS {
pingTicker = time.NewTicker(time.Hour * time.Duration(common.Configuration.ESSPingInterval))
go func() {
common.GoRoutineStarted()
keepRunning := true
for keepRunning {
select {
case <-pingTicker.C:
communications.Comm.SendPing()
case <-pingStopChannel:
keepRunning = false
}
}
pingTicker = nil
common.GoRoutineEnded()
}()
}
if common.Configuration.NodeType == common.CSS && common.Configuration.RemoveESSRegistrationTime > 0 {
removeESSTicker = time.NewTicker(time.Hour * 24 * time.Duration(common.Configuration.RemoveESSRegistrationTime))
lastTimestamp := time.Now()
go func() {
common.GoRoutineStarted()
keepRunning := true
for keepRunning {
select {
case <-removeESSTicker.C:
if leader.CheckIfLeader() {
store.RemoveInactiveDestinations(lastTimestamp)
}
lastTimestamp = time.Now()
case <-removeESSStopChannel:
keepRunning = false
}
}
removeESSTicker = nil
common.GoRoutineEnded()
}()
}
err = startHTTPServer(ipAddress, registerHandlers, swaggerFile)
if err == nil {
common.Running = true
started = true
common.HealthStatus.NodeStarted()
keepOnGoing := true
for keepOnGoing {
select {
case channel := <-waitersForStartChannel:
select {
case channel <- 1:
default:
}
default:
keepOnGoing = false
}
}
}
return err
}
// Stop stops the Sync Server
func Stop(quiesceTime int, unregisterSelf bool) {
startStopLock.Lock()
defer startStopLock.Unlock()
keepGoing := true
if common.Configuration.NodeType == common.ESS || unregisterSelf {
// call unregister
keepGoing = false
if err := communications.Comm.Unregister(); err != nil {
if trace.IsLogging(logger.DEBUG) {
trace.Debug("In base. err from unregister: %s\n", err)
}
}
dbPath := common.Configuration.PersistenceRootPath + "/sync/db/ess-sync.db"
time.Sleep(time.Duration(1) * time.Second)
_, err := os.Stat(dbPath)
if os.IsNotExist(err) {
if trace.IsLogging(logger.DEBUG) {
trace.Debug("In base. ess db is deleted, because got this err when retrieve db file: %s\n", err)
}
// ess db already been deleted, keep stopping the server
keepGoing = true
}
}
if !keepGoing {
if trace.IsLogging(logger.ERROR) {
trace.Error("Got error from ESS unregister, continue on ESS stop.")
}
}
if keepGoing {
common.Running = false
leader.StopLeadershipPeriodicUpdate()
if trace.IsLogging(logger.INFO) {
trace.Info("Stopping in %d seconds", quiesceTime)
}
if quiesceTime > 0 {
timer := time.NewTimer(time.Duration(quiesceTime) * time.Second)
<-timer.C
}
stopHTTPServing()
communication.StopCommunication()
security.Stop()
resendStopChannel <- 1
if resendTimer != nil {
resendTimer.Stop()
}
activateStopChannel <- 1
if activateTimer != nil {
activateTimer.Stop()
}
maintenanceStopChannel <- 1
if maintenanceTimer != nil {
maintenanceTimer.Stop()
}
pingStopChannel <- 1
if pingTicker != nil {
pingTicker.Stop()
}
removeESSStopChannel <- 1
if removeESSTicker != nil {
removeESSTicker.Stop()
}
common.BlockUntilNoRunningGoRoutines()
store.Stop()
if waitingOnBlockChannel {
blockChannel <- 1
}
started = false
}
}
// BlockUntilShutdown blocks the current "thread"
func BlockUntilShutdown() {
waitingOnBlockChannel = true
_ = <-blockChannel
}
// AddWaiterForStartup adds another channel for someone waiting for the Sync Service to start
func AddWaiterForStartup(channel chan int) error {
select {
case waitersForStartChannel <- channel:
return nil
default:
return &common.InternalError{Message: "Too many calls to wait for startup."}
}
}
func checkIPAddress(host string) (string, common.SyncServiceError) {
if host == "" {
h, err := os.Hostname()
if err != nil {
return "", &common.SetupError{Message: fmt.Sprintf("Failed to get hostname. Error: %s\n", err.Error())}
}
host = h
}
ips, err := net.LookupIP(host)
if err != nil {
return "", &common.SetupError{Message: fmt.Sprintf("Failed to get IP for the host. Error: %s\n", err.Error())}
}
ipAddress := ""
for _, ip := range ips {
if ip4 := ip.To4(); ip4 != nil {
ipAddress = ip4.String()
}
}
if ipAddress == "" {
return "", &common.SetupError{Message: fmt.Sprintf("Failed to get IP for the host.")}
}
return ipAddress, nil
}