...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package container
17
18 import (
19 "context"
20
21 "go.uber.org/fx"
22 v1 "k8s.io/api/core/v1"
23 "sigs.k8s.io/controller-runtime/pkg/client"
24
25 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
26 "github.com/chaos-mesh/chaos-mesh/controllers/config"
27 "github.com/chaos-mesh/chaos-mesh/pkg/selector/generic"
28 "github.com/chaos-mesh/chaos-mesh/pkg/selector/pod"
29 )
30
31 type SelectImpl struct {
32 c client.Client
33 r client.Reader
34
35 generic.Option
36 }
37
38 type Container struct {
39 v1.Pod
40 ContainerName string
41 }
42
43 func (c *Container) Id() string {
44 return c.Pod.Namespace + "/" + c.Pod.Name + "/" + c.ContainerName
45 }
46
47 func (impl *SelectImpl) Select(ctx context.Context, cs *v1alpha1.ContainerSelector) ([]*Container, error) {
48 pods, err := pod.SelectAndFilterPods(ctx, impl.c, impl.r, &cs.PodSelector, impl.ClusterScoped, impl.TargetNamespace, impl.EnableFilterNamespace)
49 if err != nil {
50 return nil, err
51 }
52
53 containerNameMap := make(map[string]struct{})
54 for _, name := range cs.ContainerNames {
55 containerNameMap[name] = struct{}{}
56 }
57
58 var result []*Container
59 for _, pod := range pods {
60 if len(cs.ContainerNames) == 0 {
61 result = append(result, &Container{
62 Pod: pod,
63 ContainerName: pod.Spec.Containers[0].Name,
64 })
65 continue
66 }
67
68 for _, container := range pod.Spec.Containers {
69 if _, ok := containerNameMap[container.Name]; ok {
70 result = append(result, &Container{
71 Pod: pod,
72 ContainerName: container.Name,
73 })
74 }
75 }
76 }
77
78 return result, nil
79 }
80
81 type Params struct {
82 fx.In
83
84 Client client.Client
85 Reader client.Reader `name:"no-cache"`
86 }
87
88 func New(params Params) *SelectImpl {
89 return &SelectImpl{
90 params.Client,
91 params.Reader,
92 generic.Option{
93 ClusterScoped: config.ControllerCfg.ClusterScoped,
94 TargetNamespace: config.ControllerCfg.TargetNamespace,
95 EnableFilterNamespace: config.ControllerCfg.EnableFilterNamespace,
96 },
97 }
98 }
99