...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package namespace
17
18 import (
19 "context"
20
21 "github.com/go-logr/logr"
22 "github.com/pkg/errors"
23 v1 "k8s.io/api/core/v1"
24 "k8s.io/apimachinery/pkg/types"
25 "sigs.k8s.io/controller-runtime/pkg/client"
26
27 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
28 "github.com/chaos-mesh/chaos-mesh/pkg/selector/generic"
29 )
30
31 const Name = "namespace"
32
33 type namespaceSelector struct {
34 generic.Option
35 namespaces []string
36 }
37
38 var _ generic.Selector = &namespaceSelector{}
39
40 func (s *namespaceSelector) ListOption() client.ListOption {
41 if !s.ClusterScoped {
42 return client.InNamespace(s.TargetNamespace)
43 }
44 return nil
45 }
46
47 func (s *namespaceSelector) ListFunc(_ client.Reader) generic.ListFunc {
48 return nil
49 }
50
51 func (s *namespaceSelector) Match(obj client.Object) bool {
52 if len(s.namespaces) == 0 {
53 return true
54 }
55
56 for _, namespace := range s.namespaces {
57 if namespace == obj.GetNamespace() {
58 return true
59 }
60 }
61 return false
62 }
63
64 func New(spec v1alpha1.GenericSelectorSpec, option generic.Option) (generic.Selector, error) {
65 if !option.ClusterScoped {
66 if len(spec.Namespaces) > 1 {
67 return nil, errors.New("could NOT use more than 1 namespace selector within namespace scoped mode")
68 } else if len(spec.Namespaces) == 1 {
69 if spec.Namespaces[0] != option.TargetNamespace {
70 return nil, errors.Errorf("could NOT list pods from out of scoped namespace: %s", spec.Namespaces[0])
71 }
72 }
73 }
74
75 return &namespaceSelector{
76 Option: generic.Option{
77 ClusterScoped: option.ClusterScoped,
78 TargetNamespace: option.TargetNamespace,
79 EnableFilterNamespace: option.EnableFilterNamespace,
80 },
81 namespaces: spec.Namespaces,
82 }, nil
83 }
84
85 func CheckNamespace(ctx context.Context, c client.Client, namespace string, logger logr.Logger) bool {
86 ok, err := IsAllowedNamespaces(ctx, c, namespace)
87 if err != nil {
88 logger.Error(err, "fail to check whether this namespace is allowed", "namespace", namespace)
89 return false
90 }
91
92 if !ok {
93 logger.Info("namespace is not enabled for chaos-mesh", "namespace", namespace)
94 }
95 return ok
96 }
97
98 func IsAllowedNamespaces(ctx context.Context, c client.Client, namespace string) (bool, error) {
99 ns := &v1.Namespace{}
100
101 err := c.Get(ctx, types.NamespacedName{Name: namespace}, ns)
102 if err != nil {
103 return false, err
104 }
105
106 if ns.Annotations[generic.InjectAnnotationKey] == "enabled" {
107 return true, nil
108 }
109
110 return false, nil
111 }
112