...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package utils
15
16 import (
17 "context"
18
19 v1 "k8s.io/api/core/v1"
20 "sigs.k8s.io/controller-runtime/pkg/client"
21
22 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
23 "github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
24 "github.com/chaos-mesh/chaos-mesh/controllers/utils/controller"
25 chaosdaemonclient "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/client"
26 )
27
28 type ContianerRecordDecoder struct {
29 client.Client
30 *chaosdaemon.ChaosDaemonClientBuilder
31 }
32
33 func NewContainerRecordDecoder(c client.Client, builder *chaosdaemon.ChaosDaemonClientBuilder) *ContianerRecordDecoder {
34 return &ContianerRecordDecoder{
35 Client: c,
36 ChaosDaemonClientBuilder: builder,
37 }
38 }
39
40 type DecodedContainerRecord struct {
41 PbClient chaosdaemonclient.ChaosDaemonClientInterface
42 ContainerId string
43
44 Pod *v1.Pod
45 }
46
47 func (d *ContianerRecordDecoder) DecodeContainerRecord(ctx context.Context, record *v1alpha1.Record) (decoded DecodedContainerRecord, err error) {
48 var pod v1.Pod
49 podId, containerName := controller.ParseNamespacedNameContainer(record.Id)
50 err = d.Client.Get(ctx, podId, &pod)
51 if err != nil {
52
53 err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, err)
54 return
55 }
56 decoded.Pod = &pod
57 if len(pod.Status.ContainerStatuses) == 0 {
58
59 err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, nil)
60 return
61 }
62
63 for _, container := range pod.Status.ContainerStatuses {
64 if container.Name == containerName {
65 decoded.ContainerId = container.ContainerID
66 break
67 }
68 }
69 if len(decoded.ContainerId) == 0 {
70
71 err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, nil)
72 return
73 }
74
75 decoded.PbClient, err = d.ChaosDaemonClientBuilder.Build(ctx, &pod)
76 if err != nil {
77 return
78 }
79
80 return
81 }
82