remove dynamic client

This commit is contained in:
Nikhita Raghunath 2017-10-25 12:43:07 +05:30
parent aed9ad4b08
commit 1e3918e4b1
12 changed files with 0 additions and 851 deletions

View File

@ -1,53 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["roundtrip_test.go"],
importpath = "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1",
library = ":go_default_library",
deps = [
"//vendor/github.com/google/gofuzz:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/testing/fuzzer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/testing/roundtrip:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"register.go",
"types.go",
"zz_generated.deepcopy.go",
],
importpath = "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1",
deps = [
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,18 +0,0 @@
/*
Copyright 2017 The Kubernetes 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.
*/
// +k8s:deepcopy-gen=package
package v1

View File

@ -1,49 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
)
// GroupName is the group name used in this package.
const GroupName = "cr.client-go.k8s.io"
// SchemeGroupVersion is the group version used to register these objects.
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
// Resource takes an unqualified resource and returns a Group-qualified GroupResource.
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Example{},
&ExampleList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -1,66 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 v1
import (
"math/rand"
"testing"
"github.com/google/gofuzz"
"k8s.io/apimachinery/pkg/api/testing/fuzzer"
roundtrip "k8s.io/apimachinery/pkg/api/testing/roundtrip"
metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
)
var _ runtime.Object = &Example{}
var _ metav1.ObjectMetaAccessor = &Example{}
var _ runtime.Object = &ExampleList{}
var _ metav1.ListMetaAccessor = &ExampleList{}
func exampleFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
return []interface{}{
func(obj *ExampleList, c fuzz.Continue) {
c.FuzzNoCustom(obj)
obj.Items = make([]Example, c.Intn(10))
for i := range obj.Items {
c.Fuzz(&obj.Items[i])
}
},
}
}
// TestRoundTrip tests that the third-party kinds can be marshaled and unmarshaled correctly to/from JSON
// without the loss of information. Moreover, deep copy is tested.
func TestRoundTrip(t *testing.T) {
scheme := runtime.NewScheme()
codecs := serializer.NewCodecFactory(scheme)
AddToScheme(scheme)
seed := rand.Int63()
fuzzerFuncs := fuzzer.MergeFuzzerFuncs(metafuzzer.Funcs, exampleFuzzerFuncs)
fuzzer := fuzzer.FuzzerFor(fuzzerFuncs, rand.NewSource(seed), codecs)
roundtrip.RoundTripSpecificKindWithoutProtobuf(t, SchemeGroupVersion.WithKind("Example"), scheme, codecs, fuzzer, nil)
roundtrip.RoundTripSpecificKindWithoutProtobuf(t, SchemeGroupVersion.WithKind("ExampleList"), scheme, codecs, fuzzer, nil)
}

View File

@ -1,55 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const ExampleResourcePlural = "examples"
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type Example struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
Spec ExampleSpec `json:"spec"`
Status ExampleStatus `json:"status,omitempty"`
}
type ExampleSpec struct {
Foo string `json:"foo"`
Bar bool `json:"bar"`
}
type ExampleStatus struct {
State ExampleState `json:"state,omitempty"`
Message string `json:"message,omitempty"`
}
type ExampleState string
const (
ExampleStateCreated ExampleState = "Created"
ExampleStateProcessed ExampleState = "Processed"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type ExampleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []Example `json:"items"`
}

View File

