feat(analytics): adding google analytics for ZFSPV

Whenever a volume is provisioned and de-provisioned we will send a google event with mainly following details :
1.    pvName (will shown as app title in google analytics)
2.    size of the volume
3.    event type : volume-provision, volume-deprovision
4.    storage type zfs-localpv
5.    replicacount as 1
6.    ClientId as default namespace uuid

Apart from this, we send the event once in 24 hr, which will have some info like number of nodes, node type, kubernetes version etc.

This metric is cotrolled by OPENEBS_IO_ENABLE_ANALYTICS env. We can set it to false if we don't want to send the metrics.

Signed-off-by: Pawan <pawan@mayadata.io>
This commit is contained in:
Pawan 2020-02-26 11:31:24 +05:30 committed by Kiran Mova
parent 0fc86d843b
commit d608dbacd8
28 changed files with 1731 additions and 18 deletions

View file

@ -0,0 +1,43 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
"k8s.io/client-go/kubernetes"
)
// ClientsetGetter abstracts fetching of kubernetes clientset
type ClientsetGetter interface {
Get() (*kubernetes.Clientset, error)
}
type clientset struct{}
// Clientset returns a pointer to clientset struct
func Clientset() *clientset {
return &clientset{}
}
// Get returns a new instance of kubernetes clientset
func (c *clientset) Get() (*kubernetes.Clientset, error) {
config, err := Config().Get()
if err != nil {
return nil, errors.Wrap(err, "failed to get kubernetes clientset")
}
return kubernetes.NewForConfig(config)
}

View file

@ -0,0 +1,38 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"testing"
)
func TestClientsetGet(t *testing.T) {
tests := map[string]struct {
iserr bool
}{
"101": {true},
}
for name, mock := range tests {
t.Run(name, func(t *testing.T) {
_, err := Clientset().Get()
if !mock.iserr && err != nil {
t.Fatalf("Test '%s' failed: expected no error: actual '%s'", name, err)
}
})
}
}

View file

@ -0,0 +1,99 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/openebs/zfs-localpv/pkg/common/env"
"github.com/pkg/errors"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"strings"
)
// ConfigGetter abstracts fetching of kubernetes client config
type ConfigGetter interface {
Get() (*rest.Config, error)
Name() string
}
// configFromENV is an implementation of ConfigGetter
type configFromENV struct{}
// Name returns the name of this config getter instance
func (c *configFromENV) Name() string {
return "k8s-config-from-env"
}
// Get returns kubernetes rest config based on kubernetes environment values
func (c *configFromENV) Get() (*rest.Config, error) {
k8sMaster := env.Get(env.KubeMaster)
kubeConfig := env.Get(env.KubeConfig)
if len(strings.TrimSpace(k8sMaster)) == 0 && len(strings.TrimSpace(kubeConfig)) == 0 {
return nil, errors.New("missing kubernetes master as well as kubeconfig: failed to get kubernetes client config")
}
return clientcmd.BuildConfigFromFlags(k8sMaster, kubeConfig)
}
// configFromREST is an implementation of ConfigGetter
type configFromREST struct{}
// Name returns the name of this config getter instance
func (c *configFromREST) Name() string {
return "k8s-config-from-rest"
}
// Get returns kubernetes rest config based on in-cluster config implementation
func (c *configFromREST) Get() (*rest.Config, error) {
return rest.InClusterConfig()
}
// ConfigGetters holds a list of ConfigGetter instances
//
// NOTE:
// This is an implementation of ConfigGetter
type ConfigGetters []ConfigGetter
// Name returns the name of this config getter instance
func (c ConfigGetters) Name() string {
return "list-of-k8s-config-getter"
}
// Get fetches the kubernetes client config that is used to make kubernetes API
// calls. It makes use of its list of getter instances to fetch kubernetes
// config.
func (c ConfigGetters) Get() (config *rest.Config, err error) {
var errs []error
for _, g := range c {
config, err = g.Get()
if err == nil {
return
}
errs = append(errs, errors.Wrapf(err, "failed to get kubernetes client config via %s", g.Name()))
}
// at this point; all getters have failed
err = errors.Errorf("%+v", errs)
err = errors.Wrap(err, "failed to get kubernetes client config")
return
}
// Config provides appropriate config getter instances that help in fetching
// kubernetes client config to invoke kubernetes API calls
func Config() ConfigGetter {
return ConfigGetters{&configFromENV{}, &configFromREST{}}
}

