forked from vmware-tanzu/k-bench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pod_manager.go
1343 lines (1161 loc) · 44.7 KB
/
pod_manager.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-2020 VMware, Inc.
SPDX-License-Identifier: Apache-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.
*/
package manager
import (
//"log"
//"encoding/json"
"bytes"
"fmt"
osexec "os/exec"
"sort"
"strconv"
"strings"
"sync"
"time"
"context"
log "github.com/sirupsen/logrus"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
scheme "k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/remotecommand"
"k-bench/perf_util"
)
const podNamePrefix string = "kbench-pod-"
/*
* PodManager manages pods actions and stats.
*/
type PodManager struct {
// This is a shared client
client *kubernetes.Clientset
// This is an array of clients used for pod operations
clientsets []*kubernetes.Clientset
// Below are used to store the server side timestamps (round to seconds)
createTimes map[string]metav1.Time // pod creation timestamp
scheduleTimes map[string]metav1.Time // timestamp for pod schedule event
startTimes map[string]metav1.Time // pod accepted by kubelet, image not pulled
pulledTimes map[string]metav1.Time // image pulled time
runTimes map[string]metav1.Time // container(s) become running
// Maps to store client times (based on PodConditionType) with higher precision
cFirstTimes map[string]metav1.Time // client sees the first add/update
cSchedTimes map[string]metav1.Time // client sees PodScheduled == True
cInitedTimes map[string]metav1.Time // client sees Initialized == True
// there is no pulled event handler for client
cReadyTimes map[string]metav1.Time // client sees Ready == True
// A map to track the API response time for the supported actions
apiTimes map[string][]time.Duration
namespace string // The benchmark's default namespace for pod
source string
config *restclient.Config
podNs map[string]string // Used to track pods to namespaces mappings
nsSet map[string]bool // Used to track created non-default namespaces
// Mutex used to update pod startup stats
statsMutex sync.Mutex
// Mutex to update pod set
podMutex sync.Mutex
// Mutex to update api latency
alMutex sync.Mutex
// Action functions
ActionFuncs map[string]func(*PodManager, interface{}) error
// Cache related structures
podController cache.Controller
podChan chan struct{}
podThroughput float32
podAvgLatency float32
negRes bool
startTimestamp string
createToScheLatency, scheToStartLatency perf_util.OperationLatencyMetric
startToPulledLatency, pulledToRunLatency perf_util.OperationLatencyMetric
createToRunLatency, firstToSchedLatency perf_util.OperationLatencyMetric
schedToInitdLatency, initdToReadyLatency perf_util.OperationLatencyMetric
firstToReadyLatency, createToReadyLatency perf_util.OperationLatencyMetric
}
func NewPodManager() Manager {
ctt := make(map[string]metav1.Time, 0)
sct := make(map[string]metav1.Time, 0)
stt := make(map[string]metav1.Time, 0)
put := make(map[string]metav1.Time, 0)
rut := make(map[string]metav1.Time, 0)
cft := make(map[string]metav1.Time, 0)
cst := make(map[string]metav1.Time, 0)
cit := make(map[string]metav1.Time, 0)
crt := make(map[string]metav1.Time, 0)
apt := make(map[string][]time.Duration, 0)
pn := make(map[string]string, 0)
ns := make(map[string]bool, 0)
af := make(map[string]func(*PodManager, interface{}) error, 0)
af[CREATE_ACTION] = (*PodManager).Create
af[RUN_ACTION] = (*PodManager).Run
af[DELETE_ACTION] = (*PodManager).Delete
af[LIST_ACTION] = (*PodManager).List
af[GET_ACTION] = (*PodManager).Get
af[UPDATE_ACTION] = (*PodManager).Update
af[COPY_ACTION] = (*PodManager).Copy
pc := make(chan struct{})
return &PodManager{
createTimes: ctt,
scheduleTimes: sct,
startTimes: stt,
pulledTimes: put,
runTimes: rut,
cFirstTimes: cft,
cSchedTimes: cst,
cInitedTimes: cit,
cReadyTimes: crt,
apiTimes: apt,
namespace: apiv1.NamespaceDefault,
podNs: pn,
nsSet: ns,
statsMutex: sync.Mutex{},
podMutex: sync.Mutex{},
alMutex: sync.Mutex{},
ActionFuncs: af,
//podController: nil,
podChan: pc,
startTimestamp: metav1.Now().Format("2006-01-02T15-04-05"),
}
}
// This function checks the pod's status and updates various timestamps.
func (mgr *PodManager) checkAndUpdate(p *apiv1.Pod) {
//log.Infof("checkAndUpdate called for %s, status: %v", p.Name, p.Status)
mgr.statsMutex.Lock()
defer mgr.statsMutex.Unlock()
// Store server-side pod start time (acknowledged by Kubelet, but image not pulled)
if p.Status.StartTime != nil {
if _, ok := mgr.startTimes[p.Name]; !ok {
// Store the server side timestamp
mgr.startTimes[p.Name] = *p.Status.StartTime
}
}
// Store the time when the client gets notified about this pod for the first time
if _, ok := mgr.cFirstTimes[p.Name]; !ok {
mgr.cFirstTimes[p.Name] = metav1.Now()
}
if p.Status.Phase == apiv1.PodRunning {
// Store various times upon the first time when client sees a pod is running
if _, ok := mgr.cReadyTimes[p.Name]; !ok {
// Record server side timestamp for pod creation
mgr.createTimes[p.Name] = p.CreationTimestamp
mgr.cReadyTimes[p.Name] = metav1.Now()
var lastRunningTime metav1.Time
for _, cs := range p.Status.ContainerStatuses {
if cs.State.Running != nil {
if lastRunningTime.Before(&cs.State.Running.StartedAt) {
lastRunningTime = cs.State.Running.StartedAt
}
}
}
if lastRunningTime != metav1.NewTime(time.Time{}) {
mgr.runTimes[p.Name] = lastRunningTime
// If cInitedTime has not been recorded, use cSchedTime as an approximation
if _, ok := mgr.cInitedTimes[p.Name]; !ok {
if st, stok := mgr.cSchedTimes[p.Name]; stok {
mgr.cInitedTimes[p.Name] = st
}
}
} else {
log.Errorf("Pod %v is running, but none of its containers is", p.Name)
}
}
} else if p.Status.Phase == apiv1.PodPending {
for _, cond := range p.Status.Conditions {
// Record client time (server time around to seconds) when PodCondition changes
if cond.Type == apiv1.PodScheduled {
if _, ok := mgr.cSchedTimes[p.Name]; !ok {
mgr.cSchedTimes[p.Name] = metav1.Now()
}
} else if cond.Type == apiv1.PodInitialized {
// This should also be the pod's startTime
if _, ok := mgr.cReadyTimes[p.Name]; ok {
// PodInitialized callback can be delayed, in such case use cSchedTime
// as an approximation
mgr.cInitedTimes[p.Name] = mgr.cSchedTimes[p.Name]
} else if _, ok := mgr.cInitedTimes[p.Name]; !ok {
mgr.cInitedTimes[p.Name] = metav1.Now()
}
break
}
}
}
}
// This function adds cache with watch list and event handler
func (mgr *PodManager) initCache(resourceType string) {
_, mgr.podController = cache.NewInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = labels.SelectorFromSet(
labels.Set{"app": AppName, "type": resourceType}).String()
obj, err := mgr.client.CoreV1().Pods("").List(context.Background(), options)
return runtime.Object(obj), err
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = labels.SelectorFromSet(
labels.Set{"app": AppName, "type": resourceType}).String()
return mgr.client.CoreV1().Pods("").Watch(context.Background(), options)
},
},
&apiv1.Pod{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
p, ok := obj.(*apiv1.Pod)
if !ok {
log.Error("Failed to cast observed object to *v1.Pod.")
}
go mgr.checkAndUpdate(p)
},
UpdateFunc: func(oldObj, newObj interface{}) {
p, ok := newObj.(*apiv1.Pod)
if !ok {
log.Error("Failed to cast observed object to *v1.Pod.")
}
go mgr.checkAndUpdate(p)
},
},
)
//mgr.podController = &controller
go mgr.podController.Run(mgr.podChan)
}
/*
* This function updates the stats before deletion
*/
func (mgr *PodManager) UpdateBeforeDeletion(name string, ns string) {
// Before deletion, make sure schedule and pulled time retrieved for this pod
// As deletes may happen in multi-threaded section, need to protect the update
mgr.statsMutex.Lock()
if _, ok := mgr.scheduleTimes[name]; !ok {
selector := fields.Set{
"involvedObject.kind": "Pod",
"involvedObject.namespace": ns,
//"source": apiv1.DefaultSchedulerName,
}.AsSelector().String()
options := metav1.ListOptions{FieldSelector: selector}
//TODO: move the below statement out side the lock?
events, err := mgr.client.CoreV1().Events("").List(context.Background(), options)
if err != nil {
log.Error(err)
} else {
scheEvents := make(map[string]metav1.Time, 0)
pulledEvents := make(map[string]metav1.Time, 0)
for _, event := range events.Items {
if event.Source.Component == apiv1.DefaultSchedulerName {
scheEvents[event.InvolvedObject.Name] = event.FirstTimestamp
} else if event.Reason == "Pulled" {
pulledEvents[event.InvolvedObject.Name] = event.FirstTimestamp
}
}
for k := range mgr.createTimes {
if _, sche_exist := scheEvents[k]; sche_exist {
mgr.scheduleTimes[k] = scheEvents[k]
}
if _, pull_exist := scheEvents[k]; pull_exist {
mgr.pulledTimes[k] = pulledEvents[k]
}
}
}
}
mgr.statsMutex.Unlock()
}
/*
* This function implements the Init interface and is used to initialize the manager
*/
func (mgr *PodManager) Init(
kubeConfig *restclient.Config,
nsName string,
createNamespace bool,
maxClients int,
resourceType string,
) {
mgr.namespace = nsName
mgr.source = perf_util.GetHostnameFromUrl(kubeConfig.Host)
mgr.config = kubeConfig
sharedClient, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
panic(err)
}
mgr.client = sharedClient
mgr.clientsets = make([]*kubernetes.Clientset, maxClients)
for i := 0; i < maxClients; i++ {
client, ce := kubernetes.NewForConfig(kubeConfig)
if ce != nil {
panic(ce)
}
mgr.clientsets[i] = client
}
if createNamespace {
nsSpec := &apiv1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: nsName}}
_, err := mgr.client.CoreV1().Namespaces().Create(context.Background(), nsSpec, metav1.CreateOptions{})
if err != nil {
log.Warningf("Fail to create namespace %s, %v", nsName, err)
} else {
mgr.nsSet[nsName] = true
}
}
mgr.initCache(resourceType)
}
/*
* This function implements the CREATE action.
*/
func (mgr *PodManager) Create(spec interface{}) error {
switch s := spec.(type) {
default:
log.Errorf("Invalid spec type %T for Pod create action.", s)
return fmt.Errorf("Invalid spec type %T for Pod create action.", s)
case *apiv1.Pod:
tid, _ := strconv.Atoi(s.Labels["tid"])
cid := tid % len(mgr.clientsets)
ns := mgr.namespace
if s.Namespace != "" {
ns = s.Namespace
mgr.podMutex.Lock()
if _, exist := mgr.nsSet[ns]; !exist && ns != apiv1.NamespaceDefault {
nsSpec := &apiv1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}
_, err := mgr.client.CoreV1().Namespaces().Create(context.Background(), nsSpec, metav1.CreateOptions{})
if err != nil {
if strings.Contains(err.Error(), "already exists") {
mgr.nsSet[ns] = true
} else {
log.Warningf("Fail to create namespace %s, %v", ns, err)
}
} else {
mgr.nsSet[ns] = true
}
}
mgr.podMutex.Unlock()
}
startTime := metav1.Now()
pod, err := mgr.clientsets[cid].CoreV1().Pods(ns).Create(context.Background(), s, metav1.CreateOptions{})
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
if err != nil {
return err
}
mgr.alMutex.Lock()
mgr.apiTimes[CREATE_ACTION] = append(mgr.apiTimes[CREATE_ACTION], latency)
mgr.alMutex.Unlock()
mgr.podMutex.Lock()
mgr.podNs[pod.Name] = ns
mgr.podMutex.Unlock()
}
return nil
}
/*
* This function implements the LIST action.
*/
func (mgr *PodManager) List(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec type %T for Pod list action.", s)
return fmt.Errorf("Invalid spec type %T for Pod list action.", s)
case ActionSpec:
options := GetListOptions(s)
cid := s.Tid % len(mgr.clientsets)
ns := mgr.namespace
if s.Namespace != "" {
ns = s.Namespace
}
startTime := metav1.Now()
pods, err := mgr.clientsets[cid].CoreV1().Pods(ns).List(context.Background(), options)
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
if err != nil {
return err
}
log.Infof("Listed %v pods", len(pods.Items))
mgr.alMutex.Lock()
mgr.apiTimes[LIST_ACTION] = append(mgr.apiTimes[LIST_ACTION], latency)
mgr.alMutex.Unlock()
}
return nil
}
/*
* This function implements the GET action.
*/
func (mgr *PodManager) Get(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec type %T for Pod get action.", s)
return fmt.Errorf("Invalid spec type %T for Pod get action.", s)
case ActionSpec:
cid := s.Tid % len(mgr.clientsets)
ns := mgr.namespace
if s.Namespace != "" {
ns = s.Namespace
}
// Labels (or other filters) are ignored as they do not make sense to GET
startTime := metav1.Now()
pod, err := mgr.clientsets[cid].CoreV1().Pods(ns).Get(
context.Background(), s.Name, metav1.GetOptions{})
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
if err != nil {
return err
}
log.Infof("Got pod %v", pod.Name)
mgr.alMutex.Lock()
mgr.apiTimes[GET_ACTION] = append(mgr.apiTimes[GET_ACTION], latency)
mgr.alMutex.Unlock()
}
return nil
}
/*
* This function implements the RUN action.
*/
func (mgr *PodManager) Run(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec type %T for Pod run action.", s)
return fmt.Errorf("Invalid spec type %T for Pod run action.", s)
case RunSpec:
cid := s.ActionFilter.Tid % len(mgr.clientsets)
// Find pod(s) using filter first, then name
options := GetListOptions(s.ActionFilter)
ns := mgr.namespace
if s.ActionFilter.Namespace != "" {
ns = s.ActionFilter.Namespace
}
pods := make([]apiv1.Pod, 0)
podList, err := mgr.clientsets[cid].CoreV1().Pods(ns).List(context.Background(), options)
if err != nil {
return err
}
pods = podList.Items
startTime := metav1.Now()
for _, pod := range pods {
for _, container := range pod.Spec.Containers {
log.Infof("Run: Container %v found for pod %v", container.Name,
pod.Name)
// TBD - In future, add a container name prefix and filter containers
// based on this prefix
runrequest := mgr.clientsets[cid].CoreV1().RESTClient().Post().
Resource("pods").
Name(pod.Name).
Namespace(ns).
SubResource("exec").
Param("container", container.Name)
runrequest.VersionedParams(&apiv1.PodExecOptions{
Container: container.Name,
Command: []string{"/bin/sh", "-c", s.RunCommand},
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
var mystdout, mystderr bytes.Buffer
exec, err := remotecommand.NewSPDYExecutor(mgr.config,
"POST", runrequest.URL())
if err != nil {
return err
}
exec.Stream(remotecommand.StreamOptions{
Stdin: nil,
Stdout: &mystdout,
Stderr: &mystderr,
Tty: false,
})
log.Infof("Container %v on pod %v, Run out: %v err: %v",
container.Name, pod.Name, mystdout.String(),
mystderr.String())
}
}
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
// TBD - invoke s.RunCommand on this pod
mgr.alMutex.Lock()
mgr.apiTimes[RUN_ACTION] = append(mgr.apiTimes[RUN_ACTION], latency)
mgr.alMutex.Unlock()
}
return nil
}
/*
* This function implements the COPY action.
*/
func (mgr *PodManager) Copy(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec type %T for Pod copy action.", s)
return fmt.Errorf("Invalid spec type %T for Pod copy action.", s)
case CopySpec:
cid := s.ActionFilter.Tid % len(mgr.clientsets)
// Find pod(s) using filter first, then name
options := GetListOptions(s.ActionFilter)
ns := mgr.namespace
if s.ActionFilter.Namespace != "" {
ns = s.ActionFilter.Namespace
}
pods := make([]apiv1.Pod, 0)
podList, err := mgr.clientsets[cid].CoreV1().Pods(ns).List(context.Background(), options)
if err != nil {
return err
}
pods = podList.Items
startTime := metav1.Now()
for _, pod := range pods {
// Currently we copy files at pod level (to/from the first container).
var fromPath, toPath string
if s.Upload == true {
fromPath = s.LocalPath
toPath = pod.Namespace + "/" + pod.Name + ":" + s.ContainerPath
} else {
toPath = s.ParentOutDir + "/" + s.LocalPath + "/"
toPath += mgr.startTimestamp + "/" + pod.Name
fromPath = pod.Namespace + "/" + pod.Name + ":" + s.ContainerPath
}
args := []string{"cp", fromPath, toPath}
copyr, copye := osexec.Command("kubectl", args...).CombinedOutput()
if copye != nil {
log.Errorf("Error copying file(s) for pod: %v", pod.Name)
} else {
log.Infof(string(copyr))
}
}
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
mgr.alMutex.Lock()
mgr.apiTimes[COPY_ACTION] = append(mgr.apiTimes[COPY_ACTION], latency)
mgr.alMutex.Unlock()
}
return nil
}
/*
* This function implements the UPDATE action.
*/
func (mgr *PodManager) Update(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec type %T for Pod update action.", s)
return fmt.Errorf("Invalid spec type %T for Pod update action.", s)
case ActionSpec:
cid := s.Tid % len(mgr.clientsets)
options := GetListOptions(s)
ns := mgr.namespace
if s.Namespace != "" {
ns = s.Namespace
}
pods := make([]apiv1.Pod, 0)
podList, err := mgr.clientsets[cid].CoreV1().Pods(ns).List(context.Background(), options)
if err != nil {
return err
}
pods = podList.Items
newActiveDeadline := int64(10000)
for _, currPod := range pods {
currPod.Spec.ActiveDeadlineSeconds = &newActiveDeadline
startTime := metav1.Now()
pod, err := mgr.clientsets[cid].CoreV1().Pods(ns).Update(
context.Background(), &currPod, metav1.UpdateOptions{})
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
if err != nil {
return err
}
log.Infof("Updated ActiveDeadlineSeconds for pod %v", pod.Name)
mgr.alMutex.Lock()
mgr.apiTimes[UPDATE_ACTION] = append(mgr.apiTimes[UPDATE_ACTION], latency)
mgr.alMutex.Unlock()
}
}
return nil
}
/*
* This function implements the DELETE action.
*/
func (mgr *PodManager) Delete(n interface{}) error {
switch s := n.(type) {
default:
log.Errorf("Invalid spec %T for Pod delete action.", s)
return fmt.Errorf("Invalid spec %T for Pod delete action.", s)
case ActionSpec:
cid := s.Tid % len(mgr.clientsets)
options := GetListOptions(s)
ns := mgr.namespace
/*if space, ok := mgr.podNs[s.Name]; ok {
ns = space
}*/
if s.Namespace != "" {
ns = s.Namespace
}
pods := make([]apiv1.Pod, 0)
podList, err := mgr.clientsets[cid].CoreV1().Pods(ns).List(context.Background(), options)
if err != nil {
return err
}
pods = podList.Items
for _, currPod := range pods {
log.Infof("Deleting pod %v", currPod.Name)
if _, ok := mgr.scheduleTimes[currPod.Name]; !ok {
mgr.UpdateBeforeDeletion(currPod.Name, ns)
}
// Delete the pod
startTime := metav1.Now()
mgr.clientsets[cid].CoreV1().Pods(ns).Delete(context.Background(), currPod.Name, metav1.DeleteOptions{})
latency := metav1.Now().Time.Sub(startTime.Time).Round(time.Microsecond)
mgr.alMutex.Lock()
mgr.apiTimes[DELETE_ACTION] = append(mgr.apiTimes[DELETE_ACTION], latency)
mgr.alMutex.Unlock()
mgr.podMutex.Lock()
// Delete it from the pod set
_, ok := mgr.podNs[currPod.Name]
if ok {
delete(mgr.podNs, currPod.Name)
}
mgr.podMutex.Unlock()
}
}
return nil
}
/*
* This function implements the DeleteAll manager interface. It is used to clean
* all the resources that are created by the pod manager.
*/
func (mgr *PodManager) DeleteAll() error {
if len(mgr.podNs) > 0 {
log.Infof("Deleting all pods created by the pod manager...")
for name, _ := range mgr.podNs {
// Just use tid 0 so that the first client is used to delete all pods
mgr.Delete(ActionSpec{
Name: name,
Tid: 0})
}
mgr.podNs = make(map[string]string, 0)
} else {
log.Infof("Found no pod to delete, maybe they have already been deleted.")
}
if mgr.namespace != apiv1.NamespaceDefault {
mgr.client.CoreV1().Namespaces().Delete(context.Background(), mgr.namespace, metav1.DeleteOptions{})
}
// Delete other non default namespaces
for ns, _ := range mgr.nsSet {
if ns != apiv1.NamespaceDefault {
mgr.client.CoreV1().Namespaces().Delete(context.Background(), ns, metav1.DeleteOptions{})
}
}
mgr.nsSet = make(map[string]bool, 0)
close(mgr.podChan)
return nil
}
/*
* This function returns whether all the created pods become ready
*/
func (mgr *PodManager) IsStable() bool {
return len(mgr.cReadyTimes) == len(mgr.apiTimes[CREATE_ACTION])
}
/*
* This function computes all the metrics and stores the results into the log file.
*/
func (mgr *PodManager) LogStats() {
log.Infof("------------------------------------ Pod Operation Summary " +
"-----------------------------------")
log.Infof("%-50v %-10v", "Number of valid pod creation requests:",
len(mgr.apiTimes[CREATE_ACTION]))
log.Infof("%-50v %-10v", "Number of created pods:", len(mgr.cFirstTimes))
log.Infof("%-50v %-10v", "Number of scheduled pods:", len(mgr.cSchedTimes))
log.Infof("%-50v %-10v", "Number of initialized pods:", len(mgr.cInitedTimes))
log.Infof("%-50v %-10v", "Number of started pods:", len(mgr.startTimes))
log.Infof("%-50v %-10v", "Number of running pods:", len(mgr.cReadyTimes))
log.Infof("%-50v %-10v", "Pod creation throughput (pods/minutes):",
mgr.podThroughput)
log.Infof("%-50v %-10v", "Pod creation average latency:",
mgr.podAvgLatency)
log.Infof("--------------------------------- Pod Startup Latencies (ms) " +
"---------------------------------")
log.Infof("%-50v %-10v %-10v %-10v %-10v", " ", "median", "min", "max", "99%")
var latency perf_util.OperationLatencyMetric
latency = mgr.createToScheLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod creation latency stats (server): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod creation latency stats (server): ",
"---", "---", "---", "---")
}
latency = mgr.scheToStartLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod scheduling latency stats (server): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod scheduling latency stats (server): ",
"---", "---", "---", "---")
}
latency = mgr.startToPulledLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod image pulling latency stats (server): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod image pulling latency stats (server): ",
"---", "---", "---", "---")
}
latency = mgr.pulledToRunLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod starting latency stats (server): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod starting latency stats (server): ",
"---", "---", "---", "---")
}
latency = mgr.createToRunLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod startup total latency (server): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod startup total latency (server): ",
"---", "---", "---", "---")
}
latency = mgr.createToReadyLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod client-server e2e latency: ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod client-server e2e latency (create-to-ready): ",
"---", "---", "---", "---")
}
latency = mgr.firstToSchedLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod scheduling latency stats (client): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod scheduling latency stats (client): ",
"---", "---", "---", "---")
}
latency = mgr.schedToInitdLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod initialization latency on kubelet (client): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod initialization latency on kubelet (client): ",
"---", "---", "---", "---")
}
latency = mgr.initdToReadyLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod starting latency stats (client): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod starting latency stats (client): ",
"---", "---", "---", "---")
}
latency = mgr.firstToReadyLatency
if latency.Valid {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod startup total latency (client): ",
latency.Latency.Mid, latency.Latency.Min, latency.Latency.Max, latency.Latency.P99)
} else {
log.Infof("%-50v %-10v %-10v %-10v %-10v",
"Pod startup total latency (client): ",
"---", "---", "---", "---")
}
log.Infof("--------------------------------- Pod API Call Latencies (ms) " +
"--------------------------------")
log.Infof("%-50v %-10v %-10v %-10v %-10v", " ", "median", "min", "max", "99%")
var mid, min, max, p99 float32
for m, _ := range mgr.apiTimes {
mid = float32(mgr.apiTimes[m][len(mgr.apiTimes[m])/2]) / float32(time.Millisecond)
min = float32(mgr.apiTimes[m][0]) / float32(time.Millisecond)
max = float32(mgr.apiTimes[m][len(mgr.apiTimes[m])-1]) / float32(time.Millisecond)
p99 = float32(mgr.apiTimes[m][len(mgr.apiTimes[m])-1-len(mgr.apiTimes[m])/100]) /
float32(time.Millisecond)
log.Infof("%-50v %-10v %-10v %-10v %-10v", m+" pod latency: ", mid, min, max, p99)
}
if mgr.scheToStartLatency.Latency.Mid < 0 {
log.Warning("There might be time skew between server and nodes, " +
"server side metrics such as scheduling latency stats (server) above is negative.")
}
// If we see negative server side results or server-client latency is larger than client latency by more than 3x
if mgr.negRes || mgr.createToReadyLatency.Latency.Mid/3 > mgr.firstToReadyLatency.Latency.Mid {
log.Warning("There might be time skew between client and server, " +
"and certain results (e.g., client-server e2e latency) above " +
"may have been affected.")
}
}
func (mgr *PodManager) GetResourceName(userPodPrefix string, opNum int, tid int) string {
if userPodPrefix == "" {
return podNamePrefix + "oid-" + strconv.Itoa(opNum) + "-tid-" + strconv.Itoa(tid)
} else {
return userPodPrefix + "-" + podNamePrefix + "oid-" + strconv.Itoa(opNum) + "-tid-" + strconv.Itoa(tid)
}
}
func (mgr *PodManager) SendMetricToWavefront(
now time.Time,
wfTags []perf_util.WavefrontTag,
wavefrontPathDir string,
prefix string) {
var points []perf_util.WavefrontDataPoint
points = append(points, perf_util.WavefrontDataPoint{"pod.creation.throuput",
mgr.podThroughput, now, mgr.source, wfTags})
//create to sched
if mgr.createToScheLatency.Valid {
points = append(points, perf_util.WavefrontDataPoint{"pod.server.creation.median.latency",
mgr.createToScheLatency.Latency.Mid, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.creation.min.latency",
mgr.createToScheLatency.Latency.Min, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.creation.max.latency",
mgr.createToScheLatency.Latency.Max, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.creation.p99.latency",
mgr.createToScheLatency.Latency.P99, now, mgr.source, wfTags})
}
if mgr.scheToStartLatency.Valid {
points = append(points, perf_util.WavefrontDataPoint{"pod.server.scheduling.median.latency",
mgr.scheToStartLatency.Latency.Mid, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.scheduling.min.latency",
mgr.scheToStartLatency.Latency.Min, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.scheduling.max.latency",
mgr.scheToStartLatency.Latency.Max, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.scheduling.p99.latency",
mgr.scheToStartLatency.Latency.P99, now, mgr.source, wfTags})
}
if mgr.startToPulledLatency.Valid {
points = append(points, perf_util.WavefrontDataPoint{"pod.server.image.pulling.median.latency",
mgr.startToPulledLatency.Latency.Mid, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.image.pulling.min.latency",
mgr.startToPulledLatency.Latency.Min, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.image.pulling.max.latency",
mgr.startToPulledLatency.Latency.Max, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.image.pulling.p99.latency",
mgr.startToPulledLatency.Latency.P99, now, mgr.source, wfTags})
}
if mgr.pulledToRunLatency.Valid {
points = append(points, perf_util.WavefrontDataPoint{"pod.server.starting.median.latency",
mgr.pulledToRunLatency.Latency.Mid, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.starting.min.latency",
mgr.pulledToRunLatency.Latency.Min, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.starting.max.latency",
mgr.pulledToRunLatency.Latency.Max, now, mgr.source, wfTags})
points = append(points, perf_util.WavefrontDataPoint{"pod.server.starting.p99.latency",
mgr.pulledToRunLatency.Latency.P99, now, mgr.source, wfTags})
}