@ -1,146 +0,0 @@
// +build !ignore_autogenerated
/*
Copyright 2017 The Kubernetes 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.
*/
// This file was autogenerated by deepcopy-gen. Do not edit it manually!
package v1
import (
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
reflect "reflect"
)
// GetGeneratedDeepCopyFuncs returns the generated funcs, since we aren't registering them.
//
// Deprecated: deepcopy registration will go away when static deepcopy is fully implemented.
func GetGeneratedDeepCopyFuncs() []conversion.GeneratedDeepCopyFunc {
return []conversion.GeneratedDeepCopyFunc{
{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
in.(*Example).DeepCopyInto(out.(*Example))
return nil
}, InType: reflect.TypeOf(&Example{})},
{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
in.(*ExampleList).DeepCopyInto(out.(*ExampleList))
return nil
}, InType: reflect.TypeOf(&ExampleList{})},
{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
in.(*ExampleSpec).DeepCopyInto(out.(*ExampleSpec))
return nil
}, InType: reflect.TypeOf(&ExampleSpec{})},
{Fn: func(in interface{}, out interface{}, c *conversion.Cloner) error {
in.(*ExampleStatus).DeepCopyInto(out.(*ExampleStatus))
return nil
}, InType: reflect.TypeOf(&ExampleStatus{})},
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Example) DeepCopyInto(out *Example) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
out.Status = in.Status
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Example.
func (in *Example) DeepCopy() *Example {
if in == nil {
return nil
}
out := new(Example)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Example) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ExampleList) DeepCopyInto(out *ExampleList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Example, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExampleList.
func (in *ExampleList) DeepCopy() *ExampleList {
if in == nil {
return nil
}
out := new(ExampleList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ExampleList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
} else {
return nil
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ExampleSpec) DeepCopyInto(out *ExampleSpec) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExampleSpec.
func (in *ExampleSpec) DeepCopy() *ExampleSpec {
if in == nil {
return nil
}
out := new(ExampleSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ExampleStatus) DeepCopyInto(out *ExampleStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExampleStatus.
func (in *ExampleStatus) DeepCopy() *ExampleStatus {
if in == nil {
return nil
}
out := new(ExampleStatus)
in.DeepCopyInto(out)
return out
}

View File

@ -1,40 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"client.go",
"cr.go",
],
importpath = "k8s.io/apiextensions-apiserver/examples/client-go/client",
deps = [
"//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,45 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 client
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/rest"
crv1 "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1"
)
func NewClient(cfg *rest.Config) (*rest.RESTClient, *runtime.Scheme, error) {
scheme := runtime.NewScheme()
if err := crv1.AddToScheme(scheme); err != nil {
return nil, nil, err
}
config := *cfg
config.GroupVersion = &crv1.SchemeGroupVersion
config.APIPath = "/apis"
config.ContentType = runtime.ContentTypeJSON
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(scheme)}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, nil, err
}
return client, scheme, nil
}

View File

@ -1,103 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 client
import (
"fmt"
"reflect"
"time"
apiv1 "k8s.io/api/core/v1"
crv1 "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/rest"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
)
const exampleCRDName = crv1.ExampleResourcePlural + "." + crv1.GroupName
func CreateCustomResourceDefinition(clientset apiextensionsclient.Interface) (*apiextensionsv1beta1.CustomResourceDefinition, error) {
crd := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: exampleCRDName,
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: crv1.GroupName,
Version: crv1.SchemeGroupVersion.Version,
Scope: apiextensionsv1beta1.NamespaceScoped,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: crv1.ExampleResourcePlural,
Kind: reflect.TypeOf(crv1.Example{}).Name(),
},
},
}
_, err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd)
if err != nil {
return nil, err
}
// wait for CRD being established
err = wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {
crd, err = clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(exampleCRDName, metav1.GetOptions{})
if err != nil {
return false, err
}
for _, cond := range crd.Status.Conditions {
switch cond.Type {
case apiextensionsv1beta1.Established:
if cond.Status == apiextensionsv1beta1.ConditionTrue {
return true, err
}
case apiextensionsv1beta1.NamesAccepted:
if cond.Status == apiextensionsv1beta1.ConditionFalse {
fmt.Printf("Name conflict: %v\n", cond.Reason)
}
}
}
return false, err
})
if err != nil {
deleteErr := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(exampleCRDName, nil)
if deleteErr != nil {
return nil, errors.NewAggregate([]error{err, deleteErr})
}
return nil, err
}
return crd, nil
}
func WaitForExampleInstanceProcessed(exampleClient *rest.RESTClient, name string) error {
return wait.Poll(100*time.Millisecond, 10*time.Second, func() (bool, error) {
var example crv1.Example
err := exampleClient.Get().
Resource(crv1.ExampleResourcePlural).
Namespace(apiv1.NamespaceDefault).
Name(name).
Do().Into(&example)
if err == nil && example.Status.State == crv1.ExampleStateProcessed {
return true, nil
}
return false, err
})
}

View File

