Skip to content

Commit 22f6002

Browse files
authoredOct 14, 2021
Add conditions.Factory (#58)
The conditions.NewCondition function reads cluster state to determine the namespace the operator is running in so that it can manipulate the correct OperatorConditions object in a cluster. However this function's dependency on a specific file existing in a specific location makes it difficult to test code that uses it. The Factory interface is introduced to enable users to provide their own implementations for building a Condition object to manage OperatorCondition resources. Users can now build a factory and inject it into code that builds new conditions. This enables code under test to use the Factory abstraction and enables operator authors to inject custom functionality needed when writing tests. Signed-off-by: Joe Lanford <joe.lanford@gmail.com>
1 parent 27f57aa commit 22f6002

File tree

5 files changed

+265
-139
lines changed

5 files changed

+265
-139
lines changed
 

‎conditions/conditions.go

+5-53
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,17 @@ package conditions
1717
import (
1818
"context"
1919
"fmt"
20-
"os"
2120

2221
apiv2 "github.com/operator-framework/api/pkg/operators/v2"
23-
"github.com/operator-framework/operator-lib/internal/utils"
2422
"k8s.io/apimachinery/pkg/api/meta"
2523
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2624
"k8s.io/apimachinery/pkg/types"
2725
"sigs.k8s.io/controller-runtime/pkg/client"
2826
)
2927

3028
var (
31-
// readNamespace gets the namespacedName of the operator.
32-
readNamespace = utils.GetOperatorNamespace
33-
)
34-
35-
const (
36-
// operatorCondEnvVar is the env variable which
37-
// contains the name of the Condition CR associated to the operator,
38-
// set by OLM.
39-
operatorCondEnvVar = "OPERATOR_CONDITION_NAME"
29+
// ErrNoOperatorCondition indicates that the operator condition CRD is nil
30+
ErrNoOperatorCondition = fmt.Errorf("operator Condition CRD is nil")
4031
)
4132

4233
// condition is a Condition that gets and sets a specific
@@ -49,21 +40,6 @@ type condition struct {
4940

5041
var _ Condition = &condition{}
5142

52-
// NewCondition returns a new Condition interface using the provided client
53-
// for the specified conditionType. The condition will internally fetch the namespacedName
54-
// of the operatorConditionCRD.
55-
func NewCondition(cl client.Client, condType apiv2.ConditionType) (Condition, error) {
56-
objKey, err := GetNamespacedName()
57-
if err != nil {
58-
return nil, err
59-
}
60-
return &condition{
61-
namespacedName: *objKey,
62-
condType: condType,
63-
client: cl,
64-
}, nil
65-
}
66-
6743
// Get implements conditions.Get
6844
func (c *condition) Get(ctx context.Context) (*metav1.Condition, error) {
6945
operatorCond := &apiv2.OperatorCondition{}
@@ -92,33 +68,9 @@ func (c *condition) Set(ctx context.Context, status metav1.ConditionStatus, opti
9268
Status: status,
9369
}
9470

95-
if len(option) != 0 {
96-
for _, opt := range option {
97-
opt(newCond)
98-
}
71+
for _, opt := range option {
72+
opt(newCond)
9973
}
10074
meta.SetStatusCondition(&operatorCond.Spec.Conditions, *newCond)
101-
err = c.client.Update(ctx, operatorCond)
102-
if err != nil {
103-
return err
104-
}
105-
return nil
106-
}
107-
108-
// GetNamespacedName returns the NamespacedName of the CR. It returns an error
109-
// when the name of the CR cannot be found from the environment variable set by
110-
// OLM. Hence, GetNamespacedName() can provide the NamespacedName when the operator
111-
// is running on cluster and is being managed by OLM. If running locally, operator
112-
// writers are encouraged to skip this method or gracefully handle the errors by logging
113-
// a message.
114-
func GetNamespacedName() (*types.NamespacedName, error) {
115-
conditionName := os.Getenv(operatorCondEnvVar)
116-
if conditionName == "" {
117-
return nil, fmt.Errorf("could not determine operator condition name: environment variable %s not set", operatorCondEnvVar)
118-
}
119-
operatorNs, err := readNamespace()
120-
if err != nil {
121-
return nil, fmt.Errorf("could not determine operator namespace: %v", err)
122-
}
123-
return &types.NamespacedName{Name: conditionName, Namespace: operatorNs}, nil
75+
return c.client.Update(ctx, operatorCond)
12476
}

‎conditions/conditions_test.go

+1-85
Original file line numberDiff line numberDiff line change
@@ -32,48 +32,12 @@ import (
3232
"sigs.k8s.io/controller-runtime/pkg/client/fake"
3333
)
3434

35-
const (
36-
conditionFoo apiv2.ConditionType = "conditionFoo"
37-
conditionBar apiv2.ConditionType = "conditionBar"
38-
)
39-
4035
var _ = Describe("Condition", func() {
4136
var ns = "default"
4237
ctx := context.TODO()
4338
var clock kubeclock.Clock = &kubeclock.RealClock{}
44-
var transitionTime metav1.Time = metav1.Time{Time: clock.Now()}
39+
var transitionTime = metav1.Time{Time: clock.Now()}
4540
var cl client.Client
46-
var err error
47-
48-
BeforeEach(func() {
49-
sch := runtime.NewScheme()
50-
err = apiv2.AddToScheme(sch)
51-
Expect(err).NotTo(HaveOccurred())
52-
cl = fake.NewClientBuilder().WithScheme(sch).Build()
53-
})
54-
55-
Describe("NewCondition", func() {
56-
It("should create a new condition", func() {
57-
err := os.Setenv(operatorCondEnvVar, "test-operator-condition")
58-
Expect(err).NotTo(HaveOccurred())
59-
readNamespace = func() (string, error) {
60-
return ns, nil
61-
}
62-
63-
c, err := NewCondition(cl, conditionFoo)
64-
Expect(err).NotTo(HaveOccurred())
65-
Expect(c).NotTo(BeNil())
66-
})
67-
68-
It("should error when namespacedName cannot be found", func() {
69-
err := os.Unsetenv(operatorCondEnvVar)
70-
Expect(err).NotTo(HaveOccurred())
71-
72-
c, err := NewCondition(cl, conditionFoo)
73-
Expect(err).To(HaveOccurred())
74-
Expect(c).To(BeNil())
75-
})
76-
})
7741

7842
Describe("Get/Set", func() {
7943
var operatorCond *apiv2.OperatorCondition
@@ -160,7 +124,6 @@ var _ = Describe("Condition", func() {
160124
Expect(apierrors.IsNotFound(err)).To(BeTrue())
161125
Expect(con).To(BeNil())
162126
})
163-
164127
})
165128

166129
Context("Set", func() {
@@ -211,53 +174,6 @@ var _ = Describe("Condition", func() {
211174
Expect(err).To(HaveOccurred())
212175
Expect(apierrors.IsNotFound(err)).To(BeTrue())
213176
})
214-
215-
})
216-
217-
})
218-
219-
Describe("GetNamespacedName", func() {
220-
It("should error when name of the operator condition cannot be found", func() {
221-
err := os.Unsetenv(operatorCondEnvVar)
222-
Expect(err).NotTo(HaveOccurred())
223-
224-
objKey, err := GetNamespacedName()
225-
Expect(err).To(HaveOccurred())
226-
Expect(objKey).To(BeNil())
227-
Expect(err.Error()).To(ContainSubstring("could not determine operator condition name"))
228-
})
229-
230-
It("should error when object namespace cannot be found", func() {
231-
err := os.Setenv(operatorCondEnvVar, "test")
232-
Expect(err).NotTo(HaveOccurred())
233-
234-
readNamespace = func() (string, error) {
235-
return "", os.ErrNotExist
236-
}
237-
238-
objKey, err := GetNamespacedName()
239-
Expect(err).To(HaveOccurred())
240-
Expect(objKey).To(BeNil())
241-
Expect(err.Error()).To(ContainSubstring("could not determine operator namespace"))
242-
})
243-
244-
It("should return the right namespaced name from SA namespace file", func() {
245-
err := os.Setenv(operatorCondEnvVar, "test")
246-
Expect(err).NotTo(HaveOccurred())
247-
248-
readNamespace = func() (string, error) {
249-
return "testns", nil
250-
}
251-
objKey, err := GetNamespacedName()
252-
Expect(err).NotTo(HaveOccurred())
253-
Expect(objKey).NotTo(BeNil())
254-
Expect(objKey.Name).To(BeEquivalentTo("test"))
255-
Expect(objKey.Namespace).To(BeEquivalentTo("testns"))
256177
})
257178
})
258179
})
259-
260-
func deleteCondition(ctx context.Context, client client.Client, obj client.Object) {
261-
err := client.Delete(ctx, obj)
262-
Expect(err).NotTo(HaveOccurred())
263-
}

‎conditions/factory.go

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Copyright 2021 The Operator-SDK Authors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package conditions
16+
17+
import (
18+
"fmt"
19+
"os"
20+
21+
apiv2 "github.com/operator-framework/api/pkg/operators/v2"
22+
"k8s.io/apimachinery/pkg/types"
23+
"sigs.k8s.io/controller-runtime/pkg/client"
24+
25+
"github.com/operator-framework/operator-lib/internal/utils"
26+
)
27+
28+
// Factory define the interface for building Conditions.
29+
type Factory interface {
30+
NewCondition(apiv2.ConditionType) (Condition, error)
31+
GetNamespacedName() (*types.NamespacedName, error)
32+
}
33+
34+
// InClusterFactory is a conditions factory that can build conditions and get
35+
// the namespaced name of the operator's condition based on an in-cluster
36+
// configuration.
37+
type InClusterFactory struct {
38+
Client client.Client
39+
}
40+
41+
// NewCondition creates a new Condition using the provided client and condition
42+
// type. The condition's name and namespace are determined by the Factory's GetName
43+
// and GetNamespace functions.
44+
func (f InClusterFactory) NewCondition(condType apiv2.ConditionType) (Condition, error) {
45+
objKey, err := f.GetNamespacedName()
46+
if err != nil {
47+
return nil, err
48+
}
49+
return &condition{
50+
namespacedName: *objKey,
51+
condType: condType,
52+
client: f.Client,
53+
}, nil
54+
}
55+
56+
// GetNamespacedName returns the NamespacedName of the CR. It returns an error
57+
// when the name of the CR cannot be found from the environment variable set by
58+
// OLM. Hence, GetNamespacedName() can provide the NamespacedName when the operator
59+
// is running on cluster and is being managed by OLM.
60+
func (f InClusterFactory) GetNamespacedName() (*types.NamespacedName, error) {
61+
conditionName, err := f.getConditionName()
62+
if err != nil {
63+
return nil, fmt.Errorf("get operator condition name: %v", err)
64+
}
65+
conditionNamespace, err := f.getConditionNamespace()
66+
if err != nil {
67+
return nil, fmt.Errorf("get operator condition namespace: %v", err)
68+
}
69+
70+
return &types.NamespacedName{Name: conditionName, Namespace: conditionNamespace}, nil
71+
}
72+
73+
const (
74+
// operatorCondEnvVar is the env variable which
75+
// contains the name of the Condition CR associated to the operator,
76+
// set by OLM.
77+
operatorCondEnvVar = "OPERATOR_CONDITION_NAME"
78+
)
79+
80+
// getConditionName reads and returns the OPERATOR_CONDITION_NAME environment
81+
// variable. If the variable is unset or empty, it returns an error.
82+
func (f InClusterFactory) getConditionName() (string, error) {
83+
name := os.Getenv(operatorCondEnvVar)
84+
if name == "" {
85+
return "", fmt.Errorf("could not determine operator condition name: environment variable %s not set", operatorCondEnvVar)
86+
}
87+
return name, nil
88+
}
89+
90+
// readNamespace gets the namespacedName of the operator.
91+
var readNamespace = utils.GetOperatorNamespace
92+
93+
// getConditionNamespace reads the namespace file mounted into a pod in a
94+
// cluster via its service account volume. If the file is not found or cannot be
95+
// read, this function returns an error.
96+
func (f InClusterFactory) getConditionNamespace() (string, error) {
97+
return readNamespace()
98+
}
99+
100+
// NewCondition returns a new Condition interface using the provided client
101+
// for the specified conditionType. The condition will internally fetch the namespacedName
102+
// of the operatorConditionCRD.
103+
//
104+
// Deprecated: Use InClusterFactory{cl}.NewCondition() instead.
105+
func NewCondition(cl client.Client, condType apiv2.ConditionType) (Condition, error) {
106+
return InClusterFactory{cl}.NewCondition(condType)
107+
}
108+
109+
// GetNamespacedName returns the NamespacedName of the CR. It returns an error
110+
// when the name of the CR cannot be found from the environment variable set by
111+
// OLM. Hence, GetNamespacedName() can provide the NamespacedName when the operator
112+
// is running on cluster and is being managed by OLM. If running locally, operator
113+
// writers are encouraged to skip this method or gracefully handle the errors by logging
114+
// a message.
115+
//
116+
// Deprecated: InClusterFactory{}.GetNamespacedName().
117+
func GetNamespacedName() (*types.NamespacedName, error) {
118+
return InClusterFactory{}.GetNamespacedName()
119+
}

‎conditions/factory_test.go

+140
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// Copyright 2021 The Operator-SDK Authors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package conditions
16+
17+
import (
18+
"context"
19+
"os"
20+
21+
. "github.com/onsi/ginkgo"
22+
. "github.com/onsi/gomega"
23+
apiv2 "github.com/operator-framework/api/pkg/operators/v2"
24+
"k8s.io/apimachinery/pkg/runtime"
25+
"k8s.io/apimachinery/pkg/types"
26+
"sigs.k8s.io/controller-runtime/pkg/client"
27+
"sigs.k8s.io/controller-runtime/pkg/client/fake"
28+
)
29+
30+
const (
31+
conditionFoo apiv2.ConditionType = "conditionFoo"
32+
conditionBar apiv2.ConditionType = "conditionBar"
33+
)
34+
35+
var _ = Describe("NewCondition", func() {
36+
var cl client.Client
37+
BeforeEach(func() {
38+
sch := runtime.NewScheme()
39+
err := apiv2.AddToScheme(sch)
40+
Expect(err).NotTo(HaveOccurred())
41+
cl = fake.NewClientBuilder().WithScheme(sch).Build()
42+
})
43+
44+
testNewCondition(func(ct apiv2.ConditionType) (Condition, error) {
45+
return NewCondition(cl, ct)
46+
})
47+
})
48+
49+
var _ = Describe("GetNamespacedName", func() {
50+
testGetNamespacedName(GetNamespacedName)
51+
})
52+
53+
var _ = Describe("InClusterFactory", func() {
54+
var cl client.Client
55+
var f InClusterFactory
56+
57+
BeforeEach(func() {
58+
sch := runtime.NewScheme()
59+
err := apiv2.AddToScheme(sch)
60+
Expect(err).NotTo(HaveOccurred())
61+
cl = fake.NewClientBuilder().WithScheme(sch).Build()
62+
f = InClusterFactory{cl}
63+
})
64+
65+
Describe("NewCondition", func() {
66+
testNewCondition(f.NewCondition)
67+
})
68+
69+
Describe("GetNamespacedName", func() {
70+
testGetNamespacedName(f.GetNamespacedName)
71+
})
72+
})
73+
74+
func testNewCondition(fn func(apiv2.ConditionType) (Condition, error)) {
75+
It("should create a new condition", func() {
76+
err := os.Setenv(operatorCondEnvVar, "test-operator-condition")
77+
Expect(err).NotTo(HaveOccurred())
78+
readNamespace = func() (string, error) {
79+
return "default", nil
80+
}
81+
82+
c, err := fn(conditionFoo)
83+
Expect(err).NotTo(HaveOccurred())
84+
Expect(c).NotTo(BeNil())
85+
})
86+
87+
It("should error when namespacedName cannot be found", func() {
88+
err := os.Unsetenv(operatorCondEnvVar)
89+
Expect(err).NotTo(HaveOccurred())
90+
91+
c, err := fn(conditionFoo)
92+
Expect(err).To(HaveOccurred())
93+
Expect(c).To(BeNil())
94+
})
95+
}
96+
97+
func testGetNamespacedName(fn func() (*types.NamespacedName, error)) {
98+
It("should error when name of the operator condition cannot be found", func() {
99+
err := os.Unsetenv(operatorCondEnvVar)
100+
Expect(err).NotTo(HaveOccurred())
101+
102+
objKey, err := fn()
103+
Expect(err).To(HaveOccurred())
104+
Expect(objKey).To(BeNil())
105+
Expect(err.Error()).To(ContainSubstring("could not determine operator condition name"))
106+
})
107+
108+
It("should error when object namespace cannot be found", func() {
109+
err := os.Setenv(operatorCondEnvVar, "test")
110+
Expect(err).NotTo(HaveOccurred())
111+
112+
readNamespace = func() (string, error) {
113+
return "", os.ErrNotExist
114+
}
115+
116+
objKey, err := fn()
117+
Expect(err).To(HaveOccurred())
118+
Expect(objKey).To(BeNil())
119+
Expect(err.Error()).To(ContainSubstring("get operator condition namespace: file does not exist"))
120+
})
121+
122+
It("should return the right namespaced name from SA namespace file", func() {
123+
err := os.Setenv(operatorCondEnvVar, "test")
124+
Expect(err).NotTo(HaveOccurred())
125+
126+
readNamespace = func() (string, error) {
127+
return "testns", nil
128+
}
129+
objKey, err := fn()
130+
Expect(err).NotTo(HaveOccurred())
131+
Expect(objKey).NotTo(BeNil())
132+
Expect(objKey.Name).To(BeEquivalentTo("test"))
133+
Expect(objKey.Namespace).To(BeEquivalentTo("testns"))
134+
})
135+
}
136+
137+
func deleteCondition(ctx context.Context, client client.Client, obj client.Object) {
138+
err := client.Delete(ctx, obj)
139+
Expect(err).NotTo(HaveOccurred())
140+
}

‎go.sum

-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb0
3636
github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c=
3737
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
3838
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
39-
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
4039
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
4140
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
4241
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=

0 commit comments

Comments
 (0)
Please sign in to comment.