2020-01-09 11:47:38 +00:00
|
|
|
/*
|
2022-07-04 16:53:02 +00:00
|
|
|
Copyright 2022 DigitalOcean
|
2020-01-09 11:47:38 +00:00
|
|
|
|
|
|
|
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 kube
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-09-19 13:47:35 +00:00
|
|
|
|
2020-01-22 10:24:44 +00:00
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
|
|
"k8s.io/apimachinery/pkg/fields"
|
2020-01-09 11:47:38 +00:00
|
|
|
)
|
2020-05-26 21:03:14 +00:00
|
|
|
|
2020-01-20 05:34:13 +00:00
|
|
|
// ObjectFilter stores k8s object's fields that needs to be included or excluded while running checks
|
|
|
|
type ObjectFilter struct {
|
2020-01-22 10:24:44 +00:00
|
|
|
IncludeNamespace string
|
|
|
|
ExcludeNamespace string
|
2020-01-09 11:47:38 +00:00
|
|
|
}
|
|
|
|
|
2020-01-20 05:34:13 +00:00
|
|
|
// NewObjectFilter is a constructor to initialize an instance of ObjectFilter
|
2020-01-22 10:24:44 +00:00
|
|
|
func NewObjectFilter(includeNamespace, excludeNamespace string) (ObjectFilter, error) {
|
|
|
|
if len(includeNamespace) > 0 && len(excludeNamespace) > 0 {
|
2020-01-20 05:34:13 +00:00
|
|
|
return ObjectFilter{}, fmt.Errorf("cannot specify both include and exclude namespace conditions")
|
2020-01-09 11:47:38 +00:00
|
|
|
}
|
2020-01-20 05:34:13 +00:00
|
|
|
return ObjectFilter{
|
2020-01-22 10:24:44 +00:00
|
|
|
IncludeNamespace: includeNamespace,
|
|
|
|
ExcludeNamespace: excludeNamespace,
|
2020-01-09 11:47:38 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-01-22 10:24:44 +00:00
|
|
|
// NamespaceOptions returns ListOptions for filtering by namespace
|
|
|
|
func (f ObjectFilter) NamespaceOptions(opts metav1.ListOptions) metav1.ListOptions {
|
|
|
|
if len(f.IncludeNamespace) > 0 {
|
2020-05-26 21:03:14 +00:00
|
|
|
opts.FieldSelector = fields.OneTermEqualSelector("metadata.namespace", f.IncludeNamespace).String()
|
2020-01-09 11:47:38 +00:00
|
|
|
}
|
2020-01-22 10:24:44 +00:00
|
|
|
if len(f.ExcludeNamespace) > 0 {
|
2020-05-26 21:03:14 +00:00
|
|
|
opts.FieldSelector = fields.OneTermNotEqualSelector("metadata.namespace", f.ExcludeNamespace).String()
|
2020-01-09 11:47:38 +00:00
|
|
|
}
|
2020-01-22 10:24:44 +00:00
|
|
|
return opts
|
2020-05-26 21:03:14 +00:00
|
|
|
}
|