View file

@ -0,0 +1,74 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/openebs/zfs-localpv/pkg/common/env"
"os"
"testing"
)
// test if configFromENV implements ConfigGetter interface
var _ ConfigGetter = &configFromENV{}
// test if configFromREST implements ConfigGetter interface
var _ ConfigGetter = &configFromREST{}
// test if ConfigGetters implements ConfigGetter interface
var _ ConfigGetter = ConfigGetters{}
func TestConfigFromENV(t *testing.T) {
tests := map[string]struct {
masterip string
kubeconfig string
iserr bool
}{
"101": {"", "", true},
"102": {"", "/etc/config/kubeconfig", true},
"103": {"0.0.0.0", "", false},
"104": {"0.0.0.0", "/etc/config/config", true},
}
// Sub tests is not used here as env key is set & unset to test. Since env
// is a global setting, the tests should run serially
for name, mock := range tests {
masterip := os.Getenv(string(env.KubeMaster))
defer os.Setenv(string(env.KubeMaster), masterip)
kubeconfig := os.Getenv(string(env.KubeConfig))
defer os.Setenv(string(env.KubeConfig), kubeconfig)
err := os.Setenv(string(env.KubeMaster), mock.masterip)
if err != nil {
t.Fatalf("Test '%s' failed: %s", name, err)
}
err = os.Setenv(string(env.KubeConfig), mock.kubeconfig)
if err != nil {
t.Fatalf("Test '%s' failed: %s", name, err)
}
c := &configFromENV{}
config, err := c.Get()
if !mock.iserr && config == nil {
t.Fatalf("Test '%s' failed: expected config: actual nil config", name)
}
if !mock.iserr && err != nil {
t.Fatalf("Test '%s' failed: expected no error: actual %s", name, err)
}
}
}

View file

@ -0,0 +1,52 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strings"
)
// ConfigMapGetter abstracts fetching of ConfigMap instance from kubernetes
// cluster
type ConfigMapGetter interface {
Get(options metav1.GetOptions) (*corev1.ConfigMap, error)
}
type configmap struct {
namespace string // namespace where this configmap exists
name string // name of this configmap
}
// ConfigMap returns a new instance of configmap
func ConfigMap(namespace, name string) *configmap {
return &configmap{namespace: namespace, name: name}
}
// Get returns configmap instance from kubernetes cluster
func (c *configmap) Get(options metav1.GetOptions) (cm *corev1.ConfigMap, err error) {
if len(strings.TrimSpace(c.name)) == 0 {
return nil, errors.Errorf("missing config map name: failed to get config map from namespace %s", c.namespace)
}
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get config map %s %s", c.namespace, c.name)
}
return cs.CoreV1().ConfigMaps(c.namespace).Get(c.name, options)
}

View file

@ -0,0 +1,47 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"testing"
)
// test if configmap implements ConfigMapGetter interface
var _ ConfigMapGetter = &configmap{}
func TestConfigMapGet(t *testing.T) {
tests := map[string]struct {
namespace string
name string
options metav1.GetOptions
iserr bool
}{
"101": {"", "", metav1.GetOptions{}, true},
"102": {"default", "", metav1.GetOptions{}, true},
"103": {"default", "myconf", metav1.GetOptions{}, true},
}
for name, mock := range tests {
t.Run(name, func(t *testing.T) {
_, err := ConfigMap(mock.namespace, mock.name).Get(mock.options)
if !mock.iserr && err != nil {
t.Fatalf("Test '%s' failed: expected no error: actual '%s'", name, err)
}
})
}
}

View file

