1
0
Fork 0
mirror of https://github.com/prometheus-operator/prometheus-operator.git synced 2025-04-21 11:48:53 +00:00

*: update k8s.io/client-go to 3.0-beta

This commit is contained in:
Frederic Branczyk 2017-05-11 14:05:39 +02:00
parent 2878850da6
commit e31a9dc1f3
No known key found for this signature in database
GPG key ID: CA14788B1E48B256
681 changed files with 127627 additions and 176941 deletions

View file

@ -27,16 +27,17 @@ import (
"github.com/coreos/prometheus-operator/third_party/workqueue"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api"
apierrors "k8s.io/client-go/pkg/api/errors"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/apps/v1beta1"
extensionsobj "k8s.io/client-go/pkg/apis/extensions/v1beta1"
"k8s.io/client-go/pkg/fields"
"k8s.io/client-go/pkg/labels"
utilruntime "k8s.io/client-go/pkg/util/runtime"
"k8s.io/client-go/tools/cache"
)
@ -164,7 +165,7 @@ func (c *Operator) keyFunc(obj interface{}) (string, bool) {
return k, true
}
func (c *Operator) getObject(obj interface{}) (meta.Object, bool) {
func (c *Operator) getObject(obj interface{}) (metav1.Object, bool) {
ts, ok := obj.(cache.DeletedFinalStateUnknown)
if ok {
obj = ts.Obj
@ -376,8 +377,8 @@ func (c *Operator) sync(key string) error {
return c.syncVersion(am)
}
func ListOptions(name string) v1.ListOptions {
return v1.ListOptions{
func ListOptions(name string) metav1.ListOptions {
return metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(fields.Set(map[string]string{
"app": "alertmanager",
"alertmanager": name,
@ -503,7 +504,7 @@ func (c *Operator) destroyAlertmanager(key string) error {
func (c *Operator) createTPRs() error {
tprs := []*extensionsobj.ThirdPartyResource{
{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: tprAlertmanager,
},
Versions: []extensionsobj.APIVersion{

View file

@ -19,10 +19,11 @@ import (
"net/url"
"path"
"k8s.io/client-go/pkg/api/resource"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/apps/v1beta1"
"k8s.io/client-go/pkg/util/intstr"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
)
@ -60,7 +61,7 @@ func makeStatefulSet(am *v1alpha1.Alertmanager, old *v1beta1.StatefulSet, config
}
statefulset := &v1beta1.StatefulSet{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: prefixedName(am.Name),
Labels: am.ObjectMeta.Labels,
Annotations: am.ObjectMeta.Annotations,
@ -81,7 +82,7 @@ func makeStatefulSet(am *v1alpha1.Alertmanager, old *v1beta1.StatefulSet, config
})
} else {
pvc := v1.PersistentVolumeClaim{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: volumeName(am.Name),
},
Spec: v1.PersistentVolumeClaimSpec{
@ -106,7 +107,7 @@ func makeStatefulSet(am *v1alpha1.Alertmanager, old *v1beta1.StatefulSet, config
func makeStatefulSetService(p *v1alpha1.Alertmanager) *v1.Service {
svc := &v1.Service{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: governingServiceName,
Labels: map[string]string{
"operated-alertmanager": "true",
@ -178,7 +179,7 @@ func makeStatefulSetSpec(a *v1alpha1.Alertmanager, config Config) v1beta1.Statef
ServiceName: governingServiceName,
Replicas: a.Spec.Replicas,
Template: v1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "alertmanager",
"alertmanager": a.Name,

View file

@ -17,12 +17,11 @@ package v1alpha1
import (
"encoding/json"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/watch"
"k8s.io/client-go/rest"
)
@ -39,9 +38,9 @@ type AlertmanagerInterface interface {
Create(*Alertmanager) (*Alertmanager, error)
Get(name string) (*Alertmanager, error)
Update(*Alertmanager) (*Alertmanager, error)
Delete(name string, options *v1.DeleteOptions) error
List(opts api.ListOptions) (runtime.Object, error)
Watch(opts api.ListOptions) (watch.Interface, error)
Delete(name string, options *metav1.DeleteOptions) error
List(opts metav1.ListOptions) (runtime.Object, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
}
type alertmanagers struct {
@ -54,7 +53,7 @@ func newAlertmanagers(r rest.Interface, c *dynamic.Client, namespace string) *al
return &alertmanagers{
r,
c.Resource(
&unversioned.APIResource{
&metav1.APIResource{
Kind: TPRAlertmanagersKind,
Name: TPRAlertmanagerName,
Namespaced: true,
@ -101,11 +100,11 @@ func (a *alertmanagers) Update(o *Alertmanager) (*Alertmanager, error) {
return AlertmanagerFromUnstructured(ua)
}
func (a *alertmanagers) Delete(name string, options *v1.DeleteOptions) error {
func (a *alertmanagers) Delete(name string, options *metav1.DeleteOptions) error {
return a.client.Delete(name, options)
}
func (a *alertmanagers) List(opts api.ListOptions) (runtime.Object, error) {
func (a *alertmanagers) List(opts metav1.ListOptions) (runtime.Object, error) {
req := a.restClient.Get().
Namespace(a.ns).
Resource("alertmanagers").
@ -120,7 +119,7 @@ func (a *alertmanagers) List(opts api.ListOptions) (runtime.Object, error) {
return &p, json.Unmarshal(b, &p)
}
func (a *alertmanagers) Watch(opts api.ListOptions) (watch.Interface, error) {
func (a *alertmanagers) Watch(opts metav1.ListOptions) (watch.Interface, error) {
r, err := a.restClient.Get().
Prefix("watch").
Namespace(a.ns).
@ -138,7 +137,7 @@ func (a *alertmanagers) Watch(opts api.ListOptions) (watch.Interface, error) {
}
// AlertmanagerFromUnstructured unmarshals an Alertmanager object from dynamic client's unstructured
func AlertmanagerFromUnstructured(r *runtime.Unstructured) (*Alertmanager, error) {
func AlertmanagerFromUnstructured(r *unstructured.Unstructured) (*Alertmanager, error) {
b, err := json.Marshal(r.Object)
if err != nil {
return nil, err
@ -153,14 +152,14 @@ func AlertmanagerFromUnstructured(r *runtime.Unstructured) (*Alertmanager, error
}
// UnstructuredFromAlertmanager marshals an Alertmanager object into dynamic client's unstructured
func UnstructuredFromAlertmanager(a *Alertmanager) (*runtime.Unstructured, error) {
func UnstructuredFromAlertmanager(a *Alertmanager) (*unstructured.Unstructured, error) {
a.TypeMeta.Kind = TPRAlertmanagersKind
a.TypeMeta.APIVersion = TPRGroup + "/" + TPRVersion
b, err := json.Marshal(a)
if err != nil {
return nil, err
}
var r runtime.Unstructured
var r unstructured.Unstructured
if err := json.Unmarshal(b, &r.Object); err != nil {
return nil, err
}

View file

@ -15,10 +15,10 @@
package v1alpha1
import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime/serializer"
"k8s.io/client-go/rest"
)
@ -72,7 +72,7 @@ func NewForConfig(c *rest.Config) (*MonitoringV1alpha1Client, error) {
}
func setConfigDefaults(config *rest.Config) {
config.GroupVersion = &unversioned.GroupVersion{
config.GroupVersion = &schema.GroupVersion{
Group: TPRGroup,
Version: TPRVersion,
}

View file

@ -17,12 +17,11 @@ package v1alpha1
import (
"encoding/json"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/watch"
"k8s.io/client-go/rest"
)
@ -39,9 +38,9 @@ type PrometheusInterface interface {
Create(*Prometheus) (*Prometheus, error)
Get(name string) (*Prometheus, error)
Update(*Prometheus) (*Prometheus, error)
Delete(name string, options *v1.DeleteOptions) error
List(opts api.ListOptions) (runtime.Object, error)
Watch(opts api.ListOptions) (watch.Interface, error)
Delete(name string, options *metav1.DeleteOptions) error
List(opts metav1.ListOptions) (runtime.Object, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
}
type prometheuses struct {
@ -54,7 +53,7 @@ func newPrometheuses(r rest.Interface, c *dynamic.Client, namespace string) *pro
return &prometheuses{
r,
c.Resource(
&unversioned.APIResource{
&metav1.APIResource{
Kind: TPRPrometheusesKind,
Name: TPRPrometheusName,
Namespaced: true,
@ -101,11 +100,11 @@ func (p *prometheuses) Update(o *Prometheus) (*Prometheus, error) {
return PrometheusFromUnstructured(up)
}
func (p *prometheuses) Delete(name string, options *v1.DeleteOptions) error {
func (p *prometheuses) Delete(name string, options *metav1.DeleteOptions) error {
return p.client.Delete(name, options)
}
func (p *prometheuses) List(opts api.ListOptions) (runtime.Object, error) {
func (p *prometheuses) List(opts metav1.ListOptions) (runtime.Object, error) {
req := p.restClient.Get().
Namespace(p.ns).
Resource("prometheuses").
@ -120,7 +119,7 @@ func (p *prometheuses) List(opts api.ListOptions) (runtime.Object, error) {
return &prom, json.Unmarshal(b, &prom)
}
func (p *prometheuses) Watch(opts api.ListOptions) (watch.Interface, error) {
func (p *prometheuses) Watch(opts metav1.ListOptions) (watch.Interface, error) {
r, err := p.restClient.Get().
Prefix("watch").
Namespace(p.ns).
@ -138,7 +137,7 @@ func (p *prometheuses) Watch(opts api.ListOptions) (watch.Interface, error) {
}
// PrometheusFromUnstructured unmarshals a Prometheus object from dynamic client's unstructured
func PrometheusFromUnstructured(r *runtime.Unstructured) (*Prometheus, error) {
func PrometheusFromUnstructured(r *unstructured.Unstructured) (*Prometheus, error) {
b, err := json.Marshal(r.Object)
if err != nil {
return nil, err
@ -153,14 +152,14 @@ func PrometheusFromUnstructured(r *runtime.Unstructured) (*Prometheus, error) {
}
// UnstructuredFromPrometheus marshals a Prometheus object into dynamic client's unstructured
func UnstructuredFromPrometheus(p *Prometheus) (*runtime.Unstructured, error) {
func UnstructuredFromPrometheus(p *Prometheus) (*unstructured.Unstructured, error) {
p.TypeMeta.Kind = TPRPrometheusesKind
p.TypeMeta.APIVersion = TPRGroup + "/" + TPRVersion
b, err := json.Marshal(p)
if err != nil {
return nil, err
}
var r runtime.Unstructured
var r unstructured.Unstructured
if err := json.Unmarshal(b, &r.Object); err != nil {
return nil, err
}

View file

@ -17,12 +17,11 @@ package v1alpha1
import (
"encoding/json"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/watch"
"k8s.io/client-go/rest"
)
@ -39,9 +38,9 @@ type ServiceMonitorInterface interface {
Create(*ServiceMonitor) (*ServiceMonitor, error)
Get(name string) (*ServiceMonitor, error)
Update(*ServiceMonitor) (*ServiceMonitor, error)
Delete(name string, options *v1.DeleteOptions) error
List(opts api.ListOptions) (runtime.Object, error)
Watch(opts api.ListOptions) (watch.Interface, error)
Delete(name string, options *metav1.DeleteOptions) error
List(opts metav1.ListOptions) (runtime.Object, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
}
type servicemonitors struct {
@ -54,7 +53,7 @@ func newServiceMonitors(r rest.Interface, c *dynamic.Client, namespace string) *
return &servicemonitors{
r,
c.Resource(
&unversioned.APIResource{
&metav1.APIResource{
Kind: TPRServiceMonitorsKind,
Name: TPRServiceMonitorName,
Namespaced: true,
@ -101,11 +100,11 @@ func (s *servicemonitors) Update(o *ServiceMonitor) (*ServiceMonitor, error) {
return ServiceMonitorFromUnstructured(us)
}
func (s *servicemonitors) Delete(name string, options *v1.DeleteOptions) error {
func (s *servicemonitors) Delete(name string, options *metav1.DeleteOptions) error {
return s.client.Delete(name, options)
}
func (s *servicemonitors) List(opts api.ListOptions) (runtime.Object, error) {
func (s *servicemonitors) List(opts metav1.ListOptions) (runtime.Object, error) {
req := s.restClient.Get().
Namespace(s.ns).
Resource("servicemonitors").
@ -120,7 +119,7 @@ func (s *servicemonitors) List(opts api.ListOptions) (runtime.Object, error) {
return &sm, json.Unmarshal(b, &sm)
}
func (s *servicemonitors) Watch(opts api.ListOptions) (watch.Interface, error) {
func (s *servicemonitors) Watch(opts metav1.ListOptions) (watch.Interface, error) {
r, err := s.restClient.Get().
Prefix("watch").
Namespace(s.ns).
@ -138,7 +137,7 @@ func (s *servicemonitors) Watch(opts api.ListOptions) (watch.Interface, error) {
}
// ServiceMonitorFromUnstructured unmarshals a ServiceMonitor object from dynamic client's unstructured
func ServiceMonitorFromUnstructured(r *runtime.Unstructured) (*ServiceMonitor, error) {
func ServiceMonitorFromUnstructured(r *unstructured.Unstructured) (*ServiceMonitor, error) {
b, err := json.Marshal(r.Object)
if err != nil {
return nil, err
@ -153,14 +152,14 @@ func ServiceMonitorFromUnstructured(r *runtime.Unstructured) (*ServiceMonitor, e
}
// UnstructuredFromServiceMonitor marshals a ServiceMonitor object into dynamic client's unstructured
func UnstructuredFromServiceMonitor(s *ServiceMonitor) (*runtime.Unstructured, error) {
func UnstructuredFromServiceMonitor(s *ServiceMonitor) (*unstructured.Unstructured, error) {
s.TypeMeta.Kind = TPRServiceMonitorsKind
s.TypeMeta.APIVersion = TPRGroup + "/" + TPRVersion
b, err := json.Marshal(s)
if err != nil {
return nil, err
}
var r runtime.Unstructured
var r unstructured.Unstructured
if err := json.Unmarshal(b, &r.Object); err != nil {
return nil, err
}

View file

@ -15,17 +15,17 @@
package v1alpha1
import (
"k8s.io/client-go/pkg/api/unversioned"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/intstr"
)
// Prometheus defines a Prometheus deployment.
type Prometheus struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard objects metadata. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
v1.ObjectMeta `json:"metadata,omitempty"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of the desired behavior of the Prometheus cluster. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status
Spec PrometheusSpec `json:"spec"`
@ -38,10 +38,10 @@ type Prometheus struct {
// PrometheusList is a list of Prometheuses.
type PrometheusList struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard list metadata
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
unversioned.ListMeta `json:"metadata,omitempty"`
metav1.ListMeta `json:"metadata,omitempty"`
// List of Prometheuses
Items []*Prometheus `json:"items"`
}
@ -50,7 +50,7 @@ type PrometheusList struct {
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status
type PrometheusSpec struct {
// ServiceMonitors to be selected for target discovery.
ServiceMonitorSelector *unversioned.LabelSelector `json:"serviceMonitorSelector,omitempty"`
ServiceMonitorSelector *metav1.LabelSelector `json:"serviceMonitorSelector,omitempty"`
// Version of Prometheus to be deployed.
Version string `json:"version,omitempty"`
// When a Prometheus deployment is paused, no actions except for deletion
@ -78,7 +78,7 @@ type PrometheusSpec struct {
// Storage spec to specify how storage shall be used.
Storage *StorageSpec `json:"storage,omitempty"`
// A selector to select which ConfigMaps to mount for loading rule files from.
RuleSelector *unversioned.LabelSelector `json:"ruleSelector,omitempty"`
RuleSelector *metav1.LabelSelector `json:"ruleSelector,omitempty"`
// Define details regarding alerting.
Alerting AlertingSpec `json:"alerting,omitempty"`
// Define resources requests and limits for single Pods.
@ -134,7 +134,7 @@ type StorageSpec struct {
// info: https://kubernetes.io/docs/user-guide/persistent-volumes/#storageclasses
Class string `json:"class"`
// A label query over volumes to consider for binding.
Selector *unversioned.LabelSelector `json:"selector"`
Selector *metav1.LabelSelector `json:"selector"`
// Resources represents the minimum resources the volume should have. More
// info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources
Resources v1.ResourceRequirements `json:"resources"`
@ -155,10 +155,10 @@ type AlertmanagerEndpoints struct {
// ServiceMonitor defines monitoring for a set of services.
type ServiceMonitor struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard objects metadata. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
v1.ObjectMeta `json:"metadata,omitempty"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of desired Service selection for target discrovery by
// Prometheus.
Spec ServiceMonitorSpec `json:"spec"`
@ -171,7 +171,7 @@ type ServiceMonitorSpec struct {
// A list of endpoints allowed as part of this ServiceMonitor.
Endpoints []Endpoint `json:"endpoints,omitempty"`
// Selector to select Endpoints objects.
Selector unversioned.LabelSelector `json:"selector"`
Selector metav1.LabelSelector `json:"selector"`
// Selector to select which namespaces the Endpoints objects are discovered from.
NamespaceSelector NamespaceSelector `json:"namespaceSelector,omitempty"`
}
@ -203,7 +203,7 @@ type Endpoint struct {
// More info: https://prometheus.io/docs/operating/configuration/#endpoints
type BasicAuth struct {
// The secret that contains the username for authenticate
Username v1.SecretKeySelector`json:"username,omitempty"`
Username v1.SecretKeySelector `json:"username,omitempty"`
// The secret that contains the password for authenticate
Password v1.SecretKeySelector `json:"password,omitempty"`
}
@ -224,20 +224,20 @@ type TLSConfig struct {
// A list of ServiceMonitors.
type ServiceMonitorList struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard list metadata
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
unversioned.ListMeta `json:"metadata,omitempty"`
metav1.ListMeta `json:"metadata,omitempty"`
// List of ServiceMonitors
Items []*ServiceMonitor `json:"items"`
}
// Describes an Alertmanager cluster.
type Alertmanager struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard objects metadata. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
v1.ObjectMeta `json:"metadata,omitempty"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of the desired behavior of the Alertmanager cluster. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status
Spec AlertmanagerSpec `json:"spec"`
@ -284,10 +284,10 @@ type AlertmanagerSpec struct {
// A list of Alertmanagers.
type AlertmanagerList struct {
unversioned.TypeMeta `json:",inline"`
metav1.TypeMeta `json:",inline"`
// Standard list metadata
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
unversioned.ListMeta `json:"metadata,omitempty"`
metav1.ListMeta `json:"metadata,omitempty"`
// List of Alertmanagers
Items []Alertmanager `json:"items"`
}
@ -322,7 +322,7 @@ type NamespaceSelector struct {
// List of namespace names.
MatchNames []string `json:"matchNames,omitempty"`
// TODO(fabxc): this should embed unversioned.LabelSelector eventually.
// TODO(fabxc): this should embed metav1.LabelSelector eventually.
// Currently the selector is only used for namespaces which require more complex
// implementation to support label selections.
}

View file

@ -21,11 +21,11 @@ import (
"time"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
clientv1 "k8s.io/client-go/kubernetes/typed/core/v1"
apierrors "k8s.io/client-go/pkg/api/errors"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/rest"
)
@ -106,14 +106,14 @@ func IsResourceNotFoundError(err error) bool {
if !ok {
return false
}
if se.Status().Code == http.StatusNotFound && se.Status().Reason == unversioned.StatusReasonNotFound {
if se.Status().Code == http.StatusNotFound && se.Status().Reason == metav1.StatusReasonNotFound {
return true
}
return false
}
func CreateOrUpdateService(sclient clientv1.ServiceInterface, svc *v1.Service) error {
service, err := sclient.Get(svc.Name)
service, err := sclient.Get(svc.Name, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return errors.Wrap(err, "retrieving service object failed")
}
@ -135,7 +135,7 @@ func CreateOrUpdateService(sclient clientv1.ServiceInterface, svc *v1.Service) e
}
func CreateOrUpdateEndpoints(eclient clientv1.EndpointsInterface, eps *v1.Endpoints) error {
endpoints, err := eclient.Get(eps.Name)
endpoints, err := eclient.Get(eps.Name, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return errors.Wrap(err, "retrieving existing kubelet endpoints object failed")
}

View file

@ -27,17 +27,17 @@ import (
"github.com/coreos/prometheus-operator/third_party/workqueue"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api"
apierrors "k8s.io/client-go/pkg/api/errors"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/apps/v1beta1"
extensionsobj "k8s.io/client-go/pkg/apis/extensions/v1beta1"
"k8s.io/client-go/pkg/fields"
"k8s.io/client-go/pkg/labels"
utilruntime "k8s.io/client-go/pkg/util/runtime"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
@ -320,7 +320,7 @@ func nodeAddress(node *v1.Node) (string, map[v1.NodeAddressType][]string, error)
func (c *Operator) syncNodeEndpoints() {
eps := &v1.Endpoints{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: c.kubeletObjectName,
Labels: map[string]string{
"k8s-app": "kubelet",
@ -362,7 +362,7 @@ func (c *Operator) syncNodeEndpoints() {
})
svc := &v1.Service{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: c.kubeletObjectName,
Labels: map[string]string{
"k8s-app": "kubelet",
@ -454,7 +454,7 @@ func (c *Operator) handleConfigMapUpdate(old, cur interface{}) {
}
}
func (c *Operator) getObject(obj interface{}) (meta.Object, bool) {
func (c *Operator) getObject(obj interface{}) (metav1.Object, bool) {
ts, ok := obj.(cache.DeletedFinalStateUnknown)
if ok {
obj = ts.Obj
@ -676,7 +676,7 @@ func (c *Operator) sync(key string) error {
func (c *Operator) ruleFileConfigMaps(p *v1alpha1.Prometheus) ([]*v1.ConfigMap, error) {
res := []*v1.ConfigMap{}
ruleSelector, err := unversioned.LabelSelectorAsSelector(p.Spec.RuleSelector)
ruleSelector, err := metav1.LabelSelectorAsSelector(p.Spec.RuleSelector)
if err != nil {
return nil, err
}
@ -691,8 +691,8 @@ func (c *Operator) ruleFileConfigMaps(p *v1alpha1.Prometheus) ([]*v1.ConfigMap,
return res, nil
}
func ListOptions(name string) v1.ListOptions {
return v1.ListOptions{
func ListOptions(name string) metav1.ListOptions {
return metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(fields.Set(map[string]string{
"app": "prometheus",
"prometheus": name,
@ -751,7 +751,7 @@ func PrometheusStatus(kclient kubernetes.Interface, p *v1alpha1.Prometheus) (*v1
if err != nil {
return nil, nil, errors.Wrap(err, "retrieving pods of failed")
}
sset, err := kclient.Apps().StatefulSets(p.Namespace).Get(statefulSetNameFromPrometheusName(p.Name))
sset, err := kclient.Apps().StatefulSets(p.Namespace).Get(statefulSetNameFromPrometheusName(p.Name), metav1.GetOptions{})
if err != nil {
return nil, nil, errors.Wrap(err, "retrieving stateful set failed")
}
@ -842,7 +842,7 @@ func (c *Operator) destroyPrometheus(key string) error {
// TODO(fabxc): add an ownerRef at creation so we don't delete Secrets
// manually created for Prometheus servers with no ServiceMonitor selectors.
s := c.kclient.Core().Secrets(sset.Namespace)
secret, err := s.Get(sset.Name)
secret, err := s.Get(sset.Name, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return errors.Wrap(err, "retrieving config Secret failed")
}
@ -920,7 +920,7 @@ func (c *Operator) createConfig(p *v1alpha1.Prometheus, ruleFileConfigMaps []*v1
sClient := c.kclient.CoreV1().Secrets(p.Namespace)
listSecrets, err := sClient.List(v1.ListOptions{})
listSecrets, err := sClient.List(metav1.ListOptions{})
if err != nil {
return err
@ -947,7 +947,7 @@ func (c *Operator) createConfig(p *v1alpha1.Prometheus, ruleFileConfigMaps []*v1
}
s.Data["prometheus.yaml"] = []byte(conf)
_, err = sClient.Get(s.Name)
_, err = sClient.Get(s.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
_, err = sClient.Create(s)
} else if err == nil {
@ -960,7 +960,7 @@ func (c *Operator) selectServiceMonitors(p *v1alpha1.Prometheus) (map[string]*v1
// Selectors might overlap. Deduplicate them along the keyFunc.
res := make(map[string]*v1alpha1.ServiceMonitor)
selector, err := unversioned.LabelSelectorAsSelector(p.Spec.ServiceMonitorSelector)
selector, err := metav1.LabelSelectorAsSelector(p.Spec.ServiceMonitorSelector)
if err != nil {
return nil, err
}
@ -980,7 +980,7 @@ func (c *Operator) selectServiceMonitors(p *v1alpha1.Prometheus) (map[string]*v1
func (c *Operator) createTPRs() error {
tprs := []*extensionsobj.ThirdPartyResource{
{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: tprServiceMonitor,
},
Versions: []extensionsobj.APIVersion{
@ -989,7 +989,7 @@ func (c *Operator) createTPRs() error {
Description: "Prometheus monitoring for a service",
},
{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: tprPrometheus,
},
Versions: []extensionsobj.APIVersion{

View file

@ -20,7 +20,7 @@ import (
"strings"
yaml "gopkg.in/yaml.v2"
"k8s.io/client-go/pkg/api/unversioned"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
)
@ -140,25 +140,25 @@ func generateServiceMonitorConfig(m *v1alpha1.ServiceMonitor, ep v1alpha1.Endpoi
// `In`, `NotIn`, `Exists`, and `DoesNotExist`, into relabeling rules.
for _, exp := range m.Spec.Selector.MatchExpressions {
switch exp.Operator {
case unversioned.LabelSelectorOpIn:
case metav1.LabelSelectorOpIn:
relabelings = append(relabelings, map[string]interface{}{
"action": "keep",
"source_labels": []string{"__meta_kubernetes_service_label_" + sanitizeLabelName(exp.Key)},
"regex": strings.Join(exp.Values, "|"),
})
case unversioned.LabelSelectorOpNotIn:
case metav1.LabelSelectorOpNotIn:
relabelings = append(relabelings, map[string]interface{}{
"action": "drop",
"source_labels": []string{"__meta_kubernetes_service_label_" + sanitizeLabelName(exp.Key)},
"regex": strings.Join(exp.Values, "|"),
})
case unversioned.LabelSelectorOpExists:
case metav1.LabelSelectorOpExists:
relabelings = append(relabelings, map[string]interface{}{
"action": "keep",
"source_labels": []string{"__meta_kubernetes_service_label_" + sanitizeLabelName(exp.Key)},
"regex": ".+",
})
case unversioned.LabelSelectorOpDoesNotExist:
case metav1.LabelSelectorOpDoesNotExist:
relabelings = append(relabelings, map[string]interface{}{
"action": "drop",
"source_labels": []string{"__meta_kubernetes_service_label_" + sanitizeLabelName(exp.Key)},

View file

@ -21,10 +21,11 @@ import (
"net/url"
"path"
"k8s.io/client-go/pkg/api/resource"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/apps/v1beta1"
"k8s.io/client-go/pkg/util/intstr"
"strings"
@ -81,7 +82,7 @@ func makeStatefulSet(p v1alpha1.Prometheus, old *v1beta1.StatefulSet, config *Co
}
statefulset := &v1beta1.StatefulSet{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: prefixedName(p.Name),
Labels: p.ObjectMeta.Labels,
Annotations: p.ObjectMeta.Annotations,
@ -102,7 +103,7 @@ func makeStatefulSet(p v1alpha1.Prometheus, old *v1beta1.StatefulSet, config *Co
})
} else {
pvc := v1.PersistentVolumeClaim{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: volumeName(p.Name),
},
Spec: v1.PersistentVolumeClaimSpec{
@ -188,7 +189,7 @@ func makeConfigSecret(name string, configMaps []*v1.ConfigMap) (*v1.Secret, erro
}
return &v1.Secret{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: configSecretName(name),
Labels: managedByOperatorLabels,
},
@ -201,7 +202,7 @@ func makeConfigSecret(name string, configMaps []*v1.ConfigMap) (*v1.Secret, erro
func makeStatefulSetService(p *v1alpha1.Prometheus) *v1.Service {
svc := &v1.Service{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: governingServiceName,
Labels: map[string]string{
"operated-prometheus": "true",
@ -376,7 +377,7 @@ func makeStatefulSetSpec(p v1alpha1.Prometheus, c *Config, ruleConfigMaps []*v1.
ServiceName: governingServiceName,
Replicas: p.Spec.Replicas,
Template: v1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "prometheus",
"prometheus": p.Name,

View file

@ -21,6 +21,7 @@ import (
"testing"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/pkg/api/v1"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
@ -192,7 +193,7 @@ func TestMeshInitialization(t *testing.T) {
var amountAlertmanagers int32 = 3
alertmanager := &v1alpha1.Alertmanager{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
},
Spec: v1alpha1.AlertmanagerSpec{
@ -258,7 +259,7 @@ receivers:
`
cfg := &v1.Secret{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("alertmanager-%s", alertmanager.Name),
},
Data: map[string][]byte{

View file

@ -20,10 +20,11 @@ import (
"os"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/intstr"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/pkg/util/yaml"
"github.com/coreos/prometheus-operator/pkg/alertmanager"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
@ -46,7 +47,7 @@ receivers:
func (f *Framework) MakeBasicAlertmanager(name string, replicas int32) *v1alpha1.Alertmanager {
return &v1alpha1.Alertmanager{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: v1alpha1.AlertmanagerSpec{
@ -63,7 +64,7 @@ func (f *Framework) MakeAlertmanagerNodePortService(name, group string, nodePort
func (f *Framework) MakeAlertmanagerService(name, group string, serviceType v1.ServiceType) *v1.Service {
service := &v1.Service{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("alertmanager-%s", name),
Labels: map[string]string{
"group": group,

View file

@ -1,10 +1,10 @@
package framework
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
rbacv1alpha1 "k8s.io/client-go/pkg/apis/rbac/v1alpha1"
"k8s.io/client-go/pkg/util/yaml"
)
func CreateClusterRole(kubeClient kubernetes.Interface, relativePath string) error {
@ -13,7 +13,7 @@ func CreateClusterRole(kubeClient kubernetes.Interface, relativePath string) err
return err
}
_, err = kubeClient.RbacV1alpha1().ClusterRoles().Get(clusterRole.Name)
_, err = kubeClient.RbacV1alpha1().ClusterRoles().Get(clusterRole.Name, metav1.GetOptions{})
if err == nil {
// ClusterRole already exists -> Update
@ -39,7 +39,7 @@ func DeleteClusterRole(kubeClient kubernetes.Interface, relativePath string) err
return err
}
if err := kubeClient.RbacV1alpha1().ClusterRoles().Delete(clusterRole.Name, &v1.DeleteOptions{}); err != nil {
if err := kubeClient.RbacV1alpha1().ClusterRoles().Delete(clusterRole.Name, &metav1.DeleteOptions{}); err != nil {
return err
}

View file

@ -1,10 +1,10 @@
package framework
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
rbacv1alpha1 "k8s.io/client-go/pkg/apis/rbac/v1alpha1"
"k8s.io/client-go/pkg/util/yaml"
)
func CreateClusterRoleBinding(kubeClient kubernetes.Interface, relativePath string) error {
@ -13,7 +13,7 @@ func CreateClusterRoleBinding(kubeClient kubernetes.Interface, relativePath stri
return err
}
_, err = kubeClient.RbacV1alpha1().ClusterRoleBindings().Get(clusterRoleBinding.Name)
_, err = kubeClient.RbacV1alpha1().ClusterRoleBindings().Get(clusterRoleBinding.Name, metav1.GetOptions{})
if err == nil {
// ClusterRoleBinding already exists -> Update
@ -38,7 +38,7 @@ func DeleteClusterRoleBinding(kubeClient kubernetes.Interface, relativePath stri
return err
}
if err := kubeClient.RbacV1alpha1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &v1.DeleteOptions{}); err != nil {
if err := kubeClient.RbacV1alpha1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &metav1.DeleteOptions{}); err != nil {
return err
}

View file

@ -1,10 +1,10 @@
package framework
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"
"k8s.io/client-go/pkg/util/yaml"
)
func MakeDeployment(pathToYaml string) (*v1beta1.Deployment, error) {
@ -29,7 +29,7 @@ func CreateDeployment(kubeClient kubernetes.Interface, namespace string, d *v1be
}
func DeleteDeployment(kubeClient kubernetes.Interface, namespace, name string) error {
d, err := kubeClient.Extensions().Deployments(namespace).Get(name)
d, err := kubeClient.Extensions().Deployments(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return err
}
@ -41,5 +41,5 @@ func DeleteDeployment(kubeClient kubernetes.Interface, namespace, name string) e
if err != nil {
return err
}
return kubeClient.Extensions().Deployments(namespace).Delete(d.Name, &v1.DeleteOptions{})
return kubeClient.Extensions().Deployments(namespace).Delete(d.Name, &metav1.DeleteOptions{})
}

View file

@ -18,9 +18,10 @@ import (
"net/http"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/fields"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
@ -108,7 +109,7 @@ func (f *Framework) setupPrometheusOperator(opImage string) error {
return err
}
opts := v1.ListOptions{LabelSelector: fields.SelectorFromSet(fields.Set(deploy.Spec.Template.ObjectMeta.Labels)).String()}
opts := metav1.ListOptions{LabelSelector: fields.SelectorFromSet(fields.Set(deploy.Spec.Template.ObjectMeta.Labels)).String()}
err = WaitForPodsReady(f.KubeClient, f.Namespace.Name, f.DefaultTimeout, 1, opts)
if err != nil {
return errors.Wrap(err, "failed to wait for prometheus operator to become ready")

View file

@ -7,9 +7,10 @@ import (
"path/filepath"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/rest"
"github.com/coreos/prometheus-operator/pkg/k8sutil"
@ -32,7 +33,7 @@ func PathToOSFile(relativPath string) (*os.File, error) {
// WaitForPodsReady waits for a selection of Pods to be running and each
// container to pass its readiness check.
func WaitForPodsReady(kubeClient kubernetes.Interface, namespace string, timeout time.Duration, expectedReplicas int, opts v1.ListOptions) error {
func WaitForPodsReady(kubeClient kubernetes.Interface, namespace string, timeout time.Duration, expectedReplicas int, opts metav1.ListOptions) error {
return wait.Poll(time.Second, timeout, func() (bool, error) {
pl, err := kubeClient.Core().Pods(namespace).List(opts)
if err != nil {
@ -58,7 +59,7 @@ func WaitForPodsReady(kubeClient kubernetes.Interface, namespace string, timeout
})
}
func WaitForPodsRunImage(kubeClient kubernetes.Interface, namespace string, expectedReplicas int, image string, opts v1.ListOptions) error {
func WaitForPodsRunImage(kubeClient kubernetes.Interface, namespace string, expectedReplicas int, image string, opts metav1.ListOptions) error {
return wait.Poll(time.Second, time.Minute*5, func() (bool, error) {
pl, err := kubeClient.Core().Pods(namespace).List(opts)
if err != nil {

View file

@ -20,18 +20,18 @@ import (
"time"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"
"k8s.io/client-go/pkg/util/intstr"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/pkg/util/yaml"
)
func MakeBasicIngress(serviceName string, servicePort int) *v1beta1.Ingress {
return &v1beta1.Ingress{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: "monitoring",
},
Spec: v1beta1.IngressSpec{
@ -129,7 +129,7 @@ func GetIngressIP(kubeClient kubernetes.Interface, namespace string, ingressName
var ingress *v1beta1.Ingress
err := wait.Poll(time.Millisecond*500, time.Minute*5, func() (bool, error) {
var err error
ingress, err = kubeClient.Extensions().Ingresses(namespace).Get(ingressName)
ingress, err = kubeClient.Extensions().Ingresses(namespace).Get(ingressName, metav1.GetOptions{})
if err != nil {
return false, errors.Wrap(err, fmt.Sprintf("requesting the ingress %v failed", ingressName))
}

View file

@ -4,15 +4,15 @@ import (
"fmt"
"testing"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"github.com/pkg/errors"
)
func CreateNamespace(kubeClient kubernetes.Interface, name string) (*v1.Namespace, error) {
namespace, err := kubeClient.Core().Namespaces().Create(&v1.Namespace{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
})

View file

@ -21,11 +21,11 @@ import (
"net/http"
"time"
"k8s.io/client-go/pkg/api/resource"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/intstr"
"k8s.io/client-go/pkg/util/wait"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
"github.com/coreos/prometheus-operator/pkg/prometheus"
@ -34,18 +34,18 @@ import (
func (f *Framework) MakeBasicPrometheus(ns, name, group string, replicas int32) *v1alpha1.Prometheus {
return &v1alpha1.Prometheus{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
},
Spec: v1alpha1.PrometheusSpec{
Replicas: &replicas,
ServiceMonitorSelector: &unversioned.LabelSelector{
ServiceMonitorSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"group": group,
},
},
RuleSelector: &unversioned.LabelSelector{
RuleSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"role": "rulefile",
},
@ -73,14 +73,14 @@ func (f *Framework) AddAlertingToPrometheus(p *v1alpha1.Prometheus, ns, name str
func (f *Framework) MakeBasicServiceMonitor(name string) *v1alpha1.ServiceMonitor {
return &v1alpha1.ServiceMonitor{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"group": name,
},
},
Spec: v1alpha1.ServiceMonitorSpec{
Selector: unversioned.LabelSelector{
Selector: metav1.LabelSelector{
MatchLabels: map[string]string{
"group": name,
},
@ -103,7 +103,7 @@ func (f *Framework) MakeBasicPrometheusNodePortService(name, group string, nodeP
func (f *Framework) MakePrometheusService(name, group string, serviceType v1.ServiceType) *v1.Service {
service := &v1.Service{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("prometheus-%s", name),
Labels: map[string]string{
"group": group,

View file

@ -18,10 +18,11 @@ import (
"os"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/pkg/util/yaml"
)
func createReplicationControllerViaYml(kubeClient kubernetes.Interface, namespace string, filepath string) error {
@ -77,7 +78,7 @@ func scaleDownReplicationController(kubeClient kubernetes.Interface, namespace s
}
return wait.Poll(time.Second, time.Minute*5, func() (bool, error) {
currentRC, err := rCAPI.Get(rC.Name)
currentRC, err := rCAPI.Get(rC.Name, metav1.GetOptions{})
if err != nil {
return false, err
}

View file

@ -19,10 +19,10 @@ import (
"time"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/wait"
)
func CreateServiceAndWaitUntilReady(kubeClient kubernetes.Interface, namespace string, service *v1.Service) (finalizerFn, error) {
@ -72,7 +72,7 @@ func DeleteServiceAndWaitUntilGone(kubeClient kubernetes.Interface, namespace st
}
func getEndpoints(kubeClient kubernetes.Interface, namespace, serviceName string) (*v1.Endpoints, error) {
endpoints, err := kubeClient.CoreV1().Endpoints(namespace).Get(serviceName)
endpoints, err := kubeClient.CoreV1().Endpoints(namespace).Get(serviceName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("requesting endpoints for servce %v failed", serviceName))
}

View file

@ -1,9 +1,9 @@
package framework
import (
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/yaml"
)
func CreateServiceAccount(kubeClient kubernetes.Interface, namespace string, relativPath string) error {

View file

@ -1,12 +1,13 @@
package framework
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"
"k8s.io/client-go/pkg/util/wait"
"k8s.io/client-go/pkg/util/yaml"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"
)
func CreateAndWaitForThirdPartyRessource(kubeClient kubernetes.Interface, relativePath string, apiPath string) error {
@ -59,7 +60,7 @@ func DeleteThirdPartyResource(kubeClient kubernetes.Interface, relativePath stri
return err
}
if err := kubeClient.Extensions().ThirdPartyResources().Delete(tpr.Name, &v1.DeleteOptions{}); err != nil {
if err := kubeClient.Extensions().ThirdPartyResources().Delete(tpr.Name, &metav1.DeleteOptions{}); err != nil {
return err
}

View file

@ -25,9 +25,10 @@ import (
"testing"
"time"
"k8s.io/client-go/pkg/api/resource"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/wait"
"github.com/coreos/prometheus-operator/pkg/alertmanager"
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
@ -170,7 +171,7 @@ func TestPrometheusReloadConfig(t *testing.T) {
name := "test"
replicas := int32(1)
p := &v1alpha1.Prometheus{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
},
@ -197,7 +198,7 @@ scrape_configs:
`
cfg := &v1.Secret{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("prometheus-%s", name),
},
Data: map[string][]byte{
@ -257,7 +258,7 @@ func TestPrometheusReloadRules(t *testing.T) {
name := "test"
ruleFileConfigMap := &v1.ConfigMap{
ObjectMeta: v1.ObjectMeta{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("prometheus-%s-rules", name),
Labels: map[string]string{
"role": "rulefile",
@ -327,7 +328,7 @@ func TestPrometheusDiscovery(t *testing.T) {
ctx.AddFinalizerFn(finalizerFn)
}
_, err := framework.KubeClient.CoreV1().Secrets(ns).Get(fmt.Sprintf("prometheus-%s", prometheusName))
_, err := framework.KubeClient.CoreV1().Secrets(ns).Get(fmt.Sprintf("prometheus-%s", prometheusName), metav1.GetOptions{})
if err != nil {
t.Fatal("Generated Secret could not be retrieved: ", err)
}
@ -367,7 +368,7 @@ func TestPrometheusAlertmanagerDiscovery(t *testing.T) {
t.Fatalf("Creating ServiceMonitor failed: %v", err)
}
_, err := framework.KubeClient.CoreV1().Secrets(ns).Get(fmt.Sprintf("prometheus-%s", prometheusName))
_, err := framework.KubeClient.CoreV1().Secrets(ns).Get(fmt.Sprintf("prometheus-%s", prometheusName), metav1.GetOptions{})
if err != nil {
t.Fatalf("Generated Secret could not be retrieved: %v", err)
}

View file

@ -21,7 +21,7 @@ import (
"time"
"github.com/coreos/prometheus-operator/third_party/clock"
utilruntime "k8s.io/client-go/pkg/util/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
// DelayingInterface is an Interface that can Add an item at a later time. This makes it easier to

View file

@ -19,7 +19,7 @@ package workqueue
import (
"sync"
utilruntime "k8s.io/client-go/pkg/util/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
type DoWorkPieceFunc func(piece int)

202
vendor/k8s.io/apimachinery/LICENSE generated vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

27
vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS generated vendored Executable file
View file

@ -0,0 +1,27 @@
reviewers:
- thockin
- lavalamp
- smarterclayton
- wojtek-t
- deads2k
- brendandburns
- derekwaynecarr
- caesarxuchao
- mikedanese
- liggitt
- nikhiljindal
- gmarek
- erictune
- saad-ali
- janetkuo
- timstclair
- eparis
- timothysc
- dims
- spxtr
- hongchaodeng
- krousey
- satnam6502
- cjcullen
- david-mcmahon
- goltermann

View file

@ -15,4 +15,4 @@ limitations under the License.
*/
// Package errors provides detailed error types for api field validation.
package errors
package errors // import "k8s.io/apimachinery/pkg/api/errors"

View file

@ -22,9 +22,10 @@ import (
"net/http"
"strings"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/util/validation/field"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// HTTP Status codes not in the golang http package.
@ -40,13 +41,13 @@ const (
// StatusError is an error intended for consumption by a REST API server; it can also be
// reconstructed by clients from a REST response. Public to allow easy type switches.
type StatusError struct {
ErrStatus unversioned.Status
ErrStatus metav1.Status
}
// APIStatus is exposed by errors that can be converted to an api.Status object
// for finer grained details.
type APIStatus interface {
Status() unversioned.Status
Status() metav1.Status
}
var _ error = &StatusError{}
@ -57,8 +58,8 @@ func (e *StatusError) Error() string {
}
// Status allows access to e's status without having to know the detailed workings
// of StatusError. Used by pkg/apiserver.
func (e *StatusError) Status() unversioned.Status {
// of StatusError.
func (e *StatusError) Status() metav1.Status {
return e.ErrStatus
}
@ -80,23 +81,23 @@ func (u *UnexpectedObjectError) Error() string {
return fmt.Sprintf("unexpected object: %v", u.Object)
}
// FromObject generates an StatusError from an unversioned.Status, if that is the type of obj; otherwise,
// FromObject generates an StatusError from an metav1.Status, if that is the type of obj; otherwise,
// returns an UnexpecteObjectError.
func FromObject(obj runtime.Object) error {
switch t := obj.(type) {
case *unversioned.Status:
case *metav1.Status:
return &StatusError{*t}
}
return &UnexpectedObjectError{obj}
}
// NewNotFound returns a new error which indicates that the resource of the kind and the name was not found.
func NewNotFound(qualifiedResource unversioned.GroupResource, name string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewNotFound(qualifiedResource schema.GroupResource, name string) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusNotFound,
Reason: unversioned.StatusReasonNotFound,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonNotFound,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: name,
@ -106,12 +107,12 @@ func NewNotFound(qualifiedResource unversioned.GroupResource, name string) *Stat
}
// NewAlreadyExists returns an error indicating the item requested exists by that identifier.
func NewAlreadyExists(qualifiedResource unversioned.GroupResource, name string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewAlreadyExists(qualifiedResource schema.GroupResource, name string) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusConflict,
Reason: unversioned.StatusReasonAlreadyExists,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonAlreadyExists,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: name,
@ -127,21 +128,21 @@ func NewUnauthorized(reason string) *StatusError {
if len(message) == 0 {
message = "not authorized"
}
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusUnauthorized,
Reason: unversioned.StatusReasonUnauthorized,
Reason: metav1.StatusReasonUnauthorized,
Message: message,
}}
}
// NewForbidden returns an error indicating the requested action was forbidden
func NewForbidden(qualifiedResource unversioned.GroupResource, name string, err error) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewForbidden(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusForbidden,
Reason: unversioned.StatusReasonForbidden,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonForbidden,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: name,
@ -151,12 +152,12 @@ func NewForbidden(qualifiedResource unversioned.GroupResource, name string, err
}
// NewConflict returns an error indicating the item can't be updated as provided.
func NewConflict(qualifiedResource unversioned.GroupResource, name string, err error) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewConflict(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusConflict,
Reason: unversioned.StatusReasonConflict,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonConflict,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: name,
@ -167,30 +168,30 @@ func NewConflict(qualifiedResource unversioned.GroupResource, name string, err e
// NewGone returns an error indicating the item no longer available at the server and no forwarding address is known.
func NewGone(message string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusGone,
Reason: unversioned.StatusReasonGone,
Reason: metav1.StatusReasonGone,
Message: message,
}}
}
// NewInvalid returns an error indicating the item is invalid and cannot be processed.
func NewInvalid(qualifiedKind unversioned.GroupKind, name string, errs field.ErrorList) *StatusError {
causes := make([]unversioned.StatusCause, 0, len(errs))
func NewInvalid(qualifiedKind schema.GroupKind, name string, errs field.ErrorList) *StatusError {
causes := make([]metav1.StatusCause, 0, len(errs))
for i := range errs {
err := errs[i]
causes = append(causes, unversioned.StatusCause{
Type: unversioned.CauseType(err.Type),
causes = append(causes, metav1.StatusCause{
Type: metav1.CauseType(err.Type),
Message: err.ErrorBody(),
Field: err.Field,
})
}
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: StatusUnprocessableEntity, // RFC 4918: StatusUnprocessableEntity
Reason: unversioned.StatusReasonInvalid,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonInvalid,
Details: &metav1.StatusDetails{
Group: qualifiedKind.Group,
Kind: qualifiedKind.Kind,
Name: name,
@ -202,31 +203,31 @@ func NewInvalid(qualifiedKind unversioned.GroupKind, name string, errs field.Err
// NewBadRequest creates an error that indicates that the request is invalid and can not be processed.
func NewBadRequest(reason string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusBadRequest,
Reason: unversioned.StatusReasonBadRequest,
Reason: metav1.StatusReasonBadRequest,
Message: reason,
}}
}
// NewServiceUnavailable creates an error that indicates that the requested service is unavailable.
func NewServiceUnavailable(reason string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusServiceUnavailable,
Reason: unversioned.StatusReasonServiceUnavailable,
Reason: metav1.StatusReasonServiceUnavailable,
Message: reason,
}}
}
// NewMethodNotSupported returns an error indicating the requested action is not supported on this kind.
func NewMethodNotSupported(qualifiedResource unversioned.GroupResource, action string) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewMethodNotSupported(qualifiedResource schema.GroupResource, action string) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusMethodNotAllowed,
Reason: unversioned.StatusReasonMethodNotAllowed,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonMethodNotAllowed,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
},
@ -236,12 +237,12 @@ func NewMethodNotSupported(qualifiedResource unversioned.GroupResource, action s
// NewServerTimeout returns an error indicating the requested action could not be completed due to a
// transient error, and the client should try again.
func NewServerTimeout(qualifiedResource unversioned.GroupResource, operation string, retryAfterSeconds int) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
func NewServerTimeout(qualifiedResource schema.GroupResource, operation string, retryAfterSeconds int) *StatusError {
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusInternalServerError,
Reason: unversioned.StatusReasonServerTimeout,
Details: &unversioned.StatusDetails{
Reason: metav1.StatusReasonServerTimeout,
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: operation,
@ -253,18 +254,18 @@ func NewServerTimeout(qualifiedResource unversioned.GroupResource, operation str
// NewServerTimeoutForKind should not exist. Server timeouts happen when accessing resources, the Kind is just what we
// happened to be looking at when the request failed. This delegates to keep code sane, but we should work towards removing this.
func NewServerTimeoutForKind(qualifiedKind unversioned.GroupKind, operation string, retryAfterSeconds int) *StatusError {
return NewServerTimeout(unversioned.GroupResource{Group: qualifiedKind.Group, Resource: qualifiedKind.Kind}, operation, retryAfterSeconds)
func NewServerTimeoutForKind(qualifiedKind schema.GroupKind, operation string, retryAfterSeconds int) *StatusError {
return NewServerTimeout(schema.GroupResource{Group: qualifiedKind.Group, Resource: qualifiedKind.Kind}, operation, retryAfterSeconds)
}
// NewInternalError returns an error indicating the item is invalid and cannot be processed.
func NewInternalError(err error) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusInternalServerError,
Reason: unversioned.StatusReasonInternalError,
Details: &unversioned.StatusDetails{
Causes: []unversioned.StatusCause{{Message: err.Error()}},
Reason: metav1.StatusReasonInternalError,
Details: &metav1.StatusDetails{
Causes: []metav1.StatusCause{{Message: err.Error()}},
},
Message: fmt.Sprintf("Internal error occurred: %v", err),
}}
@ -273,56 +274,57 @@ func NewInternalError(err error) *StatusError {
// NewTimeoutError returns an error indicating that a timeout occurred before the request
// could be completed. Clients may retry, but the operation may still complete.
func NewTimeoutError(message string, retryAfterSeconds int) *StatusError {
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: StatusServerTimeout,
Reason: unversioned.StatusReasonTimeout,
Reason: metav1.StatusReasonTimeout,
Message: fmt.Sprintf("Timeout: %s", message),
Details: &unversioned.StatusDetails{
Details: &metav1.StatusDetails{
RetryAfterSeconds: int32(retryAfterSeconds),
},
}}
}
// NewGenericServerResponse returns a new error for server responses that are not in a recognizable form.
func NewGenericServerResponse(code int, verb string, qualifiedResource unversioned.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError {
reason := unversioned.StatusReasonUnknown
func NewGenericServerResponse(code int, verb string, qualifiedResource schema.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError {
reason := metav1.StatusReasonUnknown
message := fmt.Sprintf("the server responded with the status code %d but did not return more information", code)
switch code {
case http.StatusConflict:
if verb == "POST" {
reason = unversioned.StatusReasonAlreadyExists
reason = metav1.StatusReasonAlreadyExists
} else {
reason = unversioned.StatusReasonConflict
reason = metav1.StatusReasonConflict
}
message = "the server reported a conflict"
case http.StatusNotFound:
reason = unversioned.StatusReasonNotFound
reason = metav1.StatusReasonNotFound
message = "the server could not find the requested resource"
case http.StatusBadRequest:
reason = unversioned.StatusReasonBadRequest
reason = metav1.StatusReasonBadRequest
message = "the server rejected our request for an unknown reason"
case http.StatusUnauthorized:
reason = unversioned.StatusReasonUnauthorized
reason = metav1.StatusReasonUnauthorized
message = "the server has asked for the client to provide credentials"
case http.StatusForbidden:
reason = unversioned.StatusReasonForbidden
message = "the server does not allow access to the requested resource"
reason = metav1.StatusReasonForbidden
// the server message has details about who is trying to perform what action. Keep its message.
message = serverMessage
case http.StatusMethodNotAllowed:
reason = unversioned.StatusReasonMethodNotAllowed
reason = metav1.StatusReasonMethodNotAllowed
message = "the server does not allow this method on the requested resource"
case StatusUnprocessableEntity:
reason = unversioned.StatusReasonInvalid
reason = metav1.StatusReasonInvalid
message = "the server rejected our request due to an error in our request"
case StatusServerTimeout:
reason = unversioned.StatusReasonServerTimeout
reason = metav1.StatusReasonServerTimeout
message = "the server cannot complete the requested operation at this time, try again later"
case StatusTooManyRequests:
reason = unversioned.StatusReasonTimeout
reason = metav1.StatusReasonTimeout
message = "the server has received too many requests and has asked us to try again later"
default:
if code >= 500 {
reason = unversioned.StatusReasonInternalError
reason = metav1.StatusReasonInternalError
message = fmt.Sprintf("an error on the server (%q) has prevented the request from succeeding", serverMessage)
}
}
@ -332,22 +334,22 @@ func NewGenericServerResponse(code int, verb string, qualifiedResource unversion
case !qualifiedResource.Empty():
message = fmt.Sprintf("%s (%s %s)", message, strings.ToLower(verb), qualifiedResource.String())
}
var causes []unversioned.StatusCause
var causes []metav1.StatusCause
if isUnexpectedResponse {
causes = []unversioned.StatusCause{
causes = []metav1.StatusCause{
{
Type: unversioned.CauseTypeUnexpectedServerResponse,
Type: metav1.CauseTypeUnexpectedServerResponse,
Message: serverMessage,
},
}
} else {
causes = nil
}
return &StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
return &StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: int32(code),
Reason: reason,
Details: &unversioned.StatusDetails{
Details: &metav1.StatusDetails{
Group: qualifiedResource.Group,
Kind: qualifiedResource.Resource,
Name: name,
@ -361,56 +363,62 @@ func NewGenericServerResponse(code int, verb string, qualifiedResource unversion
// IsNotFound returns true if the specified error was created by NewNotFound.
func IsNotFound(err error) bool {
return reasonForError(err) == unversioned.StatusReasonNotFound
return reasonForError(err) == metav1.StatusReasonNotFound
}
// IsAlreadyExists determines if the err is an error which indicates that a specified resource already exists.
func IsAlreadyExists(err error) bool {
return reasonForError(err) == unversioned.StatusReasonAlreadyExists
return reasonForError(err) == metav1.StatusReasonAlreadyExists
}
// IsConflict determines if the err is an error which indicates the provided update conflicts.
func IsConflict(err error) bool {
return reasonForError(err) == unversioned.StatusReasonConflict
return reasonForError(err) == metav1.StatusReasonConflict
}
// IsInvalid determines if the err is an error which indicates the provided resource is not valid.
func IsInvalid(err error) bool {
return reasonForError(err) == unversioned.StatusReasonInvalid
return reasonForError(err) == metav1.StatusReasonInvalid
}
// IsMethodNotSupported determines if the err is an error which indicates the provided action could not
// be performed because it is not supported by the server.
func IsMethodNotSupported(err error) bool {
return reasonForError(err) == unversioned.StatusReasonMethodNotAllowed
return reasonForError(err) == metav1.StatusReasonMethodNotAllowed
}
// IsBadRequest determines if err is an error which indicates that the request is invalid.
func IsBadRequest(err error) bool {
return reasonForError(err) == unversioned.StatusReasonBadRequest
return reasonForError(err) == metav1.StatusReasonBadRequest
}
// IsUnauthorized determines if err is an error which indicates that the request is unauthorized and
// requires authentication by the user.
func IsUnauthorized(err error) bool {
return reasonForError(err) == unversioned.StatusReasonUnauthorized
return reasonForError(err) == metav1.StatusReasonUnauthorized
}
// IsForbidden determines if err is an error which indicates that the request is forbidden and cannot
// be completed as requested.
func IsForbidden(err error) bool {
return reasonForError(err) == unversioned.StatusReasonForbidden
return reasonForError(err) == metav1.StatusReasonForbidden
}
// IsTimeout determines if err is an error which indicates that request times out due to long
// processing.
func IsTimeout(err error) bool {
return reasonForError(err) == metav1.StatusReasonTimeout
}
// IsServerTimeout determines if err is an error which indicates that the request needs to be retried
// by the client.
func IsServerTimeout(err error) bool {
return reasonForError(err) == unversioned.StatusReasonServerTimeout
return reasonForError(err) == metav1.StatusReasonServerTimeout
}
// IsInternalError determines if err is an error which indicates an internal server error.
func IsInternalError(err error) bool {
return reasonForError(err) == unversioned.StatusReasonInternalError
return reasonForError(err) == metav1.StatusReasonInternalError
}
// IsTooManyRequests determines if err is an error which indicates that there are too many requests
@ -431,7 +439,7 @@ func IsUnexpectedServerError(err error) bool {
case APIStatus:
if d := t.Status().Details; d != nil {
for _, cause := range d.Causes {
if cause.Type == unversioned.CauseTypeUnexpectedServerResponse {
if cause.Type == metav1.CauseTypeUnexpectedServerResponse {
return true
}
}
@ -453,7 +461,7 @@ func SuggestsClientDelay(err error) (int, bool) {
case APIStatus:
if t.Status().Details != nil {
switch t.Status().Reason {
case unversioned.StatusReasonServerTimeout, unversioned.StatusReasonTimeout:
case metav1.StatusReasonServerTimeout, metav1.StatusReasonTimeout:
return int(t.Status().Details.RetryAfterSeconds), true
}
}
@ -461,10 +469,10 @@ func SuggestsClientDelay(err error) (int, bool) {
return 0, false
}
func reasonForError(err error) unversioned.StatusReason {
func reasonForError(err error) metav1.StatusReason {
switch t := err.(type) {
case APIStatus:
return t.Status().Reason
}
return unversioned.StatusReasonUnknown
return metav1.StatusReasonUnknown
}

26
vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS generated vendored Executable file
View file

@ -0,0 +1,26 @@
reviewers:
- thockin
- smarterclayton
- wojtek-t
- deads2k
- brendandburns
- derekwaynecarr
- caesarxuchao
- mikedanese
- liggitt
- nikhiljindal
- gmarek
- kargakis
- janetkuo
- ncdc
- eparis
- dims
- krousey
- markturansky
- fabioy
- resouer
- david-mcmahon
- mfojtik
- jianhuiz
- feihujiang
- ghodss

View file

@ -14,28 +14,21 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package api
package meta
import (
"strings"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/util/sets"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
)
// Instantiates a DefaultRESTMapper based on types registered in api.Scheme
func NewDefaultRESTMapper(defaultGroupVersions []unversioned.GroupVersion, interfacesFunc meta.VersionInterfacesFunc,
importPathPrefix string, ignoredKinds, rootScoped sets.String) *meta.DefaultRESTMapper {
return NewDefaultRESTMapperFromScheme(defaultGroupVersions, interfacesFunc, importPathPrefix, ignoredKinds, rootScoped, Scheme)
}
// NewDefaultRESTMapperFromScheme instantiates a DefaultRESTMapper based on types registered in the given scheme.
func NewDefaultRESTMapperFromScheme(defaultGroupVersions []schema.GroupVersion, interfacesFunc VersionInterfacesFunc,
importPathPrefix string, ignoredKinds, rootScoped sets.String, scheme *runtime.Scheme) *DefaultRESTMapper {
// Instantiates a DefaultRESTMapper based on types registered in the given scheme.
func NewDefaultRESTMapperFromScheme(defaultGroupVersions []unversioned.GroupVersion, interfacesFunc meta.VersionInterfacesFunc,
importPathPrefix string, ignoredKinds, rootScoped sets.String, scheme *runtime.Scheme) *meta.DefaultRESTMapper {
mapper := meta.NewDefaultRESTMapper(defaultGroupVersions, interfacesFunc)
mapper := NewDefaultRESTMapper(defaultGroupVersions, interfacesFunc)
// enumerate all supported versions, get the kinds, and register with the mapper how to address
// our resources.
for _, gv := range defaultGroupVersions {
@ -47,9 +40,9 @@ func NewDefaultRESTMapperFromScheme(defaultGroupVersions []unversioned.GroupVers
if !strings.Contains(oType.PkgPath(), importPathPrefix) || ignoredKinds.Has(kind) {
continue
}
scope := meta.RESTScopeNamespace
scope := RESTScopeNamespace
if rootScoped.Has(kind) {
scope = meta.RESTScopeRoot
scope = RESTScopeRoot
}
mapper.Add(gvk, scope)
}

View file

@ -16,4 +16,4 @@ limitations under the License.
// Package meta provides functions for retrieving API metadata from objects
// belonging to the Kubernetes API
package meta
package meta // import "k8s.io/apimachinery/pkg/api/meta"

View file

@ -19,15 +19,15 @@ package meta
import (
"fmt"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// AmbiguousResourceError is returned if the RESTMapper finds multiple matches for a resource
type AmbiguousResourceError struct {
PartialResource unversioned.GroupVersionResource
PartialResource schema.GroupVersionResource
MatchingResources []unversioned.GroupVersionResource
MatchingKinds []unversioned.GroupVersionKind
MatchingResources []schema.GroupVersionResource
MatchingKinds []schema.GroupVersionKind
}
func (e *AmbiguousResourceError) Error() string {
@ -44,10 +44,10 @@ func (e *AmbiguousResourceError) Error() string {
// AmbiguousKindError is returned if the RESTMapper finds multiple matches for a kind
type AmbiguousKindError struct {
PartialKind unversioned.GroupVersionKind
PartialKind schema.GroupVersionKind
MatchingResources []unversioned.GroupVersionResource
MatchingKinds []unversioned.GroupVersionKind
MatchingResources []schema.GroupVersionResource
MatchingKinds []schema.GroupVersionKind
}
func (e *AmbiguousKindError) Error() string {
@ -76,7 +76,7 @@ func IsAmbiguousError(err error) bool {
// NoResourceMatchError is returned if the RESTMapper can't find any match for a resource
type NoResourceMatchError struct {
PartialResource unversioned.GroupVersionResource
PartialResource schema.GroupVersionResource
}
func (e *NoResourceMatchError) Error() string {
@ -85,7 +85,7 @@ func (e *NoResourceMatchError) Error() string {
// NoKindMatchError is returned if the RESTMapper can't find any match for a kind
type NoKindMatchError struct {
PartialKind unversioned.GroupVersionKind
PartialKind schema.GroupVersionKind
}
func (e *NoKindMatchError) Error() string {

View file

@ -19,8 +19,8 @@ package meta
import (
"fmt"
"k8s.io/client-go/pkg/api/unversioned"
utilerrors "k8s.io/client-go/pkg/util/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
)
// FirstHitRESTMapper is a wrapper for multiple RESTMappers which returns the
@ -33,7 +33,7 @@ func (m FirstHitRESTMapper) String() string {
return fmt.Sprintf("FirstHitRESTMapper{\n\t%v\n}", m.MultiRESTMapper)
}
func (m FirstHitRESTMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
func (m FirstHitRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
errors := []error{}
for _, t := range m.MultiRESTMapper {
ret, err := t.ResourceFor(resource)
@ -43,10 +43,10 @@ func (m FirstHitRESTMapper) ResourceFor(resource unversioned.GroupVersionResourc
errors = append(errors, err)
}
return unversioned.GroupVersionResource{}, collapseAggregateErrors(errors)
return schema.GroupVersionResource{}, collapseAggregateErrors(errors)
}
func (m FirstHitRESTMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
func (m FirstHitRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
errors := []error{}
for _, t := range m.MultiRESTMapper {
ret, err := t.KindFor(resource)
@ -56,13 +56,13 @@ func (m FirstHitRESTMapper) KindFor(resource unversioned.GroupVersionResource) (
errors = append(errors, err)
}
return unversioned.GroupVersionKind{}, collapseAggregateErrors(errors)
return schema.GroupVersionKind{}, collapseAggregateErrors(errors)
}
// RESTMapping provides the REST mapping for the resource based on the
// kind and version. This implementation supports multiple REST schemas and
// return the first match.
func (m FirstHitRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) {
func (m FirstHitRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
errors := []error{}
for _, t := range m.MultiRESTMapper {
ret, err := t.RESTMapping(gk, versions...)

View file

@ -20,18 +20,16 @@ import (
"fmt"
"reflect"
"k8s.io/client-go/pkg/conversion"
"k8s.io/client-go/pkg/runtime"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
)
// IsListType returns true if the provided Object has a slice called Items
func IsListType(obj runtime.Object) bool {
// if we're a runtime.Unstructured, check to see if we have an `items` key
// This is a list type for recognition, but other Items type methods will fail on it
// and give you errors.
if unstructured, ok := obj.(*runtime.Unstructured); ok {
_, ok := unstructured.Object["items"]
return ok
// if we're a runtime.Unstructured, check whether this is a list.
// TODO: refactor GetItemsPtr to use an interface that returns []runtime.Object
if unstructured, ok := obj.(runtime.Unstructured); ok {
return unstructured.IsList()
}
_, err := GetItemsPtr(obj)

View file

@ -17,10 +17,10 @@ limitations under the License.
package meta
import (
"k8s.io/client-go/pkg/api/meta/metatypes"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/types"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
)
// VersionInterfaces contains the interfaces one should use for dealing with types of a particular version.
@ -29,45 +29,6 @@ type VersionInterfaces struct {
MetadataAccessor
}
type ObjectMetaAccessor interface {
GetObjectMeta() Object
}
// Object lets you work with object metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field (Name, UID, Namespace on lists) will be a no-op and return
// a default value.
type Object interface {
GetNamespace() string
SetNamespace(namespace string)
GetName() string
SetName(name string)
GetGenerateName() string
SetGenerateName(name string)
GetUID() types.UID
SetUID(uid types.UID)
GetResourceVersion() string
SetResourceVersion(version string)
GetSelfLink() string
SetSelfLink(selfLink string)
GetCreationTimestamp() unversioned.Time
SetCreationTimestamp(timestamp unversioned.Time)
GetDeletionTimestamp() *unversioned.Time
SetDeletionTimestamp(timestamp *unversioned.Time)
GetLabels() map[string]string
SetLabels(labels map[string]string)
GetAnnotations() map[string]string
SetAnnotations(annotations map[string]string)
GetFinalizers() []string
SetFinalizers(finalizers []string)
GetOwnerReferences() []metatypes.OwnerReference
SetOwnerReferences([]metatypes.OwnerReference)
GetClusterName() string
SetClusterName(clusterName string)
}
var _ Object = &runtime.Unstructured{}
type ListMetaAccessor interface {
GetListMeta() List
}
@ -75,10 +36,10 @@ type ListMetaAccessor interface {
// List lets you work with list metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field will be a no-op and return a default value.
type List unversioned.List
type List metav1.List
// Type exposes the type and APIVersion of versioned or internal API objects.
type Type unversioned.Type
type Type metav1.Type
// MetadataAccessor lets you work with object and list metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
@ -143,7 +104,7 @@ type RESTMapping struct {
// Resource is a string representing the name of this resource as a REST client would see it
Resource string
GroupVersionKind unversioned.GroupVersionKind
GroupVersionKind schema.GroupVersionKind
// Scope contains the information needed to deal with REST Resources that are in a resource hierarchy
Scope RESTScope
@ -163,21 +124,23 @@ type RESTMapping struct {
// TODO: split into sub-interfaces
type RESTMapper interface {
// KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error)
KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)
// KindsFor takes a partial resource and returns the list of potential kinds in priority order
KindsFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error)
KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)
// ResourceFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
ResourceFor(input unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error)
ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error)
// ResourcesFor takes a partial resource and returns the list of potential resource in priority order
ResourcesFor(input unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error)
ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)
// RESTMapping identifies a preferred resource mapping for the provided group kind.
RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error)
// RESTMappings returns all resource mappings for the provided group kind.
RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error)
RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)
// RESTMappings returns all resource mappings for the provided group kind if no
// version search is provided. Otherwise identifies a preferred resource mapping for
// the provided version(s).
RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)
AliasesForResource(resource string) ([]string, bool)
ResourceSingularizer(resource string) (singular string, err error)

View file

@ -20,13 +20,13 @@ import (
"fmt"
"reflect"
"k8s.io/client-go/pkg/api/meta/metatypes"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/conversion"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/types"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
)
// errNotList is returned when an object implements the Object style interfaces but not the List style
@ -42,21 +42,21 @@ func ListAccessor(obj interface{}) (List, error) {
switch t := obj.(type) {
case List:
return t, nil
case unversioned.List:
case metav1.List:
return t, nil
case ListMetaAccessor:
if m := t.GetListMeta(); m != nil {
return m, nil
}
return nil, errNotList
case unversioned.ListMetaAccessor:
case metav1.ListMetaAccessor:
if m := t.GetListMeta(); m != nil {
return m, nil
}
return nil, errNotList
case Object:
case metav1.Object:
return t, nil
case ObjectMetaAccessor:
case metav1.ObjectMetaAccessor:
if m := t.GetObjectMeta(); m != nil {
return m, nil
}
@ -75,16 +75,16 @@ var errNotObject = fmt.Errorf("object does not implement the Object interfaces")
// required fields are missing. Fields that are not required return the default
// value and are a no-op if set.
// TODO: return bool instead of error
func Accessor(obj interface{}) (Object, error) {
func Accessor(obj interface{}) (metav1.Object, error) {
switch t := obj.(type) {
case Object:
case metav1.Object:
return t, nil
case ObjectMetaAccessor:
case metav1.ObjectMetaAccessor:
if m := t.GetObjectMeta(); m != nil {
return m, nil
}
return nil, errNotObject
case List, unversioned.List, ListMetaAccessor, unversioned.ListMetaAccessor:
case List, metav1.List, ListMetaAccessor, metav1.ListMetaAccessor:
return nil, errNotObject
default:
return nil, errNotObject
@ -140,9 +140,9 @@ func (obj objectAccessor) GetAPIVersion() string {
func (obj objectAccessor) SetAPIVersion(version string) {
gvk := obj.GetObjectKind().GroupVersionKind()
gv, err := unversioned.ParseGroupVersion(version)
gv, err := schema.ParseGroupVersion(version)
if err != nil {
gv = unversioned.GroupVersion{Version: version}
gv = schema.GroupVersion{Version: version}
}
gvk.Group, gvk.Version = gv.Group, gv.Version
obj.GetObjectKind().SetGroupVersionKind(gvk)
@ -313,7 +313,7 @@ func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) e
}
// extractFromOwnerReference extracts v to o. v is the OwnerReferences field of an object.
func extractFromOwnerReference(v reflect.Value, o *metatypes.OwnerReference) error {
func extractFromOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {
if err := runtime.Field(v, "APIVersion", &o.APIVersion); err != nil {
return err
}
@ -334,11 +334,19 @@ func extractFromOwnerReference(v reflect.Value, o *metatypes.OwnerReference) err
controller := *controllerPtr
o.Controller = &controller
}
var blockOwnerDeletionPtr *bool
if err := runtime.Field(v, "BlockOwnerDeletion", &blockOwnerDeletionPtr); err != nil {
return err
}
if blockOwnerDeletionPtr != nil {
block := *blockOwnerDeletionPtr
o.BlockOwnerDeletion = &block
}
return nil
}
// setOwnerReference sets v to o. v is the OwnerReferences field of an object.
func setOwnerReference(v reflect.Value, o *metatypes.OwnerReference) error {
func setOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {
if err := runtime.SetField(o.APIVersion, v, "APIVersion"); err != nil {
return err
}
@ -357,6 +365,12 @@ func setOwnerReference(v reflect.Value, o *metatypes.OwnerReference) error {
return err
}
}
if o.BlockOwnerDeletion != nil {
block := *(o.BlockOwnerDeletion)
if err := runtime.SetField(&block, v, "BlockOwnerDeletion"); err != nil {
return err
}
}
return nil
}
@ -371,8 +385,8 @@ type genericAccessor struct {
kind *string
resourceVersion *string
selfLink *string
creationTimestamp *unversioned.Time
deletionTimestamp **unversioned.Time
creationTimestamp *metav1.Time
deletionTimestamp **metav1.Time
labels *map[string]string
annotations *map[string]string
ownerReferences reflect.Value
@ -467,19 +481,19 @@ func (a genericAccessor) SetSelfLink(selfLink string) {
*a.selfLink = selfLink
}
func (a genericAccessor) GetCreationTimestamp() unversioned.Time {
func (a genericAccessor) GetCreationTimestamp() metav1.Time {
return *a.creationTimestamp
}
func (a genericAccessor) SetCreationTimestamp(timestamp unversioned.Time) {
func (a genericAccessor) SetCreationTimestamp(timestamp metav1.Time) {
*a.creationTimestamp = timestamp
}
func (a genericAccessor) GetDeletionTimestamp() *unversioned.Time {
func (a genericAccessor) GetDeletionTimestamp() *metav1.Time {
return *a.deletionTimestamp
}
func (a genericAccessor) SetDeletionTimestamp(timestamp *unversioned.Time) {
func (a genericAccessor) SetDeletionTimestamp(timestamp *metav1.Time) {
*a.deletionTimestamp = timestamp
}
@ -520,8 +534,8 @@ func (a genericAccessor) SetFinalizers(finalizers []string) {
*a.finalizers = finalizers
}
func (a genericAccessor) GetOwnerReferences() []metatypes.OwnerReference {
var ret []metatypes.OwnerReference
func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference {
var ret []metav1.OwnerReference
s := a.ownerReferences
if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice {
glog.Errorf("expect %v to be a pointer to slice", s)
@ -529,7 +543,7 @@ func (a genericAccessor) GetOwnerReferences() []metatypes.OwnerReference {
}
s = s.Elem()
// Set the capacity to one element greater to avoid copy if the caller later append an element.
ret = make([]metatypes.OwnerReference, s.Len(), s.Len()+1)
ret = make([]metav1.OwnerReference, s.Len(), s.Len()+1)
for i := 0; i < s.Len(); i++ {
if err := extractFromOwnerReference(s.Index(i), &ret[i]); err != nil {
glog.Errorf("extractFromOwnerReference failed: %v", err)
@ -539,7 +553,7 @@ func (a genericAccessor) GetOwnerReferences() []metatypes.OwnerReference {
return ret
}
func (a genericAccessor) SetOwnerReferences(references []metatypes.OwnerReference) {
func (a genericAccessor) SetOwnerReferences(references []metav1.OwnerReference) {
s := a.ownerReferences
if s.Kind() != reflect.Ptr || s.Elem().Kind() != reflect.Slice {
glog.Errorf("expect %v to be a pointer to slice", s)

View file

@ -20,9 +20,9 @@ import (
"fmt"
"strings"
"k8s.io/client-go/pkg/api/unversioned"
utilerrors "k8s.io/client-go/pkg/util/errors"
"k8s.io/client-go/pkg/util/sets"
"k8s.io/apimachinery/pkg/runtime/schema"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
)
// MultiRESTMapper is a wrapper for multiple RESTMappers.
@ -51,8 +51,8 @@ func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string,
return
}
func (m MultiRESTMapper) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
allGVRs := []unversioned.GroupVersionResource{}
func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
allGVRs := []schema.GroupVersionResource{}
for _, t := range m {
gvrs, err := t.ResourcesFor(resource)
// ignore "no match" errors, but any other error percolates back up
@ -86,8 +86,8 @@ func (m MultiRESTMapper) ResourcesFor(resource unversioned.GroupVersionResource)
return allGVRs, nil
}
func (m MultiRESTMapper) KindsFor(resource unversioned.GroupVersionResource) (gvk []unversioned.GroupVersionKind, err error) {
allGVKs := []unversioned.GroupVersionKind{}
func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {
allGVKs := []schema.GroupVersionKind{}
for _, t := range m {
gvks, err := t.KindsFor(resource)
// ignore "no match" errors, but any other error percolates back up
@ -121,34 +121,34 @@ func (m MultiRESTMapper) KindsFor(resource unversioned.GroupVersionResource) (gv
return allGVKs, nil
}
func (m MultiRESTMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
resources, err := m.ResourcesFor(resource)
if err != nil {
return unversioned.GroupVersionResource{}, err
return schema.GroupVersionResource{}, err
}
if len(resources) == 1 {
return resources[0], nil
}
return unversioned.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
}
func (m MultiRESTMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
kinds, err := m.KindsFor(resource)
if err != nil {
return unversioned.GroupVersionKind{}, err
return schema.GroupVersionKind{}, err
}
if len(kinds) == 1 {
return kinds[0], nil
}
return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
}
// RESTMapping provides the REST mapping for the resource based on the
// kind and version. This implementation supports multiple REST schemas and
// return the first match.
func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) {
func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
allMappings := []*RESTMapping{}
errors := []error{}
@ -171,7 +171,7 @@ func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...strin
return allMappings[0], nil
}
if len(allMappings) > 1 {
var kinds []unversioned.GroupVersionKind
var kinds []schema.GroupVersionKind
for _, m := range allMappings {
kinds = append(kinds, m.GroupVersionKind)
}
@ -185,12 +185,12 @@ func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...strin
// RESTMappings returns all possible RESTMappings for the provided group kind, or an error
// if the type is not recognized.
func (m MultiRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) {
func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
var allMappings []*RESTMapping
var errors []error
for _, t := range m {
currMappings, err := t.RESTMappings(gk)
currMappings, err := t.RESTMappings(gk, versions...)
// ignore "no match" errors, but any other error percolates back up
if IsNoMatchError(err) {
continue

View file

@ -19,7 +19,7 @@ package meta
import (
"fmt"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/apimachinery/pkg/runtime/schema"
)
const (
@ -39,13 +39,13 @@ type PriorityRESTMapper struct {
// The list of all matching resources is narrowed based on the patterns until only one remains.
// A pattern with no matches is skipped. A pattern with more than one match uses its
// matches as the list to continue matching against.
ResourcePriority []unversioned.GroupVersionResource
ResourcePriority []schema.GroupVersionResource
// KindPriority is a list of priority patterns to apply to matching kinds.
// The list of all matching kinds is narrowed based on the patterns until only one remains.
// A pattern with no matches is skipped. A pattern with more than one match uses its
// matches as the list to continue matching against.
KindPriority []unversioned.GroupVersionKind
KindPriority []schema.GroupVersionKind
}
func (m PriorityRESTMapper) String() string {
@ -53,18 +53,18 @@ func (m PriorityRESTMapper) String() string {
}
// ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit.
func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
originalGVRs, err := m.Delegate.ResourcesFor(partiallySpecifiedResource)
if err != nil {
return unversioned.GroupVersionResource{}, err
return schema.GroupVersionResource{}, err
}
if len(originalGVRs) == 1 {
return originalGVRs[0], nil
}
remainingGVRs := append([]unversioned.GroupVersionResource{}, originalGVRs...)
remainingGVRs := append([]schema.GroupVersionResource{}, originalGVRs...)
for _, pattern := range m.ResourcePriority {
matchedGVRs := []unversioned.GroupVersionResource{}
matchedGVRs := []schema.GroupVersionResource{}
for _, gvr := range remainingGVRs {
if resourceMatches(pattern, gvr) {
matchedGVRs = append(matchedGVRs, gvr)
@ -85,22 +85,22 @@ func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource unversioned.G
}
}
return unversioned.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingResources: originalGVRs}
return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingResources: originalGVRs}
}
// KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit.
func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
originalGVKs, err := m.Delegate.KindsFor(partiallySpecifiedResource)
if err != nil {
return unversioned.GroupVersionKind{}, err
return schema.GroupVersionKind{}, err
}
if len(originalGVKs) == 1 {
return originalGVKs[0], nil
}
remainingGVKs := append([]unversioned.GroupVersionKind{}, originalGVKs...)
remainingGVKs := append([]schema.GroupVersionKind{}, originalGVKs...)
for _, pattern := range m.KindPriority {
matchedGVKs := []unversioned.GroupVersionKind{}
matchedGVKs := []schema.GroupVersionKind{}
for _, gvr := range remainingGVKs {
if kindMatches(pattern, gvr) {
matchedGVKs = append(matchedGVKs, gvr)
@ -121,10 +121,10 @@ func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource unversioned.Group
}
}
return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingKinds: originalGVKs}
return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingKinds: originalGVKs}
}
func resourceMatches(pattern unversioned.GroupVersionResource, resource unversioned.GroupVersionResource) bool {
func resourceMatches(pattern schema.GroupVersionResource, resource schema.GroupVersionResource) bool {
if pattern.Group != AnyGroup && pattern.Group != resource.Group {
return false
}
@ -138,7 +138,7 @@ func resourceMatches(pattern unversioned.GroupVersionResource, resource unversio
return true
}
func kindMatches(pattern unversioned.GroupVersionKind, kind unversioned.GroupVersionKind) bool {
func kindMatches(pattern schema.GroupVersionKind, kind schema.GroupVersionKind) bool {
if pattern.Group != AnyGroup && pattern.Group != kind.Group {
return false
}
@ -152,7 +152,7 @@ func kindMatches(pattern unversioned.GroupVersionKind, kind unversioned.GroupVer
return true
}
func (m PriorityRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (mapping *RESTMapping, err error) {
func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) {
mappings, err := m.Delegate.RESTMappings(gk)
if err != nil {
return nil, err
@ -161,11 +161,11 @@ func (m PriorityRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...st
// any versions the user provides take priority
priorities := m.KindPriority
if len(versions) > 0 {
priorities = make([]unversioned.GroupVersionKind, 0, len(m.KindPriority)+len(versions))
priorities = make([]schema.GroupVersionKind, 0, len(m.KindPriority)+len(versions))
for _, version := range versions {
gv, err := unversioned.ParseGroupVersion(version)
if err != nil {
return nil, err
gv := schema.GroupVersion{
Version: version,
Group: gk.Group,
}
priorities = append(priorities, gv.WithKind(AnyKind))
}
@ -198,15 +198,15 @@ func (m PriorityRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...st
return remaining[0], nil
}
var kinds []unversioned.GroupVersionKind
var kinds []schema.GroupVersionKind
for _, m := range mappings {
kinds = append(kinds, m.GroupVersionKind)
}
return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds}
}
func (m PriorityRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) {
return m.Delegate.RESTMappings(gk)
func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
return m.Delegate.RESTMappings(gk, versions...)
}
func (m PriorityRESTMapper) AliasesForResource(alias string) (aliases []string, ok bool) {
@ -217,10 +217,10 @@ func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular stri
return m.Delegate.ResourceSingularizer(resource)
}
func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
return m.Delegate.ResourcesFor(partiallySpecifiedResource)
}
func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource unversioned.GroupVersionResource) (gvk []unversioned.GroupVersionKind, err error) {
func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {
return m.Delegate.KindsFor(partiallySpecifiedResource)
}

View file

@ -22,8 +22,8 @@ import (
"sort"
"strings"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// Implements RESTScope interface
@ -70,13 +70,13 @@ var RESTScopeRoot = &restScope{
// TODO: Only accept plural for some operations for increased control?
// (`get pod bar` vs `get pods bar`)
type DefaultRESTMapper struct {
defaultGroupVersions []unversioned.GroupVersion
defaultGroupVersions []schema.GroupVersion
resourceToKind map[unversioned.GroupVersionResource]unversioned.GroupVersionKind
kindToPluralResource map[unversioned.GroupVersionKind]unversioned.GroupVersionResource
kindToScope map[unversioned.GroupVersionKind]RESTScope
singularToPlural map[unversioned.GroupVersionResource]unversioned.GroupVersionResource
pluralToSingular map[unversioned.GroupVersionResource]unversioned.GroupVersionResource
resourceToKind map[schema.GroupVersionResource]schema.GroupVersionKind
kindToPluralResource map[schema.GroupVersionKind]schema.GroupVersionResource
kindToScope map[schema.GroupVersionKind]RESTScope
singularToPlural map[schema.GroupVersionResource]schema.GroupVersionResource
pluralToSingular map[schema.GroupVersionResource]schema.GroupVersionResource
interfacesFunc VersionInterfacesFunc
@ -92,19 +92,19 @@ var _ RESTMapper = &DefaultRESTMapper{}
// VersionInterfacesFunc returns the appropriate typer, and metadata accessor for a
// given api version, or an error if no such api version exists.
type VersionInterfacesFunc func(version unversioned.GroupVersion) (*VersionInterfaces, error)
type VersionInterfacesFunc func(version schema.GroupVersion) (*VersionInterfaces, error)
// NewDefaultRESTMapper initializes a mapping between Kind and APIVersion
// to a resource name and back based on the objects in a runtime.Scheme
// and the Kubernetes API conventions. Takes a group name, a priority list of the versions
// to search when an object has no default version (set empty to return an error),
// and a function that retrieves the correct metadata for a given version.
func NewDefaultRESTMapper(defaultGroupVersions []unversioned.GroupVersion, f VersionInterfacesFunc) *DefaultRESTMapper {
resourceToKind := make(map[unversioned.GroupVersionResource]unversioned.GroupVersionKind)
kindToPluralResource := make(map[unversioned.GroupVersionKind]unversioned.GroupVersionResource)
kindToScope := make(map[unversioned.GroupVersionKind]RESTScope)
singularToPlural := make(map[unversioned.GroupVersionResource]unversioned.GroupVersionResource)
pluralToSingular := make(map[unversioned.GroupVersionResource]unversioned.GroupVersionResource)
func NewDefaultRESTMapper(defaultGroupVersions []schema.GroupVersion, f VersionInterfacesFunc) *DefaultRESTMapper {
resourceToKind := make(map[schema.GroupVersionResource]schema.GroupVersionKind)
kindToPluralResource := make(map[schema.GroupVersionKind]schema.GroupVersionResource)
kindToScope := make(map[schema.GroupVersionKind]RESTScope)
singularToPlural := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
pluralToSingular := make(map[schema.GroupVersionResource]schema.GroupVersionResource)
aliasToResource := make(map[string][]string)
// TODO: verify name mappings work correctly when versions differ
@ -120,7 +120,7 @@ func NewDefaultRESTMapper(defaultGroupVersions []unversioned.GroupVersion, f Ver
}
}
func (m *DefaultRESTMapper) Add(kind unversioned.GroupVersionKind, scope RESTScope) {
func (m *DefaultRESTMapper) Add(kind schema.GroupVersionKind, scope RESTScope) {
plural, singular := KindToResource(kind)
m.singularToPlural[singular] = plural
@ -144,10 +144,10 @@ var unpluralizedSuffixes = []string{
// KindToResource converts Kind to a resource name.
// Broken. This method only "sort of" works when used outside of this package. It assumes that Kinds and Resources match
// and they aren't guaranteed to do so.
func KindToResource(kind unversioned.GroupVersionKind) ( /*plural*/ unversioned.GroupVersionResource /*singular*/, unversioned.GroupVersionResource) {
func KindToResource(kind schema.GroupVersionKind) ( /*plural*/ schema.GroupVersionResource /*singular*/, schema.GroupVersionResource) {
kindName := kind.Kind
if len(kindName) == 0 {
return unversioned.GroupVersionResource{}, unversioned.GroupVersionResource{}
return schema.GroupVersionResource{}, schema.GroupVersionResource{}
}
singularName := strings.ToLower(kindName)
singular := kind.GroupVersion().WithResource(singularName)
@ -171,13 +171,13 @@ func KindToResource(kind unversioned.GroupVersionKind) ( /*plural*/ unversioned.
// ResourceSingularizer implements RESTMapper
// It converts a resource name from plural to singular (e.g., from pods to pod)
func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, error) {
partialResource := unversioned.GroupVersionResource{Resource: resourceType}
partialResource := schema.GroupVersionResource{Resource: resourceType}
resources, err := m.ResourcesFor(partialResource)
if err != nil {
return resourceType, err
}
singular := unversioned.GroupVersionResource{}
singular := schema.GroupVersionResource{}
for _, curr := range resources {
currSingular, ok := m.pluralToSingular[curr]
if !ok {
@ -201,7 +201,7 @@ func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, e
}
// coerceResourceForMatching makes the resource lower case and converts internal versions to unspecified (legacy behavior)
func coerceResourceForMatching(resource unversioned.GroupVersionResource) unversioned.GroupVersionResource {
func coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource {
resource.Resource = strings.ToLower(resource.Resource)
if resource.Version == runtime.APIVersionInternal {
resource.Version = ""
@ -210,7 +210,7 @@ func coerceResourceForMatching(resource unversioned.GroupVersionResource) unvers
return resource
}
func (m *DefaultRESTMapper) ResourcesFor(input unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
resource := coerceResourceForMatching(input)
hasResource := len(resource.Resource) > 0
@ -221,7 +221,7 @@ func (m *DefaultRESTMapper) ResourcesFor(input unversioned.GroupVersionResource)
return nil, fmt.Errorf("a resource must be present, got: %v", resource)
}
ret := []unversioned.GroupVersionResource{}
ret := []schema.GroupVersionResource{}
switch {
case hasGroup && hasVersion:
// fully qualified. Find the exact match
@ -297,19 +297,19 @@ func (m *DefaultRESTMapper) ResourcesFor(input unversioned.GroupVersionResource)
return ret, nil
}
func (m *DefaultRESTMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
resources, err := m.ResourcesFor(resource)
if err != nil {
return unversioned.GroupVersionResource{}, err
return schema.GroupVersionResource{}, err
}
if len(resources) == 1 {
return resources[0], nil
}
return unversioned.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}
}
func (m *DefaultRESTMapper) KindsFor(input unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error) {
func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
resource := coerceResourceForMatching(input)
hasResource := len(resource.Resource) > 0
@ -320,7 +320,7 @@ func (m *DefaultRESTMapper) KindsFor(input unversioned.GroupVersionResource) ([]
return nil, fmt.Errorf("a resource must be present, got: %v", resource)
}
ret := []unversioned.GroupVersionKind{}
ret := []schema.GroupVersionKind{}
switch {
// fully qualified. Find the exact match
case hasGroup && hasVersion:
@ -376,21 +376,21 @@ func (m *DefaultRESTMapper) KindsFor(input unversioned.GroupVersionResource) ([]
return ret, nil
}
func (m *DefaultRESTMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
kinds, err := m.KindsFor(resource)
if err != nil {
return unversioned.GroupVersionKind{}, err
return schema.GroupVersionKind{}, err
}
if len(kinds) == 1 {
return kinds[0], nil
}
return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}
}
type kindByPreferredGroupVersion struct {
list []unversioned.GroupVersionKind
sortOrder []unversioned.GroupVersion
list []schema.GroupVersionKind
sortOrder []schema.GroupVersion
}
func (o kindByPreferredGroupVersion) Len() int { return len(o.list) }
@ -427,8 +427,8 @@ func (o kindByPreferredGroupVersion) Less(i, j int) bool {
}
type resourceByPreferredGroupVersion struct {
list []unversioned.GroupVersionResource
sortOrder []unversioned.GroupVersion
list []schema.GroupVersionResource
sortOrder []schema.GroupVersion
}
func (o resourceByPreferredGroupVersion) Len() int { return len(o.list) }
@ -468,91 +468,56 @@ func (o resourceByPreferredGroupVersion) Less(i, j int) bool {
// RESTClient should use to operate on the provided group/kind in order of versions. If a version search
// order is not provided, the search order provided to DefaultRESTMapper will be used to resolve which
// version should be used to access the named group/kind.
// TODO: consider refactoring to use RESTMappings in a way that preserves version ordering and preference
func (m *DefaultRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) {
// Pick an appropriate version
var gvk *unversioned.GroupVersionKind
func (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {
mappings, err := m.RESTMappings(gk, versions...)
if err != nil {
return nil, err
}
if len(mappings) == 0 {
return nil, &NoKindMatchError{PartialKind: gk.WithVersion("")}
}
// since we rely on RESTMappings method
// take the first match and return to the caller
// as this was the existing behavior.
return mappings[0], nil
}
// RESTMappings returns the RESTMappings for the provided group kind. If a version search order
// is not provided, the search order provided to DefaultRESTMapper will be used.
func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {
mappings := make([]*RESTMapping, 0)
potentialGVK := make([]schema.GroupVersionKind, 0)
hadVersion := false
// Pick an appropriate version
for _, version := range versions {
if len(version) == 0 || version == runtime.APIVersionInternal {
continue
}
currGVK := gk.WithVersion(version)
hadVersion = true
if _, ok := m.kindToPluralResource[currGVK]; ok {
gvk = &currGVK
potentialGVK = append(potentialGVK, currGVK)
break
}
}
// Use the default preferred versions
if !hadVersion && (gvk == nil) {
if !hadVersion && len(potentialGVK) == 0 {
for _, gv := range m.defaultGroupVersions {
if gv.Group != gk.Group {
continue
}
currGVK := gk.WithVersion(gv.Version)
if _, ok := m.kindToPluralResource[currGVK]; ok {
gvk = &currGVK
break
}
potentialGVK = append(potentialGVK, gk.WithVersion(gv.Version))
}
}
if gvk == nil {
if len(potentialGVK) == 0 {
return nil, &NoKindMatchError{PartialKind: gk.WithVersion("")}
}
// Ensure we have a REST mapping
resource, ok := m.kindToPluralResource[*gvk]
if !ok {
found := []unversioned.GroupVersion{}
for _, gv := range m.defaultGroupVersions {
if _, ok := m.kindToPluralResource[*gvk]; ok {
found = append(found, gv)
}
}
if len(found) > 0 {
return nil, fmt.Errorf("object with kind %q exists in versions %v, not %v", gvk.Kind, found, gvk.GroupVersion().String())
}
return nil, fmt.Errorf("the provided version %q and kind %q cannot be mapped to a supported object", gvk.GroupVersion().String(), gvk.Kind)
}
// Ensure we have a REST scope
scope, ok := m.kindToScope[*gvk]
if !ok {
return nil, fmt.Errorf("the provided version %q and kind %q cannot be mapped to a supported scope", gvk.GroupVersion().String(), gvk.Kind)
}
interfaces, err := m.interfacesFunc(gvk.GroupVersion())
if err != nil {
return nil, fmt.Errorf("the provided version %q has no relevant versions: %v", gvk.GroupVersion().String(), err)
}
retVal := &RESTMapping{
Resource: resource.Resource,
GroupVersionKind: *gvk,
Scope: scope,
ObjectConvertor: interfaces.ObjectConvertor,
MetadataAccessor: interfaces.MetadataAccessor,
}
return retVal, nil
}
// RESTMappings returns the RESTMappings for the provided group kind in a rough internal preferred order. If no
// kind is found it will return a NoResourceMatchError.
func (m *DefaultRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) {
// Use the default preferred versions
var mappings []*RESTMapping
for _, gv := range m.defaultGroupVersions {
if gv.Group != gk.Group {
continue
}
gvk := gk.WithVersion(gv.Version)
gvr, ok := m.kindToPluralResource[gvk]
for _, gvk := range potentialGVK {
//Ensure we have a REST mapping
res, ok := m.kindToPluralResource[gvk]
if !ok {
continue
}
@ -569,7 +534,7 @@ func (m *DefaultRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMappi
}
mappings = append(mappings, &RESTMapping{
Resource: gvr.Resource,
Resource: res.Resource,
GroupVersionKind: gvk,
Scope: scope,
@ -579,7 +544,7 @@ func (m *DefaultRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMappi
}
if len(mappings) == 0 {
return nil, &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}}
return nil, &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}}
}
return mappings, nil
}

View file

@ -17,15 +17,15 @@ limitations under the License.
package meta
import (
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// InterfacesForUnstructured returns VersionInterfaces suitable for
// dealing with runtime.Unstructured objects.
func InterfacesForUnstructured(unversioned.GroupVersion) (*VersionInterfaces, error) {
// dealing with unstructured.Unstructured objects.
func InterfacesForUnstructured(schema.GroupVersion) (*VersionInterfaces, error) {
return &VersionInterfaces{
ObjectConvertor: &runtime.UnstructuredObjectConverter{},
ObjectConvertor: &unstructured.UnstructuredObjectConverter{},
MetadataAccessor: NewAccessor(),
}, nil
}

17
vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS generated vendored Executable file
View file

@ -0,0 +1,17 @@
reviewers:
- thockin
- lavalamp
- smarterclayton
- wojtek-t
- derekwaynecarr
- mikedanese
- saad-ali
- janetkuo
- timstclair
- eparis
- timothysc
- jbeda
- xiang90
- mbohlool
- david-mcmahon
- goltermann

View file

@ -0,0 +1,71 @@
/*
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.
*/
// Code generated by protoc-gen-gogo.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
// DO NOT EDIT!
/*
Package resource is a generated protocol buffer package.
It is generated from these files:
k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
It has these top-level messages:
Quantity
*/
package resource
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
const _ = proto.GoGoProtoPackageIsVersion1
func (m *Quantity) Reset() { *m = Quantity{} }
func (*Quantity) ProtoMessage() {}
func (*Quantity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} }
func init() {
proto.RegisterType((*Quantity)(nil), "k8s.io.apimachinery.pkg.api.resource.Quantity")
}
var fileDescriptorGenerated = []byte{
// 253 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x74, 0x8f, 0xb1, 0x4a, 0x03, 0x41,
0x10, 0x86, 0x77, 0x1b, 0x89, 0x57, 0x06, 0x11, 0x49, 0xb1, 0x17, 0xc4, 0x42, 0x04, 0x77, 0x0a,
0x9b, 0x60, 0x69, 0x6f, 0xa1, 0xa5, 0xdd, 0xdd, 0x65, 0xdc, 0x2c, 0x67, 0x76, 0x8f, 0xd9, 0x59,
0x21, 0x5d, 0x4a, 0xcb, 0x94, 0x96, 0xb9, 0xb7, 0x49, 0x99, 0xd2, 0xc2, 0xc2, 0x3b, 0x5f, 0x44,
0x72, 0xc9, 0x81, 0x08, 0x76, 0xf3, 0xfd, 0xc3, 0x37, 0xfc, 0x93, 0xdc, 0x97, 0x93, 0xa0, 0xad,
0x87, 0x32, 0xe6, 0x48, 0x0e, 0x19, 0x03, 0xbc, 0xa2, 0x9b, 0x7a, 0x82, 0xc3, 0x22, 0xab, 0xec,
0x3c, 0x2b, 0x66, 0xd6, 0x21, 0x2d, 0xa0, 0x2a, 0xcd, 0x2e, 0x00, 0xc2, 0xe0, 0x23, 0x15, 0x08,
0x06, 0x1d, 0x52, 0xc6, 0x38, 0xd5, 0x15, 0x79, 0xf6, 0xc3, 0x8b, 0xbd, 0xa5, 0x7f, 0x5b, 0xba,
0x2a, 0xcd, 0x2e, 0xd0, 0xbd, 0x35, 0xba, 0x36, 0x96, 0x67, 0x31, 0xd7, 0x85, 0x9f, 0x83, 0xf1,
0xc6, 0x43, 0x27, 0xe7, 0xf1, 0xb9, 0xa3, 0x0e, 0xba, 0x69, 0x7f, 0x74, 0x74, 0xf3, 0x5f, 0x95,
0xc8, 0xf6, 0x05, 0xac, 0xe3, 0xc0, 0xf4, 0xb7, 0xc9, 0xf9, 0x24, 0x19, 0x3c, 0xc4, 0xcc, 0xb1,
0xe5, 0xc5, 0xf0, 0x34, 0x39, 0x0a, 0x4c, 0xd6, 0x99, 0x33, 0x39, 0x96, 0x97, 0xc7, 0x8f, 0x07,
0xba, 0x3d, 0x79, 0x5f, 0xa7, 0xe2, 0xad, 0x4e, 0xc5, 0xaa, 0x4e, 0xc5, 0xba, 0x4e, 0xc5, 0xf2,
0x73, 0x2c, 0xee, 0xae, 0x36, 0x8d, 0x12, 0xdb, 0x46, 0x89, 0x8f, 0x46, 0x89, 0x65, 0xab, 0xe4,
0xa6, 0x55, 0x72, 0xdb, 0x2a, 0xf9, 0xd5, 0x2a, 0xb9, 0xfa, 0x56, 0xe2, 0x69, 0xd0, 0x7f, 0xf2,
0x13, 0x00, 0x00, 0xff, 0xff, 0xdf, 0x3c, 0xf3, 0xc9, 0x3f, 0x01, 0x00, 0x00,
}

View file

@ -19,9 +19,9 @@ limitations under the License.
syntax = 'proto2';
package k8s.io.kubernetes.pkg.api.resource;
package k8s.io.apimachinery.pkg.api.resource;
import "k8s.io/kubernetes/pkg/util/intstr/generated.proto";
import "k8s.io/apimachinery/pkg/util/intstr/generated.proto";
// Package-wide variables from generator "generated".
option go_package = "resource";

View file

@ -29,7 +29,7 @@ import (
"github.com/go-openapi/spec"
inf "gopkg.in/inf.v0"
"k8s.io/client-go/pkg/genericapiserver/openapi/common"
"k8s.io/apimachinery/pkg/openapi"
)
// Quantity is a fixed-point representation of a number.
@ -399,8 +399,8 @@ func (q Quantity) DeepCopy() Quantity {
}
// OpenAPIDefinition returns openAPI definition for this type.
func (_ Quantity) OpenAPIDefinition() common.OpenAPIDefinition {
return common.OpenAPIDefinition{
func (_ Quantity) OpenAPIDefinition() openapi.OpenAPIDefinition {
return openapi.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},

View file

@ -24,16 +24,8 @@ package announced
import (
"fmt"
"k8s.io/client-go/pkg/apimachinery/registered"
"k8s.io/client-go/pkg/runtime"
)
var (
DefaultGroupFactoryRegistry = make(APIGroupFactoryRegistry)
// These functions will announce your group or version.
AnnounceGroupVersion = DefaultGroupFactoryRegistry.AnnounceGroupVersion
AnnounceGroup = DefaultGroupFactoryRegistry.AnnounceGroup
"k8s.io/apimachinery/pkg/apimachinery/registered"
"k8s.io/apimachinery/pkg/runtime"
)
// APIGroupFactoryRegistry allows for groups and versions to announce themselves,

View file

@ -21,13 +21,12 @@ import (
"github.com/golang/glog"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/apimachinery"
"k8s.io/client-go/pkg/apimachinery/registered"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/util/sets"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apimachinery"
"k8s.io/apimachinery/pkg/apimachinery/registered"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
)
type SchemeFunc func(*runtime.Scheme) error
@ -43,10 +42,16 @@ type GroupVersionFactoryArgs struct {
// GroupMetaFactoryArgs contains the group-level args of a GroupMetaFactory.
type GroupMetaFactoryArgs struct {
// GroupName is the name of the API-Group
//
// example: 'servicecatalog.k8s.io'
GroupName string
VersionPreferenceOrder []string
ImportPrefix string
// ImportPrefix is the base go package of the API-Group
//
// example: 'k8s.io/kubernetes/pkg/apis/autoscaling'
ImportPrefix string
// RootScopedKinds are resources that are not namespaced.
RootScopedKinds sets.String // nil is allowed
IgnoredKinds sets.String // nil is allowed
@ -79,8 +84,8 @@ func NewGroupMetaFactory(groupArgs *GroupMetaFactoryArgs, versions VersionToSche
// programmer importing the wrong set of packages. If this assumption doesn't
// work for you, just call DefaultGroupFactoryRegistry.AnnouncePreconstructedFactory
// yourself.
func (gmf *GroupMetaFactory) Announce() *GroupMetaFactory {
if err := DefaultGroupFactoryRegistry.AnnouncePreconstructedFactory(gmf); err != nil {
func (gmf *GroupMetaFactory) Announce(groupFactoryRegistry APIGroupFactoryRegistry) *GroupMetaFactory {
if err := groupFactoryRegistry.AnnouncePreconstructedFactory(gmf); err != nil {
panic(err)
}
return gmf
@ -107,7 +112,7 @@ type GroupMetaFactory struct {
VersionArgs map[string]*GroupVersionFactoryArgs
// assembled by Register()
prioritizedVersionList []unversioned.GroupVersion
prioritizedVersionList []schema.GroupVersion
}
// Register constructs the finalized prioritized version list and sanity checks
@ -124,11 +129,11 @@ func (gmf *GroupMetaFactory) Register(m *registered.APIRegistrationManager) erro
if pvSet.Len() != len(gmf.GroupArgs.VersionPreferenceOrder) {
return fmt.Errorf("preference order for group %v has duplicates: %v", gmf.GroupArgs.GroupName, gmf.GroupArgs.VersionPreferenceOrder)
}
prioritizedVersions := []unversioned.GroupVersion{}
prioritizedVersions := []schema.GroupVersion{}
for _, v := range gmf.GroupArgs.VersionPreferenceOrder {
prioritizedVersions = append(
prioritizedVersions,
unversioned.GroupVersion{
schema.GroupVersion{
Group: gmf.GroupArgs.GroupName,
Version: v,
},
@ -136,7 +141,7 @@ func (gmf *GroupMetaFactory) Register(m *registered.APIRegistrationManager) erro
}
// Go through versions that weren't explicitly prioritized.
unprioritizedVersions := []unversioned.GroupVersion{}
unprioritizedVersions := []schema.GroupVersion{}
for _, v := range gmf.VersionArgs {
if v.GroupName != gmf.GroupArgs.GroupName {
return fmt.Errorf("found %v/%v in group %v?", v.GroupName, v.VersionName, gmf.GroupArgs.GroupName)
@ -145,7 +150,7 @@ func (gmf *GroupMetaFactory) Register(m *registered.APIRegistrationManager) erro
pvSet.Delete(v.VersionName)
continue
}
unprioritizedVersions = append(unprioritizedVersions, unversioned.GroupVersion{Group: v.GroupName, Version: v.VersionName})
unprioritizedVersions = append(unprioritizedVersions, schema.GroupVersion{Group: v.GroupName, Version: v.VersionName})
}
if len(unprioritizedVersions) > 1 {
glog.Warningf("group %v has multiple unprioritized versions: %#v. They will have an arbitrary preference order!", gmf.GroupArgs.GroupName, unprioritizedVersions)
@ -159,7 +164,7 @@ func (gmf *GroupMetaFactory) Register(m *registered.APIRegistrationManager) erro
return nil
}
func (gmf *GroupMetaFactory) newRESTMapper(scheme *runtime.Scheme, externalVersions []unversioned.GroupVersion, groupMeta *apimachinery.GroupMeta) meta.RESTMapper {
func (gmf *GroupMetaFactory) newRESTMapper(scheme *runtime.Scheme, externalVersions []schema.GroupVersion, groupMeta *apimachinery.GroupMeta) meta.RESTMapper {
// the list of kinds that are scoped at the root of the api hierarchy
// if a kind is not enumerated here, it is assumed to have a namespace scope
rootScoped := sets.NewString()
@ -171,7 +176,7 @@ func (gmf *GroupMetaFactory) newRESTMapper(scheme *runtime.Scheme, externalVersi
ignoredKinds = gmf.GroupArgs.IgnoredKinds
}
return api.NewDefaultRESTMapperFromScheme(
return meta.NewDefaultRESTMapperFromScheme(
externalVersions,
groupMeta.InterfacesFor,
gmf.GroupArgs.ImportPrefix,
@ -183,7 +188,7 @@ func (gmf *GroupMetaFactory) newRESTMapper(scheme *runtime.Scheme, externalVersi
// Enable enables group versions that are allowed, adds methods to the scheme, etc.
func (gmf *GroupMetaFactory) Enable(m *registered.APIRegistrationManager, scheme *runtime.Scheme) error {
externalVersions := []unversioned.GroupVersion{}
externalVersions := []schema.GroupVersion{}
for _, v := range gmf.prioritizedVersionList {
if !m.IsAllowedVersion(v) {
continue
@ -214,7 +219,7 @@ func (gmf *GroupMetaFactory) Enable(m *registered.APIRegistrationManager, scheme
for _, v := range externalVersions {
gvf := gmf.VersionArgs[v.Version]
if err := groupMeta.AddVersionInterfaces(
unversioned.GroupVersion{Group: gvf.GroupName, Version: gvf.VersionName},
schema.GroupVersion{Group: gvf.GroupName, Version: gvf.VersionName},
&meta.VersionInterfaces{
ObjectConvertor: scheme,
MetadataAccessor: accessor,
@ -235,11 +240,11 @@ func (gmf *GroupMetaFactory) Enable(m *registered.APIRegistrationManager, scheme
// RegisterAndEnable is provided only to allow this code to get added in multiple steps.
// It's really bad that this is called in init() methods, but supporting this
// temporarily lets us do the change incrementally.
func (gmf *GroupMetaFactory) RegisterAndEnable() error {
if err := gmf.Register(registered.DefaultAPIRegistrationManager); err != nil {
func (gmf *GroupMetaFactory) RegisterAndEnable(registry *registered.APIRegistrationManager, scheme *runtime.Scheme) error {
if err := gmf.Register(registry); err != nil {
return err
}
if err := gmf.Enable(registered.DefaultAPIRegistrationManager, api.Scheme); err != nil {
if err := gmf.Enable(registry, scheme); err != nil {
return err
}

View file

@ -17,4 +17,4 @@ limitations under the License.
// Package apimachinery contains the generic API machinery code that
// is common to both server and clients.
// This package should never import specific API objects.
package apimachinery
package apimachinery // import "k8s.io/apimachinery/pkg/apimachinery"

View file

@ -19,20 +19,15 @@ package registered
import (
"fmt"
"os"
"sort"
"strings"
"github.com/golang/glog"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/apimachinery"
"k8s.io/client-go/pkg/util/sets"
)
var (
DefaultAPIRegistrationManager = NewOrDie(os.Getenv("KUBE_API_VERSIONS"))
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apimachinery"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
)
// APIRegistrationManager provides the concept of what API groups are enabled.
@ -45,16 +40,16 @@ var (
// isn't easy right now because there are so many callers of this package.
type APIRegistrationManager struct {
// registeredGroupVersions stores all API group versions for which RegisterGroup is called.
registeredVersions map[unversioned.GroupVersion]struct{}
registeredVersions map[schema.GroupVersion]struct{}
// thirdPartyGroupVersions are API versions which are dynamically
// registered (and unregistered) via API calls to the apiserver
thirdPartyGroupVersions []unversioned.GroupVersion
thirdPartyGroupVersions []schema.GroupVersion
// enabledVersions represents all enabled API versions. It should be a
// subset of registeredVersions. Please call EnableVersions() to add
// enabled versions.
enabledVersions map[unversioned.GroupVersion]struct{}
enabledVersions map[schema.GroupVersion]struct{}
// map of group meta for all groups.
groupMetaMap map[string]*apimachinery.GroupMeta
@ -63,7 +58,7 @@ type APIRegistrationManager struct {
// KUBE_API_VERSIONS environment variable. The install package of each group
// checks this list before add their versions to the latest package and
// Scheme. This list is small and order matters, so represent as a slice
envRequestedVersions []unversioned.GroupVersion
envRequestedVersions []schema.GroupVersion
}
// NewAPIRegistrationManager constructs a new manager. The argument ought to be
@ -71,16 +66,16 @@ type APIRegistrationManager struct {
// wish to test.
func NewAPIRegistrationManager(kubeAPIVersions string) (*APIRegistrationManager, error) {
m := &APIRegistrationManager{
registeredVersions: map[unversioned.GroupVersion]struct{}{},
thirdPartyGroupVersions: []unversioned.GroupVersion{},
enabledVersions: map[unversioned.GroupVersion]struct{}{},
registeredVersions: map[schema.GroupVersion]struct{}{},
thirdPartyGroupVersions: []schema.GroupVersion{},
enabledVersions: map[schema.GroupVersion]struct{}{},
groupMetaMap: map[string]*apimachinery.GroupMeta{},
envRequestedVersions: []unversioned.GroupVersion{},
envRequestedVersions: []schema.GroupVersion{},
}
if len(kubeAPIVersions) != 0 {
for _, version := range strings.Split(kubeAPIVersions, ",") {
gv, err := unversioned.ParseGroupVersion(version)
gv, err := schema.ParseGroupVersion(version)
if err != nil {
return nil, fmt.Errorf("invalid api version: %s in KUBE_API_VERSIONS: %s.",
version, kubeAPIVersions)
@ -99,30 +94,8 @@ func NewOrDie(kubeAPIVersions string) *APIRegistrationManager {
return m
}
// People are calling global functions. Let them continue to do that (for now).
var (
ValidateEnvRequestedVersions = DefaultAPIRegistrationManager.ValidateEnvRequestedVersions
AllPreferredGroupVersions = DefaultAPIRegistrationManager.AllPreferredGroupVersions
RESTMapper = DefaultAPIRegistrationManager.RESTMapper
GroupOrDie = DefaultAPIRegistrationManager.GroupOrDie
AddThirdPartyAPIGroupVersions = DefaultAPIRegistrationManager.AddThirdPartyAPIGroupVersions
IsThirdPartyAPIGroupVersion = DefaultAPIRegistrationManager.IsThirdPartyAPIGroupVersion
RegisteredGroupVersions = DefaultAPIRegistrationManager.RegisteredGroupVersions
IsRegisteredVersion = DefaultAPIRegistrationManager.IsRegisteredVersion
IsRegistered = DefaultAPIRegistrationManager.IsRegistered
Group = DefaultAPIRegistrationManager.Group
EnabledVersionsForGroup = DefaultAPIRegistrationManager.EnabledVersionsForGroup
EnabledVersions = DefaultAPIRegistrationManager.EnabledVersions
IsEnabledVersion = DefaultAPIRegistrationManager.IsEnabledVersion
IsAllowedVersion = DefaultAPIRegistrationManager.IsAllowedVersion
EnableVersions = DefaultAPIRegistrationManager.EnableVersions
RegisterGroup = DefaultAPIRegistrationManager.RegisterGroup
RegisterVersions = DefaultAPIRegistrationManager.RegisterVersions
InterfacesFor = DefaultAPIRegistrationManager.InterfacesFor
)
// RegisterVersions adds the given group versions to the list of registered group versions.
func (m *APIRegistrationManager) RegisterVersions(availableVersions []unversioned.GroupVersion) {
func (m *APIRegistrationManager) RegisterVersions(availableVersions []schema.GroupVersion) {
for _, v := range availableVersions {
m.registeredVersions[v] = struct{}{}
}
@ -132,7 +105,7 @@ func (m *APIRegistrationManager) RegisterVersions(availableVersions []unversione
func (m *APIRegistrationManager) RegisterGroup(groupMeta apimachinery.GroupMeta) error {
groupName := groupMeta.GroupVersion.Group
if _, found := m.groupMetaMap[groupName]; found {
return fmt.Errorf("group %v is already registered", m.groupMetaMap)
return fmt.Errorf("group %q is already registered in groupsMap: %v", groupName, m.groupMetaMap)
}
m.groupMetaMap[groupName] = &groupMeta
return nil
@ -141,8 +114,8 @@ func (m *APIRegistrationManager) RegisterGroup(groupMeta apimachinery.GroupMeta)
// EnableVersions adds the versions for the given group to the list of enabled versions.
// Note that the caller should call RegisterGroup before calling this method.
// The caller of this function is responsible to add the versions to scheme and RESTMapper.
func (m *APIRegistrationManager) EnableVersions(versions ...unversioned.GroupVersion) error {
var unregisteredVersions []unversioned.GroupVersion
func (m *APIRegistrationManager) EnableVersions(versions ...schema.GroupVersion) error {
var unregisteredVersions []schema.GroupVersion
for _, v := range versions {
if _, found := m.registeredVersions[v]; !found {
unregisteredVersions = append(unregisteredVersions, v)
@ -158,7 +131,7 @@ func (m *APIRegistrationManager) EnableVersions(versions ...unversioned.GroupVer
// IsAllowedVersion returns if the version is allowed by the KUBE_API_VERSIONS
// environment variable. If the environment variable is empty, then it always
// returns true.
func (m *APIRegistrationManager) IsAllowedVersion(v unversioned.GroupVersion) bool {
func (m *APIRegistrationManager) IsAllowedVersion(v schema.GroupVersion) bool {
if len(m.envRequestedVersions) == 0 {
return true
}
@ -171,15 +144,15 @@ func (m *APIRegistrationManager) IsAllowedVersion(v unversioned.GroupVersion) bo
}
// IsEnabledVersion returns if a version is enabled.
func (m *APIRegistrationManager) IsEnabledVersion(v unversioned.GroupVersion) bool {
func (m *APIRegistrationManager) IsEnabledVersion(v schema.GroupVersion) bool {
_, found := m.enabledVersions[v]
return found
}
// EnabledVersions returns all enabled versions. Groups are randomly ordered, but versions within groups
// are priority order from best to worst
func (m *APIRegistrationManager) EnabledVersions() []unversioned.GroupVersion {
ret := []unversioned.GroupVersion{}
func (m *APIRegistrationManager) EnabledVersions() []schema.GroupVersion {
ret := []schema.GroupVersion{}
for _, groupMeta := range m.groupMetaMap {
for _, version := range groupMeta.GroupVersions {
if m.IsEnabledVersion(version) {
@ -191,13 +164,13 @@ func (m *APIRegistrationManager) EnabledVersions() []unversioned.GroupVersion {
}
// EnabledVersionsForGroup returns all enabled versions for a group in order of best to worst
func (m *APIRegistrationManager) EnabledVersionsForGroup(group string) []unversioned.GroupVersion {
func (m *APIRegistrationManager) EnabledVersionsForGroup(group string) []schema.GroupVersion {
groupMeta, ok := m.groupMetaMap[group]
if !ok {
return []unversioned.GroupVersion{}
return []schema.GroupVersion{}
}
ret := []unversioned.GroupVersion{}
ret := []schema.GroupVersion{}
for _, version := range groupMeta.GroupVersions {
if m.IsEnabledVersion(version) {
ret = append(ret, version)
@ -224,14 +197,14 @@ func (m *APIRegistrationManager) IsRegistered(group string) bool {
}
// IsRegisteredVersion returns if a version is registered.
func (m *APIRegistrationManager) IsRegisteredVersion(v unversioned.GroupVersion) bool {
func (m *APIRegistrationManager) IsRegisteredVersion(v schema.GroupVersion) bool {
_, found := m.registeredVersions[v]
return found
}
// RegisteredGroupVersions returns all registered group versions.
func (m *APIRegistrationManager) RegisteredGroupVersions() []unversioned.GroupVersion {
ret := []unversioned.GroupVersion{}
func (m *APIRegistrationManager) RegisteredGroupVersions() []schema.GroupVersion {
ret := []schema.GroupVersion{}
for groupVersion := range m.registeredVersions {
ret = append(ret, groupVersion)
}
@ -239,7 +212,7 @@ func (m *APIRegistrationManager) RegisteredGroupVersions() []unversioned.GroupVe
}
// IsThirdPartyAPIGroupVersion returns true if the api version is a user-registered group/version.
func (m *APIRegistrationManager) IsThirdPartyAPIGroupVersion(gv unversioned.GroupVersion) bool {
func (m *APIRegistrationManager) IsThirdPartyAPIGroupVersion(gv schema.GroupVersion) bool {
for ix := range m.thirdPartyGroupVersions {
if m.thirdPartyGroupVersions[ix] == gv {
return true
@ -252,9 +225,9 @@ func (m *APIRegistrationManager) IsThirdPartyAPIGroupVersion(gv unversioned.Grou
// registers them in the API machinery and enables them.
// Skips GroupVersions that are already registered.
// Returns the list of GroupVersions that were skipped.
func (m *APIRegistrationManager) AddThirdPartyAPIGroupVersions(gvs ...unversioned.GroupVersion) []unversioned.GroupVersion {
filteredGVs := []unversioned.GroupVersion{}
skippedGVs := []unversioned.GroupVersion{}
func (m *APIRegistrationManager) AddThirdPartyAPIGroupVersions(gvs ...schema.GroupVersion) []schema.GroupVersion {
filteredGVs := []schema.GroupVersion{}
skippedGVs := []schema.GroupVersion{}
for ix := range gvs {
if !m.IsRegisteredVersion(gvs[ix]) {
filteredGVs = append(filteredGVs, gvs[ix])
@ -274,7 +247,7 @@ func (m *APIRegistrationManager) AddThirdPartyAPIGroupVersions(gvs ...unversione
}
// InterfacesFor is a union meta.VersionInterfacesFunc func for all registered types
func (m *APIRegistrationManager) InterfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
func (m *APIRegistrationManager) InterfacesFor(version schema.GroupVersion) (*meta.VersionInterfaces, error) {
groupMeta, err := m.Group(version.Group)
if err != nil {
return nil, err
@ -303,7 +276,7 @@ func (m *APIRegistrationManager) GroupOrDie(group string) *apimachinery.GroupMet
// 1. legacy kube group preferred version, extensions preferred version, metrics perferred version, legacy
// kube any version, extensions any version, metrics any version, all other groups alphabetical preferred version,
// all other groups alphabetical.
func (m *APIRegistrationManager) RESTMapper(versionPatterns ...unversioned.GroupVersion) meta.RESTMapper {
func (m *APIRegistrationManager) RESTMapper(versionPatterns ...schema.GroupVersion) meta.RESTMapper {
unionMapper := meta.MultiRESTMapper{}
unionedGroups := sets.NewString()
for enabledVersion := range m.enabledVersions {
@ -315,8 +288,8 @@ func (m *APIRegistrationManager) RESTMapper(versionPatterns ...unversioned.Group
}
if len(versionPatterns) != 0 {
resourcePriority := []unversioned.GroupVersionResource{}
kindPriority := []unversioned.GroupVersionKind{}
resourcePriority := []schema.GroupVersionResource{}
kindPriority := []schema.GroupVersionKind{}
for _, versionPriority := range versionPatterns {
resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource))
kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind))
@ -326,8 +299,8 @@ func (m *APIRegistrationManager) RESTMapper(versionPatterns ...unversioned.Group
}
if len(m.envRequestedVersions) != 0 {
resourcePriority := []unversioned.GroupVersionResource{}
kindPriority := []unversioned.GroupVersionKind{}
resourcePriority := []schema.GroupVersionResource{}
kindPriority := []schema.GroupVersionKind{}
for _, versionPriority := range m.envRequestedVersions {
resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource))
@ -357,9 +330,9 @@ func (m *APIRegistrationManager) RESTMapper(versionPatterns ...unversioned.Group
// prioritiesForGroups returns the resource and kind priorities for a PriorityRESTMapper, preferring the preferred version of each group first,
// then any non-preferred version of the group second.
func (m *APIRegistrationManager) prioritiesForGroups(groups ...string) ([]unversioned.GroupVersionResource, []unversioned.GroupVersionKind) {
resourcePriority := []unversioned.GroupVersionResource{}
kindPriority := []unversioned.GroupVersionKind{}
func (m *APIRegistrationManager) prioritiesForGroups(groups ...string) ([]schema.GroupVersionResource, []schema.GroupVersionKind) {
resourcePriority := []schema.GroupVersionResource{}
kindPriority := []schema.GroupVersionKind{}
for _, group := range groups {
availableVersions := m.EnabledVersionsForGroup(group)
@ -369,8 +342,8 @@ func (m *APIRegistrationManager) prioritiesForGroups(groups ...string) ([]unvers
}
}
for _, group := range groups {
resourcePriority = append(resourcePriority, unversioned.GroupVersionResource{Group: group, Version: meta.AnyVersion, Resource: meta.AnyResource})
kindPriority = append(kindPriority, unversioned.GroupVersionKind{Group: group, Version: meta.AnyVersion, Kind: meta.AnyKind})
resourcePriority = append(resourcePriority, schema.GroupVersionResource{Group: group, Version: meta.AnyVersion, Resource: meta.AnyResource})
kindPriority = append(kindPriority, schema.GroupVersionKind{Group: group, Version: meta.AnyVersion, Kind: meta.AnyKind})
}
return resourcePriority, kindPriority
@ -392,8 +365,8 @@ func (m *APIRegistrationManager) AllPreferredGroupVersions() string {
// ValidateEnvRequestedVersions returns a list of versions that are requested in
// the KUBE_API_VERSIONS environment variable, but not enabled.
func (m *APIRegistrationManager) ValidateEnvRequestedVersions() []unversioned.GroupVersion {
var missingVersions []unversioned.GroupVersion
func (m *APIRegistrationManager) ValidateEnvRequestedVersions() []schema.GroupVersion {
var missingVersions []schema.GroupVersion
for _, v := range m.envRequestedVersions {
if _, found := m.enabledVersions[v]; !found {
missingVersions = append(missingVersions, v)

View file

@ -19,24 +19,18 @@ package apimachinery
import (
"fmt"
"k8s.io/client-go/pkg/api/meta"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/runtime"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupMeta stores the metadata of a group.
type GroupMeta struct {
// GroupVersion represents the preferred version of the group.
GroupVersion unversioned.GroupVersion
GroupVersion schema.GroupVersion
// GroupVersions is Group + all versions in that group.
GroupVersions []unversioned.GroupVersion
// Codec is the default codec for serializing output that should use
// the preferred version. Use this Codec when writing to
// disk, a data store that is not dynamically versioned, or in tests.
// This codec can decode any object that the schema is aware of.
Codec runtime.Codec
GroupVersions []schema.GroupVersion
// SelfLinker can set or get the SelfLink field of all API types.
// TODO: when versioning changes, make this part of each API definition.
@ -52,16 +46,16 @@ type GroupMeta struct {
// string, or an error if the version is not known.
// TODO: make this stop being a func pointer and always use the default
// function provided below once every place that populates this field has been changed.
InterfacesFor func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error)
InterfacesFor func(version schema.GroupVersion) (*meta.VersionInterfaces, error)
// InterfacesByVersion stores the per-version interfaces.
InterfacesByVersion map[unversioned.GroupVersion]*meta.VersionInterfaces
InterfacesByVersion map[schema.GroupVersion]*meta.VersionInterfaces
}
// DefaultInterfacesFor returns the default Codec and ResourceVersioner for a given version
// string, or an error if the version is not known.
// TODO: Remove the "Default" prefix.
func (gm *GroupMeta) DefaultInterfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
func (gm *GroupMeta) DefaultInterfacesFor(version schema.GroupVersion) (*meta.VersionInterfaces, error) {
if v, ok := gm.InterfacesByVersion[version]; ok {
return v, nil
}
@ -73,12 +67,12 @@ func (gm *GroupMeta) DefaultInterfacesFor(version unversioned.GroupVersion) (*me
// (If you use this, be sure to set .InterfacesFor = .DefaultInterfacesFor)
// TODO: remove the "Interfaces" suffix and make this also maintain the
// .GroupVersions member.
func (gm *GroupMeta) AddVersionInterfaces(version unversioned.GroupVersion, interfaces *meta.VersionInterfaces) error {
func (gm *GroupMeta) AddVersionInterfaces(version schema.GroupVersion, interfaces *meta.VersionInterfaces) error {
if e, a := gm.GroupVersion.Group, version.Group; a != e {
return fmt.Errorf("got a version in group %v, but am in group %v", a, e)
}
if gm.InterfacesByVersion == nil {
gm.InterfacesByVersion = make(map[unversioned.GroupVersion]*meta.VersionInterfaces)
gm.InterfacesByVersion = make(map[schema.GroupVersion]*meta.VersionInterfaces)
}
gm.InterfacesByVersion[version] = interfaces

33
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS generated vendored Executable file
View file

@ -0,0 +1,33 @@
reviewers:
- thockin
- smarterclayton
- wojtek-t
- deads2k
- brendandburns
- caesarxuchao
- liggitt
- nikhiljindal
- gmarek
- erictune
- davidopp
- sttts
- quinton-hoole
- kargakis
- luxas
- janetkuo
- justinsb
- ncdc
- timothysc
- soltysh
- dims
- madhusudancs
- hongchaodeng
- krousey
- mml
- mbohlool
- david-mcmahon
- therc
- mqliang
- kevin-wangzefeng
- jianhuiz
- feihujiang

View file

@ -14,25 +14,24 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package api
package v1
import (
"fmt"
"strconv"
"strings"
"k8s.io/client-go/pkg/api/resource"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/conversion"
"k8s.io/client-go/pkg/fields"
"k8s.io/client-go/pkg/labels"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/util/intstr"
utillabels "k8s.io/client-go/pkg/util/labels"
"k8s.io/client-go/pkg/util/validation/field"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
)
func addConversionFuncs(scheme *runtime.Scheme) error {
func AddConversionFuncs(scheme *runtime.Scheme) error {
return scheme.AddConversionFuncs(
Convert_unversioned_TypeMeta_To_unversioned_TypeMeta,
Convert_v1_TypeMeta_To_v1_TypeMeta,
Convert_unversioned_ListMeta_To_unversioned_ListMeta,
@ -67,6 +66,8 @@ func addConversionFuncs(scheme *runtime.Scheme) error {
Convert_map_to_unversioned_LabelSelector,
Convert_unversioned_LabelSelector_to_map,
Convert_Slice_string_To_Slice_int32,
)
}
@ -154,7 +155,7 @@ func Convert_bool_To_Pointer_bool(in *bool, out **bool, s conversion.Scope) erro
}
// +k8s:conversion-fn=drop
func Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(in, out *unversioned.TypeMeta, s conversion.Scope) error {
func Convert_v1_TypeMeta_To_v1_TypeMeta(in, out *TypeMeta, s conversion.Scope) error {
// These values are explicitly not copied
//out.APIVersion = in.APIVersion
//out.Kind = in.Kind
@ -162,7 +163,7 @@ func Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(in, out *unversioned.T
}
// +k8s:conversion-fn=copy-only
func Convert_unversioned_ListMeta_To_unversioned_ListMeta(in, out *unversioned.ListMeta, s conversion.Scope) error {
func Convert_unversioned_ListMeta_To_unversioned_ListMeta(in, out *ListMeta, s conversion.Scope) error {
*out = *in
return nil
}
@ -174,14 +175,14 @@ func Convert_intstr_IntOrString_To_intstr_IntOrString(in, out *intstr.IntOrStrin
}
// +k8s:conversion-fn=copy-only
func Convert_unversioned_Time_To_unversioned_Time(in *unversioned.Time, out *unversioned.Time, s conversion.Scope) error {
func Convert_unversioned_Time_To_unversioned_Time(in *Time, out *Time, s conversion.Scope) error {
// Cannot deep copy these, because time.Time has unexported fields.
*out = *in
return nil
}
// Convert_Slice_string_To_unversioned_Time allows converting a URL query parameter value
func Convert_Slice_string_To_unversioned_Time(input *[]string, out *unversioned.Time, s conversion.Scope) error {
func Convert_Slice_string_To_unversioned_Time(input *[]string, out *Time, s conversion.Scope) error {
str := ""
if len(*input) > 0 {
str = (*input)[0]
@ -229,22 +230,35 @@ func Convert_resource_Quantity_To_resource_Quantity(in *resource.Quantity, out *
return nil
}
func Convert_map_to_unversioned_LabelSelector(in *map[string]string, out *unversioned.LabelSelector, s conversion.Scope) error {
func Convert_map_to_unversioned_LabelSelector(in *map[string]string, out *LabelSelector, s conversion.Scope) error {
if in == nil {
return nil
}
out = new(unversioned.LabelSelector)
out = new(LabelSelector)
for labelKey, labelValue := range *in {
utillabels.AddLabelToSelector(out, labelKey, labelValue)
AddLabelToSelector(out, labelKey, labelValue)
}
return nil
}
func Convert_unversioned_LabelSelector_to_map(in *unversioned.LabelSelector, out *map[string]string, s conversion.Scope) error {
func Convert_unversioned_LabelSelector_to_map(in *LabelSelector, out *map[string]string, s conversion.Scope) error {
var err error
*out, err = unversioned.LabelSelectorAsMap(in)
if err != nil {
err = field.Invalid(field.NewPath("labelSelector"), *in, fmt.Sprintf("cannot convert to old selector: %v", err))
}
*out, err = LabelSelectorAsMap(in)
return err
}
// Convert_Slice_string_To_Slice_int32 converts multiple query parameters or
// a single query parameter with a comma delimited value to multiple int32.
// This is used for port forwarding which needs the ports as int32.
func Convert_Slice_string_To_Slice_int32(in *[]string, out *[]int32, s conversion.Scope) error {
for _, s := range *in {
for _, v := range strings.Split(s, ",") {
x, err := strconv.ParseUint(v, 10, 16)
if err != nil {
return fmt.Errorf("cannot convert to []int32: %v", err)
}
*out = append(*out, int32(x))
}
}
return nil
}

View file

@ -18,4 +18,5 @@ limitations under the License.
// +k8s:openapi-gen=true
// +k8s:defaulter-gen=TypeMeta
package unversioned
// +groupName=meta.k8s.io
package v1

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
import (
"encoding/json"

View file

@ -19,13 +19,14 @@ limitations under the License.
syntax = 'proto2';
package k8s.io.kubernetes.pkg.api.unversioned;
package k8s.io.apimachinery.pkg.apis.meta.v1;
import "k8s.io/kubernetes/pkg/runtime/generated.proto";
import "k8s.io/kubernetes/pkg/util/intstr/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
import "k8s.io/apimachinery/pkg/util/intstr/generated.proto";
// Package-wide variables from generator "generated".
option go_package = "unversioned";
option go_package = "v1";
// APIGroup contains the name, the supported versions, and the preferred version
// of a group.
@ -68,6 +69,13 @@ message APIResource {
// kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')
optional string kind = 3;
// verbs is a list of supported kube verbs (this includes get, list, watch, create,
// update, patch, delete, deletecollection, and proxy)
optional Verbs verbs = 4;
// shortNames is a list of suggested short names of the resource.
repeated string shortNames = 5;
}
// APIResourceList is a list of APIResource, it is used to expose the name of the
@ -99,6 +107,35 @@ message APIVersions {
repeated ServerAddressByClientCIDR serverAddressByClientCIDRs = 2;
}
// DeleteOptions may be provided when deleting an API object.
message DeleteOptions {
// The duration in seconds before the object should be deleted. Value must be non-negative integer.
// The value zero indicates delete immediately. If this value is nil, the default grace period for the
// specified type will be used.
// Defaults to a per object value if not specified. zero means delete immediately.
// +optional
optional int64 gracePeriodSeconds = 1;
// Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be
// returned.
// +optional
optional Preconditions preconditions = 2;
// Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7.
// Should the dependent objects be orphaned. If true/false, the "orphan"
// finalizer will be added to/removed from the object's finalizers list.
// Either this field or PropagationPolicy may be set, but not both.
// +optional
optional bool orphanDependents = 3;
// Whether and how garbage collection will be performed.
// Either this field or OrphanDependents may be set, but not both.
// The default policy is decided by the existing finalizer set in the
// metadata.finalizers and the resource-specific default policy.
// +optional
optional string propagationPolicy = 4;
}
// Duration is a wrapper around time.Duration which supports correct
// marshaling to YAML and JSON. In particular, it marshals into strings, which
// can be used as map keys in json.
@ -108,13 +145,22 @@ message Duration {
// ExportOptions is the query options to the standard REST get call.
message ExportOptions {
// Should this value be exported. Export strips fields that a user can not specify.`
// Should this value be exported. Export strips fields that a user can not specify.
optional bool export = 1;
// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
optional bool exact = 2;
}
// GetOptions is the standard query options to the standard REST get call.
message GetOptions {
// When specified:
// - if unset, then the result is returned from remote storage based on quorum-read flag;
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
// - if set to non zero, then the result is at least as fresh as given rv.
optional string resourceVersion = 1;
}
// GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying
// concepts during lookup stages without having partially valid types
//
@ -231,6 +277,225 @@ message ListMeta {
optional string resourceVersion = 2;
}
// ListOptions is the query options to a standard REST list call.
message ListOptions {
// A selector to restrict the list of returned objects by their labels.
// Defaults to everything.
// +optional
optional string labelSelector = 1;
// A selector to restrict the list of returned objects by their fields.
// Defaults to everything.
// +optional
optional string fieldSelector = 2;
// Watch for changes to the described resources and return them as a stream of
// add, update, and remove notifications. Specify resourceVersion.
// +optional
optional bool watch = 3;
// When specified with a watch call, shows changes that occur after that particular version of a resource.
// Defaults to changes from the beginning of history.
// When specified for list:
// - if unset, then the result is returned from remote storage based on quorum-read flag;
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
// - if set to non zero, then the result is at least as fresh as given rv.
// +optional
optional string resourceVersion = 4;
// Timeout for the list/watch call.
// +optional
optional int64 timeoutSeconds = 5;
}
// ObjectMeta is metadata that all persisted resources must have, which includes all objects
// users must create.
message ObjectMeta {
// Name must be unique within a namespace. Is required when creating resources, although
// some resources may allow a client to request the generation of an appropriate name
// automatically. Name is primarily intended for creation idempotence and configuration
// definition.
// Cannot be updated.
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
// +optional
optional string name = 1;
// GenerateName is an optional prefix, used by the server, to generate a unique
// name ONLY IF the Name field has not been provided.
// If this field is used, the name returned to the client will be different
// than the name passed. This value will also be combined with a unique suffix.
// The provided value has the same validation rules as the Name field,
// and may be truncated by the length of the suffix required to make the value
// unique on the server.
//
// If this field is specified and the generated name exists, the server will
// NOT return a 409 - instead, it will either return 201 Created or 500 with Reason
// ServerTimeout indicating a unique name could not be found in the time allotted, and the client
// should retry (optionally after the time indicated in the Retry-After header).
//
// Applied only if Name is not specified.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency
// +optional
optional string generateName = 2;
// Namespace defines the space within each name must be unique. An empty namespace is
// equivalent to the "default" namespace, but "default" is the canonical representation.
// Not all objects are required to be scoped to a namespace - the value of this field for
// those objects will be empty.
//
// Must be a DNS_LABEL.
// Cannot be updated.
// More info: http://kubernetes.io/docs/user-guide/namespaces
// +optional
optional string namespace = 3;
// SelfLink is a URL representing this object.
// Populated by the system.
// Read-only.
// +optional
optional string selfLink = 4;
// UID is the unique in time and space value for this object. It is typically generated by
// the server on successful creation of a resource and is not allowed to change on PUT
// operations.
//
// Populated by the system.
// Read-only.
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
// +optional
optional string uid = 5;
// An opaque value that represents the internal version of this object that can
// be used by clients to determine when objects have changed. May be used for optimistic
// concurrency, change detection, and the watch operation on a resource or set of resources.
// Clients must treat these values as opaque and passed unmodified back to the server.
// They may only be valid for a particular resource or set of resources.
//
// Populated by the system.
// Read-only.
// Value must be treated as opaque by clients and .
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency
// +optional
optional string resourceVersion = 6;
// A sequence number representing a specific generation of the desired state.
// Populated by the system. Read-only.
// +optional
optional int64 generation = 7;
// CreationTimestamp is a timestamp representing the server time when this object was
// created. It is not guaranteed to be set in happens-before order across separate operations.
// Clients may not set this value. It is represented in RFC3339 form and is in UTC.
//
// Populated by the system.
// Read-only.
// Null for lists.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
// +optional
optional Time creationTimestamp = 8;
// DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This
// field is set by the server when a graceful deletion is requested by the user, and is not
// directly settable by a client. The resource is expected to be deleted (no longer visible
// from resource lists, and not reachable by name) after the time in this field. Once set,
// this value may not be unset or be set further into the future, although it may be shortened
// or the resource may be deleted prior to this time. For example, a user may request that
// a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination
// signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard
// termination signal (SIGKILL) to the container and after cleanup, remove the pod from the
// API. In the presence of network partitions, this object may still exist after this
// timestamp, until an administrator or automated process can determine the resource is
// fully terminated.
// If not set, graceful deletion of the object has not been requested.
//
// Populated by the system when a graceful deletion is requested.
// Read-only.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
// +optional
optional Time deletionTimestamp = 9;
// Number of seconds allowed for this object to gracefully terminate before
// it will be removed from the system. Only set when deletionTimestamp is also set.
// May only be shortened.
// Read-only.
// +optional
optional int64 deletionGracePeriodSeconds = 10;
// Map of string keys and values that can be used to organize and categorize
// (scope and select) objects. May match selectors of replication controllers
// and services.
// More info: http://kubernetes.io/docs/user-guide/labels
// +optional
map<string, string> labels = 11;
// Annotations is an unstructured key value map stored with a resource that may be
// set by external tools to store and retrieve arbitrary metadata. They are not
// queryable and should be preserved when modifying objects.
// More info: http://kubernetes.io/docs/user-guide/annotations
// +optional
map<string, string> annotations = 12;
// List of objects depended by this object. If ALL objects in the list have
// been deleted, this object will be garbage collected. If this object is managed by a controller,
// then an entry in this list will point to this controller, with the controller field set to true.
// There cannot be more than one managing controller.
// +optional
repeated OwnerReference ownerReferences = 13;
// Must be empty before the object is deleted from the registry. Each entry
// is an identifier for the responsible component that will remove the entry
// from the list. If the deletionTimestamp of the object is non-nil, entries
// in this list can only be removed.
// +optional
repeated string finalizers = 14;
// The name of the cluster which the object belongs to.
// This is used to distinguish resources with same name and namespace in different clusters.
// This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.
// +optional
optional string clusterName = 15;
}
// OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there
// is no namespace field.
message OwnerReference {
// API version of the referent.
optional string apiVersion = 5;
// Kind of the referent.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
optional string kind = 1;
// Name of the referent.
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
optional string name = 3;
// UID of the referent.
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
optional string uid = 4;
// If true, this reference points to the managing controller.
// +optional
optional bool controller = 6;
// If true, AND if the owner has the "foregroundDeletion" finalizer, then
// the owner cannot be deleted from the key-value store until this
// reference is removed.
// Defaults to false.
// To set this field, a user needs "delete" permission of the owner,
// otherwise 422 (Unprocessable Entity) will be returned.
// +optional
optional bool blockOwnerDeletion = 7;
}
// Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.
message Preconditions {
// Specifies the target UID.
// +optional
optional string uid = 1;
}
// RootPaths lists the paths available at root.
// For example: "/healthz", "/apis".
message RootPaths {
@ -398,3 +663,27 @@ message TypeMeta {
optional string apiVersion = 2;
}
// Verbs masks the value so protobuf can generate
//
// +protobuf.nullable=true
// +protobuf.options.(gogoproto.goproto_stringer)=false
message Verbs {
// items, if empty, will result in an empty slice
repeated string items = 1;
}
// Event represents a single event to a watched resource.
//
// +protobuf=true
message WatchEvent {
optional string type = 1;
// Object is:
// * If Type is Added or Modified: the new state of the object.
// * If Type is Deleted: the state of the object immediately before deletion.
// * If Type is Error: *Status is recommended; other types may make sense
// depending on context.
optional k8s.io.apimachinery.pkg.runtime.RawExtension object = 2;
}

View file

@ -0,0 +1,148 @@
/*
Copyright 2015 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 (
"encoding/json"
"fmt"
"strings"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying
// concepts during lookup stages without having partially valid types
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
type GroupResource struct {
Group string `protobuf:"bytes,1,opt,name=group"`
Resource string `protobuf:"bytes,2,opt,name=resource"`
}
func (gr *GroupResource) String() string {
if len(gr.Group) == 0 {
return gr.Resource
}
return gr.Resource + "." + gr.Group
}
// GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion
// to avoid automatic coersion. It doesn't use a GroupVersion to avoid custom marshalling
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
type GroupVersionResource struct {
Group string `protobuf:"bytes,1,opt,name=group"`
Version string `protobuf:"bytes,2,opt,name=version"`
Resource string `protobuf:"bytes,3,opt,name=resource"`
}
func (gvr *GroupVersionResource) String() string {
return strings.Join([]string{gvr.Group, "/", gvr.Version, ", Resource=", gvr.Resource}, "")
}
// GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying
// concepts during lookup stages without having partially valid types
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
type GroupKind struct {
Group string `protobuf:"bytes,1,opt,name=group"`
Kind string `protobuf:"bytes,2,opt,name=kind"`
}
func (gk *GroupKind) String() string {
if len(gk.Group) == 0 {
return gk.Kind
}
return gk.Kind + "." + gk.Group
}
// GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
// to avoid automatic coersion. It doesn't use a GroupVersion to avoid custom marshalling
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
type GroupVersionKind struct {
Group string `protobuf:"bytes,1,opt,name=group"`
Version string `protobuf:"bytes,2,opt,name=version"`
Kind string `protobuf:"bytes,3,opt,name=kind"`
}
func (gvk GroupVersionKind) String() string {
return gvk.Group + "/" + gvk.Version + ", Kind=" + gvk.Kind
}
// GroupVersion contains the "group" and the "version", which uniquely identifies the API.
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
type GroupVersion struct {
Group string `protobuf:"bytes,1,opt,name=group"`
Version string `protobuf:"bytes,2,opt,name=version"`
}
// Empty returns true if group and version are empty
func (gv GroupVersion) Empty() bool {
return len(gv.Group) == 0 && len(gv.Version) == 0
}
// String puts "group" and "version" into a single "group/version" string. For the legacy v1
// it returns "v1".
func (gv GroupVersion) String() string {
// special case the internal apiVersion for the legacy kube types
if gv.Empty() {
return ""
}
// special case of "v1" for backward compatibility
if len(gv.Group) == 0 && gv.Version == "v1" {
return gv.Version
}
if len(gv.Group) > 0 {
return gv.Group + "/" + gv.Version
}
return gv.Version
}
// MarshalJSON implements the json.Marshaller interface.
func (gv GroupVersion) MarshalJSON() ([]byte, error) {
s := gv.String()
if strings.Count(s, "/") > 1 {
return []byte{}, fmt.Errorf("illegal GroupVersion %v: contains more than one /", s)
}
return json.Marshal(s)
}
func (gv *GroupVersion) unmarshal(value []byte) error {
var s string
if err := json.Unmarshal(value, &s); err != nil {
return err
}
parsed, err := schema.ParseGroupVersion(s)
if err != nil {
return err
}
gv.Group, gv.Version = parsed.Group, parsed.Version
return nil
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (gv *GroupVersion) UnmarshalJSON(value []byte) error {
return gv.unmarshal(value)
}
// UnmarshalTEXT implements the Ugorji's encoding.TextUnmarshaler interface.
func (gv *GroupVersion) UnmarshalText(value []byte) error {
return gv.unmarshal(value)
}

View file

@ -14,13 +14,15 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
import (
"fmt"
"k8s.io/client-go/pkg/labels"
"k8s.io/client-go/pkg/selection"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
)
// LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements
@ -181,3 +183,52 @@ func ExtractGroupVersions(l *APIGroupList) []string {
}
return groupVersions
}
// HasAnnotation returns a bool if passed in annotation exists
func HasAnnotation(obj ObjectMeta, ann string) bool {
_, found := obj.Annotations[ann]
return found
}
// SetMetaDataAnnotation sets the annotation and value
func SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string) {
if obj.Annotations == nil {
obj.Annotations = make(map[string]string)
}
obj.Annotations[ann] = value
}
// SingleObject returns a ListOptions for watching a single object.
func SingleObject(meta ObjectMeta) ListOptions {
return ListOptions{
FieldSelector: fields.OneTermEqualSelector("metadata.name", meta.Name).String(),
ResourceVersion: meta.ResourceVersion,
}
}
// NewDeleteOptions returns a DeleteOptions indicating the resource should
// be deleted within the specified grace period. Use zero to indicate
// immediate deletion. If you would prefer to use the default grace period,
// use &metav1.DeleteOptions{} directly.
func NewDeleteOptions(grace int64) *DeleteOptions {
return &DeleteOptions{GracePeriodSeconds: &grace}
}
// NewPreconditionDeleteOptions returns a DeleteOptions with a UID precondition set.
func NewPreconditionDeleteOptions(uid string) *DeleteOptions {
u := types.UID(uid)
p := Preconditions{UID: &u}
return &DeleteOptions{Preconditions: &p}
}
// NewUIDPreconditions returns a Preconditions with UID set.
func NewUIDPreconditions(uid string) *Preconditions {
u := types.UID(uid)
return &Preconditions{UID: &u}
}
// HasObjectMetaSystemFieldValues returns true if fields that are managed by the system on ObjectMeta have values.
func HasObjectMetaSystemFieldValues(meta *ObjectMeta) bool {
return !meta.CreationTimestamp.Time.IsZero() ||
len(meta.UID) != 0
}

View file

@ -14,69 +14,18 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package labels
import (
"fmt"
"k8s.io/client-go/pkg/api/unversioned"
)
// Clones the given map and returns a new map with the given key and value added.
// Returns the given map, if labelKey is empty.
func CloneAndAddLabel(labels map[string]string, labelKey string, labelValue uint32) map[string]string {
if labelKey == "" {
// Don't need to add a label.
return labels
}
// Clone.
newLabels := map[string]string{}
for key, value := range labels {
newLabels[key] = value
}
newLabels[labelKey] = fmt.Sprintf("%d", labelValue)
return newLabels
}
// CloneAndRemoveLabel clones the given map and returns a new map with the given key removed.
// Returns the given map, if labelKey is empty.
func CloneAndRemoveLabel(labels map[string]string, labelKey string) map[string]string {
if labelKey == "" {
// Don't need to add a label.
return labels
}
// Clone.
newLabels := map[string]string{}
for key, value := range labels {
newLabels[key] = value
}
delete(newLabels, labelKey)
return newLabels
}
// AddLabel returns a map with the given key and value added to the given map.
func AddLabel(labels map[string]string, labelKey string, labelValue string) map[string]string {
if labelKey == "" {
// Don't need to add a label.
return labels
}
if labels == nil {
labels = make(map[string]string)
}
labels[labelKey] = labelValue
return labels
}
package v1
// Clones the given selector and returns a new selector with the given key and value added.
// Returns the given selector, if labelKey is empty.
func CloneSelectorAndAddLabel(selector *unversioned.LabelSelector, labelKey string, labelValue uint32) *unversioned.LabelSelector {
func CloneSelectorAndAddLabel(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {
if labelKey == "" {
// Don't need to add a label.
return selector
}
// Clone.
newSelector := new(unversioned.LabelSelector)
newSelector := new(LabelSelector)
// TODO(madhusudancs): Check if you can use deepCopy_extensions_LabelSelector here.
newSelector.MatchLabels = make(map[string]string)
@ -85,10 +34,10 @@ func CloneSelectorAndAddLabel(selector *unversioned.LabelSelector, labelKey stri
newSelector.MatchLabels[key] = val
}
}
newSelector.MatchLabels[labelKey] = fmt.Sprintf("%d", labelValue)
newSelector.MatchLabels[labelKey] = labelValue
if selector.MatchExpressions != nil {
newMExps := make([]unversioned.LabelSelectorRequirement, len(selector.MatchExpressions))
newMExps := make([]LabelSelectorRequirement, len(selector.MatchExpressions))
for i, me := range selector.MatchExpressions {
newMExps[i].Key = me.Key
newMExps[i].Operator = me.Operator
@ -108,7 +57,7 @@ func CloneSelectorAndAddLabel(selector *unversioned.LabelSelector, labelKey stri
}
// AddLabelToSelector returns a selector with the given key and value added to the given selector's MatchLabels.
func AddLabelToSelector(selector *unversioned.LabelSelector, labelKey string, labelValue string) *unversioned.LabelSelector {
func AddLabelToSelector(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {
if labelKey == "" {
// Don't need to add a label.
return selector
@ -121,6 +70,6 @@ func AddLabelToSelector(selector *unversioned.LabelSelector, labelKey string, la
}
// SelectorHasLabel checks if the given selector contains the given label key in its MatchLabels
func SelectorHasLabel(selector *unversioned.LabelSelector, labelKey string) bool {
func SelectorHasLabel(selector *LabelSelector, labelKey string) bool {
return len(selector.MatchLabels[labelKey]) > 0
}

209
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go generated vendored Normal file
View file

@ -0,0 +1,209 @@
/*
Copyright 2016 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 (
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
)
// ObjectMetaFor returns a pointer to a provided object's ObjectMeta.
// TODO: allow runtime.Unknown to extract this object
// TODO: Remove this function and use meta.ObjectMetaAccessor() instead.
func ObjectMetaFor(obj runtime.Object) (*ObjectMeta, error) {
v, err := conversion.EnforcePtr(obj)
if err != nil {
return nil, err
}
var meta *ObjectMeta
err = runtime.FieldPtr(v, "ObjectMeta", &meta)
return meta, err
}
// ListMetaFor returns a pointer to a provided object's ListMeta,
// or an error if the object does not have that pointer.
// TODO: allow runtime.Unknown to extract this object
// TODO: Remove this function and use meta.ObjectMetaAccessor() instead.
func ListMetaFor(obj runtime.Object) (*ListMeta, error) {
v, err := conversion.EnforcePtr(obj)
if err != nil {
return nil, err
}
var meta *ListMeta
err = runtime.FieldPtr(v, "ListMeta", &meta)
return meta, err
}
// TODO: move this, Object, List, and Type to a different package
type ObjectMetaAccessor interface {
GetObjectMeta() Object
}
// Object lets you work with object metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field (Name, UID, Namespace on lists) will be a no-op and return
// a default value.
type Object interface {
GetNamespace() string
SetNamespace(namespace string)
GetName() string
SetName(name string)
GetGenerateName() string
SetGenerateName(name string)
GetUID() types.UID
SetUID(uid types.UID)
GetResourceVersion() string
SetResourceVersion(version string)
GetSelfLink() string
SetSelfLink(selfLink string)
GetCreationTimestamp() Time
SetCreationTimestamp(timestamp Time)
GetDeletionTimestamp() *Time
SetDeletionTimestamp(timestamp *Time)
GetLabels() map[string]string
SetLabels(labels map[string]string)
GetAnnotations() map[string]string
SetAnnotations(annotations map[string]string)
GetFinalizers() []string
SetFinalizers(finalizers []string)
GetOwnerReferences() []OwnerReference
SetOwnerReferences([]OwnerReference)
GetClusterName() string
SetClusterName(clusterName string)
}
// ListMetaAccessor retrieves the list interface from an object
type ListMetaAccessor interface {
GetListMeta() List
}
// List lets you work with list metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field will be a no-op and return a default value.
// TODO: move this, and TypeMeta and ListMeta, to a different package
type List interface {
GetResourceVersion() string
SetResourceVersion(version string)
GetSelfLink() string
SetSelfLink(selfLink string)
}
// Type exposes the type and APIVersion of versioned or internal API objects.
// TODO: move this, and TypeMeta and ListMeta, to a different package
type Type interface {
GetAPIVersion() string
SetAPIVersion(version string)
GetKind() string
SetKind(kind string)
}
func (meta *ListMeta) GetResourceVersion() string { return meta.ResourceVersion }
func (meta *ListMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }
func (meta *ListMeta) GetSelfLink() string { return meta.SelfLink }
func (meta *ListMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }
func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }
// SetGroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta
func (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind) {
obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()
}
// GroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta
func (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind {
return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
}
func (obj *ListMeta) GetListMeta() List { return obj }
func (obj *ObjectMeta) GetObjectMeta() Object { return obj }
// Namespace implements metav1.Object for any object with an ObjectMeta typed field. Allows
// fast, direct access to metadata fields for API objects.
func (meta *ObjectMeta) GetNamespace() string { return meta.Namespace }
func (meta *ObjectMeta) SetNamespace(namespace string) { meta.Namespace = namespace }
func (meta *ObjectMeta) GetName() string { return meta.Name }
func (meta *ObjectMeta) SetName(name string) { meta.Name = name }
func (meta *ObjectMeta) GetGenerateName() string { return meta.GenerateName }
func (meta *ObjectMeta) SetGenerateName(generateName string) { meta.GenerateName = generateName }
func (meta *ObjectMeta) GetUID() types.UID { return meta.UID }
func (meta *ObjectMeta) SetUID(uid types.UID) { meta.UID = uid }
func (meta *ObjectMeta) GetResourceVersion() string { return meta.ResourceVersion }
func (meta *ObjectMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }
func (meta *ObjectMeta) GetSelfLink() string { return meta.SelfLink }
func (meta *ObjectMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }
func (meta *ObjectMeta) GetCreationTimestamp() Time { return meta.CreationTimestamp }
func (meta *ObjectMeta) SetCreationTimestamp(creationTimestamp Time) {
meta.CreationTimestamp = creationTimestamp
}
func (meta *ObjectMeta) GetDeletionTimestamp() *Time { return meta.DeletionTimestamp }
func (meta *ObjectMeta) SetDeletionTimestamp(deletionTimestamp *Time) {
meta.DeletionTimestamp = deletionTimestamp
}
func (meta *ObjectMeta) GetLabels() map[string]string { return meta.Labels }
func (meta *ObjectMeta) SetLabels(labels map[string]string) { meta.Labels = labels }
func (meta *ObjectMeta) GetAnnotations() map[string]string { return meta.Annotations }
func (meta *ObjectMeta) SetAnnotations(annotations map[string]string) { meta.Annotations = annotations }
func (meta *ObjectMeta) GetFinalizers() []string { return meta.Finalizers }
func (meta *ObjectMeta) SetFinalizers(finalizers []string) { meta.Finalizers = finalizers }
func (meta *ObjectMeta) GetOwnerReferences() []OwnerReference {
ret := make([]OwnerReference, len(meta.OwnerReferences))
for i := 0; i < len(meta.OwnerReferences); i++ {
ret[i].Kind = meta.OwnerReferences[i].Kind
ret[i].Name = meta.OwnerReferences[i].Name
ret[i].UID = meta.OwnerReferences[i].UID
ret[i].APIVersion = meta.OwnerReferences[i].APIVersion
if meta.OwnerReferences[i].Controller != nil {
value := *meta.OwnerReferences[i].Controller
ret[i].Controller = &value
}
if meta.OwnerReferences[i].BlockOwnerDeletion != nil {
value := *meta.OwnerReferences[i].BlockOwnerDeletion
ret[i].BlockOwnerDeletion = &value
}
}
return ret
}
func (meta *ObjectMeta) SetOwnerReferences(references []OwnerReference) {
newReferences := make([]OwnerReference, len(references))
for i := 0; i < len(references); i++ {
newReferences[i].Kind = references[i].Kind
newReferences[i].Name = references[i].Name
newReferences[i].UID = references[i].UID
newReferences[i].APIVersion = references[i].APIVersion
if references[i].Controller != nil {
value := *references[i].Controller
newReferences[i].Controller = &value
}
if references[i].BlockOwnerDeletion != nil {
value := *references[i].BlockOwnerDeletion
newReferences[i].BlockOwnerDeletion = &value
}
}
meta.OwnerReferences = newReferences
}
func (meta *ObjectMeta) GetClusterName() string {
return meta.ClusterName
}
func (meta *ObjectMeta) SetClusterName(clusterName string) {
meta.ClusterName = clusterName
}

View file

@ -0,0 +1,82 @@
/*
Copyright 2014 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 (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupName is the group name for this API.
const GroupName = "meta.k8s.io"
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
// WatchEventKind is name reserved for serializing watch events.
const WatchEventKind = "WatchEvent"
// Kind takes an unqualified kind and returns a Group qualified GroupKind
func Kind(kind string) schema.GroupKind {
return SchemeGroupVersion.WithKind(kind).GroupKind()
}
// AddToGroupVersion registers common meta types into schemas.
func AddToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion) {
scheme.AddKnownTypeWithName(groupVersion.WithKind(WatchEventKind), &WatchEvent{})
scheme.AddKnownTypeWithName(
schema.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal}.WithKind(WatchEventKind),
&InternalEvent{},
)
// Supports legacy code paths, most callers should use metav1.ParameterCodec for now
scheme.AddKnownTypes(groupVersion,
&ListOptions{},
&ExportOptions{},
&GetOptions{},
&DeleteOptions{},
)
scheme.AddConversionFuncs(
Convert_versioned_Event_to_watch_Event,
Convert_versioned_InternalEvent_to_versioned_Event,
Convert_watch_Event_to_versioned_Event,
Convert_versioned_Event_to_versioned_InternalEvent,
)
// register manually. This usually goes through the SchemeBuilder, which we cannot use here.
scheme.AddGeneratedDeepCopyFuncs(GetGeneratedDeepCopyFuncs()...)
AddConversionFuncs(scheme)
RegisterDefaults(scheme)
}
// scheme is the registry for the common types that adhere to the meta v1 API spec.
var scheme = runtime.NewScheme()
// ParameterCodec knows about query parameters used with the meta v1 API spec.
var ParameterCodec = runtime.NewParameterCodec(scheme)
func init() {
scheme.AddUnversionedTypes(SchemeGroupVersion,
&ListOptions{},
&ExportOptions{},
&GetOptions{},
&DeleteOptions{},
)
// register manually. This usually goes through the SchemeBuilder, which we cannot use here.
scheme.AddGeneratedDeepCopyFuncs(GetGeneratedDeepCopyFuncs()...)
RegisterDefaults(scheme)
}

View file

@ -14,13 +14,13 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
import (
"encoding/json"
"time"
"k8s.io/client-go/pkg/genericapiserver/openapi/common"
"k8s.io/apimachinery/pkg/openapi"
"github.com/go-openapi/spec"
"github.com/google/gofuzz"
@ -145,8 +145,8 @@ func (t Time) MarshalJSON() ([]byte, error) {
return json.Marshal(t.UTC().Format(time.RFC3339))
}
func (_ Time) OpenAPIDefinition() common.OpenAPIDefinition {
return common.OpenAPIDefinition{
func (_ Time) OpenAPIDefinition() openapi.OpenAPIDefinition {
return openapi.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
import (
"time"

View file

@ -23,9 +23,14 @@ limitations under the License.
// (e.g. LabelSelector).
// In the future, we will probably move these categories of objects into
// separate packages.
package unversioned
package v1
import "strings"
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/types"
)
// TypeMeta describes an individual object in an API response or request
// with strings representing the type of the object and its API schema version.
@ -66,15 +71,305 @@ type ListMeta struct {
ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,2,opt,name=resourceVersion"`
}
// These are internal finalizer values for Kubernetes-like APIs, must be qualified name unless defined here
const (
FinalizerOrphanDependents string = "orphan"
FinalizerDeleteDependents string = "foregroundDeletion"
)
// ObjectMeta is metadata that all persisted resources must have, which includes all objects
// users must create.
type ObjectMeta struct {
// Name must be unique within a namespace. Is required when creating resources, although
// some resources may allow a client to request the generation of an appropriate name
// automatically. Name is primarily intended for creation idempotence and configuration
// definition.
// Cannot be updated.
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
// +optional
Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`
// GenerateName is an optional prefix, used by the server, to generate a unique
// name ONLY IF the Name field has not been provided.
// If this field is used, the name returned to the client will be different
// than the name passed. This value will also be combined with a unique suffix.
// The provided value has the same validation rules as the Name field,
// and may be truncated by the length of the suffix required to make the value
// unique on the server.
//
// If this field is specified and the generated name exists, the server will
// NOT return a 409 - instead, it will either return 201 Created or 500 with Reason
// ServerTimeout indicating a unique name could not be found in the time allotted, and the client
// should retry (optionally after the time indicated in the Retry-After header).
//
// Applied only if Name is not specified.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency
// +optional
GenerateName string `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"`
// Namespace defines the space within each name must be unique. An empty namespace is
// equivalent to the "default" namespace, but "default" is the canonical representation.
// Not all objects are required to be scoped to a namespace - the value of this field for
// those objects will be empty.
//
// Must be a DNS_LABEL.
// Cannot be updated.
// More info: http://kubernetes.io/docs/user-guide/namespaces
// +optional
Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`
// SelfLink is a URL representing this object.
// Populated by the system.
// Read-only.
// +optional
SelfLink string `json:"selfLink,omitempty" protobuf:"bytes,4,opt,name=selfLink"`
// UID is the unique in time and space value for this object. It is typically generated by
// the server on successful creation of a resource and is not allowed to change on PUT
// operations.
//
// Populated by the system.
// Read-only.
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
// +optional
UID types.UID `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`
// An opaque value that represents the internal version of this object that can
// be used by clients to determine when objects have changed. May be used for optimistic
// concurrency, change detection, and the watch operation on a resource or set of resources.
// Clients must treat these values as opaque and passed unmodified back to the server.
// They may only be valid for a particular resource or set of resources.
//
// Populated by the system.
// Read-only.
// Value must be treated as opaque by clients and .
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency
// +optional
ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"`
// A sequence number representing a specific generation of the desired state.
// Populated by the system. Read-only.
// +optional
Generation int64 `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"`
// CreationTimestamp is a timestamp representing the server time when this object was
// created. It is not guaranteed to be set in happens-before order across separate operations.
// Clients may not set this value. It is represented in RFC3339 form and is in UTC.
//
// Populated by the system.
// Read-only.
// Null for lists.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
// +optional
CreationTimestamp Time `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"`
// DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This
// field is set by the server when a graceful deletion is requested by the user, and is not
// directly settable by a client. The resource is expected to be deleted (no longer visible
// from resource lists, and not reachable by name) after the time in this field. Once set,
// this value may not be unset or be set further into the future, although it may be shortened
// or the resource may be deleted prior to this time. For example, a user may request that
// a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination
// signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard
// termination signal (SIGKILL) to the container and after cleanup, remove the pod from the
// API. In the presence of network partitions, this object may still exist after this
// timestamp, until an administrator or automated process can determine the resource is
// fully terminated.
// If not set, graceful deletion of the object has not been requested.
//
// Populated by the system when a graceful deletion is requested.
// Read-only.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
// +optional
DeletionTimestamp *Time `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"`
// Number of seconds allowed for this object to gracefully terminate before
// it will be removed from the system. Only set when deletionTimestamp is also set.
// May only be shortened.
// Read-only.
// +optional
DeletionGracePeriodSeconds *int64 `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"`
// Map of string keys and values that can be used to organize and categorize
// (scope and select) objects. May match selectors of replication controllers
// and services.
// More info: http://kubernetes.io/docs/user-guide/labels
// +optional
Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`
// Annotations is an unstructured key value map stored with a resource that may be
// set by external tools to store and retrieve arbitrary metadata. They are not
// queryable and should be preserved when modifying objects.
// More info: http://kubernetes.io/docs/user-guide/annotations
// +optional
Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"`
// List of objects depended by this object. If ALL objects in the list have
// been deleted, this object will be garbage collected. If this object is managed by a controller,
// then an entry in this list will point to this controller, with the controller field set to true.
// There cannot be more than one managing controller.
// +optional
OwnerReferences []OwnerReference `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"`
// Must be empty before the object is deleted from the registry. Each entry
// is an identifier for the responsible component that will remove the entry
// from the list. If the deletionTimestamp of the object is non-nil, entries
// in this list can only be removed.
// +optional
Finalizers []string `json:"finalizers,omitempty" patchStrategy:"merge" protobuf:"bytes,14,rep,name=finalizers"`
// The name of the cluster which the object belongs to.
// This is used to distinguish resources with same name and namespace in different clusters.
// This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.
// +optional
ClusterName string `json:"clusterName,omitempty" protobuf:"bytes,15,opt,name=clusterName"`
}
const (
// NamespaceDefault means the object is in the default namespace which is applied when not specified by clients
NamespaceDefault string = "default"
// NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces
NamespaceAll string = ""
// NamespaceNone is the argument for a context when there is no namespace.
NamespaceNone string = ""
// NamespaceSystem is the system namespace where we place system components.
NamespaceSystem string = "kube-system"
// NamespacePublic is the namespace where we place public info (ConfigMaps)
NamespacePublic string = "kube-public"
)
// OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there
// is no namespace field.
type OwnerReference struct {
// API version of the referent.
APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"`
// Kind of the referent.
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"`
// Name of the referent.
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
Name string `json:"name" protobuf:"bytes,3,opt,name=name"`
// UID of the referent.
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
UID types.UID `json:"uid" protobuf:"bytes,4,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"`
// If true, this reference points to the managing controller.
// +optional
Controller *bool `json:"controller,omitempty" protobuf:"varint,6,opt,name=controller"`
// If true, AND if the owner has the "foregroundDeletion" finalizer, then
// the owner cannot be deleted from the key-value store until this
// reference is removed.
// Defaults to false.
// To set this field, a user needs "delete" permission of the owner,
// otherwise 422 (Unprocessable Entity) will be returned.
// +optional
BlockOwnerDeletion *bool `json:"blockOwnerDeletion,omitempty" protobuf:"varint,7,opt,name=blockOwnerDeletion"`
}
// ListOptions is the query options to a standard REST list call.
type ListOptions struct {
TypeMeta `json:",inline"`
// A selector to restrict the list of returned objects by their labels.
// Defaults to everything.
// +optional
LabelSelector string `json:"labelSelector,omitempty" protobuf:"bytes,1,opt,name=labelSelector"`
// A selector to restrict the list of returned objects by their fields.
// Defaults to everything.
// +optional
FieldSelector string `json:"fieldSelector,omitempty" protobuf:"bytes,2,opt,name=fieldSelector"`
// Watch for changes to the described resources and return them as a stream of
// add, update, and remove notifications. Specify resourceVersion.
// +optional
Watch bool `json:"watch,omitempty" protobuf:"varint,3,opt,name=watch"`
// When specified with a watch call, shows changes that occur after that particular version of a resource.
// Defaults to changes from the beginning of history.
// When specified for list:
// - if unset, then the result is returned from remote storage based on quorum-read flag;
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
// - if set to non zero, then the result is at least as fresh as given rv.
// +optional
ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,4,opt,name=resourceVersion"`
// Timeout for the list/watch call.
// +optional
TimeoutSeconds *int64 `json:"timeoutSeconds,omitempty" protobuf:"varint,5,opt,name=timeoutSeconds"`
}
// ExportOptions is the query options to the standard REST get call.
type ExportOptions struct {
TypeMeta `json:",inline"`
// Should this value be exported. Export strips fields that a user can not specify.`
// Should this value be exported. Export strips fields that a user can not specify.
Export bool `json:"export" protobuf:"varint,1,opt,name=export"`
// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
Exact bool `json:"exact" protobuf:"varint,2,opt,name=exact"`
}
// GetOptions is the standard query options to the standard REST get call.
type GetOptions struct {
TypeMeta `json:",inline"`
// When specified:
// - if unset, then the result is returned from remote storage based on quorum-read flag;
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
// - if set to non zero, then the result is at least as fresh as given rv.
ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,1,opt,name=resourceVersion"`
}
// DeletionPropagation decides if a deletion will propagate to the dependents of
// the object, and how the garbage collector will handle the propagation.
type DeletionPropagation string
const (
// Orphans the dependents.
DeletePropagationOrphan DeletionPropagation = "Orphan"
// Deletes the object from the key-value store, the garbage collector will
// delete the dependents in the background.
DeletePropagationBackground DeletionPropagation = "Background"
// The object exists in the key-value store until the garbage collector
// deletes all the dependents whose ownerReference.blockOwnerDeletion=true
// from the key-value store. API sever will put the "foregroundDeletion"
// finalizer on the object, and sets its deletionTimestamp. This policy is
// cascading, i.e., the dependents will be deleted with Foreground.
DeletePropagationForeground DeletionPropagation = "Foreground"
)
// DeleteOptions may be provided when deleting an API object.
type DeleteOptions struct {
TypeMeta `json:",inline"`
// The duration in seconds before the object should be deleted. Value must be non-negative integer.
// The value zero indicates delete immediately. If this value is nil, the default grace period for the
// specified type will be used.
// Defaults to a per object value if not specified. zero means delete immediately.
// +optional
GracePeriodSeconds *int64 `json:"gracePeriodSeconds,omitempty" protobuf:"varint,1,opt,name=gracePeriodSeconds"`
// Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be
// returned.
// +optional
Preconditions *Preconditions `json:"preconditions,omitempty" protobuf:"bytes,2,opt,name=preconditions"`
// Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7.
// Should the dependent objects be orphaned. If true/false, the "orphan"
// finalizer will be added to/removed from the object's finalizers list.
// Either this field or PropagationPolicy may be set, but not both.
// +optional
OrphanDependents *bool `json:"orphanDependents,omitempty" protobuf:"varint,3,opt,name=orphanDependents"`
// Whether and how garbage collection will be performed.
// Either this field or OrphanDependents may be set, but not both.
// The default policy is decided by the existing finalizer set in the
// metadata.finalizers and the resource-specific default policy.
// +optional
PropagationPolicy *DeletionPropagation `json:"propagationPolicy,omitempty" protobuf:"varint,4,opt,name=propagationPolicy"`
}
// Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.
type Preconditions struct {
// Specifies the target UID.
// +optional
UID *types.UID `json:"uid,omitempty" protobuf:"bytes,1,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"`
}
// Status is a return value for calls that don't return other objects.
type Status struct {
TypeMeta `json:",inline"`
@ -393,6 +688,21 @@ type APIResource struct {
Namespaced bool `json:"namespaced" protobuf:"varint,2,opt,name=namespaced"`
// kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')
Kind string `json:"kind" protobuf:"bytes,3,opt,name=kind"`
// verbs is a list of supported kube verbs (this includes get, list, watch, create,
// update, patch, delete, deletecollection, and proxy)
Verbs Verbs `json:"verbs" protobuf:"bytes,4,opt,name=verbs"`
// shortNames is a list of suggested short names of the resource.
ShortNames []string `json:"shortNames,omitempty" protobuf:"bytes,5,rep,name=shortNames"`
}
// Verbs masks the value so protobuf can generate
//
// +protobuf.nullable=true
// +protobuf.options.(gogoproto.goproto_stringer)=false
type Verbs []string
func (vs Verbs) String() string {
return fmt.Sprintf("%v", []string(vs))
}
// APIResourceList is a list of APIResource, it is used to expose the name of the

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
// This file contains a collection of methods that can be used from go-restful to
// generate Swagger API documentation for its models. Please read this PR for more
@ -53,6 +53,8 @@ var map_APIResource = map[string]string{
"name": "name is the name of the resource.",
"namespaced": "namespaced indicates if a resource is namespaced or not.",
"kind": "kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')",
"verbs": "verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy)",
"shortNames": "shortNames is a list of suggested short names of the resource.",
}
func (APIResource) SwaggerDoc() map[string]string {
@ -79,16 +81,37 @@ func (APIVersions) SwaggerDoc() map[string]string {
return map_APIVersions
}
var map_DeleteOptions = map[string]string{
"": "DeleteOptions may be provided when deleting an API object.",
"gracePeriodSeconds": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
"preconditions": "Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.",
"orphanDependents": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
"propagationPolicy": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy.",
}
func (DeleteOptions) SwaggerDoc() map[string]string {
return map_DeleteOptions
}
var map_ExportOptions = map[string]string{
"": "ExportOptions is the query options to the standard REST get call.",
"export": "Should this value be exported. Export strips fields that a user can not specify.`",
"exact": "Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'",
"export": "Should this value be exported. Export strips fields that a user can not specify.",
"exact": "Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.",
}
func (ExportOptions) SwaggerDoc() map[string]string {
return map_ExportOptions
}
var map_GetOptions = map[string]string{
"": "GetOptions is the standard query options to the standard REST get call.",
"resourceVersion": "When specified: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.",
}
func (GetOptions) SwaggerDoc() map[string]string {
return map_GetOptions
}
var map_GroupVersionForDiscovery = map[string]string{
"": "GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensibility.",
"groupVersion": "groupVersion specifies the API group and version in the form \"group/version\"",
@ -130,6 +153,56 @@ func (ListMeta) SwaggerDoc() map[string]string {
return map_ListMeta
}
var map_ListOptions = map[string]string{
"": "ListOptions is the query options to a standard REST list call.",
"labelSelector": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
"fieldSelector": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
"watch": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.",
"resourceVersion": "When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.",
"timeoutSeconds": "Timeout for the list/watch call.",
}
func (ListOptions) SwaggerDoc() map[string]string {
return map_ListOptions
}
var map_ObjectMeta = map[string]string{
"": "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.",
"name": "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
"generateName": "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).\n\nApplied only if Name is not specified. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency",
"namespace": "Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces",
"selfLink": "SelfLink is a URL representing this object. Populated by the system. Read-only.",
"uid": "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids",
"resourceVersion": "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency",
"generation": "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.",
"creationTimestamp": "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
"deletionTimestamp": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field. Once set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
"deletionGracePeriodSeconds": "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.",
"labels": "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels",
"annotations": "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations",
"ownerReferences": "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.",
"finalizers": "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed.",
"clusterName": "The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.",
}
func (ObjectMeta) SwaggerDoc() map[string]string {
return map_ObjectMeta
}
var map_OwnerReference = map[string]string{
"": "OwnerReference contains enough information to let you identify an owning object. Currently, an owning object must be in the same namespace, so there is no namespace field.",
"apiVersion": "API version of the referent.",
"kind": "Kind of the referent. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds",
"name": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",
"uid": "UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids",
"controller": "If true, this reference points to the managing controller.",
"blockOwnerDeletion": "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.",
}
func (OwnerReference) SwaggerDoc() map[string]string {
return map_OwnerReference
}
var map_Patch = map[string]string{
"": "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.",
}
@ -138,6 +211,15 @@ func (Patch) SwaggerDoc() map[string]string {
return map_Patch
}
var map_Preconditions = map[string]string{
"": "Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.",
"uid": "Specifies the target UID.",
}
func (Preconditions) SwaggerDoc() map[string]string {
return map_Preconditions
}
var map_RootPaths = map[string]string{
"": "RootPaths lists the paths available at root. For example: \"/healthz\", \"/apis\".",
"paths": "paths are the paths available at root.",

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package runtime
package unstructured
import (
"bytes"
@ -26,12 +26,73 @@ import (
"github.com/golang/glog"
"k8s.io/client-go/pkg/api/meta/metatypes"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/types"
"k8s.io/client-go/pkg/util/json"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/json"
)
// Unstructured allows objects that do not have Golang structs registered to be manipulated
// generically. This can be used to deal with the API objects from a plug-in. Unstructured
// objects still have functioning TypeMeta features-- kind, version, etc.
//
// WARNING: This object has accessors for the v1 standard metadata. You *MUST NOT* use this
// type if you are dealing with objects that are not in the server meta v1 schema.
//
// TODO: make the serialization part of this type distinct from the field accessors.
type Unstructured struct {
// Object is a JSON compatible map with string, float, int, bool, []interface{}, or
// map[string]interface{}
// children.
Object map[string]interface{}
}
var _ metav1.Object = &Unstructured{}
var _ runtime.Unstructured = &Unstructured{}
var _ runtime.Unstructured = &UnstructuredList{}
func (obj *Unstructured) GetObjectKind() schema.ObjectKind { return obj }
func (obj *UnstructuredList) GetObjectKind() schema.ObjectKind { return obj }
func (obj *Unstructured) IsUnstructuredObject() {}
func (obj *UnstructuredList) IsUnstructuredObject() {}
func (obj *Unstructured) IsList() bool {
if obj.Object != nil {
_, ok := obj.Object["items"]
return ok
}
return false
}
func (obj *UnstructuredList) IsList() bool { return true }
func (obj *Unstructured) UnstructuredContent() map[string]interface{} {
if obj.Object == nil {
obj.Object = make(map[string]interface{})
}
return obj.Object
}
// UnstructuredContent returns a map contain an overlay of the Items field onto
// the Object field. Items always overwrites overlay. Changing "items" in the
// returned object will affect items in the underlying Items field, but changing
// the "items" slice itself will have no effect.
// TODO: expose SetUnstructuredContent on runtime.Unstructured that allows
// items to be changed.
func (obj *UnstructuredList) UnstructuredContent() map[string]interface{} {
out := obj.Object
if out == nil {
out = make(map[string]interface{})
}
items := make([]interface{}, len(obj.Items))
for i, item := range obj.Items {
items[i] = item.Object
}
out["items"] = items
return out
}
// MarshalJSON ensures that the unstructured object produces proper
// JSON when passed to Go's standard JSON library.
func (u *Unstructured) MarshalJSON() ([]byte, error) {
@ -141,38 +202,54 @@ func (u *Unstructured) setNestedMap(value map[string]string, fields ...string) {
setNestedMap(u.Object, value, fields...)
}
func extractOwnerReference(src interface{}) metatypes.OwnerReference {
func extractOwnerReference(src interface{}) metav1.OwnerReference {
v := src.(map[string]interface{})
controllerPtr, ok := (getNestedField(v, "controller")).(*bool)
// though this field is a *bool, but when decoded from JSON, it's
// unmarshalled as bool.
var controllerPtr *bool
controller, ok := (getNestedField(v, "controller")).(bool)
if !ok {
controllerPtr = nil
} else {
if controllerPtr != nil {
controller := *controllerPtr
controllerPtr = &controller
}
controllerCopy := controller
controllerPtr = &controllerCopy
}
return metatypes.OwnerReference{
Kind: getNestedString(v, "kind"),
Name: getNestedString(v, "name"),
APIVersion: getNestedString(v, "apiVersion"),
UID: (types.UID)(getNestedString(v, "uid")),
Controller: controllerPtr,
var blockOwnerDeletionPtr *bool
blockOwnerDeletion, ok := (getNestedField(v, "blockOwnerDeletion")).(bool)
if !ok {
blockOwnerDeletionPtr = nil
} else {
blockOwnerDeletionCopy := blockOwnerDeletion
blockOwnerDeletionPtr = &blockOwnerDeletionCopy
}
return metav1.OwnerReference{
Kind: getNestedString(v, "kind"),
Name: getNestedString(v, "name"),
APIVersion: getNestedString(v, "apiVersion"),
UID: (types.UID)(getNestedString(v, "uid")),
Controller: controllerPtr,
BlockOwnerDeletion: blockOwnerDeletionPtr,
}
}
func setOwnerReference(src metatypes.OwnerReference) map[string]interface{} {
func setOwnerReference(src metav1.OwnerReference) map[string]interface{} {
ret := make(map[string]interface{})
controllerPtr := src.Controller
if controllerPtr != nil {
controller := *controllerPtr
controllerPtr = &controller
}
blockOwnerDeletionPtr := src.BlockOwnerDeletion
if blockOwnerDeletionPtr != nil {
blockOwnerDeletion := *blockOwnerDeletionPtr
blockOwnerDeletionPtr = &blockOwnerDeletion
}
setNestedField(ret, src.Kind, "kind")
setNestedField(ret, src.Name, "name")
setNestedField(ret, src.APIVersion, "apiVersion")
setNestedField(ret, string(src.UID), "uid")
setNestedField(ret, controllerPtr, "controller")
setNestedField(ret, blockOwnerDeletionPtr, "blockOwnerDeletion")
return ret
}
@ -201,20 +278,20 @@ func getOwnerReferences(object map[string]interface{}) ([]map[string]interface{}
return ownerReferences, nil
}
func (u *Unstructured) GetOwnerReferences() []metatypes.OwnerReference {
func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference {
original, err := getOwnerReferences(u.Object)
if err != nil {
glog.V(6).Info(err)
return nil
}
ret := make([]metatypes.OwnerReference, 0, len(original))
ret := make([]metav1.OwnerReference, 0, len(original))
for i := 0; i < len(original); i++ {
ret = append(ret, extractOwnerReference(original[i]))
}
return ret
}
func (u *Unstructured) SetOwnerReferences(references []metatypes.OwnerReference) {
func (u *Unstructured) SetOwnerReferences(references []metav1.OwnerReference) {
var newReferences = make([]map[string]interface{}, 0, len(references))
for i := 0; i < len(references); i++ {
newReferences = append(newReferences, setOwnerReference(references[i]))
@ -286,19 +363,19 @@ func (u *Unstructured) SetSelfLink(selfLink string) {
u.setNestedField(selfLink, "metadata", "selfLink")
}
func (u *Unstructured) GetCreationTimestamp() unversioned.Time {
var timestamp unversioned.Time
func (u *Unstructured) GetCreationTimestamp() metav1.Time {
var timestamp metav1.Time
timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "creationTimestamp"))
return timestamp
}
func (u *Unstructured) SetCreationTimestamp(timestamp unversioned.Time) {
func (u *Unstructured) SetCreationTimestamp(timestamp metav1.Time) {
ts, _ := timestamp.MarshalQueryParameter()
u.setNestedField(ts, "metadata", "creationTimestamp")
}
func (u *Unstructured) GetDeletionTimestamp() *unversioned.Time {
var timestamp unversioned.Time
func (u *Unstructured) GetDeletionTimestamp() *metav1.Time {
var timestamp metav1.Time
timestamp.UnmarshalQueryParameter(getNestedString(u.Object, "metadata", "deletionTimestamp"))
if timestamp.IsZero() {
return nil
@ -306,7 +383,7 @@ func (u *Unstructured) GetDeletionTimestamp() *unversioned.Time {
return &timestamp
}
func (u *Unstructured) SetDeletionTimestamp(timestamp *unversioned.Time) {
func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time) {
ts, _ := timestamp.MarshalQueryParameter()
u.setNestedField(ts, "metadata", "deletionTimestamp")
}
@ -327,15 +404,15 @@ func (u *Unstructured) SetAnnotations(annotations map[string]string) {
u.setNestedMap(annotations, "metadata", "annotations")
}
func (u *Unstructured) SetGroupVersionKind(gvk unversioned.GroupVersionKind) {
func (u *Unstructured) SetGroupVersionKind(gvk schema.GroupVersionKind) {
u.SetAPIVersion(gvk.GroupVersion().String())
u.SetKind(gvk.Kind)
}
func (u *Unstructured) GroupVersionKind() unversioned.GroupVersionKind {
gv, err := unversioned.ParseGroupVersion(u.GetAPIVersion())
func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind {
gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
if err != nil {
return unversioned.GroupVersionKind{}
return schema.GroupVersionKind{}
}
gvk := gv.WithKind(u.GetKind())
return gvk
@ -421,15 +498,15 @@ func (u *UnstructuredList) SetSelfLink(selfLink string) {
u.setNestedField(selfLink, "metadata", "selfLink")
}
func (u *UnstructuredList) SetGroupVersionKind(gvk unversioned.GroupVersionKind) {
func (u *UnstructuredList) SetGroupVersionKind(gvk schema.GroupVersionKind) {
u.SetAPIVersion(gvk.GroupVersion().String())
u.SetKind(gvk.Kind)
}
func (u *UnstructuredList) GroupVersionKind() unversioned.GroupVersionKind {
gv, err := unversioned.ParseGroupVersion(u.GetAPIVersion())
func (u *UnstructuredList) GroupVersionKind() schema.GroupVersionKind {
gv, err := schema.ParseGroupVersion(u.GetAPIVersion())
if err != nil {
return unversioned.GroupVersionKind{}
return schema.GroupVersionKind{}
}
gvk := gv.WithKind(u.GetKind())
return gvk
@ -438,11 +515,11 @@ func (u *UnstructuredList) GroupVersionKind() unversioned.GroupVersionKind {
// UnstructuredJSONScheme is capable of converting JSON data into the Unstructured
// type, which can be used for generic access to objects without a predefined scheme.
// TODO: move into serializer/json.
var UnstructuredJSONScheme Codec = unstructuredJSONScheme{}
var UnstructuredJSONScheme runtime.Codec = unstructuredJSONScheme{}
type unstructuredJSONScheme struct{}
func (s unstructuredJSONScheme) Decode(data []byte, _ *unversioned.GroupVersionKind, obj Object) (Object, *unversioned.GroupVersionKind, error) {
func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
var err error
if obj != nil {
err = s.decodeInto(data, obj)
@ -456,13 +533,13 @@ func (s unstructuredJSONScheme) Decode(data []byte, _ *unversioned.GroupVersionK
gvk := obj.GetObjectKind().GroupVersionKind()
if len(gvk.Kind) == 0 {
return nil, &gvk, NewMissingKindErr(string(data))
return nil, &gvk, runtime.NewMissingKindErr(string(data))
}
return obj, &gvk, nil
}
func (unstructuredJSONScheme) Encode(obj Object, w io.Writer) error {
func (unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error {
switch t := obj.(type) {
case *Unstructured:
return json.NewEncoder(w).Encode(t.Object)
@ -474,7 +551,7 @@ func (unstructuredJSONScheme) Encode(obj Object, w io.Writer) error {
t.Object["items"] = items
defer func() { delete(t.Object, "items") }()
return json.NewEncoder(w).Encode(t.Object)
case *Unknown:
case *runtime.Unknown:
// TODO: Unstructured needs to deal with ContentType.
_, err := w.Write(t.Raw)
return err
@ -483,7 +560,7 @@ func (unstructuredJSONScheme) Encode(obj Object, w io.Writer) error {
}
}
func (s unstructuredJSONScheme) decode(data []byte) (Object, error) {
func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error) {
type detector struct {
Items gojson.RawMessage
}
@ -504,16 +581,16 @@ func (s unstructuredJSONScheme) decode(data []byte) (Object, error) {
return unstruct, err
}
func (s unstructuredJSONScheme) decodeInto(data []byte, obj Object) error {
func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error {
switch x := obj.(type) {
case *Unstructured:
return s.decodeToUnstructured(data, x)
case *UnstructuredList:
return s.decodeToList(data, x)
case *VersionedObjects:
case *runtime.VersionedObjects:
o, err := s.decode(data)
if err == nil {
x.Objects = []Object{o}
x.Objects = []runtime.Object{o}
}
return err
default:
@ -595,9 +672,9 @@ func (UnstructuredObjectConverter) Convert(in, out, context interface{}) error {
return nil
}
func (UnstructuredObjectConverter) ConvertToVersion(in Object, target GroupVersioner) (Object, error) {
func (UnstructuredObjectConverter) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error) {
if kind := in.GetObjectKind().GroupVersionKind(); !kind.Empty() {
gvk, ok := target.KindForGroupVersionKinds([]unversioned.GroupVersionKind{kind})
gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{kind})
if !ok {
// TODO: should this be a typed error?
return nil, fmt.Errorf("%v is unstructured and is not suitable for converting to %q", kind, target)

View file

@ -14,35 +14,30 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package versioned
package v1
import (
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/conversion"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/watch"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
)
// WatchEventKind is name reserved for serializing watch events.
const WatchEventKind = "WatchEvent"
// Event represents a single event to a watched resource.
//
// +protobuf=true
type WatchEvent struct {
Type string `json:"type" protobuf:"bytes,1,opt,name=type"`
// AddToGroupVersion registers the watch external and internal kinds with the scheme, and ensures the proper
// conversions are in place.
func AddToGroupVersion(scheme *runtime.Scheme, groupVersion unversioned.GroupVersion) {
scheme.AddKnownTypeWithName(groupVersion.WithKind(WatchEventKind), &Event{})
scheme.AddKnownTypeWithName(
unversioned.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal}.WithKind(WatchEventKind),
&InternalEvent{},
)
scheme.AddConversionFuncs(
Convert_versioned_Event_to_watch_Event,
Convert_versioned_InternalEvent_to_versioned_Event,
Convert_watch_Event_to_versioned_Event,
Convert_versioned_Event_to_versioned_InternalEvent,
)
// Object is:
// * If Type is Added or Modified: the new state of the object.
// * If Type is Deleted: the state of the object immediately before deletion.
// * If Type is Error: *Status is recommended; other types may make sense
// depending on context.
Object runtime.RawExtension `json:"object" protobuf:"bytes,2,opt,name=object"`
}
func Convert_watch_Event_to_versioned_Event(in *watch.Event, out *Event, s conversion.Scope) error {
func Convert_watch_Event_to_versioned_Event(in *watch.Event, out *WatchEvent, s conversion.Scope) error {
out.Type = string(in.Type)
switch t := in.Object.(type) {
case *runtime.Unknown:
@ -55,11 +50,11 @@ func Convert_watch_Event_to_versioned_Event(in *watch.Event, out *Event, s conve
return nil
}
func Convert_versioned_InternalEvent_to_versioned_Event(in *InternalEvent, out *Event, s conversion.Scope) error {
func Convert_versioned_InternalEvent_to_versioned_Event(in *InternalEvent, out *WatchEvent, s conversion.Scope) error {
return Convert_watch_Event_to_versioned_Event((*watch.Event)(in), out, s)
}
func Convert_versioned_Event_to_watch_Event(in *Event, out *watch.Event, s conversion.Scope) error {
func Convert_versioned_Event_to_watch_Event(in *WatchEvent, out *watch.Event, s conversion.Scope) error {
out.Type = watch.EventType(in.Type)
if in.Object.Object != nil {
out.Object = in.Object.Object
@ -73,12 +68,13 @@ func Convert_versioned_Event_to_watch_Event(in *Event, out *watch.Event, s conve
return nil
}
func Convert_versioned_Event_to_versioned_InternalEvent(in *Event, out *InternalEvent, s conversion.Scope) error {
func Convert_versioned_Event_to_versioned_InternalEvent(in *WatchEvent, out *InternalEvent, s conversion.Scope) error {
return Convert_versioned_Event_to_watch_Event(in, (*watch.Event)(out), s)
}
// InternalEvent makes watch.Event versioned
// +protobuf=false
type InternalEvent watch.Event
func (e *InternalEvent) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind }
func (e *Event) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind }
func (e *InternalEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
func (e *WatchEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package unversioned
package v1
const (
// If you add a new topology domain here, also consider adding it to the set of default values
@ -27,6 +27,23 @@ const (
LabelOS = "beta.kubernetes.io/os"
LabelArch = "beta.kubernetes.io/arch"
// Historically fluentd was a manifest pod the was migrated to DaemonSet.
// To avoid situation during cluster upgrade when there are two instances
// of fluentd running on a node, kubelet need to mark node on which
// fluentd in not running as a manifest pod with LabelFluentdDsReady.
LabelFluentdDsReady = "alpha.kubernetes.io/fluentd-ds-ready"
// When feature-gate for TaintBasedEvictions=true flag is enabled,
// TaintNodeNotReady would be automatically added by node controller
// when node is not ready, and removed when node becomes ready.
TaintNodeNotReady = "node.alpha.kubernetes.io/notReady"
// When feature-gate for TaintBasedEvictions=true flag is enabled,
// TaintNodeUnreachable would be automatically added by node controller
// when node becomes unreachable (corresponding to NodeReady status ConditionUnknown)
// and removed when node becomes reachable (NodeReady status ConditionTrue).
TaintNodeUnreachable = "node.alpha.kubernetes.io/unreachable"
)
// Role labels are applied to Nodes to mark their purpose. In particular, we

View file

@ -0,0 +1,554 @@
// +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"
types "k8s.io/apimachinery/pkg/types"
reflect "reflect"
)
// GetGeneratedDeepCopyFuncs returns the generated funcs, since we aren't registering them.
func GetGeneratedDeepCopyFuncs() []conversion.GeneratedDeepCopyFunc {
return []conversion.GeneratedDeepCopyFunc{
{Fn: DeepCopy_v1_APIGroup, InType: reflect.TypeOf(&APIGroup{})},
{Fn: DeepCopy_v1_APIGroupList, InType: reflect.TypeOf(&APIGroupList{})},
{Fn: DeepCopy_v1_APIResource, InType: reflect.TypeOf(&APIResource{})},
{Fn: DeepCopy_v1_APIResourceList, InType: reflect.TypeOf(&APIResourceList{})},
{Fn: DeepCopy_v1_APIVersions, InType: reflect.TypeOf(&APIVersions{})},
{Fn: DeepCopy_v1_DeleteOptions, InType: reflect.TypeOf(&DeleteOptions{})},
{Fn: DeepCopy_v1_Duration, InType: reflect.TypeOf(&Duration{})},
{Fn: DeepCopy_v1_ExportOptions, InType: reflect.TypeOf(&ExportOptions{})},
{Fn: DeepCopy_v1_GetOptions, InType: reflect.TypeOf(&GetOptions{})},
{Fn: DeepCopy_v1_GroupKind, InType: reflect.TypeOf(&GroupKind{})},
{Fn: DeepCopy_v1_GroupResource, InType: reflect.TypeOf(&GroupResource{})},
{Fn: DeepCopy_v1_GroupVersion, InType: reflect.TypeOf(&GroupVersion{})},
{Fn: DeepCopy_v1_GroupVersionForDiscovery, InType: reflect.TypeOf(&GroupVersionForDiscovery{})},
{Fn: DeepCopy_v1_GroupVersionKind, InType: reflect.TypeOf(&GroupVersionKind{})},
{Fn: DeepCopy_v1_GroupVersionResource, InType: reflect.TypeOf(&GroupVersionResource{})},
{Fn: DeepCopy_v1_InternalEvent, InType: reflect.TypeOf(&InternalEvent{})},
{Fn: DeepCopy_v1_LabelSelector, InType: reflect.TypeOf(&LabelSelector{})},
{Fn: DeepCopy_v1_LabelSelectorRequirement, InType: reflect.TypeOf(&LabelSelectorRequirement{})},
{Fn: DeepCopy_v1_ListMeta, InType: reflect.TypeOf(&ListMeta{})},
{Fn: DeepCopy_v1_ListOptions, InType: reflect.TypeOf(&ListOptions{})},
{Fn: DeepCopy_v1_ObjectMeta, InType: reflect.TypeOf(&ObjectMeta{})},
{Fn: DeepCopy_v1_OwnerReference, InType: reflect.TypeOf(&OwnerReference{})},
{Fn: DeepCopy_v1_Patch, InType: reflect.TypeOf(&Patch{})},
{Fn: DeepCopy_v1_Preconditions, InType: reflect.TypeOf(&Preconditions{})},
{Fn: DeepCopy_v1_RootPaths, InType: reflect.TypeOf(&RootPaths{})},
{Fn: DeepCopy_v1_ServerAddressByClientCIDR, InType: reflect.TypeOf(&ServerAddressByClientCIDR{})},
{Fn: DeepCopy_v1_Status, InType: reflect.TypeOf(&Status{})},
{Fn: DeepCopy_v1_StatusCause, InType: reflect.TypeOf(&StatusCause{})},
{Fn: DeepCopy_v1_StatusDetails, InType: reflect.TypeOf(&StatusDetails{})},
{Fn: DeepCopy_v1_Time, InType: reflect.TypeOf(&Time{})},
{Fn: DeepCopy_v1_Timestamp, InType: reflect.TypeOf(&Timestamp{})},
{Fn: DeepCopy_v1_TypeMeta, InType: reflect.TypeOf(&TypeMeta{})},
{Fn: DeepCopy_v1_WatchEvent, InType: reflect.TypeOf(&WatchEvent{})},
}
}
func DeepCopy_v1_APIGroup(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*APIGroup)
out := out.(*APIGroup)
*out = *in
if in.Versions != nil {
in, out := &in.Versions, &out.Versions
*out = make([]GroupVersionForDiscovery, len(*in))
copy(*out, *in)
}
if in.ServerAddressByClientCIDRs != nil {
in, out := &in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs
*out = make([]ServerAddressByClientCIDR, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_APIGroupList(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*APIGroupList)
out := out.(*APIGroupList)
*out = *in
if in.Groups != nil {
in, out := &in.Groups, &out.Groups
*out = make([]APIGroup, len(*in))
for i := range *in {
if newVal, err := c.DeepCopy(&(*in)[i]); err != nil {
return err
} else {
(*out)[i] = *newVal.(*APIGroup)
}
}
}
return nil
}
}
func DeepCopy_v1_APIResource(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*APIResource)
out := out.(*APIResource)
*out = *in
if in.Verbs != nil {
in, out := &in.Verbs, &out.Verbs
*out = make(Verbs, len(*in))
copy(*out, *in)
}
if in.ShortNames != nil {
in, out := &in.ShortNames, &out.ShortNames
*out = make([]string, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_APIResourceList(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*APIResourceList)
out := out.(*APIResourceList)
*out = *in
if in.APIResources != nil {
in, out := &in.APIResources, &out.APIResources
*out = make([]APIResource, len(*in))
for i := range *in {
if newVal, err := c.DeepCopy(&(*in)[i]); err != nil {
return err
} else {
(*out)[i] = *newVal.(*APIResource)
}
}
}
return nil
}
}
func DeepCopy_v1_APIVersions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*APIVersions)
out := out.(*APIVersions)
*out = *in
if in.Versions != nil {
in, out := &in.Versions, &out.Versions
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ServerAddressByClientCIDRs != nil {
in, out := &in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs
*out = make([]ServerAddressByClientCIDR, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_DeleteOptions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*DeleteOptions)
out := out.(*DeleteOptions)
*out = *in
if in.GracePeriodSeconds != nil {
in, out := &in.GracePeriodSeconds, &out.GracePeriodSeconds
*out = new(int64)
**out = **in
}
if in.Preconditions != nil {
in, out := &in.Preconditions, &out.Preconditions
if newVal, err := c.DeepCopy(*in); err != nil {
return err
} else {
*out = newVal.(*Preconditions)
}
}
if in.OrphanDependents != nil {
in, out := &in.OrphanDependents, &out.OrphanDependents
*out = new(bool)
**out = **in
}
if in.PropagationPolicy != nil {
in, out := &in.PropagationPolicy, &out.PropagationPolicy
*out = new(DeletionPropagation)
**out = **in
}
return nil
}
}
func DeepCopy_v1_Duration(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Duration)
out := out.(*Duration)
*out = *in
return nil
}
}
func DeepCopy_v1_ExportOptions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*ExportOptions)
out := out.(*ExportOptions)
*out = *in
return nil
}
}
func DeepCopy_v1_GetOptions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GetOptions)
out := out.(*GetOptions)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupKind(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupKind)
out := out.(*GroupKind)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupResource(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupResource)
out := out.(*GroupResource)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupVersion(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupVersion)
out := out.(*GroupVersion)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupVersionForDiscovery(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupVersionForDiscovery)
out := out.(*GroupVersionForDiscovery)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupVersionKind(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupVersionKind)
out := out.(*GroupVersionKind)
*out = *in
return nil
}
}
func DeepCopy_v1_GroupVersionResource(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*GroupVersionResource)
out := out.(*GroupVersionResource)
*out = *in
return nil
}
}
func DeepCopy_v1_InternalEvent(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*InternalEvent)
out := out.(*InternalEvent)
*out = *in
// in.Object is kind 'Interface'
if in.Object != nil {
if newVal, err := c.DeepCopy(&in.Object); err != nil {
return err
} else {
out.Object = *newVal.(*runtime.Object)
}
}
return nil
}
}
func DeepCopy_v1_LabelSelector(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*LabelSelector)
out := out.(*LabelSelector)
*out = *in
if in.MatchLabels != nil {
in, out := &in.MatchLabels, &out.MatchLabels
*out = make(map[string]string)
for key, val := range *in {
(*out)[key] = val
}
}
if in.MatchExpressions != nil {
in, out := &in.MatchExpressions, &out.MatchExpressions
*out = make([]LabelSelectorRequirement, len(*in))
for i := range *in {
if newVal, err := c.DeepCopy(&(*in)[i]); err != nil {
return err
} else {
(*out)[i] = *newVal.(*LabelSelectorRequirement)
}
}
}
return nil
}
}
func DeepCopy_v1_LabelSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*LabelSelectorRequirement)
out := out.(*LabelSelectorRequirement)
*out = *in
if in.Values != nil {
in, out := &in.Values, &out.Values
*out = make([]string, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_ListMeta(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*ListMeta)
out := out.(*ListMeta)
*out = *in
return nil
}
}
func DeepCopy_v1_ListOptions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*ListOptions)
out := out.(*ListOptions)
*out = *in
if in.TimeoutSeconds != nil {
in, out := &in.TimeoutSeconds, &out.TimeoutSeconds
*out = new(int64)
**out = **in
}
return nil
}
}
func DeepCopy_v1_ObjectMeta(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*ObjectMeta)
out := out.(*ObjectMeta)
*out = *in
out.CreationTimestamp = in.CreationTimestamp.DeepCopy()
if in.DeletionTimestamp != nil {
in, out := &in.DeletionTimestamp, &out.DeletionTimestamp
*out = new(Time)
**out = (*in).DeepCopy()
}
if in.DeletionGracePeriodSeconds != nil {
in, out := &in.DeletionGracePeriodSeconds, &out.DeletionGracePeriodSeconds
*out = new(int64)
**out = **in
}
if in.Labels != nil {
in, out := &in.Labels, &out.Labels
*out = make(map[string]string)
for key, val := range *in {
(*out)[key] = val
}
}
if in.Annotations != nil {
in, out := &in.Annotations, &out.Annotations
*out = make(map[string]string)
for key, val := range *in {
(*out)[key] = val
}
}
if in.OwnerReferences != nil {
in, out := &in.OwnerReferences, &out.OwnerReferences
*out = make([]OwnerReference, len(*in))
for i := range *in {
if newVal, err := c.DeepCopy(&(*in)[i]); err != nil {
return err
} else {
(*out)[i] = *newVal.(*OwnerReference)
}
}
}
if in.Finalizers != nil {
in, out := &in.Finalizers, &out.Finalizers
*out = make([]string, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_OwnerReference(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*OwnerReference)
out := out.(*OwnerReference)
*out = *in
if in.Controller != nil {
in, out := &in.Controller, &out.Controller
*out = new(bool)
**out = **in
}
if in.BlockOwnerDeletion != nil {
in, out := &in.BlockOwnerDeletion, &out.BlockOwnerDeletion
*out = new(bool)
**out = **in
}
return nil
}
}
func DeepCopy_v1_Patch(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Patch)
out := out.(*Patch)
*out = *in
return nil
}
}
func DeepCopy_v1_Preconditions(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Preconditions)
out := out.(*Preconditions)
*out = *in
if in.UID != nil {
in, out := &in.UID, &out.UID
*out = new(types.UID)
**out = **in
}
return nil
}
}
func DeepCopy_v1_RootPaths(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*RootPaths)
out := out.(*RootPaths)
*out = *in
if in.Paths != nil {
in, out := &in.Paths, &out.Paths
*out = make([]string, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_ServerAddressByClientCIDR(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*ServerAddressByClientCIDR)
out := out.(*ServerAddressByClientCIDR)
*out = *in
return nil
}
}
func DeepCopy_v1_Status(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Status)
out := out.(*Status)
*out = *in
if in.Details != nil {
in, out := &in.Details, &out.Details
if newVal, err := c.DeepCopy(*in); err != nil {
return err
} else {
*out = newVal.(*StatusDetails)
}
}
return nil
}
}
func DeepCopy_v1_StatusCause(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatusCause)
out := out.(*StatusCause)
*out = *in
return nil
}
}
func DeepCopy_v1_StatusDetails(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*StatusDetails)
out := out.(*StatusDetails)
*out = *in
if in.Causes != nil {
in, out := &in.Causes, &out.Causes
*out = make([]StatusCause, len(*in))
copy(*out, *in)
}
return nil
}
}
func DeepCopy_v1_Time(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Time)
out := out.(*Time)
*out = in.DeepCopy()
return nil
}
}
func DeepCopy_v1_Timestamp(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*Timestamp)
out := out.(*Timestamp)
*out = *in
return nil
}
}
func DeepCopy_v1_TypeMeta(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*TypeMeta)
out := out.(*TypeMeta)
*out = *in
return nil
}
}
func DeepCopy_v1_WatchEvent(in interface{}, out interface{}, c *conversion.Cloner) error {
{
in := in.(*WatchEvent)
out := out.(*WatchEvent)
*out = *in
if newVal, err := c.DeepCopy(&in.Object); err != nil {
return err
} else {
out.Object = *newVal.(*runtime.RawExtension)
}
return nil
}
}

View file

@ -0,0 +1,32 @@
// +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 defaulter-gen. Do not edit it manually!
package v1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// RegisterDefaults adds defaulters functions to the given scheme.
// Public to allow building arbitrary schemes.
// All generated defaulters are covering - they call all nested defaulters.
func RegisterDefaults(scheme *runtime.Scheme) error {
return nil
}

10
vendor/k8s.io/apimachinery/pkg/conversion/OWNERS generated vendored Normal file
View file

@ -0,0 +1,10 @@
approvers:
- derekwaynecarr
- lavalamp
- smarterclayton
- wojtek-t
reviewers:
- derekwaynecarr
- lavalamp
- smarterclayton
- wojtek-t

View file

@ -17,7 +17,7 @@ limitations under the License.
package conversion
import (
"k8s.io/client-go/pkg/third_party/forked/golang/reflect"
"k8s.io/apimachinery/third_party/forked/golang/reflect"
)
// The code for this type must be located in third_party, since it forks from

View file

@ -21,4 +21,4 @@ limitations under the License.
// but for the fields which did not change, copying is automated. This makes it
// easy to modify the structures you use in memory without affecting the format
// you store on disk or respond to in your external API calls.
package conversion
package conversion // import "k8s.io/apimachinery/pkg/conversion"

View file

@ -16,4 +16,4 @@ limitations under the License.
// Package queryparams provides conversion from versioned
// runtime objects to URL query values
package queryparams
package queryparams // import "k8s.io/apimachinery/pkg/conversion/queryparams"

View file

@ -16,4 +16,4 @@ limitations under the License.
// Package fields implements a simple field system, parsing and matching
// selectors with sets of fields.
package fields
package fields // import "k8s.io/apimachinery/pkg/fields"

View file

@ -16,7 +16,7 @@ limitations under the License.
package fields
import "k8s.io/client-go/pkg/selection"
import "k8s.io/apimachinery/pkg/selection"
// Requirements is AND of all requirements.
type Requirements []Requirement

View file

@ -17,11 +17,12 @@ limitations under the License.
package fields
import (
"bytes"
"fmt"
"sort"
"strings"
"k8s.io/client-go/pkg/selection"
"k8s.io/apimachinery/pkg/selection"
)
// Selector represents a field selector.
@ -90,7 +91,7 @@ func (t *hasTerm) Requirements() Requirements {
}
func (t *hasTerm) String() string {
return fmt.Sprintf("%v=%v", t.field, t.value)
return fmt.Sprintf("%v=%v", t.field, EscapeValue(t.value))
}
type notHasTerm struct {
@ -126,7 +127,7 @@ func (t *notHasTerm) Requirements() Requirements {
}
func (t *notHasTerm) String() string {
return fmt.Sprintf("%v!=%v", t.field, t.value)
return fmt.Sprintf("%v!=%v", t.field, EscapeValue(t.value))
}
type andTerm []Selector
@ -212,6 +213,81 @@ func SelectorFromSet(ls Set) Selector {
return andTerm(items)
}
// valueEscaper prefixes \,= characters with a backslash
var valueEscaper = strings.NewReplacer(
// escape \ characters
`\`, `\\`,
// then escape , and = characters to allow unambiguous parsing of the value in a fieldSelector
`,`, `\,`,
`=`, `\=`,
)
// Escapes an arbitrary literal string for use as a fieldSelector value
func EscapeValue(s string) string {
return valueEscaper.Replace(s)
}
// InvalidEscapeSequence indicates an error occurred unescaping a field selector
type InvalidEscapeSequence struct {
sequence string
}
func (i InvalidEscapeSequence) Error() string {
return fmt.Sprintf("invalid field selector: invalid escape sequence: %s", i.sequence)
}
// UnescapedRune indicates an error occurred unescaping a field selector
type UnescapedRune struct {
r rune
}
func (i UnescapedRune) Error() string {
return fmt.Sprintf("invalid field selector: unescaped character in value: %v", i.r)
}
// Unescapes a fieldSelector value and returns the original literal value.
// May return the original string if it contains no escaped or special characters.
func UnescapeValue(s string) (string, error) {
// if there's no escaping or special characters, just return to avoid allocation
if !strings.ContainsAny(s, `\,=`) {
return s, nil
}
v := bytes.NewBuffer(make([]byte, 0, len(s)))
inSlash := false
for _, c := range s {
if inSlash {
switch c {
case '\\', ',', '=':
// omit the \ for recognized escape sequences
v.WriteRune(c)
default:
// error on unrecognized escape sequences
return "", InvalidEscapeSequence{sequence: string([]rune{'\\', c})}
}
inSlash = false
continue
}
switch c {
case '\\':
inSlash = true
case ',', '=':
// unescaped , and = characters are not allowed in field selector values
return "", UnescapedRune{r: c}
default:
v.WriteRune(c)
}
}
// Ending with a single backslash is an invalid sequence
if inSlash {
return "", InvalidEscapeSequence{sequence: "\\"}
}
return v.String(), nil
}
// ParseSelectorOrDie takes a string representing a selector and returns an
// object suitable for matching, or panic when an error occur.
func ParseSelectorOrDie(s string) Selector {
@ -239,29 +315,83 @@ func ParseAndTransformSelector(selector string, fn TransformFunc) (Selector, err
// Function to transform selectors.
type TransformFunc func(field, value string) (newField, newValue string, err error)
func try(selectorPiece, op string) (lhs, rhs string, ok bool) {
pieces := strings.Split(selectorPiece, op)
if len(pieces) == 2 {
return pieces[0], pieces[1], true
// splitTerms returns the comma-separated terms contained in the given fieldSelector.
// Backslash-escaped commas are treated as data instead of delimiters, and are included in the returned terms, with the leading backslash preserved.
func splitTerms(fieldSelector string) []string {
if len(fieldSelector) == 0 {
return nil
}
return "", "", false
terms := make([]string, 0, 1)
startIndex := 0
inSlash := false
for i, c := range fieldSelector {
switch {
case inSlash:
inSlash = false
case c == '\\':
inSlash = true
case c == ',':
terms = append(terms, fieldSelector[startIndex:i])
startIndex = i + 1
}
}
terms = append(terms, fieldSelector[startIndex:])
return terms
}
const (
notEqualOperator = "!="
doubleEqualOperator = "=="
equalOperator = "="
)
// termOperators holds the recognized operators supported in fieldSelectors.
// doubleEqualOperator and equal are equivalent, but doubleEqualOperator is checked first
// to avoid leaving a leading = character on the rhs value.
var termOperators = []string{notEqualOperator, doubleEqualOperator, equalOperator}
// splitTerm returns the lhs, operator, and rhs parsed from the given term, along with an indicator of whether the parse was successful.
// no escaping of special characters is supported in the lhs value, so the first occurance of a recognized operator is used as the split point.
// the literal rhs is returned, and the caller is responsible for applying any desired unescaping.
func splitTerm(term string) (lhs, op, rhs string, ok bool) {
for i := range term {
remaining := term[i:]
for _, op := range termOperators {
if strings.HasPrefix(remaining, op) {
return term[0:i], op, term[i+len(op):], true
}
}
}
return "", "", "", false
}
func parseSelector(selector string, fn TransformFunc) (Selector, error) {
parts := strings.Split(selector, ",")
parts := splitTerms(selector)
sort.StringSlice(parts).Sort()
var items []Selector
for _, part := range parts {
if part == "" {
continue
}
if lhs, rhs, ok := try(part, "!="); ok {
items = append(items, &notHasTerm{field: lhs, value: rhs})
} else if lhs, rhs, ok := try(part, "=="); ok {
items = append(items, &hasTerm{field: lhs, value: rhs})
} else if lhs, rhs, ok := try(part, "="); ok {
items = append(items, &hasTerm{field: lhs, value: rhs})
} else {
lhs, op, rhs, ok := splitTerm(part)
if !ok {
return nil, fmt.Errorf("invalid selector: '%s'; can't understand '%s'", selector, part)
}
unescapedRHS, err := UnescapeValue(rhs)
if err != nil {
return nil, err
}
switch op {
case notEqualOperator:
items = append(items, &notHasTerm{field: lhs, value: unescapedRHS})
case doubleEqualOperator:
items = append(items, &hasTerm{field: lhs, value: unescapedRHS})
case equalOperator:
items = append(items, &hasTerm{field: lhs, value: unescapedRHS})
default:
return nil, fmt.Errorf("invalid selector: '%s'; can't understand '%s'", selector, part)
}
}
@ -276,3 +406,8 @@ func parseSelector(selector string, fn TransformFunc) (Selector, error) {
func OneTermEqualSelector(k, v string) Selector {
return &hasTerm{field: k, value: v}
}
// AndSelectors creates a selector that is the logical AND of all the given selectors
func AndSelectors(selectors ...Selector) Selector {
return andTerm(selectors)
}

View file

@ -16,4 +16,4 @@ limitations under the License.
// Package labels implements a simple label system, parsing and matching
// selectors with sets of labels.
package labels
package labels // import "k8s.io/apimachinery/pkg/labels"

View file

@ -24,9 +24,9 @@ import (
"strings"
"github.com/golang/glog"
"k8s.io/client-go/pkg/selection"
"k8s.io/client-go/pkg/util/sets"
"k8s.io/client-go/pkg/util/validation"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
)
// Requirements is AND of all requirements.
@ -62,7 +62,7 @@ type nothingSelector struct{}
func (n nothingSelector) Matches(_ Labels) bool { return false }
func (n nothingSelector) Empty() bool { return false }
func (n nothingSelector) String() string { return "<null>" }
func (n nothingSelector) String() string { return "" }
func (n nothingSelector) Add(_ ...Requirement) Selector { return n }
func (n nothingSelector) Requirements() (Requirements, bool) { return nil, false }
@ -728,15 +728,16 @@ func (p *Parser) parseExactValue() (sets.String, error) {
// as they parse different selectors with different syntaxes.
// The input will cause an error if it does not follow this form:
//
// <selector-syntax> ::= <requirement> | <requirement> "," <selector-syntax> ]
// <requirement> ::= [!] KEY [ <set-based-restriction> | <exact-match-restriction> ]
// <set-based-restriction> ::= "" | <inclusion-exclusion> <value-set>
// <inclusion-exclusion> ::= <inclusion> | <exclusion>
// <exclusion> ::= "notin"
// <inclusion> ::= "in"
// <value-set> ::= "(" <values> ")"
// <values> ::= VALUE | VALUE "," <values>
// <exact-match-restriction> ::= ["="|"=="|"!="] VALUE
// <selector-syntax> ::= <requirement> | <requirement> "," <selector-syntax>
// <requirement> ::= [!] KEY [ <set-based-restriction> | <exact-match-restriction> ]
// <set-based-restriction> ::= "" | <inclusion-exclusion> <value-set>
// <inclusion-exclusion> ::= <inclusion> | <exclusion>
// <exclusion> ::= "notin"
// <inclusion> ::= "in"
// <value-set> ::= "(" <values> ")"
// <values> ::= VALUE | VALUE "," <values>
// <exact-match-restriction> ::= ["="|"=="|"!="] VALUE
//
// KEY is a sequence of one or more characters following [ DNS_SUBDOMAIN "/" ] DNS_LABEL. Max length is 63 characters.
// VALUE is a sequence of zero or more characters "([A-Za-z0-9_-\.])". Max length is 63 characters.
// Delimiter is white space: (' ', '\t')
@ -792,7 +793,7 @@ func validateLabelValue(v string) error {
// SelectorFromSet returns a Selector which will match exactly the given Set. A
// nil and empty Sets are considered equivalent to Everything().
func SelectorFromSet(ls Set) Selector {
if ls == nil {
if ls == nil || len(ls) == 0 {
return internalSelector{}
}
var requirements internalSelector
@ -806,14 +807,14 @@ func SelectorFromSet(ls Set) Selector {
}
// sort to have deterministic string representation
sort.Sort(ByKey(requirements))
return internalSelector(requirements)
return requirements
}
// SelectorFromValidatedSet returns a Selector which will match exactly the given Set.
// A nil and empty Sets are considered equivalent to Everything().
// It assumes that Set is already validated and doesn't do any validation.
func SelectorFromValidatedSet(ls Set) Selector {
if ls == nil {
if ls == nil || len(ls) == 0 {
return internalSelector{}
}
var requirements internalSelector
@ -822,7 +823,7 @@ func SelectorFromValidatedSet(ls Set) Selector {
}
// sort to have deterministic string representation
sort.Sort(ByKey(requirements))
return internalSelector(requirements)
return requirements
}
// ParseToRequirements takes a string representing a selector and returns a list of

View file

@ -14,11 +14,12 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package common
package openapi
import (
"github.com/emicklei/go-restful"
"github.com/go-openapi/spec"
"strings"
)
// OpenAPIDefinition describes single type. Normally these definitions are auto-generated using gen-openapi.
@ -27,8 +28,10 @@ type OpenAPIDefinition struct {
Dependencies []string
}
type ReferenceCallback func(path string) spec.Ref
// OpenAPIDefinitions is collection of all definitions.
type OpenAPIDefinitions map[string]OpenAPIDefinition
type GetOpenAPIDefinitions func(ReferenceCallback) map[string]OpenAPIDefinition
// OpenAPIDefinitionGetter gets openAPI definitions for a given type. If a type implements this interface,
// the definition returned by it will be used, otherwise the auto-generated definitions will be used. See
@ -59,11 +62,18 @@ type Config struct {
// OpenAPIDefinitions should provide definition for all models used by routes. Failure to provide this map
// or any of the models will result in spec generation failure.
Definitions *OpenAPIDefinitions
GetDefinitions GetOpenAPIDefinitions
// GetOperationIDAndTags returns operation id and tags for a restful route. It is an optional function to customize operation IDs.
GetOperationIDAndTags func(servePath string, r *restful.Route) (string, []string, error)
// GetDefinitionName returns a friendly name for a definition base on the serving path. parameter `name` is the full name of the definition.
// It is an optional function to customize model names.
GetDefinitionName func(servePath string, name string) (string, spec.Extensions)
// PostProcessSpec runs after the spec is ready to serve. It allows a final modification to the spec before serving.
PostProcessSpec func(*spec.Swagger) (*spec.Swagger, error)
// SecurityDefinitions is list of all security definitions for OpenAPI service. If this is not nil, the user of config
// is responsible to provide DefaultSecurity and (maybe) add unauthorized response to CommonResponses.
SecurityDefinitions *spec.SecurityDefinitions
@ -141,3 +151,10 @@ func GetOpenAPITypeFormat(typeName string) (string, string) {
}
return mapped[0], mapped[1]
}
func EscapeJsonPointer(p string) string {
// Escaping reference name using rfc6901
p = strings.Replace(p, "~", "~0", -1)
p = strings.Replace(p, "/", "~1", -1)
return p
}

18
vendor/k8s.io/apimachinery/pkg/openapi/doc.go generated vendored Normal file
View file

@ -0,0 +1,18 @@
/*
Copyright 2016 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 openapi holds shared codes and types between open API code generator and spec generator.
package openapi

19
vendor/k8s.io/apimachinery/pkg/runtime/OWNERS generated vendored Normal file
View file

@ -0,0 +1,19 @@
approvers:
- caesarxuchao
- deads2k
- lavalamp
- smarterclayton
reviewers:
- lavalamp
- smarterclayton
- wojtek-t
- deads2k
- derekwaynecarr
- caesarxuchao
- mikedanese
- nikhiljindal
- gmarek
- krousey
- timothysc
- piosz
- mbohlool

View file

@ -24,8 +24,8 @@ import (
"net/url"
"reflect"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/client-go/pkg/conversion/queryparams"
"k8s.io/apimachinery/pkg/conversion/queryparams"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// codec binds an encoder and decoder.
@ -85,7 +85,7 @@ type DefaultingSerializer struct {
}
// Decode performs a decode and then allows the defaulter to act on the provided object.
func (d DefaultingSerializer) Decode(data []byte, defaultGVK *unversioned.GroupVersionKind, into Object) (Object, *unversioned.GroupVersionKind, error) {
func (d DefaultingSerializer) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
obj, gvk, err := d.Decoder.Decode(data, defaultGVK, into)
if err != nil {
return obj, gvk, err
@ -96,7 +96,7 @@ func (d DefaultingSerializer) Decode(data []byte, defaultGVK *unversioned.GroupV
// UseOrCreateObject returns obj if the canonical ObjectKind returned by the provided typer matches gvk, or
// invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.
func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk unversioned.GroupVersionKind, obj Object) (Object, error) {
func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error) {
if obj != nil {
kinds, _, err := t.ObjectKinds(obj)
if err != nil {
@ -129,7 +129,7 @@ type NoopDecoder struct {
var _ Serializer = NoopDecoder{}
func (n NoopDecoder) Decode(data []byte, gvk *unversioned.GroupVersionKind, into Object) (Object, *unversioned.GroupVersionKind, error) {
func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
return nil, nil, fmt.Errorf("decoding is not allowed for this codec: %v", reflect.TypeOf(n.Encoder))
}
@ -153,7 +153,7 @@ var _ ParameterCodec = &parameterCodec{}
// DecodeParameters converts the provided url.Values into an object of type From with the kind of into, and then
// converts that object to into (if necessary). Returns an error if the operation cannot be completed.
func (c *parameterCodec) DecodeParameters(parameters url.Values, from unversioned.GroupVersion, into Object) error {
func (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error {
if len(parameters) == 0 {
return nil
}
@ -161,11 +161,12 @@ func (c *parameterCodec) DecodeParameters(parameters url.Values, from unversione
if err != nil {
return err
}
targetGVK := targetGVKs[0]
if targetGVK.GroupVersion() == from {
return c.convertor.Convert(&parameters, into, nil)
for i := range targetGVKs {
if targetGVKs[i].GroupVersion() == from {
return c.convertor.Convert(&parameters, into, nil)
}
}
input, err := c.creator.New(from.WithKind(targetGVK.Kind))
input, err := c.creator.New(from.WithKind(targetGVKs[0].Kind))
if err != nil {
return err
}
@ -177,7 +178,7 @@ func (c *parameterCodec) DecodeParameters(parameters url.Values, from unversione
// EncodeParameters converts the provided object into the to version, then converts that object to url.Values.
// Returns an error if conversion is not possible.
func (c *parameterCodec) EncodeParameters(obj Object, to unversioned.GroupVersion) (url.Values, error) {
func (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) {
gvks, _, err := c.typer.ObjectKinds(obj)
if err != nil {
return nil, err
@ -194,27 +195,28 @@ func (c *parameterCodec) EncodeParameters(obj Object, to unversioned.GroupVersio
}
type base64Serializer struct {
Serializer
Encoder
Decoder
}
func NewBase64Serializer(s Serializer) Serializer {
return &base64Serializer{s}
func NewBase64Serializer(e Encoder, d Decoder) Serializer {
return &base64Serializer{e, d}
}
func (s base64Serializer) Encode(obj Object, stream io.Writer) error {
e := base64.NewEncoder(base64.StdEncoding, stream)
err := s.Serializer.Encode(obj, e)
err := s.Encoder.Encode(obj, e)
e.Close()
return err
}
func (s base64Serializer) Decode(data []byte, defaults *unversioned.GroupVersionKind, into Object) (Object, *unversioned.GroupVersionKind, error) {
func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
out := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(out, data)
if err != nil {
return nil, nil, err
}
return s.Serializer.Decode(out[:n], defaults, into)
return s.Decoder.Decode(out[:n], defaults, into)
}
// SerializerInfoForMediaType returns the first info in types that has a matching media type (which cannot
@ -243,30 +245,30 @@ var (
type internalGroupVersioner struct{}
// KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.
func (internalGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
func (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
for _, kind := range kinds {
if kind.Version == APIVersionInternal {
return kind, true
}
}
for _, kind := range kinds {
return unversioned.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
return schema.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
}
return unversioned.GroupVersionKind{}, false
return schema.GroupVersionKind{}, false
}
type disabledGroupVersioner struct{}
// KindForGroupVersionKinds returns false for any input.
func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
return unversioned.GroupVersionKind{}, false
func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
return schema.GroupVersionKind{}, false
}
// GroupVersioners implements GroupVersioner and resolves to the first exact match for any kind.
type GroupVersioners []GroupVersioner
// KindForGroupVersionKinds returns the first match of any of the group versioners, or false if no match occured.
func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
for _, gv := range gvs {
target, ok := gv.KindForGroupVersionKinds(kinds)
if !ok {
@ -274,22 +276,22 @@ func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []unversioned.GroupVer
}
return target, true
}
return unversioned.GroupVersionKind{}, false
return schema.GroupVersionKind{}, false
}
// Assert that unversioned.GroupVersion and GroupVersions implement GroupVersioner
var _ GroupVersioner = unversioned.GroupVersion{}
var _ GroupVersioner = unversioned.GroupVersions{}
// Assert that schema.GroupVersion and GroupVersions implement GroupVersioner
var _ GroupVersioner = schema.GroupVersion{}
var _ GroupVersioner = schema.GroupVersions{}
var _ GroupVersioner = multiGroupVersioner{}
type multiGroupVersioner struct {
target unversioned.GroupVersion
acceptedGroupKinds []unversioned.GroupKind
target schema.GroupVersion
acceptedGroupKinds []schema.GroupKind
}
// NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.
// Kind may be empty in the provided group kind, in which case any kind will match.
func NewMultiGroupVersioner(gv unversioned.GroupVersion, groupKinds ...unversioned.GroupKind) GroupVersioner {
func NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
if len(groupKinds) == 0 || (len(groupKinds) == 1 && groupKinds[0].Group == gv.Group) {
return gv
}
@ -298,7 +300,7 @@ func NewMultiGroupVersioner(gv unversioned.GroupVersion, groupKinds ...unversion
// KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will
// use the originating kind where possible.
func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupVersionKind) (unversioned.GroupVersionKind, bool) {
func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
for _, src := range kinds {
for _, kind := range v.acceptedGroupKinds {
if kind.Group != src.Group {
@ -310,5 +312,5 @@ func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []unversioned.GroupV
return v.target.WithKind(src.Kind), true
}
}
return unversioned.GroupVersionKind{}, false
return schema.GroupVersionKind{}, false
}

View file

@ -20,14 +20,14 @@ import (
"fmt"
"reflect"
"k8s.io/client-go/pkg/api/unversioned"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// CheckCodec makes sure that the codec can encode objects like internalType,
// decode all of the external types listed, and also decode them into the given
// object. (Will modify internalObject.) (Assumes JSON serialization.)
// TODO: verify that the correct external version is chosen on encode...
func CheckCodec(c Codec, internalType Object, externalTypes ...unversioned.GroupVersionKind) error {
func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error {
_, err := Encode(c, internalType)
if err != nil {
return fmt.Errorf("Internal type not encodable: %v", err)

View file

@ -23,7 +23,7 @@ import (
"strconv"
"strings"
"k8s.io/client-go/pkg/conversion"
"k8s.io/apimachinery/pkg/conversion"
)
// JSONKeyMapper uses the struct tags on a conversion to determine the key value for

View file

@ -42,4 +42,4 @@ limitations under the License.
// As a bonus, a few common types useful from all api objects and versions
// are provided in types.go.
package runtime
package runtime // import "k8s.io/apimachinery/pkg/runtime"

Some files were not shown because too many files have changed in this diff Show more