/
namespace_validator.go
45 lines (40 loc) · 1.19 KB
/
namespace_validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cmd
import (
"fmt"
core "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
clientcore "k8s.io/client-go/kubernetes/typed/core/v1"
)
// NamespaceValidator wraps the Validate method.
//
// Validate checks whether the given namespace exists or not.
// Returns nil if it exists, an error otherwise.
type NamespaceValidator interface {
Validate(name string) error
}
type namespaceValidator struct {
client clientcore.NamespaceInterface
}
// NewNamespaceValidator constructs the default NamespaceValidator.
func NewNamespaceValidator(client clientcore.NamespaceInterface) NamespaceValidator {
return &namespaceValidator{
client: client,
}
}
func (w *namespaceValidator) Validate(name string) error {
if name != core.NamespaceAll {
ns, err := w.client.Get(name, meta.GetOptions{})
if err != nil {
if statusErr, ok := err.(*errors.StatusError); ok &&
statusErr.Status().Reason == meta.StatusReasonNotFound {
return fmt.Errorf("\"%s\" not found", name)
}
return fmt.Errorf("getting namespace: %v", err)
}
if ns.Status.Phase != core.NamespaceActive {
return fmt.Errorf("invalid status: %v", ns.Status.Phase)
}
}
return nil
}