@ -0,0 +1,44 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
k8sdynamic "k8s.io/client-go/dynamic"
)
// DynamicProvider abstracts providing kubernetes dynamic client interface
type DynamicProvider interface {
Provide() (k8sdynamic.Interface, error)
}
type dynamic struct{}
// Dynamic returns a new instance of dynamic
func Dynamic() *dynamic {
return &dynamic{}
}
// Provide provides a kubernetes dynamic client capable of invoking operations
// against kubernetes resources
func (d *dynamic) Provide() (k8sdynamic.Interface, error) {
config, err := Config().Get()
if err != nil {
return nil, errors.Wrap(err, "failed to provide dynamic client")
}
return k8sdynamic.NewForConfig(config)
}

View file

@ -0,0 +1,41 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"testing"
)
// test if dynamic implements DynamicProvider interface
var _ DynamicProvider = &dynamic{}
func TestDynamicProvider(t *testing.T) {
tests := map[string]struct {
iserr bool
}{
"101": {true},
}
for name, mock := range tests {
t.Run(name, func(t *testing.T) {
_, err := Dynamic().Provide()
if !mock.iserr && err != nil {
t.Fatalf("Test '%s' failed: expected no error: actual '%s'", name, err)
}
})
}
}

View file

@ -0,0 +1,32 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/version"
)
// GetServerVersion uses the client-go Discovery client to get the
// kubernetes version struct
func GetServerVersion() (*version.Info, error) {
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get apiserver version")
}
return cs.Discovery().ServerVersion()
}

View file

@ -0,0 +1,59 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Namespacegetter abstracts fetching of Namespace from kubernetes cluster
type NamespaceGetter interface {
Get(name string, options metav1.GetOptions) (*corev1.Namespace, error)
}
// NamespaceLister abstracts fetching of a list of namespaces from kubernetes cluster
type NamespaceLister interface {
List(options metav1.ListOptions) (*corev1.NamespaceList, error)
}
type namespace struct{}
// Namespace returns a pointer to the namespace struct
func Namespace() *namespace {
return &namespace{}
}
// Get returns a namespace instance from kubernetes cluster
func (ns *namespace) Get(name string, options metav1.GetOptions) (*corev1.Namespace, error) {
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get namespace: %s", name)
} else {
return cs.CoreV1().Namespaces().Get(name, options)
}
}
// List returns a slice of namespaces defined in a Kubernetes cluster
func (ns *namespace) List(options metav1.ListOptions) (*corev1.NamespaceList, error) {
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get namespaces")
} else {
return cs.CoreV1().Namespaces().List(options)
}
}

View file

