/
mon-engine.go
784 lines (684 loc) · 22.3 KB
/
mon-engine.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/*
* Copyright (c) 2022 The AdvantEDGE Authors
*
* 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.
*/
package server
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
dkm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-key-mgr"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
met "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-metrics"
mq "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-mq"
redis "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-redis"
sbs "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-sandbox-store"
sam "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-swagger-api-mgr"
v1 "k8s.io/api/core/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
type UserData struct {
AllPodsStatus PodsStatus
ExpectedPods map[string]*PodStatus
}
type MonEngineInfo struct {
PodType string
PodName string
Namespace string
MeepApp string
MeepOrigin string
MeepScenario string
Release string
Phase string
PodInitialized string
PodReady string
PodScheduled string
PodUnschedulable string
PodConditionError string
ContainerStatusesMsg string
NbOkContainers int
NbTotalContainers int
NbPodRestart int
LogicalState string
StartTime string
}
type Sandbox struct {
Releases map[string]bool
StartTime time.Time
Running bool
}
const serviceName = "Monitoring Engine"
const moduleName = "meep-mon-engine"
const moduleNamespace = "default"
const notFoundStr = "na"
const monEngineKey = "mon-engine:"
// MQ payload fields
const fieldSandboxName = "sandbox-name"
// index in array
const EVENT_POD_ADDED = 0
const EVENT_POD_MODIFIED = 1
const EVENT_POD_DELETED = 2
// Metrics
var (
metricSboxCreateDuration = promauto.NewHistogram(prometheus.HistogramOpts{
Name: "mon_engine_sbox_create_duration",
Help: "A histogram of sandbox creation durations",
Buckets: prometheus.LinearBuckets(10, 5, 5),
})
)
var pod_event_str = [3]string{"pod added", "pod modified", "pod deleted"}
var rc *redis.Connector
var redisAddr = "meep-redis-master:6379"
var baseKey string = dkm.GetKeyRootGlobal() + monEngineKey
var stopChan = make(chan struct{})
var mqGlobal *mq.MsgQueue
var apiMgr *sam.SwaggerApiMgr
var sandboxStore *sbs.SandboxStore
var metricStore *met.MetricStore
var influxDBAddr string = "http://meep-influxdb.default.svc.cluster.local:8086"
var mutex sync.Mutex
var sandboxes map[string]*Sandbox
var depPodsList []string
var corePodsList []string
var sboxPodsList []string
var expectedDepPods map[string]*PodStatus
var expectedCorePods map[string]*PodStatus
var expectedSboxPods map[string]*PodStatus
// Init - Mon Engine initialization
func Init() (err error) {
// Retrieve dependency pod list from environment variable
expectedDepPods = make(map[string]*PodStatus)
depPodsStr := strings.TrimSpace(os.Getenv("MEEP_DEPENDENCY_PODS"))
log.Info("MEEP_DEPENDENCY_PODS: ", depPodsStr)
if depPodsStr != "" {
depPodsList = strings.Split(depPodsStr, ",")
for _, pod := range depPodsList {
podStatus := new(PodStatus)
podStatus.PodType = "core"
podStatus.Sandbox = "default"
podStatus.Name = pod
podStatus.LogicalState = "NotAvailable"
expectedDepPods[pod] = podStatus
}
}
// Retrieve core pod list from environment variable
expectedCorePods = make(map[string]*PodStatus)
corePodsStr := strings.TrimSpace(os.Getenv("MEEP_CORE_PODS"))
log.Info("MEEP_CORE_PODS: ", corePodsStr)
if corePodsStr != "" {
corePodsList = strings.Split(corePodsStr, ",")
for _, pod := range corePodsList {
podStatus := new(PodStatus)
podStatus.PodType = "core"
podStatus.Sandbox = "default"
podStatus.Name = pod
podStatus.LogicalState = "NotAvailable"
expectedCorePods[pod] = podStatus
}
}
// Retrieve sandbox pod list from environment variable
expectedSboxPods = make(map[string]*PodStatus)
sboxPodsStr := strings.TrimSpace(os.Getenv("MEEP_SANDBOX_PODS"))
log.Info("MEEP_SANDBOX_PODS: ", sboxPodsStr)
if sboxPodsStr != "" {
sboxPodsList = strings.Split(sboxPodsStr, ",")
}
// Create message queue
mqGlobal, err = mq.NewMsgQueue(mq.GetGlobalName(), moduleName, moduleNamespace, redisAddr)
if err != nil {
log.Error("Failed to create Message Queue with error: ", err)
return err
}
log.Info("Message Queue created")
// Create Swagger API Manager
apiMgr, err = sam.NewSwaggerApiMgr(moduleName, "", "", mqGlobal)
if err != nil {
log.Error("Failed to create Swagger API Manager. Error: ", err)
return err
}
log.Info("Swagger API Manager created")
// Connect to Redis DB
rc, err = redis.NewConnector(redisAddr, 0)
if err != nil {
log.Error("Failed connection to Redis: ", err)
return err
}
log.Info("Connected to Mon Engine DB")
// Empty DB
_ = rc.DBFlush(baseKey)
// Connect to Sandbox Store
sandboxStore, err = sbs.NewSandboxStore(redisAddr)
if err != nil {
log.Error("Failed connection to Sandbox Store: ", err.Error())
return err
}
log.Info("Connected to Sandbox Store")
// Connect to Metric Store
metricStore, err = met.NewMetricStore("sandbox-metrics", "global", influxDBAddr, met.MetricsDbDisabled)
if err != nil {
log.Error("Failed connection to Metric Store: ", err)
return err
}
// Initialize sandbox map
sandboxes = make(map[string]*Sandbox)
return nil
}
// Run - Mon Engine monitoring thread
func Run() (err error) {
// Initialize expected pods for existing sandboxes
if sboxMap, err := sandboxStore.GetAll(); err == nil {
for _, sbox := range sboxMap {
addExpectedPods(sbox.Name)
createSandbox(sbox.Name)
}
}
// Start Swagger API Manager (provider)
err = apiMgr.Start(true, false)
if err != nil {
log.Error("Failed to start Swagger API Manager with error: ", err.Error())
return err
}
log.Info("Swagger API Manager started")
// Add module Swagger APIs
err = apiMgr.AddApis()
if err != nil {
log.Error("Failed to add Swagger APIs with error: ", err.Error())
return err
}
log.Info("Swagger APIs successfully added")
// Register Message Queue handler
handler := mq.MsgHandler{Handler: msgHandler, UserData: nil}
_, err = mqGlobal.RegisterHandler(handler)
if err != nil {
log.Error("Failed to register MsgQueue handler: ", err.Error())
return err
}
// Start thread to watch k8s pods
err = k8sConnect()
if err != nil {
log.Error("Failed to watch k8s pods")
return err
}
return nil
}
// Stop - Shut down the service
func Stop() {
close(stopChan)
if apiMgr != nil {
// Remove APIs
err := apiMgr.RemoveApis()
if err != nil {
log.Error("Failed to remove APIs with err: ", err.Error())
}
}
}
// Message Queue handler
func msgHandler(msg *mq.Msg, userData interface{}) {
switch msg.Message {
case mq.MsgSandboxCreate:
log.Debug("RX MSG: ", mq.PrintMsg(msg))
addExpectedPods(msg.Payload[fieldSandboxName])
createSandbox(msg.Payload[fieldSandboxName])
case mq.MsgSandboxDestroy:
log.Debug("RX MSG: ", mq.PrintMsg(msg))
removeExpectedPods(msg.Payload[fieldSandboxName])
deleteSandbox(msg.Payload[fieldSandboxName])
default:
log.Trace("Ignoring unsupported message: ", mq.PrintMsg(msg))
}
}
func connectToAPISvr() (*kubernetes.Clientset, error) {
// Create the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
log.Error(err)
return nil, err
}
// Create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Error(err)
return nil, err
}
return clientset, nil
}
func printfMonEngineInfo(monEngineInfo MonEngineInfo, reason int) {
log.Debug("Monitoring Engine info *** ", pod_event_str[reason], " *** ",
" podType : ", monEngineInfo.PodType,
" podName : ", monEngineInfo.PodName,
" namespace : ", monEngineInfo.Namespace,
" meepApp : ", monEngineInfo.MeepApp,
" meepOrigin : ", monEngineInfo.MeepOrigin,
" meepScenario : ", monEngineInfo.MeepScenario,
" release : ", monEngineInfo.Release,
" phase : ", monEngineInfo.Phase,
" podInitialized : ", monEngineInfo.PodInitialized,
" podUnschedulable : ", monEngineInfo.PodUnschedulable,
" podScheduled : ", monEngineInfo.PodScheduled,
" podReady : ", monEngineInfo.PodReady,
" podConditionError : ", monEngineInfo.PodConditionError,
" ContainerStatusesMsg : ", monEngineInfo.ContainerStatusesMsg,
" NbOkContainers : ", monEngineInfo.NbOkContainers,
" NbTotalContainers : ", monEngineInfo.NbTotalContainers,
" NbPodRestart : ", monEngineInfo.NbPodRestart,
" LogicalState : ", monEngineInfo.LogicalState,
" StartTime : ", monEngineInfo.StartTime)
}
func processEvent(obj interface{}, reason int) {
var ok bool
var pod *v1.Pod
// Validate object type is Pod
if pod, ok = obj.(*v1.Pod); !ok {
return
}
var monEngineInfo MonEngineInfo
if reason != EVENT_POD_DELETED {
podConditionMsg := ""
podScheduled := "False"
podReady := "False"
podInitialized := "False"
podUnschedulable := "False"
nbConditions := len(pod.Status.Conditions)
for i := 0; i < nbConditions; i++ {
switch pod.Status.Conditions[i].Type {
case "PodScheduled":
podScheduled = string(pod.Status.Conditions[i].Status)
case "Ready":
podReady = string(pod.Status.Conditions[i].Status)
if podReady == "False" {
podConditionMsg = string(pod.Status.Conditions[i].Message)
}
case "Initialized":
podInitialized = string(pod.Status.Conditions[i].Status)
case "Unschedulable":
podUnschedulable = string(pod.Status.Conditions[i].Status)
}
}
nbContainers := len(pod.Status.ContainerStatuses)
okContainers := 0
restartCount := 0
reasonFailureStr := ""
for i := 0; i < nbContainers; i++ {
if pod.Status.ContainerStatuses[i].Ready {
okContainers++
} else if pod.Status.ContainerStatuses[i].State.Waiting != nil {
reasonFailureStr = pod.Status.ContainerStatuses[i].State.Waiting.Reason
} else if pod.Status.ContainerStatuses[i].State.Terminated != nil && reasonFailureStr != "" {
reasonFailureStr = pod.Status.ContainerStatuses[i].State.Terminated.Reason
}
//only update if the value is greater than 0, and we keep it
if restartCount == 0 {
restartCount = int(pod.Status.ContainerStatuses[i].RestartCount)
}
}
monEngineInfo.PodInitialized = podInitialized
monEngineInfo.PodUnschedulable = podUnschedulable
monEngineInfo.PodScheduled = podScheduled
monEngineInfo.PodReady = podReady
monEngineInfo.PodConditionError = podConditionMsg
monEngineInfo.ContainerStatusesMsg = reasonFailureStr
monEngineInfo.NbOkContainers = okContainers
monEngineInfo.NbTotalContainers = nbContainers
monEngineInfo.NbPodRestart = restartCount
}
//common for both the add, update and delete
monEngineInfo.Phase = string(pod.Status.Phase)
monEngineInfo.PodName = pod.Name
monEngineInfo.Namespace = pod.Namespace
monEngineInfo.MeepApp = pod.Labels["meepApp"]
monEngineInfo.MeepScenario = pod.Labels["meepScenario"]
if monEngineInfo.Release, ok = pod.Labels["release"]; !ok {
if monEngineInfo.Release, ok = pod.Labels["app.kubernetes.io/instance"]; !ok {
monEngineInfo.Release = notFoundStr
}
}
if monEngineInfo.MeepApp, ok = pod.Labels["meepApp"]; !ok {
monEngineInfo.MeepApp = notFoundStr
}
if monEngineInfo.MeepOrigin, ok = pod.Labels["meepOrigin"]; !ok {
monEngineInfo.MeepOrigin = notFoundStr
}
if monEngineInfo.MeepScenario, ok = pod.Labels["meepScenario"]; !ok {
monEngineInfo.MeepScenario = notFoundStr
}
monEngineInfo.LogicalState = monEngineInfo.Phase
monEngineInfo.PodType = getPodType(monEngineInfo.MeepOrigin, monEngineInfo.Release)
//Phase is Running but might not really be because of some other attributes
//start of override section of the LogicalState by specific conditions
if pod.GetObjectMeta().GetDeletionTimestamp() != nil {
monEngineInfo.LogicalState = "Terminating"
} else if monEngineInfo.PodReady != "True" {
monEngineInfo.LogicalState = "Pending"
} else if monEngineInfo.NbOkContainers < monEngineInfo.NbTotalContainers {
monEngineInfo.LogicalState = "Failed"
}
//end of override section
printfMonEngineInfo(monEngineInfo, reason)
// Add, update or remove entry in DB only if core or scenario pod
if monEngineInfo.PodType != notFoundStr {
if reason == EVENT_POD_DELETED {
deleteEntryInDB(&monEngineInfo)
} else {
addOrUpdateEntryInDB(&monEngineInfo)
monitorSboxCreation(&monEngineInfo)
}
} else {
log.Debug("Ignoring non-AdvantEDGE pod: ", monEngineInfo.PodName)
}
}
func addOrUpdateEntryInDB(monEngineInfo *MonEngineInfo) {
// Populate rule fields
fields := make(map[string]interface{})
fields["type"] = monEngineInfo.PodType
fields["name"] = monEngineInfo.PodName
fields["namespace"] = monEngineInfo.Namespace
fields["meepApp"] = monEngineInfo.MeepApp
fields["meepOrigin"] = monEngineInfo.MeepOrigin
fields["meepScenario"] = monEngineInfo.MeepScenario
fields["release"] = monEngineInfo.Release
fields["phase"] = monEngineInfo.Phase
fields["initialised"] = monEngineInfo.PodInitialized
fields["scheduled"] = monEngineInfo.PodScheduled
fields["ready"] = monEngineInfo.PodReady
fields["unschedulable"] = monEngineInfo.PodUnschedulable
fields["condition-error"] = monEngineInfo.PodConditionError
fields["nbOkContainers"] = monEngineInfo.NbOkContainers
fields["nbTotalContainers"] = monEngineInfo.NbTotalContainers
fields["nbPodRestart"] = monEngineInfo.NbPodRestart
fields["logicalState"] = monEngineInfo.LogicalState
fields["startTime"] = monEngineInfo.StartTime
// Make unique key
key := baseKey + monEngineInfo.Namespace + ":" + monEngineInfo.PodType + ":" + monEngineInfo.PodName
// Set rule information in DB
err := rc.SetEntry(key, fields)
if err != nil {
log.Error("Entry could not be updated in DB for ", monEngineInfo.MeepApp, ": ", err)
}
}
func deleteEntryInDB(monEngineInfo *MonEngineInfo) {
// Make unique key
key := baseKey + monEngineInfo.Namespace + ":" + monEngineInfo.PodType + ":" + monEngineInfo.PodName
// Set rule information in DB
err := rc.DelEntry(key)
if err != nil {
log.Error("Entry could not be deleted in DB for ", monEngineInfo.MeepApp, ": ", err)
}
}
func k8sConnect() (err error) {
// Connect to K8s API Server
clientset, err := connectToAPISvr()
if err != nil {
log.Error("Failed to connect with k8s API Server. Error: ", err)
return err
}
watchlist := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceAll, fields.Everything())
// also take a look at NewSharedIndexInformer
_, controller := cache.NewInformer(
watchlist,
&v1.Pod{},
0, //Duration is int64
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
processEvent(obj, EVENT_POD_ADDED)
},
DeleteFunc: func(obj interface{}) {
processEvent(obj, EVENT_POD_DELETED)
},
UpdateFunc: func(oldObj, newObj interface{}) {
processEvent(newObj, EVENT_POD_MODIFIED)
},
},
)
go controller.Run(stopChan)
return nil
}
func monitorSboxCreation(monEngineInfo *MonEngineInfo) {
mutex.Lock()
defer mutex.Unlock()
// Find matching sandbox entry
sboxName := monEngineInfo.Namespace
if sbox, found := sandboxes[sboxName]; found {
// Ignore if sbox already running
if !sbox.Running {
// Set release running state
if _, exists := sbox.Releases[monEngineInfo.Release]; exists {
sbox.Releases[monEngineInfo.Release] = (monEngineInfo.LogicalState == "Running")
// Check if sandbox is running
sboxRunning := true
for _, running := range sbox.Releases {
if !running {
sboxRunning = false
break
}
}
// If all releases are running, log sandbox creation time metric
if sboxRunning {
sbox.Running = true
creationTime := float64(time.Since(sbox.StartTime).Milliseconds()) / 1000.0
log.Info("Sbox: ", sboxName, " creationTime: ", creationTime)
var metric met.SandboxMetric
metric.Name = sboxName
metric.CreateTime = creationTime
_ = metricStore.SetSandboxMetric(met.SboxMetCreateTime, metric)
metricSboxCreateDuration.Observe(creationTime)
}
}
}
}
}
// Retrieve POD states
// GET /states
func meGetStates(w http.ResponseWriter, r *http.Request) {
var err error
var data UserData
// Retrieve query parameters
query := r.URL.Query()
queryType := query.Get("type")
querySandbox := query.Get("sandbox")
queryLong := query.Get("long")
// Get expected pods list
data.ExpectedPods = make(map[string]*PodStatus)
if queryType != "scenario" {
if querySandbox == "" || querySandbox == "all" {
for k, v := range expectedCorePods {
data.ExpectedPods[k] = v
}
for k, v := range expectedDepPods {
data.ExpectedPods[k] = v
}
}
if querySandbox != "" || querySandbox == "all" {
for _, v := range expectedSboxPods {
if v.Sandbox == querySandbox || querySandbox == "all" {
data.ExpectedPods[v.Name] = v
}
}
}
}
// Create DB key using query filters
sandboxKey := ""
if querySandbox == "" {
sandboxKey = "default:"
} else if querySandbox == "all" {
sandboxKey = "*:"
} else {
sandboxKey = querySandbox + ":"
}
typeKey := ""
if queryType != "" {
typeKey = queryType + ":"
} else {
typeKey = "*"
}
keyName := baseKey + sandboxKey + typeKey + "*"
// Retrieve pod status information from DB
if queryLong == "true" {
err = rc.ForEachEntry(keyName, getPodDetails, &data)
} else {
err = rc.ForEachEntry(keyName, getPodStatesOnly, &data)
}
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Add missing pods status
for _, podStatus := range data.ExpectedPods {
data.AllPodsStatus.PodStatus = append(data.AllPodsStatus.PodStatus, *podStatus)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// Format response
jsonResponse, err := json.Marshal(data.AllPodsStatus)
if err != nil {
log.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send response
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, string(jsonResponse))
}
func getPodDetails(key string, fields map[string]string, userData interface{}) error {
data := userData.(*UserData)
// Append pod status
var podStatus PodStatus
podStatus.PodType = fields["type"]
podStatus.Sandbox = fields["namespace"]
podStatus.Name = getPodName(fields["meepApp"], fields["name"])
podStatus.Namespace = fields["namespace"]
podStatus.MeepApp = fields["meepApp"]
podStatus.MeepOrigin = fields["meepOrigin"]
podStatus.MeepScenario = fields["meepScenario"]
podStatus.Phase = fields["phase"]
podStatus.PodInitialized = fields["initialised"]
podStatus.PodScheduled = fields["scheduled"]
podStatus.PodReady = fields["ready"]
podStatus.PodUnschedulable = fields["unschedulable"]
podStatus.PodConditionError = fields["condition-error"]
podStatus.NbOkContainers = fields["nbOkContainers"]
podStatus.NbTotalContainers = fields["nbTotalContainers"]
podStatus.NbPodRestart = fields["nbPodRestart"]
podStatus.LogicalState = fields["logicalState"]
podStatus.StartTime = fields["startTime"]
data.AllPodsStatus.PodStatus = append(data.AllPodsStatus.PodStatus, podStatus)
// Remove from expected pods
delete(data.ExpectedPods, fields["release"])
return nil
}
func getPodStatesOnly(key string, fields map[string]string, userData interface{}) error {
data := userData.(*UserData)
// Append pod status
var podStatus PodStatus
podStatus.PodType = fields["type"]
podStatus.Sandbox = fields["namespace"]
podStatus.Name = getPodName(fields["meepApp"], fields["name"])
podStatus.LogicalState = fields["logicalState"]
data.AllPodsStatus.PodStatus = append(data.AllPodsStatus.PodStatus, podStatus)
// Remove from expected pods
delete(data.ExpectedPods, fields["release"])
return nil
}
func getPodType(origin string, release string) string {
podType := notFoundStr
if origin == "core" || origin == "scenario" {
podType = origin
} else if release != notFoundStr {
if _, ok := expectedDepPods[release]; ok {
podType = "core"
} else if _, ok := expectedCorePods[release]; ok {
podType = "core"
}
}
return podType
}
func getPodName(app string, name string) string {
var podName string
if app != notFoundStr {
podName = app
} else {
podName = name
}
return podName
}
func addExpectedPods(sandboxName string) {
for _, pod := range sboxPodsList {
// Get sandbox-specific pod name
var podName, podKeyName string
prefix := "meep-"
sandboxPrefix := prefix + sandboxName + "-"
if strings.HasPrefix(pod, prefix) {
podName = pod
podKeyName = sandboxPrefix + pod[len(prefix):]
} else {
podName = prefix + pod
podKeyName = sandboxPrefix + pod
}
// Add to expected sandbox pods list
podStatus := new(PodStatus)
podStatus.PodType = "core"
podStatus.Sandbox = sandboxName
podStatus.Name = podName
podStatus.LogicalState = "NotAvailable"
expectedSboxPods[podKeyName] = podStatus
}
}
func removeExpectedPods(sandboxName string) {
for _, pod := range sboxPodsList {
// Get sandbox-specific pod name
var podName string
prefix := "meep-"
sandboxPrefix := prefix + sandboxName + "-"
if strings.HasPrefix(pod, prefix) {
podName = sandboxPrefix + pod[len(prefix):]
} else {
podName = sandboxPrefix + pod
}
// Delete from expected list
delete(expectedSboxPods, podName)
}
}
// Create new sandbox to monitor
func createSandbox(sandboxName string) {
mutex.Lock()
defer mutex.Unlock()
if _, exists := sandboxes[sandboxName]; !exists {
sbox := new(Sandbox)
sbox.Running = false
sbox.Releases = make(map[string]bool)
sbox.StartTime = time.Now()
for _, pod := range sboxPodsList {
sbox.Releases[pod] = false
}
sandboxes[sandboxName] = sbox
log.Info("Created new sandbox to monitor: ", sandboxName)
}
}
// Delete monitored sandbox
func deleteSandbox(sandboxName string) {
mutex.Lock()
defer mutex.Unlock()
if _, exists := sandboxes[sandboxName]; exists {
delete(sandboxes, sandboxName)
log.Info("Removed sandbox to monitor: ", sandboxName)
}
}