@ -1,33 +0,0 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["controller.go"],
importpath = "k8s.io/apiextensions-apiserver/examples/client-go/controller",
deps = [
"//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/fields:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
"//vendor/k8s.io/client-go/tools/cache:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

View File

@ -1,120 +0,0 @@
/*
Copyright 2017 The Kubernetes 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 controller
import (
"context"
"fmt"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
crv1 "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1"
)
// Watcher is an example of watching on resource create/update/delete events
type ExampleController struct {
ExampleClient *rest.RESTClient
ExampleScheme *runtime.Scheme
}
// Run starts an Example resource controller
func (c *ExampleController) Run(ctx context.Context) error {
fmt.Print("Watch Example objects\n")
// Watch Example objects
_, err := c.watchExamples(ctx)
if err != nil {
fmt.Printf("Failed to register watch for Example resource: %v\n", err)
return err
}
<-ctx.Done()
return ctx.Err()
}
func (c *ExampleController) watchExamples(ctx context.Context) (cache.Controller, error) {
source := cache.NewListWatchFromClient(
c.ExampleClient,
crv1.ExampleResourcePlural,
apiv1.NamespaceAll,
fields.Everything())
_, controller := cache.NewInformer(
source,
// The object type.
&crv1.Example{},
// resyncPeriod
// Every resyncPeriod, all resources in the cache will retrigger events.
// Set to 0 to disable the resync.
0,
// Your custom resource event handlers.
cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
})
go controller.Run(ctx.Done())
return controller, nil
}
func (c *ExampleController) onAdd(obj interface{}) {
example := obj.(*crv1.Example)
fmt.Printf("[CONTROLLER] OnAdd %s\n", example.ObjectMeta.SelfLink)
// NEVER modify objects from the store. It's a read-only, local cache.
// You can use DeepCopy() to make a deep copy of original object and modify this copy
// Or create a copy manually for better performance
exampleCopy := example.DeepCopy()
exampleCopy.Status = crv1.ExampleStatus{
State: crv1.ExampleStateProcessed,
Message: "Successfully processed by controller",
}
err := c.ExampleClient.Put().
Name(example.ObjectMeta.Name).
Namespace(example.ObjectMeta.Namespace).
Resource(crv1.ExampleResourcePlural).
Body(exampleCopy).
Do().
Error()
if err != nil {
fmt.Printf("ERROR updating status: %v\n", err)
} else {
fmt.Printf("UPDATED status: %#v\n", exampleCopy)
}
}
func (c *ExampleController) onUpdate(oldObj, newObj interface{}) {
oldExample := oldObj.(*crv1.Example)
newExample := newObj.(*crv1.Example)
fmt.Printf("[CONTROLLER] OnUpdate oldObj: %s\n", oldExample.ObjectMeta.SelfLink)
fmt.Printf("[CONTROLLER] OnUpdate newObj: %s\n", newExample.ObjectMeta.SelfLink)
}
func (c *ExampleController) onDelete(obj interface{}) {
example := obj.(*crv1.Example)
fmt.Printf("[CONTROLLER] OnDelete %s\n", example.ObjectMeta.SelfLink)
}

View File

@ -1,123 +0,0 @@
/*
Copyright 2017 The Kubernetes 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.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"context"
"flag"
"fmt"
apiv1 "k8s.io/api/core/v1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
crv1 "k8s.io/apiextensions-apiserver/examples/client-go/apis/cr/v1"
exampleclient "k8s.io/apiextensions-apiserver/examples/client-go/client"
examplecontroller "k8s.io/apiextensions-apiserver/examples/client-go/controller"
)
func main() {
masterURL := flag.String("master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
kubeconfig := flag.String("kubeconfig", "", "Path to a kube config. Only required if out-of-cluster.")
flag.Parse()
// Create the client config. Use masterURL and kubeconfig if given, otherwise assume in-cluster.
config, err := clientcmd.BuildConfigFromFlags(*masterURL, *kubeconfig)
if err != nil {
panic(err)
}
apiextensionsclientset, err := apiextensionsclient.NewForConfig(config)
if err != nil {
panic(err)
}
// initialize custom resource using a CustomResourceDefinition if it does not exist
crd, err := exampleclient.CreateCustomResourceDefinition(apiextensionsclientset)
if err != nil && !apierrors.IsAlreadyExists(err) {
panic(err)
}
if crd != nil {
defer apiextensionsclientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(crd.Name, nil)
}
// make a new config for our extension's API group, using the first config as a baseline
exampleClient, exampleScheme, err := exampleclient.NewClient(config)
if err != nil {
panic(err)
}
// start a controller on instances of our custom resource
controller := examplecontroller.ExampleController{
ExampleClient: exampleClient,
ExampleScheme: exampleScheme,
}
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
go controller.Run(ctx)
// Create an instance of our custom resource
example := &crv1.Example{
ObjectMeta: metav1.ObjectMeta{
Name: "example1",
},
Spec: crv1.ExampleSpec{
Foo: "hello",
Bar: true,
},
Status: crv1.ExampleStatus{
State: crv1.ExampleStateCreated,
Message: "Created, not processed yet",
},
}
var result crv1.Example
err = exampleClient.Post().
Resource(crv1.ExampleResourcePlural).
Namespace(apiv1.NamespaceDefault).
Body(example).
Do().Into(&result)
if err == nil {
fmt.Printf("CREATED: %#v\n", result)
} else if apierrors.IsAlreadyExists(err) {
fmt.Printf("ALREADY EXISTS: %#v\n", result)
} else {
panic(err)
}
// Poll until Example object is handled by controller and gets status updated to "Processed"
err = exampleclient.WaitForExampleInstanceProcessed(exampleClient, "example1")
if err != nil {
panic(err)
}
fmt.Print("PROCESSED\n")
// Fetch a list of our CRs
exampleList := crv1.ExampleList{}
err = exampleClient.Get().Resource(crv1.ExampleResourcePlural).Do().Into(&exampleList)
if err != nil {
panic(err)
}
fmt.Printf("LIST: %#v\n", exampleList)
}