@ -0,0 +1,81 @@
/*
Copyright 2020 The OpenEBS Authors
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 v1alpha1
import (
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// NodeGetter abstracts fetching of Node details from kubernetes cluster
type NodeGetter interface {
Get(name string, options metav1.GetOptions) (*corev1.Node, error)
}
// NodeLister abstracts fetching of Nodes from kubernetes cluster
type NodeLister interface {
List(options metav1.ListOptions) (*corev1.NodeList, error)
}
type node struct{}
func Node() *node {
return &node{}
}
// Get returns a node instance from kubernetes cluster
func (n *node) Get(name string, options metav1.GetOptions) (*corev1.Node, error) {
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get node: %s", name)
} else {
return cs.CoreV1().Nodes().Get(name, options)
}
}
// List returns a slice of Nodes registered in a Kubernetes cluster
func (n *node) List(options metav1.ListOptions) (*corev1.NodeList, error) {
cs, err := Clientset().Get()
if err != nil {
return nil, errors.Wrapf(err, "failed to get nodes")
} else {
return cs.CoreV1().Nodes().List(options)
}
}
// NumberOfNodes returns the number of nodes registered in a Kubernetes cluster
func NumberOfNodes() (int, error) {
n := Node()
nodes, err := n.List(metav1.ListOptions{})
if err != nil {
return 0, errors.Wrapf(err, "failed to get the number of nodes")
} else {
return len(nodes.Items), nil
}
}
// GetOSAndKernelVersion gets us the OS,Kernel version
func GetOSAndKernelVersion() (string, error) {
nodes := Node()
// get a single node
firstNode, err := nodes.List(metav1.ListOptions{Limit: 1})
if err != nil {
return "unknown, unknown", errors.Wrapf(err, "failed to get the os kernel/arch")
}
nodedetails := firstNode.Items[0].Status.NodeInfo
return nodedetails.OSImage + ", " + nodedetails.KernelVersion, nil
}

View file

@ -0,0 +1,361 @@
/*
Copyright 2020 The OpenEBS Authors
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.
*/
// TODO
// Move this file to pkg/k8sresource/v1alpha1
package v1alpha1
import (
"fmt"
"strings"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/klog"
)
// ResourceCreator abstracts creating an unstructured instance in kubernetes
// cluster
type ResourceCreator interface {
Create(obj *unstructured.Unstructured, subresources ...string) (*unstructured.Unstructured, error)
}
// ResourceGetter abstracts fetching an unstructured instance from kubernetes
// cluster
type ResourceGetter interface {
Get(name string, options metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error)
}
// ResourceLister abstracts fetching an unstructured list of instance from kubernetes
// cluster
type ResourceLister interface {
List(options metav1.ListOptions) (*unstructured.UnstructuredList, error)
}
// ResourceUpdater abstracts updating an unstructured instance found in
// kubernetes cluster
type ResourceUpdater interface {
Update(oldobj, newobj *unstructured.Unstructured, subresources ...string) (u *unstructured.Unstructured, err error)
}
// ResourceApplier abstracts applying an unstructured instance that may or may
// not be available in kubernetes cluster
type ResourceApplier interface {
Apply(obj *unstructured.Unstructured, subresources ...string) (*unstructured.Unstructured, error)
}
// ResourceDeleter abstracts deletes an unstructured instance that is available in kubernetes cluster
type ResourceDeleter interface {
Delete(obj *unstructured.Unstructured, subresources ...string) error
}
type resource struct {
gvr schema.GroupVersionResource // identify a resource
namespace string // namespace where this resource is to be operated at
}
// String implements Stringer interface
func (r *resource) String() string {
return r.gvr.String()
}
// Resource returns a new resource instance
func Resource(gvr schema.GroupVersionResource, namespace string) *resource {
return &resource{gvr: gvr, namespace: namespace}
}
// Create creates a new resource in kubernetes cluster
func (r *resource) Create(obj *unstructured.Unstructured, subresources ...string) (u *unstructured.Unstructured, err error) {
if obj == nil {
err = errors.Errorf("nil resource instance: failed to create resource '%s' at '%s'", r.gvr, r.namespace)
return
}
dynamic, err := Dynamic().Provide()
if err != nil {
err = errors.Wrapf(err, "failed to create resource '%s' '%s' at '%s'", r.gvr, obj.GetName(), r.namespace)
return
}
u, err = dynamic.Resource(r.gvr).Namespace(r.namespace).Create(obj, metav1.CreateOptions{}, subresources...)
if err != nil {
err = errors.Wrapf(err, "failed to create resource '%s' '%s' at '%s'", r.gvr, obj.GetName(), r.namespace)
return
}
return
}
// Delete deletes a existing resource in kubernetes cluster
func (r *resource) Delete(obj *unstructured.Unstructured, subresources ...string) error {
if obj == nil {
return errors.Errorf("nil resource instance: failed to delete resource '%s' at '%s'", r.gvr, r.namespace)
}
dynamic, err := Dynamic().Provide()
if err != nil {
return errors.Wrapf(err, "failed to delete resource '%s' '%s' at '%s'", r.gvr, obj.GetName(), r.namespace)
}
err = dynamic.Resource(r.gvr).Namespace(r.namespace).Delete(obj.GetName(), &metav1.DeleteOptions{})
if err != nil {
return errors.Wrapf(err, "failed to delete resource '%s' '%s' at '%s'", r.gvr, obj.GetName(), r.namespace)
}
return nil
}
// Get returns a specific resource from kubernetes cluster
func (r *resource) Get(name string, opts metav1.GetOptions, subresources ...string) (u *unstructured.Unstructured, err error) {
if len(strings.TrimSpace(name)) == 0 {
err = errors.Errorf("missing resource name: failed to get resource '%s' at '%s'", r.gvr, r.namespace)
return
}
dynamic, err := Dynamic().Provide()
if err != nil {
err = errors.Wrapf(err, "failed to get resource '%s' '%s' at '%s'", r.gvr, name, r.namespace)
return
}
u, err = dynamic.Resource(r.gvr).Namespace(r.namespace).Get(name, opts, subresources...)
if err != nil {
err = errors.Wrapf(err, "failed to get resource '%s' '%s' at '%s'", r.gvr, name, r.namespace)
return
}
return
}
// Update updates the resource at kubernetes cluster
func (r *resource) Update(oldobj, newobj *unstructured.Unstructured, subresources ...string) (u *unstructured.Unstructured, err error) {
if oldobj == nil {
err = errors.Errorf("nil old resource instance: failed to update resource '%s' at '%s'", r.gvr, r.namespace)
return
}
if newobj == nil {
err = errors.Errorf("nil new resource instance: failed to update resource '%s' at '%s'", r.gvr, r.namespace)
return
}
dynamic, err := Dynamic().Provide()
if err != nil {
err = errors.Wrapf(err, "failed to update resource '%s' '%s' at '%s'", r.gvr, oldobj.GetName(), r.namespace)
return
}
resourceVersion := oldobj.GetResourceVersion()
newobj.SetResourceVersion(resourceVersion)
u, err = dynamic.Resource(r.gvr).Namespace(r.namespace).Update(newobj, metav1.UpdateOptions{}, subresources...)
if err != nil {
err = errors.Wrapf(err, "failed to update resource '%s' '%s' at '%s'", r.gvr, oldobj.GetName(), r.namespace)
return
}
return
}
// List returns a list of specific resource at kubernetes cluster
func (r *resource) List(opts metav1.ListOptions) (u *unstructured.UnstructuredList, err error) {
dynamic, err := Dynamic().Provide()
if err != nil {
err = errors.Wrapf(err, "failed to list resource '%s' at '%s'", r.gvr, r.namespace)
return
}
u, err = dynamic.Resource(r.gvr).Namespace(r.namespace).List(opts)
if err != nil {
err = errors.Wrapf(err, "failed to list resource '%s' at '%s'", r.gvr, r.namespace)
return
}
return
}
// ResourceCreateOrUpdater as the name suggests manages to either
// create or update a given resource. It does so by implementing
// ResourceApplier interface
type ResourceCreateOrUpdater struct {
*resource
// Various executors required to perform Apply
// This is how this instance decouples its dependencies
Getter ResourceGetter
Creator ResourceCreator
Updater ResourceUpdater
// IsSkipUpdate will not update this resource if set to true.
// In other words, enabling this flag can only create the
// resource in the cluster if not created previously
IsSkipUpdate bool
}
// ResourceCreateOrUpdaterOption is a typed function used to
// build an instance of ResourceCreateOrUpdater
//
// NOTE:
// This follows the pattern known as "functional options". It
// is a function that operates on a given structure as a value
// to build (initialise, configure, sensible defaults, etc) this
// same structure.
type ResourceCreateOrUpdaterOption func(*ResourceCreateOrUpdater)
// ResourceCreateOrUpdaterSkipUpdate sets IsSkipUpdate based
// on the provided flag
func ResourceCreateOrUpdaterSkipUpdate(skip bool) ResourceCreateOrUpdaterOption {
return func(r *ResourceCreateOrUpdater) {
r.IsSkipUpdate = skip
}
}
// NewResourceCreateOrUpdater returns a new instance of
// ResourceCreateOrUpdater
func NewResourceCreateOrUpdater(
gvr schema.GroupVersionResource,
namespace string,
options ...ResourceCreateOrUpdaterOption,
) *ResourceCreateOrUpdater {
resource := Resource(gvr, namespace)
t := &ResourceCreateOrUpdater{
resource: resource,
Getter: resource,
Creator: resource,
Updater: resource,
}
for _, o := range options {
o(t)
}
return t
}
// String implements Stringer interface
func (r *ResourceCreateOrUpdater) String() string {
if r.resource == nil {
return fmt.Sprint("ResourceCreateOrUpdater")
}
return fmt.Sprintf("ResourceCreateOrUpdater %s", r.resource)
}
// Apply applies a resource to the kubernetes cluster. In other words, it
// creates a new resource if it does not exist or updates the existing
// resource.
func (r *ResourceCreateOrUpdater) Apply(
obj *unstructured.Unstructured,
subresources ...string,
) (resource *unstructured.Unstructured, err error) {
if r.Getter == nil {
err = errors.Errorf("%s: Apply failed: Nil getter", r)
return
}
if r.Creator == nil {
err = errors.Errorf("%s: Apply failed: Nil creator", r)
return
}
if r.Updater == nil {
err = errors.Errorf("%s: Apply failed: Nil updater", r)
return
}
if obj == nil {
err = errors.Errorf("%s: Apply failed: Nil resource", r)
return
}
resource, err = r.Getter.Get(obj.GetName(), metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(errors.Cause(err)) {
return r.Creator.Create(obj, subresources...)
}
return nil, err
}
if r.IsSkipUpdate {
klog.V(2).Infof("%s: Skipping update", r)
return resource, nil
}
return r.Updater.Update(resource, obj, subresources...)
}
// ResourceDeleteOptions is a utility instance used during the resource's delete operations
type ResourceDeleteOptions struct {
Deleter ResourceDeleter
}
// Delete is a resource that is suitable to be executed as a Delete operation
type Delete struct {
*resource
options ResourceDeleteOptions
}
// DeleteResource returns a new instance of delete resource
func DeleteResource(gvr schema.GroupVersionResource, namespace string) *Delete {
resource := Resource(gvr, namespace)
options := ResourceDeleteOptions{Deleter: resource}
return &Delete{resource: resource, options: options}
}
// Delete deletes a resource from a kubernetes cluster
func (d *Delete) Delete(obj *unstructured.Unstructured, subresources ...string) error {
if d.options.Deleter == nil {
return errors.New("nil resource deleter instance: failed to delete resource")
} else if obj == nil {
return errors.New("nil resource instance: failed to delete resource")
}
return d.options.Deleter.Delete(obj, subresources...)
}
// ResourceListOptions is a utility instance used during the resource's list operations
type ResourceListOptions struct {
Lister ResourceLister
}
// List is a resource resource that is suitable to be executed as a List operation
type List struct {
*resource
options ResourceListOptions
}
// ListResource returns a new instance of list resource
func ListResource(gvr schema.GroupVersionResource, namespace string) *List {
resource := Resource(gvr, namespace)
options := ResourceListOptions{Lister: resource}
return &List{resource: resource, options: options}
}
// List lists a resource from a kubernetes cluster
func (l *List) List(options metav1.ListOptions) (u *unstructured.UnstructuredList, err error) {
if l.options.Lister == nil {
err = errors.New("nil resource lister instance: failed to list resource")
return
}
return l.options.Lister.List(options)
}
// ResourceGetOptions is a utility instance used during the resource's get operations
type ResourceGetOptions struct {
Getter ResourceGetter
}
// Get is resource that is suitable to be executed as Get operation
type Get struct {
*resource
options ResourceGetOptions
}
// GetResource returns a new instance of get resource
func GetResource(gvr schema.GroupVersionResource, namespace string) *Get {
resource := Resource(gvr, namespace)
options := ResourceGetOptions{Getter: resource}
return &Get{resource: resource, options: options}
}
// Get gets a resource from a kubernetes cluster
func (g *Get) Get(name string, opts metav1.GetOptions, subresources ...string) (u *unstructured.Unstructured, err error) {
if g.options.Getter == nil {
err = errors.New("nil resource getter instance: failed to get resource")
return
}
return g.options.Getter.Get(name, opts, subresources...)
}

View file

@ -0,0 +1,31 @@
/*
Copyright 2020 The OpenEBS Authors
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.
*/
// TODO
// Move this file to pkg/k8sresource/v1alpha1
package v1alpha1
// verify if resource struct is an implementation of ResourceGetter
var _ ResourceGetter = &resource{}
// verify if resource struct is an implementation of ResourceCreator
var _ ResourceCreator = &resource{}
// verify if resource struct is an implementation of ResourceUpdater
var _ ResourceUpdater = &resource{}
// verify if createOrUpdate struct is an implementation of ResourceApplier
var _ ResourceApplier = &ResourceCreateOrUpdater{}