/
upstream.go
1502 lines (1352 loc) · 55.2 KB
/
upstream.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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 The KubeEdge Authors.
Copyright 2014 The Kubernetes 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.
@CHANGELOG
KubeEdge Authors: To manage node/pod status for edge deployment scenarios,
we grab some functions from `kubelet/status/status_manager.go and do some modifications, they are
1. updatePodStatus
2. updateNodeStatus
3. normalizePodStatus
4. isPodNotRunning
*/
package controller
import (
"context"
"encoding/json"
stderrors "errors"
"fmt"
"sort"
"strings"
"time"
authenticationv1 "k8s.io/api/authentication/v1"
certificatesv1 "k8s.io/api/certificates/v1"
coordinationv1 "k8s.io/api/coordination/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
apimachineryType "k8s.io/apimachinery/pkg/types"
k8sinformer "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
coordinationlisters "k8s.io/client-go/listers/coordination/v1"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/klog/v2"
beehiveContext "github.com/kubeedge/beehive/pkg/core/context"
"github.com/kubeedge/beehive/pkg/core/model"
"github.com/kubeedge/kubeedge/cloud/pkg/common/client"
"github.com/kubeedge/kubeedge/cloud/pkg/common/messagelayer"
"github.com/kubeedge/kubeedge/cloud/pkg/common/modules"
"github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/controller"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/types"
routerrule "github.com/kubeedge/kubeedge/cloud/pkg/router/rule"
common "github.com/kubeedge/kubeedge/common/constants"
edgeapi "github.com/kubeedge/kubeedge/common/types"
"github.com/kubeedge/kubeedge/pkg/apis/componentconfig/cloudcore/v1alpha1"
rulesv1 "github.com/kubeedge/kubeedge/pkg/apis/rules/v1"
crdClientset "github.com/kubeedge/kubeedge/pkg/client/clientset/versioned"
"github.com/kubeedge/kubeedge/pkg/metaserver/util"
)
// SortedContainerStatuses define A type to help sort container statuses based on container names.
type SortedContainerStatuses []v1.ContainerStatus
func (s SortedContainerStatuses) Len() int { return len(s) }
func (s SortedContainerStatuses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortedContainerStatuses) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
// SortInitContainerStatuses ensures that statuses are in the order that their
// init container appears in the pod spec
func SortInitContainerStatuses(p *v1.Pod, statuses []v1.ContainerStatus) {
containers := p.Spec.InitContainers
current := 0
for _, container := range containers {
for j := current; j < len(statuses); j++ {
if container.Name == statuses[j].Name {
statuses[current], statuses[j] = statuses[j], statuses[current]
current++
break
}
}
}
}
// UpstreamController subscribe messages from edge and sync to k8s api server
type UpstreamController struct {
kubeClient kubernetes.Interface
messageLayer messagelayer.MessageLayer
crdClient crdClientset.Interface
config v1alpha1.EdgeController
// message channel
nodeStatusChan chan model.Message
podStatusChan chan model.Message
secretChan chan model.Message
serviceAccountTokenChan chan model.Message
configMapChan chan model.Message
persistentVolumeChan chan model.Message
persistentVolumeClaimChan chan model.Message
volumeAttachmentChan chan model.Message
queryNodeChan chan model.Message
createNodeChan chan model.Message
patchNodeChan chan model.Message
updateNodeChan chan model.Message
patchPodChan chan model.Message
podDeleteChan chan model.Message
ruleStatusChan chan model.Message
createLeaseChan chan model.Message
queryLeaseChan chan model.Message
createPodChan chan model.Message
certificasesSigningRequestChan chan model.Message
// lister
podLister corelisters.PodLister
configMapLister corelisters.ConfigMapLister
secretLister corelisters.SecretLister
nodeLister corelisters.NodeLister
leaseLister coordinationlisters.LeaseLister
}
// Start UpstreamController
func (uc *UpstreamController) Start() error {
klog.Info("start upstream controller")
go uc.dispatchMessage()
for i := 0; i < int(uc.config.Load.UpdateNodeStatusWorkers); i++ {
go uc.updateNodeStatus()
}
for i := 0; i < int(uc.config.Load.UpdatePodStatusWorkers); i++ {
go uc.updatePodStatus()
}
for i := 0; i < int(uc.config.Load.QueryConfigMapWorkers); i++ {
go uc.queryConfigMap()
}
for i := 0; i < int(uc.config.Load.QuerySecretWorkers); i++ {
go uc.querySecret()
}
for i := 0; i < int(uc.config.Load.ServiceAccountTokenWorkers); i++ {
go uc.processServiceAccountToken()
}
for i := 0; i < int(uc.config.Load.QueryPersistentVolumeWorkers); i++ {
go uc.queryPersistentVolume()
}
for i := 0; i < int(uc.config.Load.QueryPersistentVolumeClaimWorkers); i++ {
go uc.queryPersistentVolumeClaim()
}
for i := 0; i < int(uc.config.Load.QueryVolumeAttachmentWorkers); i++ {
go uc.queryVolumeAttachment()
}
for i := 0; i < int(uc.config.Load.CreateNodeWorkers); i++ {
go uc.registerNode()
}
for i := 0; i < int(uc.config.Load.PatchNodeWorkers); i++ {
go uc.patchNode()
}
for i := 0; i < int(uc.config.Load.QueryNodeWorkers); i++ {
go uc.queryNode()
}
for i := 0; i < int(uc.config.Load.UpdateNodeWorkers); i++ {
go uc.updateNode()
}
for i := 0; i < int(uc.config.Load.PatchPodWorkers); i++ {
go uc.patchPod()
}
for i := 0; i < int(uc.config.Load.DeletePodWorkers); i++ {
go uc.deletePod()
}
for i := 0; i < int(uc.config.Load.CreateLeaseWorkers); i++ {
go uc.createOrUpdateLease()
}
for i := 0; i < int(uc.config.Load.QueryLeaseWorkers); i++ {
go uc.queryLease()
}
for i := 0; i < int(uc.config.Load.UpdateRuleStatusWorkers); i++ {
go uc.updateRuleStatus()
}
for i := 0; i < int(uc.config.Load.CreatePodWorks); i++ {
go uc.createPod()
}
for i := 0; i < int(uc.config.Load.CertificateSigningRequestWorkers); i++ {
go uc.processCSR()
}
return nil
}
func (uc *UpstreamController) dispatchMessage() {
for {
select {
case <-beehiveContext.Done():
klog.Info("stop dispatchMessage")
return
default:
}
msg, err := uc.messageLayer.Receive()
if err != nil {
klog.Warningf("receive message failed, %s", err)
continue
}
klog.V(5).Infof("dispatch message ID: %s", msg.GetID())
klog.V(5).Infof("dispatch message content: %+v", msg)
resourceType, err := messagelayer.GetResourceType(msg)
if err != nil {
klog.Warningf("parse message: %s resource type with error, message resource: %s, err: %v", msg.GetID(), msg.GetResource(), err)
continue
}
klog.V(5).Infof("message: %s, operation type is: %s", msg.GetID(), msg.GetOperation())
switch resourceType {
case model.ResourceTypeNodeStatus:
uc.nodeStatusChan <- msg
case model.ResourceTypePodStatus:
uc.podStatusChan <- msg
case model.ResourceTypeConfigmap:
uc.configMapChan <- msg
case model.ResourceTypeSecret:
uc.secretChan <- msg
case model.ResourceTypeServiceAccountToken:
uc.serviceAccountTokenChan <- msg
case common.ResourceTypePersistentVolume:
uc.persistentVolumeChan <- msg
case common.ResourceTypePersistentVolumeClaim:
uc.persistentVolumeClaimChan <- msg
case common.ResourceTypeVolumeAttachment:
uc.volumeAttachmentChan <- msg
case model.ResourceTypeNode:
switch msg.GetOperation() {
case model.InsertOperation:
uc.createNodeChan <- msg
case model.QueryOperation:
uc.queryNodeChan <- msg
case model.UpdateOperation:
uc.updateNodeChan <- msg
default:
klog.Errorf("message: %s, operation type: %s unsupported", msg.GetID(), msg.GetOperation())
}
case model.ResourceTypeNodePatch:
uc.patchNodeChan <- msg
case model.ResourceTypePodPatch:
uc.patchPodChan <- msg
case model.ResourceTypePod:
switch msg.GetOperation() {
case model.DeleteOperation:
uc.podDeleteChan <- msg
case model.InsertOperation:
uc.createPodChan <- msg
default:
klog.Errorf("message: %s, operation type: %s unsupported", msg.GetID(), msg.GetOperation())
}
case model.ResourceTypeRuleStatus:
uc.ruleStatusChan <- msg
case model.ResourceTypeLease:
switch msg.GetOperation() {
case model.InsertOperation, model.UpdateOperation:
uc.createLeaseChan <- msg
case model.QueryOperation:
uc.queryLeaseChan <- msg
}
case model.ResourceTypeCSR:
uc.certificasesSigningRequestChan <- msg
default:
klog.Errorf("message: %s, resource type: %s unsupported", msg.GetID(), resourceType)
}
}
}
func (uc *UpstreamController) updateRuleStatus() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop updateRuleStatus")
return
case msg := <-uc.ruleStatusChan:
klog.V(5).Infof("message %s, operation is : %s , and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
ruleID, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
var rule *rulesv1.Rule
rule, err = uc.crdClient.RulesV1().Rules(namespace).Get(context.Background(), ruleID, metaV1.GetOptions{})
if err != nil {
klog.Warningf("message: %s process failure, get rule with error: %s, namespaces: %s name: %s", msg.GetID(), err, namespace, ruleID)
continue
}
content, ok := msg.Content.(routerrule.ExecResult)
if !ok {
klog.Warningf("message: %s process failure, get rule content with error: %s, namespaces: %s name: %s", msg.GetID(), err, namespace, ruleID)
continue
}
if content.Status == "SUCCESS" {
rule.Status.SuccessMessages++
}
if content.Status == "FAIL" {
rule.Status.FailMessages++
errSlice := make([]string, 0)
rule.Status.Errors = append(errSlice, content.Error.Detail)
}
newStatus := &rulesv1.RuleStatus{
SuccessMessages: rule.Status.SuccessMessages,
FailMessages: rule.Status.FailMessages,
Errors: rule.Status.Errors,
}
body, err := json.Marshal(newStatus)
if err != nil {
klog.Warningf("message: %s process failure, content marshal err: %s", msg.GetID(), err)
continue
}
_, err = uc.crdClient.RulesV1().Rules(namespace).Patch(context.Background(), ruleID, controller.MergePatchType, body, metaV1.PatchOptions{})
if err != nil {
klog.Warningf("message: %s process failure, update ruleStatus failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, ruleID)
} else {
klog.Infof("UpdateRulestatus successfully!")
}
}
}
}
func (uc *UpstreamController) podStatusResponse(msg model.Message, content interface{}) {
resMsg := model.NewMessage(msg.GetID()).
FillBody(content).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, msg.Router.Resource, model.ResponseOperation)
if err := uc.messageLayer.Send(*resMsg); err != nil {
klog.Warningf("Send message failed: %s, operation: %s, resource: %s", err, resMsg.GetOperation(), resMsg.GetResource())
} else {
klog.V(4).Infof("Send message successfully, operation: %s, resource: %s", resMsg.GetOperation(), resMsg.GetResource())
}
}
func (uc *UpstreamController) updatePodStatus() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop updatePodStatus")
return
case msg := <-uc.podStatusChan:
klog.V(5).Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, podStatuses := uc.unmarshalPodStatusMessage(msg)
switch msg.GetOperation() {
case model.UpdateOperation:
for _, podStatus := range podStatuses {
getPod, err := uc.kubeClient.CoreV1().Pods(namespace).Get(context.Background(), podStatus.Name, metaV1.GetOptions{})
if (err == nil && getPod.UID != podStatus.UID) || errors.IsNotFound(err) {
klog.Warningf("message: %s, pod not found, namespace: %s, name: %s", msg.GetID(), namespace, podStatus.Name)
// send response message to edged
uc.podStatusResponse(msg, common.MessageSuccessfulContent)
// Send request to delete this pod on edge side
delMsg := model.NewMessage("")
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Get node ID failed with error: %s", err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypePod, podStatus.Name)
if err != nil {
klog.Warningf("Built message resource failed with error: %s", err)
continue
}
pod := &v1.Pod{}
pod.Namespace, pod.Name = namespace, podStatus.Name
delMsg.Content = pod
delMsg.BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, resource, model.DeleteOperation)
if err := uc.messageLayer.Send(*delMsg); err != nil {
klog.Warningf("Send message failed with error: %s, operation: %s, resource: %s", err, delMsg.GetOperation(), delMsg.GetResource())
} else {
klog.V(4).Infof("Send message successfully, operation: %s, resource: %s", delMsg.GetOperation(), delMsg.GetResource())
}
continue
}
if err != nil {
uc.podStatusResponse(msg, err)
klog.Warningf("message: %s, pod is nil, namespace: %s, name: %s, error: %s", msg.GetID(), namespace, podStatus.Name, err)
continue
}
status := podStatus.Status
oldStatus := getPod.Status
// Set ReadyCondition.LastTransitionTime
if readyCondition := uc.getPodCondition(&status, v1.PodReady); readyCondition != nil {
// Need to set LastTransitionTime.
lastTransitionTime := metaV1.Now()
oldReadyCondition := uc.getPodCondition(&oldStatus, v1.PodReady)
if oldReadyCondition != nil && readyCondition.Status == oldReadyCondition.Status {
lastTransitionTime = oldReadyCondition.LastTransitionTime
}
readyCondition.LastTransitionTime = lastTransitionTime
}
// Set InitializedCondition.LastTransitionTime.
if initCondition := uc.getPodCondition(&status, v1.PodInitialized); initCondition != nil {
// Need to set LastTransitionTime.
lastTransitionTime := metaV1.Now()
oldInitCondition := uc.getPodCondition(&oldStatus, v1.PodInitialized)
if oldInitCondition != nil && initCondition.Status == oldInitCondition.Status {
lastTransitionTime = oldInitCondition.LastTransitionTime
}
initCondition.LastTransitionTime = lastTransitionTime
}
// ensure that the start time does not change across updates.
if oldStatus.StartTime != nil && !oldStatus.StartTime.IsZero() {
status.StartTime = oldStatus.StartTime
} else if status.StartTime.IsZero() {
// if the status has no start time, we need to set an initial time
now := metaV1.Now()
status.StartTime = &now
}
uc.normalizePodStatus(getPod, &status)
getPod.Status = status
if updatedPod, err := uc.kubeClient.CoreV1().Pods(getPod.Namespace).UpdateStatus(context.Background(), getPod, metaV1.UpdateOptions{}); err != nil {
uc.podStatusResponse(msg, err)
klog.Warningf("message: %s, update pod status failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getPod.Namespace, getPod.Name)
} else {
klog.V(5).Infof("message: %s, update pod status successfully, namespace: %s, name: %s", msg.GetID(), updatedPod.Namespace, updatedPod.Name)
// send response message to edged
uc.podStatusResponse(msg, common.MessageSuccessfulContent)
if updatedPod.DeletionTimestamp != nil && (status.Phase == v1.PodSucceeded || status.Phase == v1.PodFailed) {
if uc.isPodNotRunning(status.ContainerStatuses) {
if err := uc.kubeClient.CoreV1().Pods(updatedPod.Namespace).Delete(context.Background(), updatedPod.Name, *metaV1.NewDeleteOptions(0)); err != nil {
klog.Warningf("message: %s, graceful delete pod failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, updatedPod.Namespace, updatedPod.Name)
} else {
klog.Infof("message: %s, pod delete successfully, namespace: %s, name: %s", msg.GetID(), updatedPod.Namespace, updatedPod.Name)
}
}
}
}
}
default:
klog.Warningf("message: %s process failure, pod status operation: %s unsupported", msg.GetID(), msg.GetOperation())
continue
}
klog.V(4).Infof("message: %s process successfully", msg.GetID())
}
}
}
// createNode create new edge node to kubernetes
func (uc *UpstreamController) createNode(name string, node *v1.Node) (*v1.Node, error) {
node.Name = name
return uc.kubeClient.CoreV1().Nodes().Create(context.Background(), node, metaV1.CreateOptions{})
}
// updateNodeStatus update node status
// Deprecated: updateNodeStatus will be deleted in subsequent versions, use patchNode instead.
func (uc *UpstreamController) updateNodeStatus() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop updateNodeStatus")
return
case msg := <-uc.nodeStatusChan:
klog.V(5).Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
data, err := msg.GetContentData()
if err != nil {
klog.Warningf("message: %s process failure, get content data failed with error: %s", msg.GetID(), err)
continue
}
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.InsertOperation:
_, err := uc.kubeClient.CoreV1().Nodes().Get(context.Background(), name, metaV1.GetOptions{})
if err == nil {
klog.Infof("node: %s already exists, do nothing", name)
uc.nodeMsgResponse(name, namespace, common.MessageSuccessfulContent, msg)
continue
}
if !errors.IsNotFound(err) {
errLog := fmt.Sprintf("get node %s info error: %v , register node failed", name, err)
klog.Error(errLog)
uc.nodeMsgResponse(name, namespace, errLog, msg)
continue
}
node := &v1.Node{}
err = json.Unmarshal(data, node)
if err != nil {
errLog := fmt.Sprintf("message: %s process failure, unmarshal marshaled message content with error: %s", msg.GetID(), err)
klog.Error(errLog)
uc.nodeMsgResponse(name, namespace, errLog, msg)
continue
}
if _, err = uc.createNode(name, node); err != nil {
errLog := fmt.Sprintf("create node %s error: %v , register node failed", name, err)
klog.Error(errLog)
uc.nodeMsgResponse(name, namespace, errLog, msg)
continue
}
uc.nodeMsgResponse(name, namespace, common.MessageSuccessfulContent, msg)
case model.UpdateOperation:
nodeStatusRequest := &edgeapi.NodeStatusRequest{}
err := json.Unmarshal(data, nodeStatusRequest)
if err != nil {
klog.Warningf("message: %s process failure, unmarshal marshaled message content with error: %s", msg.GetID(), err)
continue
}
getNode, err := uc.kubeClient.CoreV1().Nodes().Get(context.Background(), name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, node %s not found", msg.GetID(), name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespaces: %s name: %s", msg.GetID(), err, namespace, name)
continue
}
// TODO: comment below for test failure. Needs to decide whether to keep post troubleshoot
// In case the status stored at metadata service is outdated, update the heartbeat automatically
for i := range nodeStatusRequest.Status.Conditions {
if time.Since(nodeStatusRequest.Status.Conditions[i].LastHeartbeatTime.Time) > time.Duration(uc.config.NodeUpdateFrequency)*time.Second {
nodeStatusRequest.Status.Conditions[i].LastHeartbeatTime = metaV1.NewTime(time.Now())
}
}
if getNode.Annotations == nil {
getNode.Annotations = make(map[string]string)
}
for name, v := range nodeStatusRequest.ExtendResources {
if name == constants.NvidiaGPUScalarResourceName {
var gpuStatus []types.NvidiaGPUStatus
for _, er := range v {
gpuStatus = append(gpuStatus, types.NvidiaGPUStatus{ID: er.Name, Healthy: true})
}
if len(gpuStatus) > 0 {
data, _ := json.Marshal(gpuStatus)
getNode.Annotations[constants.NvidiaGPUStatusAnnotationKey] = string(data)
}
}
data, err := json.Marshal(v)
if err != nil {
klog.Warningf("message: %s process failure, extend resource list marshal with error: %s", msg.GetID(), err)
continue
}
getNode.Annotations[string(name)] = string(data)
}
// Keep the same "VolumesAttached" attribute with upstream,
// since this value is maintained by kube-controller-manager.
nodeStatusRequest.Status.VolumesAttached = getNode.Status.VolumesAttached
if getNode.Status.DaemonEndpoints.KubeletEndpoint.Port != 0 {
nodeStatusRequest.Status.DaemonEndpoints.KubeletEndpoint.Port = getNode.Status.DaemonEndpoints.KubeletEndpoint.Port
}
getNode.Status = nodeStatusRequest.Status
node, err := uc.kubeClient.CoreV1().Nodes().UpdateStatus(context.Background(), getNode, metaV1.UpdateOptions{})
if err != nil {
klog.Warningf("message: %s process failure, update node failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getNode.Namespace, getNode.Name)
continue
}
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypeNode, name)
if err != nil {
klog.Warningf("Message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg := model.NewMessage(msg.GetID()).
SetResourceVersion(node.ResourceVersion).
FillBody(common.MessageSuccessfulContent).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
if err = uc.messageLayer.Response(*resMsg); err != nil {
klog.Warningf("Message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.V(4).Infof("message: %s, update node status successfully, namespace: %s, name: %s", msg.GetID(), getNode.Namespace, getNode.Name)
default:
klog.Warningf("message: %s process failure, node status operation: %s unsupported", msg.GetID(), msg.GetOperation())
continue
}
klog.V(4).Infof("message: %s process successfully", msg.GetID())
}
}
}
func kubeClientGet(uc *UpstreamController, namespace string, name string, queryType string, msg model.Message) (metaV1.Object, error) {
var obj metaV1.Object
var err error
switch queryType {
case model.ResourceTypeConfigmap:
obj, err = uc.configMapLister.ConfigMaps(namespace).Get(name)
case model.ResourceTypeSecret:
obj, err = uc.secretLister.Secrets(namespace).Get(name)
case common.ResourceTypePersistentVolume:
obj, err = uc.kubeClient.CoreV1().PersistentVolumes().Get(context.Background(), name, metaV1.GetOptions{})
case common.ResourceTypePersistentVolumeClaim:
obj, err = uc.kubeClient.CoreV1().PersistentVolumeClaims(namespace).Get(context.Background(), name, metaV1.GetOptions{})
case common.ResourceTypeVolumeAttachment:
obj, err = uc.kubeClient.StorageV1().VolumeAttachments().Get(context.Background(), name, metaV1.GetOptions{})
case model.ResourceTypeNode:
obj, err = uc.nodeLister.Get(name)
case model.ResourceTypeServiceAccountToken:
obj, err = uc.getServiceAccountToken(namespace, name, msg)
case model.ResourceTypeLease:
obj, err = uc.leaseLister.Leases(namespace).Get(name)
case model.ResourceTypeCSR:
obj, err = uc.kubeClient.CertificatesV1().CertificateSigningRequests().Get(context.Background(), name, metaV1.GetOptions{})
default:
err = stderrors.New("wrong query type")
}
if err != nil {
return nil, err
}
if err := util.SetMetaType(obj.(runtime.Object)); err != nil {
return nil, err
}
return obj, nil
}
func queryInner(uc *UpstreamController, msg model.Message, queryType string) {
klog.V(4).Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
var err error
var namespace, name, nodeID, resource string
namespace, err = messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
return
}
name, err = messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
return
}
nodeID, err = messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
return
}
resource, err = messagelayer.BuildResource(nodeID, namespace, queryType, name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
return
}
defer func() {
if err == nil {
return
}
resMsg := model.NewMessage(msg.GetID()).
FillBody(err).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
}
}()
switch msg.GetOperation() {
case model.QueryOperation:
var object metaV1.Object
object, err = kubeClientGet(uc, namespace, name, queryType, msg)
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, resource not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
return
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
return
}
resMsg := model.NewMessage(msg.GetID()).
SetResourceVersion(object.GetResourceVersion()).
FillBody(object).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
rspErr := uc.messageLayer.Response(*resMsg)
if rspErr != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), rspErr)
return
}
klog.V(4).Infof("message: %s process successfully", msg.GetID())
default:
klog.Warningf("message: %s process failure, operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
}
func (uc *UpstreamController) queryConfigMap() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop queryConfigMap")
return
case msg := <-uc.configMapChan:
queryInner(uc, msg, model.ResourceTypeConfigmap)
}
}
}
func (uc *UpstreamController) querySecret() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop querySecret")
return
case msg := <-uc.secretChan:
queryInner(uc, msg, model.ResourceTypeSecret)
}
}
}
func (uc *UpstreamController) processServiceAccountToken() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop process service account token")
return
case msg := <-uc.serviceAccountTokenChan:
queryInner(uc, msg, model.ResourceTypeServiceAccountToken)
}
}
}
func (uc *UpstreamController) getServiceAccountToken(namespace string, name string, msg model.Message) (metaV1.Object, error) {
data, err := msg.GetContentData()
if err != nil {
klog.Errorf("get message body failed err %v", err)
return nil, err
}
tr := authenticationv1.TokenRequest{}
if err := json.Unmarshal(data, &tr); err != nil {
klog.Errorf("unmarshal token request failed err %v", err)
return nil, err
}
tokenRequest, err := uc.kubeClient.CoreV1().ServiceAccounts(namespace).CreateToken(context.TODO(), name, &tr, metaV1.CreateOptions{})
if err != nil {
klog.Errorf("apiserver get service account token failed: err %v", err)
return nil, err
}
return tokenRequest, nil
}
func (uc *UpstreamController) queryPersistentVolume() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop queryPersistentVolume")
return
case msg := <-uc.persistentVolumeChan:
queryInner(uc, msg, common.ResourceTypePersistentVolume)
}
}
}
func (uc *UpstreamController) queryPersistentVolumeClaim() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop queryPersistentVolumeClaim")
return
case msg := <-uc.persistentVolumeClaimChan:
queryInner(uc, msg, common.ResourceTypePersistentVolumeClaim)
}
}
}
func (uc *UpstreamController) queryVolumeAttachment() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop queryVolumeAttachment")
return
case msg := <-uc.volumeAttachmentChan:
queryInner(uc, msg, common.ResourceTypeVolumeAttachment)
}
}
}
func (uc *UpstreamController) registerNode() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop registerNode")
return
case msg := <-uc.createNodeChan:
klog.V(5).Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
data, err := msg.GetContentData()
if err != nil {
klog.Warningf("message: %s process failure, get content data failed with error: %v", msg.GetID(), err)
continue
}
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %v", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %v", msg.GetID(), err)
continue
}
node := &v1.Node{}
err = json.Unmarshal(data, node)
if err != nil {
errLog := fmt.Sprintf("message: %s process failure, unmarshal marshaled message content with error: %v", msg.GetID(), err)
klog.Error(errLog)
uc.nodeMsgResponse(name, namespace, errLog, msg)
continue
}
resp, err := uc.createNode(name, node)
if err != nil {
klog.Errorf("create node %s error: %v , register node failed", name, err)
}
resMsg := model.NewMessage(msg.GetID()).
FillBody(&edgeapi.ObjectResp{Object: resp, Err: err}).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, msg.GetResource(), model.ResponseOperation)
if err = uc.messageLayer.Response(*resMsg); err != nil {
klog.Warningf("Response message: %s failed, response failed with error: %v", msg.GetID(), err)
continue
}
klog.V(4).Infof("message: %s, register node successfully, namespace: %s, name: %s", msg.GetID(), namespace, name)
}
}
}
func (uc *UpstreamController) patchNode() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop patchNode")
return
case msg := <-uc.patchNodeChan:
klog.V(5).Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %v", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %v", msg.GetID(), err)
continue
}
patchBytes, err := msg.GetContentData()
if err != nil {
klog.Warningf("message: %s process failure, get data failed with error: %v", msg.GetID(), err)
continue
}
node, err := uc.kubeClient.CoreV1().Nodes().Patch(context.TODO(), name, apimachineryType.StrategicMergePatchType, patchBytes, metaV1.PatchOptions{}, "status")
if err != nil {
klog.Errorf("message: %s process failure, patch node failed with error: %v, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
}
resMsg := model.NewMessage(msg.GetID()).
SetResourceVersion(node.ResourceVersion).
FillBody(&edgeapi.ObjectResp{Object: node, Err: err}).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, msg.GetResource(), model.ResponseOperation)
if err = uc.messageLayer.Response(*resMsg); err != nil {
klog.Warningf("Message: %s process failure, response failed with error: %v", msg.GetID(), err)
continue
}
klog.V(4).Infof("message: %s, patch node status successfully, namespace: %s, name: %s", msg.GetID(), namespace, name)
}
}
}
func (uc *UpstreamController) updateNode() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("stop updateNode")
return
case msg := <-uc.updateNodeChan:
klog.V(5).Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
noderequest := &v1.Node{}
data, err := msg.GetContentData()
if err != nil {
klog.Warningf("message: %s process failure, get content data failed with error: %s", msg.GetID(), err)
continue
}
if err := json.Unmarshal(data, noderequest); err != nil {
klog.Warningf("message: %s process failure, unmarshal message content data with error: %s", msg.GetID(), err)
continue
}
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.UpdateOperation:
getNode, err := uc.kubeClient.CoreV1().Nodes().Get(context.Background(), name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, node %s not found", msg.GetID(), name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, name: %s", msg.GetID(), err, name)
continue
}
// update node labels
if getNode.Labels == nil {
getNode.Labels = make(map[string]string)
}
for key, value := range noderequest.Labels {
getNode.Labels[key] = value
}
if getNode.Annotations == nil {
getNode.Annotations = make(map[string]string)
}
for k, v := range noderequest.Annotations {
getNode.Annotations[k] = v
}
byteNode, err := json.Marshal(getNode)
if err != nil {
klog.Warningf("marshal node data failed with err: %s", err)
continue
}
node, err := uc.kubeClient.CoreV1().Nodes().Patch(context.Background(), getNode.Name, apimachineryType.StrategicMergePatchType, byteNode, metaV1.PatchOptions{})
if err != nil {
klog.Warningf("message: %s process failure, update node failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getNode.Namespace, getNode.Name)
continue
}
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypeNode, name)
if err != nil {
klog.Warningf("Message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg := model.NewMessage(msg.GetID()).
SetResourceVersion(node.ResourceVersion).
FillBody(common.MessageSuccessfulContent).
BuildRouter(modules.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)